CarFleetPro setup and deployment
CarFleetPro is a multi-tenant car rental application. The operator dashboard, rental storefronts, and demo use the same Worker and D1 schema.
Run locally
Install Node.js 22 or later, npm, and tar. From the source directory:
npm ci
npm test
npm run dev
Open http://localhost:8787 and select Live demo to try seeded records in a separate workspace. To create a real workspace, use Get started and enter your company and account details. The local database persists in .wrangler/state. The demo expires after two hours. Reset starts a fresh isolated demo.
Create a branch under Settings, add a vehicle under Fleet, and add a renter under Customers. Create a reservation with those records, then record receipts, refunds, and agreements against that reservation. Publish your catalog under Rental website. The public storefront is available at /rent/<company-slug> and saves customer requests as pending reservations.
Open Fleet, select a vehicle, and upload JPEG, PNG, or WebP files under Vehicle photos. Select the cover image for search results. The workspace supports eight photos per vehicle. The booking site shows these images for visible vehicles, and customers can open the vehicle gallery.
Under Rental website, select the payment methods guests may choose. Bank transfer requires public instructions, which the guest sees after submitting the request and in the booking lookup. Staff open the reservation, record actual receipts (including partial payments), and select Confirm booking once receipts minus refunds cover the total. The vehicle is reserved when staff confirm, subject to availability. Leaving every method disabled preserves the existing request and confirmation workflow.
To request a driving license photo, enable Require a driving license photo on website bookings under Rental website. The setting is off by default. When enabled, new website requests require a JPEG, PNG, or WebP image up to 4 MB. Workspace owners and managers can view or remove it from the reservation. Files use private object storage, and access expires after 30 days. The cleanup job removes expired uploads. Use only non-personal sample images in the demo.
Configure purchasable services in Rental extras and seasonal rates in Rate rules. A rate can target a vehicle class or every class. Overlapping rules use the matching class before general rates and then the latest effective rule. The server bills each started 24-hour period, applies the one-way fee configured under Rental website, and saves the confirmed price and extras with the booking request.
The booking site has English and Arabic interfaces. Open /rent/<company-slug>/cars?lang=ar for the Arabic vehicle catalog or /demo?view=cars&lang=ar for a sample catalog. Company names, branch text, rental terms, and custom extras appear as entered. Renters can search by location, date, time, class, transmission, and seat count, and retrieve or cancel their pending website request using its reference and email address. The weekly Fleet calendar shows reservations and maintenance. Under a reservation, record pick-up and return condition, mileage, and fuel or charge, or print a rental statement. A recorded return updates the vehicle’s location and mileage.
Deploy to Cloudflare
- Log into Wrangler using
npx wrangler login. For CI, configureCLOUDFLARE_API_TOKENwith Workers and D1 deployment access and setCLOUDFLARE_ACCOUNT_ID. - Create a production database using
npx wrangler d1 create axlerent. Replace the exampledatabase_idunderd1_databasesinwrangler.jsoncwith that production identifier. Create the photo bucket usingnpx wrangler r2 bucket create axlerent-vehicle-photos. Use separate databases, private R2 buckets, and Workers for staging and production. - Apply migrations using
npx wrangler d1 migrations apply axlerent --remote. Deploy withnpm run deploy. - Set up a Cloudflare Worker custom domain. Set
APP_ORIGINto its complete HTTPS origin usingnpx wrangler secret put APP_ORIGIN. Verify/api/health, create a workspace, and test a public booking before sharing the domain. - Generate a random one-time token of at least 32 characters. Set it with
npx wrangler secret put ADMIN_BOOTSTRAP_TOKEN. Sign in to the dedicated operations account, open/setup, and enter the token to enable/platform. Remove it withnpx wrangler secret delete ADMIN_BOOTSTRAP_TOKENafter the claim succeeds. - Protect domain access and apply Cloudflare rate controls for public traffic. Define data retention, D1 backups, and incident procedures. Test a D1 recovery before launch. The scheduled job removes expired sessions, demo workspaces, and invitations.
Deploy schema changes before activating code that relies on those changes. Keep migration files immutable after application. Reconcile application and database compatibility before reverting to an earlier Worker version.
Notify the platform owner about new companies
This optional integration sends the company name and creation time to one platform operations mailbox when a real company workspace is created. Demo sessions and team invitations do not send mail. Enable it before the signups you want to receive.
- In Resend, add a sending domain or subdomain you control. Publish the DNS records Resend provides, then verify it in Resend. Create an API key with sending access restricted to that domain.
- Apply the database migration before enabling email. For a Cloudflare database named
carfleetpro, runnpx.cmd wrangler d1 migrations apply carfleetpro --remotefrom the project folder on Windows, thennpm.cmd run deploy. Use your configured D1 name if it differs. - In the Cloudflare Worker settings, add
RESEND_API_KEY,SIGNUP_EMAIL_FROM(a single sender address on the verified domain), andSIGNUP_EMAIL_TO(your operations mailbox) as secrets. Set the API key last, and keep it out of source control and chat. - Create a test company and verify the message in your inbox and in Resend’s activity log. The registration saves first and the Worker sends the message in the background. The existing hourly Cloudflare cron retries transient errors within the provider’s idempotency window. Use Workers logs and Resend activity to diagnose delivery problems.
Publish a support address
Set the Worker variable PUBLIC_SUPPORT_EMAIL to a mailbox that your team monitors.
It appears publicly on the Support page, linked from the main site's header and footer
in English, Arabic, and Turkish. The link opens the visitor's email app. The Support
link is hidden until the address is configured. This address is independent of the
private signup notification recipient.
Booking emails and platform controls
- After applying migration
0006_platform_controls.sql, owners and managers can set Booking notification email under Rental website. Leave it empty to turn alerts off. This private address is separate from the contact address shown to visitors. - To deliver alerts, configure
RESEND_API_KEYandBOOKING_EMAIL_FROMusing a domain verified in Resend. IfBOOKING_EMAIL_FROMis empty, the Worker usesSIGNUP_EMAIL_FROM. After saving the company’s recipient, make a test request through the published rental site and verify the inbox. The email contains the company, reservation reference, and dates. - In Platform administration → Website design and trial settings, choose a color palette, a built-in cover, and the headline for each language. Leave a headline blank to use the default. Changes appear on the public CarFleetPro site when saved.
- Turning off the 14-day trial applies to future companies. Use Require subscription on an existing company to remove trial access until it has an active paid plan. The company can still open its dashboard and billing page. Clearing the requirement restores unexpired trial access, where applicable. These controls do not charge a company. Paid checkout uses the Stripe configuration below.
Configure subscriptions
CarFleetPro gives real workspaces a 14-day Starter trial. The Starter, Growth, and Scale plans use the vehicle and seat limits in src/catalog.js. Trial or paid entitlement permits operational writes. Expired customers can still read their records and open billing. The portal handles payment-method and plan changes and cancellation.
- In Stripe, create recurring monthly USD prices for Starter ($39), Growth ($99), and Scale ($249). Enable Stripe's customer portal with the desired plan switches and cancellation rules.
- Set
STRIPE_SECRET_KEY,STRIPE_PRICE_STARTER,STRIPE_PRICE_GROWTH, andSTRIPE_PRICE_SCALEwith Wrangler. Price values start withprice_. The server uses Stripe API version2024-06-20. - Register
https://<your-domain>/api/stripe/webhookforcheckout.session.completedandcustomer.subscription.created,.updated,.deleted,.paused, and.resumed. Set its signing secret asSTRIPE_WEBHOOK_SECRET. If testing locally, forward events with the Stripe CLI and use its emitted signing secret in an ignored.dev.varsfile. - In Stripe test mode, complete checkout for each plan and confirm that Stripe's signed webhook updates entitlements. Also test portal changes, payment failure, and cancellation before setting live-mode credentials. The hosted Sites preview keeps billing unavailable until credentials are configured.
Rental receipts and refunds are bookkeeping entries for payments your team has already handled. CarFleetPro does not collect renter card details. Tax rates, local receipt rules, and rental agreement wording are business-specific.
Connect GPS hardware
A company on Growth or Scale can assign a provider device identifier under Fleet. A workspace manager can issue a key under GPS tracking. Configure the tracker or a provider-managed relay to send authenticated JSON to the displayed endpoint. Each tenant has its own key. Rotating it revokes the preceding key.
POST /api/gps/<company-slug>
Authorization: Bearer <tenant-gps-key>
Content-Type: application/json
{
"device_id": "DEVICE-01",
"latitude": 37.7749,
"longitude": -122.4194,
"speed_kph": 42,
"recorded_at": "<current ISO 8601 time>"
}
A successful request returns HTTP 201. Use a current timestamp to verify the live feed and latest-position display. Configure retention for GPS and renter data according to your operating jurisdiction. Vehicles and device providers that cannot POST this format need a provider-specific relay.
Verify and operate
npm testruns the Worker and an isolated D1 database. The suite exercises rendered dashboard forms and covers authentication, tenant roles, composite relationships, conflicting reservations, rental requests, agreements, payment reconciliation, demo reset, entitlement enforcement, platform administration, and GPS ingest. Stripe lifecycle tests simulate provider responses in the test process. Use Stripe test mode for a live integration acceptance test.- Review
docs/ARCHITECTURE.mdfor the domain model, tenancy boundaries, and phase acceptance criteria. - ChatGPT Sites hosts the project on its Sites URL. The site owner manages access and can connect a custom domain from Sites, then complete DNS validation at the domain provider. For hosted subscriptions, set the Stripe variables in Sites runtime settings and deploy that environment revision. Keep platform bootstrap, Stripe, and GPS keys out of source control.
- Marketing, sign-in, registration, and the rental storefront are available in English and Arabic. The operator workspace uses English. Tenants choose their operating currency and time zone. Review local rental terms, receipts, privacy rules, and accessibility with the launch markets before commercial rollout.
Hero images are sourced from Unsplash. The website uses Inter and Tajawal from Google Fonts.
CarFleetPro architecture and implementation plan
CarFleetPro serves operators, renters, and platform administrators. Operators manage bookings and fleet operations in a tenant workspace. Renters browse a published company catalog and send a booking request. Platform administrators manage account status and review subscription and tenant counts.
Application boundaries
- A Cloudflare Worker serves the routed interface, JSON API, printable contracts, Stripe webhook, and GPS ingest endpoint. SQLite through a D1 binding is the source of truth. The same Worker runs locally and can deploy to a Cloudflare account.
- Authentication uses server-validated sessions. Workspace authorization comes from an active membership checked at request time. Owner, manager, staff, and read-only roles have separate permissions. Platform administrators manage tenant metadata through separate routes.
- Each tenant-owned record has a tenant identifier. Composite foreign keys stop records from linking across tenant boundaries. All operational reads and writes bind a tenant derived from the verified session. Public requests resolve a published tenant by slug and use a narrow booking-only path.
- Rental prices use integer minor units, one operating currency per tenant, ISO dates, and explicit booking day boundaries. The database rejects overlapping active bookings and conflicting maintenance holds even when requests arrive concurrently.
- A per-session demo creates a temporary tenant, session, and sample rows using the same application paths. Demo users cannot change live subscription or platform configuration. Old demos expire.
- Stripe Checkout and its customer portal manage subscriptions. Verified webhooks reconcile provider state. Rental payments record amounts received outside the application. GPS trackers send authenticated location updates through a documented HTTP interface.
Data model
tenants owns branches, vehicles, customers, reservations, contracts, payments, maintenance, gps_positions, and audit_log. memberships connects users with tenants. sessions stores hashed tokens and active tenant selection. invites handles expiring workspace invitations. subscriptions maps a tenant to Stripe identifiers, lifecycle, plan, and period. billing_events and rate_limits support idempotency and throttling. See the migration for executable constraints and indexes.
Delivery phases
| Phase | Implementation | Acceptance |
|---|---|---|
| 1 | Router, relational migration, money and date rules | Clean migration and composite foreign keys |
| 2 | Accounts, sessions, memberships, authorization | Sign-in, sign-out, role enforcement, isolation checks |
| 3 | Overview, date filters, reports | Counts and revenue reconcile with stored records |
| 4 | Fleet, bookings, customers, contracts, payments, maintenance | Validated CRUD and conflict prevention |
| 5 | Tenant publishing and rental request path | Published catalogs and a persisted public booking |
| 6 | SaaS marketing, pricing, onboarding | Working navigation and entry points |
| 7 | Stripe lifecycle and entitlements | Verified provider events and enforced fleet/seat limits |
| 8 | Isolated, seeded demo workspace | Creation, mutation, reset, and expiry |
| 9 | Platform administration and audit | Authorized tenant suspension and restoration |
| 10 | GPS ingest, automated verification, deployment runbook | Authenticated ingest, repeatable tests, deployment instructions |
Launch decisions include Stripe account and plan prices, operating jurisdictions and rental terms, GPS hardware compatibility, and the production hostname.
Storefront and fleet operations
- Vehicle photos use private R2 objects. Tenant-scoped D1 metadata controls cover selection and whether photos can be read through the published storefront. Deletions are queued in D1 so cleanup can be retried.
- Booking search uses branch-local times and projects the vehicle’s branch from confirmed rentals. D1 prevents overlapping bookings and conflicting branch changes. A completed handover updates the current branch and odometer.
- Rate rules and rental extras are tenant-scoped. Optional services can charge per day or rental. Customer requests save the item names, quantities, per-unit charges, and agreed price independently of future changes to the catalog.
- Reservation references and matching renter email addresses give renters access to their own booking status and cancellation of pending website requests. Booking lookup and cancellation are rate-limited.