Food Delivery ER diagram and database schema

The Food Delivery database schema is a DB Planner template with 29 tables, 269 columns and 49 relationships, free to use. Core tables include courier_earnings, courier_payouts, courier_shifts, couriers. It can be opened as an interactive ER diagram or exported as PostgreSQL, MySQL, or SQL Server DDL.

ER diagram of the Food Delivery database schema, showing 29 tables and their relationships
FIG. 1: entity relationship diagram, 29 tables
Tables
29
Columns
269
Relationships
49
Category
Logistics
Exports
DBML, SQL, Prisma, C#
Price
Free

What this schema models

A complete food delivery app database design for a three-sided marketplace of customers, restaurants and couriers: 29 tables, 22 enums and 49 relationships covering menus with dayparts and modifier groups, restaurants, opening hours and delivery zones with fee schedules, customers and saved addresses, orders with snapshotted lines, promotions and ratings, courier offers, deliveries and tracking events, courier shifts, and payments, refunds and payouts to restaurants and couriers. THE FOUR DESIGN RULES 1. Order lines are snapshots. Order items copy the item name and price, and their modifiers copy the group name, option name and price delta, so editing or deleting a menu item never changes a past order, kitchen ticket or receipt; the menu foreign keys remain for reporting only. Fees, the commission rate and the delivery address are copied onto the order the same way. 2. The order is not the delivery. The order belongs to the customer and the restaurant; a delivery is a courier assignment created from an accepted delivery offer. A courier who drops the job leaves an unassigned row and a new delivery is created, with a partial unique index allowing only one live delivery per order. Pickup orders never get a delivery at all. 3. Three sides, three ledgers. The customer side is payments and refunds; the restaurant side is ledger entries (food sales, minus commission, minus restaurant-funded promotions and refund chargebacks); the courier side is earnings by component. Each sweeps into its own payouts, and delivery fees and tips never touch the restaurant ledger. 4. Modifier groups are reusable and carry their own rules. "Choose a size" or "Add toppings" is defined once with minimum, maximum and free selections, then attached to many items through a join table. Items are placed into menu categories the same way, so one item can sit on the breakfast and the all-day menu at one price. DETAILS WORTH STEALING - Refunds record the party at fault (restaurant, courier, platform or customer), which decides who absorbs the cost; a restaurant-fault refund is charged back on its ledger. - Promotions record who funds them (platform, restaurant or shared, with the restaurant share), because that decides whose ledger the discount hits. - Ratings are split by subject, so a cold meal from a slow courier is not held against the kitchen. - Orders carry a timestamp for each milestone (placed, accepted, ready, completed, cancelled), so prep time and total wait are plain subtractions. - Opening hours allow split lunch and dinner services and shifts that run past midnight, and menus have their own time-of-day windows. - Alcohol items require an ID check at handoff: only age-verified couriers can take them, and the check is logged as a tracking event. WHAT YOU GET Clean DBML that imports directly into DB Planner, and a laid-out board with zones color-coded and framed: menus, restaurants and delivery zones, customers, orders, delivery, couriers, and money. Every table carries a note. Postgres-flavoured types, with PostGIS geography columns for locations and zones; the rest ports cleanly to MySQL or SQL Server. Useful for developers building a food delivery or online ordering marketplace, and for students who need a realistic food delivery app ER diagram for a DBMS project. This is a schema design reference; tax, tipping and courier classification rules vary by market and belong in your own business logic.

Tables (29)

Every table and its columns

menus

A restaurant can run several menus by time of day. The storefront shows those whose window contains the current local time.

Columns of the menus table
ColumnTypeConstraintsReferencesDescription
iduuidPK
restaurant_iduuidFK, not nullrestaurants.id
namevarchar(100)not nulle.g. All day, Breakfast, Late night
available_fromtimeNull, with available_to, for a menu served whenever the restaurant is open
available_totime
is_activebooleannot null, default true

menu_categories

Sections of a menu.

Columns of the menu_categories table
ColumnTypeConstraintsReferencesDescription
iduuidPK
menu_iduuidFK, not nullmenus.id
namevarchar(100)not nulle.g. Starters, Burgers, Drinks
sort_ordersmallintnot null, default 0

menu_category_items

Places an item in a category. The same coffee can sit on the breakfast and the all-day menu without being two items with two prices.

Columns of the menu_category_items table
ColumnTypeConstraintsReferences
menu_category_iduuidFK, not nullmenu_categories.id
menu_item_iduuidFK, not nullmenu_items.id
sort_ordersmallintnot null, default 0

menu_items

Dishes and drinks, defined once per restaurant. Changing a price here never touches an order already placed.

Columns of the menu_items table
ColumnTypeConstraintsReferencesDescription
iduuidPK
restaurant_iduuidFK, not nullrestaurants.id
namevarchar(200)not null
descriptiontext
price_centsintegernot null
image_keyvarchar(300)Object storage key. Images never live in the database.
is_alcoholbooleannot null, default falseRequires an ID check at handoff, so only some couriers can take it
is_availablebooleannot null, default trueSwitched off when sold out; the item stays on the menu, greyed out
created_attimestamptznot null, default `now()`

modifier_groups

A reusable set of choices with its selection rules, defined once and attached to many items.

Columns of the modifier_groups table
ColumnTypeConstraintsReferencesDescription
iduuidPK
restaurant_iduuidFK, not nullrestaurants.id
namevarchar(100)not nulle.g. Choose a size, Add toppings, Pick a side
min_selectionssmallintnot null, default 01 or more makes the group required
max_selectionssmallintnot null, default 1
free_selectionssmallintnot null, default 0Options included before price deltas apply, e.g. two free toppings

modifier_options

One choice within a modifier group.

Columns of the modifier_options table
ColumnTypeConstraintsReferencesDescription
iduuidPK
modifier_group_iduuidFK, not nullmodifier_groups.id
namevarchar(100)not nulle.g. Large, Extra cheese, No onions
price_delta_centsintegernot null, default 0Added to the item price; negative for a cheaper swap
is_defaultbooleannot null, default false
is_availablebooleannot null, default true
sort_ordersmallintnot null, default 0

menu_item_modifier_groups

Which modifier groups an item offers, in display order. Edit the "Choose a sauce" group once and every item using it changes.

Columns of the menu_item_modifier_groups table
ColumnTypeConstraintsReferences
menu_item_iduuidFK, not nullmenu_items.id
modifier_group_iduuidFK, not nullmodifier_groups.id
sort_ordersmallintnot null, default 0

delivery_zones

Areas the platform delivers in, each with its fee schedule. Fees are computed from the zone at checkout and then copied onto the order.

Columns of the delivery_zones table
ColumnTypeConstraintsReferencesDescription
iduuidPK
namevarchar(120)not nulle.g. Downtown, Riverside
cityvarchar(120)not null
timezonevarchar(64)not nullIANA zone. Opening hours and menu windows are read in it.
currencychar(3)not null
boundarygeography(MultiPolygon,4326)not null
base_delivery_fee_centsintegernot null
per_km_fee_centsintegernot null
small_order_threshold_centsintegerOrders with a subtotal under this pay the small order fee
small_order_fee_centsinteger
service_fee_bpsintegernot nullService fee in basis points of the subtotal
max_delivery_kmnumeric(5,2)not null
is_activebooleannot null, default true

restaurants

Merchants on the platform.

Columns of the restaurants table
ColumnTypeConstraintsReferencesDescription
iduuidPK
delivery_zone_iduuidFK, not nulldelivery_zones.id
namevarchar(200)not null
slugvarchar(200)unique, not null
phonevarchar(20)not null
addressvarchar(300)not null
locationgeography(Point,4326)not null
cuisinevarchar(60)
commission_bpsintegernot nullPlatform commission on the food subtotal, e.g. 2500 for 25 percent
avg_prep_minutessmallintnot null, default 20Feeds the delivery estimate and when to dispatch a courier
accepts_pickupbooleannot null, default trueCustomer pickup orders never get a delivery
statusrestaurant_statusnot null, default 'onboarding'
paused_untiltimestamptzTemporarily not taking orders, e.g. the kitchen is overwhelmed
payout_account_tokenvarchar(200)Bank account held by the payment processor
created_attimestamptznot null, default `now()`

restaurant_hours

Opening hours in the zone timezone. Several rows per day allow a split lunch and dinner service.

Columns of the restaurant_hours table
ColumnTypeConstraintsReferencesDescription
restaurant_iduuidFK, not nullrestaurants.id
day_of_weeksmallintnot null1 = Monday ... 7 = Sunday
opens_attimenot null
closes_attimenot nullEarlier than opens_at means the service runs past midnight

customers

People who order food.

Columns of the customers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
emailvarchar(254)unique, not null
phonevarchar(20)uniqueE.164. Couriers reach the customer through a masked number, never this one directly.
first_namevarchar(100)not null
last_namevarchar(100)
statusaccount_statusnot null, default 'active'
created_attimestamptznot null, default `now()`

customer_addresses

Saved delivery addresses. An order copies the address it was delivered to, so editing or deleting this row never rewrites history.

Columns of the customer_addresses table
ColumnTypeConstraintsReferencesDescription
iduuidPK
customer_iduuidFK, not nullcustomers.id
labelvarchar(60)e.g. Home, Office
line1varchar(200)not null
line2varchar(200)Apartment, floor, suite
cityvarchar(120)not null
postal_codevarchar(20)not null
countrychar(2)not null
locationgeography(Point,4326)not nullGeocoded once on save. Zone, distance and fee are computed from it.
dropoff_instructionsvarchar(500)e.g. Leave at the door, buzzer 4B
is_defaultbooleannot null, default false

payment_methods

Saved cards and wallets, as processor tokens.

Columns of the payment_methods table
ColumnTypeConstraintsReferencesDescription
iduuidPK
customer_iduuidFK, not nullcustomers.id
kindpayment_method_kindnot null
processor_tokenvarchar(200)not nullCard data stays with the payment processor; only its token is stored
brandvarchar(20)
last4char(4)
expires_ondate
is_defaultbooleannot null, default false

promotions

Discounts and free-delivery offers. Who funds a promotion matters as much as its size: a restaurant-funded discount reduces the restaurant payout, a platform-funded one does not.

Columns of the promotions table
ColumnTypeConstraintsReferencesDescription
iduuidPK
codevarchar(30)uniqueNull for an automatic promotion that needs no code
restaurant_iduuidFKrestaurants.idNull for a platform-wide promotion
kindpromotion_kindnot null
valueintegernot nullBasis points for percent_off, cents for amount_off
min_subtotal_centsinteger
max_discount_centsinteger
funded_byfunding_partynot nullDecides whose ledger the discount is charged to
restaurant_share_bpsintegerFor a shared promotion, the part of the discount the restaurant pays
first_order_onlybooleannot null, default false
valid_fromtimestamptznot null
valid_totimestamptz

orders

The customer order, as a status machine with a timestamp for each milestone, so prep time and total wait are subtractions. Every fee, rate and the address are copied here at checkout.

Columns of the orders table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_numbervarchar(12)unique, not nullShort code read out at the counter, e.g. "4F7K"
customer_iduuidFK, not nullcustomers.id
restaurant_iduuidFK, not nullrestaurants.id
fulfillmentfulfillment_kindnot null
statusorder_statusnot null, default 'placed'
customer_address_iduuidFKcustomer_addresses.idWhere the address was picked from; that row may later change
delivery_addressvarchar(500)Snapshot of the address and drop-off instructions at checkout
delivery_locationgeography(Point,4326)
promotion_iduuidFKpromotions.id
subtotal_centsintegernot nullSum of order_items line totals
delivery_fee_centsintegernot null, default 0
service_fee_centsintegernot null, default 0
small_order_fee_centsintegernot null, default 0
discount_centsintegernot null, default 0
tax_centsintegernot null, default 0
tip_centsintegernot null, default 0Passed to the courier in full
total_centsintegernot null
currencychar(3)not null
commission_bpsintegernot nullRestaurant commission rate copied at checkout
scheduled_fortimestamptzNull for as soon as possible
estimated_ready_attimestamptz
placed_attimestamptznot null, default `now()`
accepted_attimestamptzRestaurant confirmed on its tablet
ready_attimestamptzFood bagged and waiting
completed_attimestamptzDelivered, or collected by the customer for a pickup order
cancelled_attimestamptz

Indexes: (restaurant_id, placed_at), (customer_id, placed_at), (status, placed_at)

order_items

One line of an order with its name and price SNAPSHOTTED. Editing or deleting a menu item never changes a past order, ticket or receipt.

Columns of the order_items table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_iduuidFK, not nullorders.id
menu_item_iduuidFKmenu_items.idFor reporting only. Null if the item was later deleted; the snapshot still stands.
item_namevarchar(200)not nullSnapshot at checkout
base_price_centsintegernot nullSnapshot of the item price at checkout
unit_price_centsintegernot nullBase price plus the chosen modifier deltas
quantitysmallintnot null
line_total_centsintegernot null
special_instructionsvarchar(300)e.g. No ice, sauce on the side

order_item_modifiers

The choices made for a line, snapshotted the same way, so the kitchen ticket and the receipt show exactly what was ordered.

Columns of the order_item_modifiers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_item_iduuidFK, not nullorder_items.id
modifier_option_iduuidFKmodifier_options.idFor reporting only
group_namevarchar(100)not nullSnapshot, e.g. Size
option_namevarchar(100)not nullSnapshot, e.g. Large
price_delta_centsintegernot nullSnapshot; 0 when it fell inside the free selections
quantitysmallintnot null, default 1

ratings

The customer rates the food and the delivery separately, so a cold meal from a slow courier is not held against the kitchen.

Columns of the ratings table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_iduuidFK, not nullorders.id
subjectrating_subjectnot null
courier_iduuidFKcouriers.idSet when the subject is the courier
starssmallintnot null1 to 5
commentvarchar(1000)
created_attimestamptznot null, default `now()`

Indexes: (order_id, subject) unique

delivery_offers

Every offer of an order to a courier and how it ended. Dispatch fires around ready time minus travel time, so the courier arrives as the food does.

Columns of the delivery_offers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_iduuidFK, not nullorders.id
courier_iduuidFK, not nullcouriers.id
offered_pay_centsintegernot nullPay shown to the courier before accepting
pickup_distance_mintegernot null
dropoff_distance_mintegernot null
statusoffer_statusnot null, default 'offered'
offered_attimestamptznot null
expires_attimestamptznot null
responded_attimestamptz

Indexes: (order_id, offered_at), (courier_id, offered_at)

deliveries

A courier assignment, separate from the order. A courier who drops the job ends the row as unassigned and a new delivery is created, so an order can have several deliveries but only one live one.

Columns of the deliveries table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_iduuidFK, not nullorders.id
courier_iduuidFK, not nullcouriers.id
courier_shift_iduuidFK, not nullcourier_shifts.id
delivery_offer_iduuidFK, unique, not nulldelivery_offers.idThe accepted offer that created this assignment
statusdelivery_statusnot null, default 'assigned'
assigned_attimestamptznot null
at_restaurant_attimestamptz
picked_up_attimestamptz
at_customer_attimestamptz
delivered_attimestamptz
unassigned_attimestamptzSet when the courier drops the job and the order goes back to dispatch
distance_mintegerRestaurant to customer, used for courier pay
proof_photo_keyvarchar(300)Photo at the door for a leave-at-door drop-off

Indexes: (order_id), (courier_id, assigned_at)

delivery_events

Append-only tracking feed behind the live map and the support timeline: status changes, location pings, and problems reported on the way. Partition by occurred_at once volume grows.

Columns of the delivery_events table
ColumnTypeConstraintsReferencesDescription
iduuidPK
delivery_iduuidFK, not nulldeliveries.id
kinddelivery_event_kindnot null
locationgeography(Point,4326)
occurred_attimestamptznot null
detailvarchar(300)e.g. "Customer not answering, waiting at door"

Indexes: (delivery_id, occurred_at)

couriers

Delivery people.

Columns of the couriers table
ColumnTypeConstraintsReferencesDescription
iduuidPK
phonevarchar(20)unique, not null
emailvarchar(254)unique, not null
first_namevarchar(100)not null
last_namevarchar(100)not null
vehiclecourier_vehiclenot nullLimits delivery distance and order size
home_zone_iduuidFK, not nulldelivery_zones.id
statuscourier_statusnot null, default 'applicant'
background_check_cleared_attimestamptz
age_verifiedbooleannot null, default falseRequired before taking orders with alcohol
rating_avgnumeric(3,2)Cache of courier ratings
payout_account_tokenvarchar(200)
created_attimestamptznot null, default `now()`

courier_shifts

Booked blocks and time online. The active shift carries the latest location, which is what dispatch searches; the trail itself is in delivery_events.

Columns of the courier_shifts table
ColumnTypeConstraintsReferencesDescription
iduuidPK
courier_iduuidFK, not nullcouriers.id
delivery_zone_iduuidFK, not nulldelivery_zones.id
scheduled_starttimestamptzNull for an unscheduled session; set for a booked block
scheduled_endtimestamptz
started_attimestamptzWhen the courier went online
ended_attimestamptz
current_locationgeography(Point,4326)Latest position while online, overwritten every few seconds
location_updated_attimestamptz
statusshift_statusnot null, default 'scheduled'

Indexes: (current_location), (courier_id)

payments

Customer card activity as rows: authorize at checkout, capture on delivery (the tip can still change in between), release on cancellation.

Columns of the payments table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_iduuidFK, not nullorders.id
payment_method_iduuidFK, not nullpayment_methods.id
kindpayment_kindnot null
statuspayment_statusnot null, default 'pending'
amount_centsintegernot null
currencychar(3)not null
parent_payment_iduuidFKpayments.idA capture or release points at its authorization
idempotency_keyvarchar(100)unique, not nullA retry after a timeout can never charge twice
processor_referencevarchar(100)unique
created_attimestamptznot null, default `now()`

refunds

Money returned to the customer, with the party at fault recorded alongside, because who pays for a refund is the hardest question in delivery support.

Columns of the refunds table
ColumnTypeConstraintsReferencesDescription
iduuidPK
order_iduuidFK, not nullorders.id
payment_iduuidFK, not nullpayments.idThe capture being refunded
order_item_iduuidFKorder_items.idSet for a missing or wrong item; null for the whole order
amount_centsintegernot null
reasonrefund_reasonnot null
at_faultfault_partynot nullDecides who absorbs the cost. A restaurant-fault refund is charged back on its ledger.
approved_byvarchar(120)Support agent, or "auto" for rule-based approvals
processor_referencevarchar(100)unique
created_attimestamptznot null, default `now()`

restaurant_ledger_entries

What the restaurant is owed, line by line: food sales, minus commission, minus restaurant-funded promotions and chargebacks for refunds it caused. Delivery fees and tips never touch this ledger.

Columns of the restaurant_ledger_entries table
ColumnTypeConstraintsReferencesDescription
iduuidPK
restaurant_iduuidFK, not nullrestaurants.id
order_iduuidFKorders.id
refund_iduuidFKrefunds.id
restaurant_payout_iduuidFKrestaurant_payouts.idNull until swept into a payout
kindrestaurant_entry_kindnot null
amount_centsintegernot nullPositive when owed to the restaurant, negative when owed by it
currencychar(3)not null
created_attimestamptznot null, default `now()`

Indexes: (restaurant_id, created_at), (restaurant_payout_id)

restaurant_payouts

Periodic transfers to the restaurant. The statement is the list of ledger entries the payout swept.

Columns of the restaurant_payouts table
ColumnTypeConstraintsReferencesDescription
iduuidPK
restaurant_iduuidFK, not nullrestaurants.id
period_startdatenot null
period_enddatenot null
amount_centsbigintnot nullSum of the ledger entries it sweeps
currencychar(3)not null
statuspayout_statusnot null, default 'pending'
processor_referencevarchar(100)unique
paid_attimestamptz

Indexes: (restaurant_id, period_start) unique

courier_earnings

What the courier earned, per delivery and per component. Tips are their own rows and pass through in full.

Columns of the courier_earnings table
ColumnTypeConstraintsReferencesDescription
iduuidPK
courier_iduuidFK, not nullcouriers.id
delivery_iduuidFKdeliveries.idNull for earnings not tied to one delivery, e.g. a guaranteed-minimum top-up
courier_payout_iduuidFKcourier_payouts.idNull until swept into a payout
kindcourier_earning_kindnot null
amount_centsintegernot null
currencychar(3)not null
earned_attimestamptznot null

Indexes: (courier_id, earned_at), (courier_payout_id)

courier_payouts

Transfers to the courier: weekly, or an instant cash-out for a fee.

Columns of the courier_payouts table
ColumnTypeConstraintsReferencesDescription
iduuidPK
courier_iduuidFK, not nullcouriers.id
kindpayout_kindnot null
period_startdatenot null
period_enddatenot null
amount_centsbigintnot null
fee_centsintegernot null, default 0Charged for an instant cash-out
currencychar(3)not null
statuspayout_statusnot null, default 'pending'
processor_referencevarchar(100)unique
paid_attimestamptz

Enums (22)

restaurant_status
onboarding, active, paused, churned
account_status
active, suspended, closed
payment_method_kind
card, wallet, gift_card
promotion_kind
percent_off, amount_off, free_delivery, buy_one_get_one
funding_party
platform, restaurant, shared
fulfillment_kind
delivery, pickup
order_status
placed, accepted, preparing, ready, out_for_delivery, completed, rejected, cancelled
rating_subject
restaurant, courier
offer_status
offered, accepted, declined, expired
delivery_status
assigned, at_restaurant, picked_up, at_customer, delivered, unassigned, failed
delivery_event_kind
status_change, location_ping, delay_reported, customer_unreachable, item_unavailable, id_check_passed, id_check_failed
courier_vehicle
on_foot, bicycle, e_bike, scooter, car
courier_status
applicant, active, suspended, deactivated
shift_status
scheduled, active, completed, missed
payment_kind
authorization, capture, release
payment_status
pending, succeeded, failed
refund_reason
missing_item, wrong_item, quality_issue, late_delivery, never_arrived, cancelled_by_restaurant, other
fault_party
restaurant, courier, platform, customer
restaurant_entry_kind
food_sales, commission, funded_promotion, refund_chargeback, adjustment
courier_earning_kind
base_pay, distance_pay, wait_pay, peak_pay, tip, guarantee_top_up, adjustment
payout_kind
weekly, instant
payout_status
pending, paid, failed

Relationships (49)

  • courier_earnings.courier_id references couriers.id many to one
  • courier_earnings.courier_payout_id references courier_payouts.id many to one
  • courier_earnings.delivery_id references deliveries.id many to one
  • courier_payouts.courier_id references couriers.id many to one
  • courier_shifts.courier_id references couriers.id many to one
  • courier_shifts.delivery_zone_id references delivery_zones.id many to one
  • couriers.home_zone_id references delivery_zones.id many to one
  • customer_addresses.customer_id references customers.id many to one
  • deliveries.courier_id references couriers.id many to one
  • deliveries.courier_shift_id references courier_shifts.id many to one
  • deliveries.order_id references orders.id many to one
  • delivery_events.delivery_id references deliveries.id many to one
  • delivery_offers.courier_id references couriers.id many to one
  • delivery_offers.id references deliveries.delivery_offer_id one to one
  • delivery_offers.order_id references orders.id many to one
  • menu_categories.menu_id references menus.id many to one
  • menu_category_items.menu_category_id references menu_categories.id many to one
  • menu_category_items.menu_item_id references menu_items.id many to one
  • menu_item_modifier_groups.menu_item_id references menu_items.id many to one
  • menu_item_modifier_groups.modifier_group_id references modifier_groups.id many to one
  • menu_items.restaurant_id references restaurants.id many to one
  • menus.restaurant_id references restaurants.id many to one
  • modifier_groups.restaurant_id references restaurants.id many to one
  • modifier_options.modifier_group_id references modifier_groups.id many to one
  • order_item_modifiers.modifier_option_id references modifier_options.id many to one
  • order_item_modifiers.order_item_id references order_items.id many to one
  • order_items.menu_item_id references menu_items.id many to one
  • order_items.order_id references orders.id many to one
  • orders.customer_address_id references customer_addresses.id many to one
  • orders.customer_id references customers.id many to one
  • orders.promotion_id references promotions.id many to one
  • orders.restaurant_id references restaurants.id many to one
  • payment_methods.customer_id references customers.id many to one
  • payments.order_id references orders.id many to one
  • payments.parent_payment_id references payments.id many to one
  • payments.payment_method_id references payment_methods.id many to one
  • promotions.restaurant_id references restaurants.id many to one
  • ratings.courier_id references couriers.id many to one
  • ratings.order_id references orders.id many to one
  • refunds.order_id references orders.id many to one
  • refunds.order_item_id references order_items.id many to one
  • refunds.payment_id references payments.id many to one
  • restaurant_hours.restaurant_id references restaurants.id many to one
  • restaurant_ledger_entries.order_id references orders.id many to one
  • restaurant_ledger_entries.refund_id references refunds.id many to one
  • restaurant_ledger_entries.restaurant_id references restaurants.id many to one
  • restaurant_ledger_entries.restaurant_payout_id references restaurant_payouts.id many to one
  • restaurant_payouts.restaurant_id references restaurants.id many to one
  • restaurants.delivery_zone_id references delivery_zones.id many to one

Food Delivery database schema in DBML

The schema as it is written: DBML, the text format DB Planner draws its diagrams from. Copy it into any DBML tool, or open it in the diagram above.

food-delivery.dbml dbml
// Food Delivery
// Zones (header colors): menus (teal), restaurants and delivery zones (blue),
// customers (green), orders (amber), delivery (coral), couriers (gray),
// money (purple).

// ---------------------------------------------------------------------------
// MENUS: defined once, arranged by menu, customized by modifier groups
// ---------------------------------------------------------------------------

Table menus [headercolor: #4cd0b0] {
  id uuid [pk]
  restaurant_id uuid [not null, ref: > restaurants.id]
  name varchar(100) [not null, note: 'e.g. All day, Breakfast, Late night']
  available_from time [note: 'Null, with available_to, for a menu served whenever the restaurant is open']
  available_to time
  is_active boolean [not null, default: true]
  Note: 'A restaurant can run several menus by time of day. The storefront shows those whose window contains the current local time.'
}

Table menu_categories [headercolor: #4cd0b0] {
  id uuid [pk]
  menu_id uuid [not null, ref: > menus.id]
  name varchar(100) [not null, note: 'e.g. Starters, Burgers, Drinks']
  sort_order smallint [not null, default: 0]
  Note: 'Sections of a menu.'
}

Table menu_category_items [headercolor: #4cd0b0] {
  menu_category_id uuid [not null, ref: > menu_categories.id]
  menu_item_id uuid [not null, ref: > menu_items.id]
  sort_order smallint [not null, default: 0]

  indexes {
    (menu_category_id, menu_item_id) [pk]
  }

  Note: 'Places an item in a category. The same coffee can sit on the breakfast and the all-day menu without being two items with two prices.'
}

Table menu_items [headercolor: #4cd0b0] {
  id uuid [pk]
  restaurant_id uuid [not null, ref: > restaurants.id]
  name varchar(200) [not null]
  description text
  price_cents integer [not null]
  image_key varchar(300) [note: 'Object storage key. Images never live in the database.']
  is_alcohol boolean [not null, default: false, note: 'Requires an ID check at handoff, so only some couriers can take it']
  is_available boolean [not null, default: true, note: 'Switched off when sold out; the item stays on the menu, greyed out']
  created_at timestamptz [not null, default: `now()`]
  Note: 'Dishes and drinks, defined once per restaurant. Changing a price here never touches an order already placed.'
}

Table modifier_groups [headercolor: #4cd0b0] {
  id uuid [pk]
  restaurant_id uuid [not null, ref: > restaurants.id]
  name varchar(100) [not null, note: 'e.g. Choose a size, Add toppings, Pick a side']
  min_selections smallint [not null, default: 0, note: '1 or more makes the group required']
  max_selections smallint [not null, default: 1]
  free_selections smallint [not null, default: 0, note: 'Options included before price deltas apply, e.g. two free toppings']
  Note: 'A reusable set of choices with its selection rules, defined once and attached to many items.'
}

Table modifier_options [headercolor: #4cd0b0] {
  id uuid [pk]
  modifier_group_id uuid [not null, ref: > modifier_groups.id]
  name varchar(100) [not null, note: 'e.g. Large, Extra cheese, No onions']
  price_delta_cents integer [not null, default: 0, note: 'Added to the item price; negative for a cheaper swap']
  is_default boolean [not null, default: false]
  is_available boolean [not null, default: true]
  sort_order smallint [not null, default: 0]
  Note: 'One choice within a modifier group.'
}

Table menu_item_modifier_groups [headercolor: #4cd0b0] {
  menu_item_id uuid [not null, ref: > menu_items.id]
  modifier_group_id uuid [not null, ref: > modifier_groups.id]
  sort_order smallint [not null, default: 0]

  indexes {
    (menu_item_id, modifier_group_id) [pk]
  }

  Note: 'Which modifier groups an item offers, in display order. Edit the "Choose a sauce" group once and every item using it changes.'
}

// ---------------------------------------------------------------------------
// RESTAURANTS AND DELIVERY ZONES
// ---------------------------------------------------------------------------

Table delivery_zones [headercolor: #4c8bf5] {
  id uuid [pk]
  name varchar(120) [not null, note: 'e.g. Downtown, Riverside']
  city varchar(120) [not null]
  timezone varchar(64) [not null, note: 'IANA zone. Opening hours and menu windows are read in it.']
  currency char(3) [not null]
  boundary geography(MultiPolygon,4326) [not null]
  base_delivery_fee_cents integer [not null]
  per_km_fee_cents integer [not null]
  small_order_threshold_cents integer [note: 'Orders with a subtotal under this pay the small order fee']
  small_order_fee_cents integer
  service_fee_bps integer [not null, note: 'Service fee in basis points of the subtotal']
  max_delivery_km numeric(5,2) [not null]
  is_active boolean [not null, default: true]
  Note: 'Areas the platform delivers in, each with its fee schedule. Fees are computed from the zone at checkout and then copied onto the order.'
}

Table restaurants [headercolor: #4c8bf5] {
  id uuid [pk]
  delivery_zone_id uuid [not null, ref: > delivery_zones.id]
  name varchar(200) [not null]
  slug varchar(200) [not null, unique]
  phone varchar(20) [not null]
  address varchar(300) [not null]
  location geography(Point,4326) [not null]
  cuisine varchar(60)
  commission_bps integer [not null, note: 'Platform commission on the food subtotal, e.g. 2500 for 25 percent']
  avg_prep_minutes smallint [not null, default: 20, note: 'Feeds the delivery estimate and when to dispatch a courier']
  accepts_pickup boolean [not null, default: true, note: 'Customer pickup orders never get a delivery']
  status restaurant_status [not null, default: 'onboarding']
  paused_until timestamptz [note: 'Temporarily not taking orders, e.g. the kitchen is overwhelmed']
  payout_account_token varchar(200) [note: 'Bank account held by the payment processor']
  created_at timestamptz [not null, default: `now()`]
  Note: 'Merchants on the platform.'
}

Table restaurant_hours [headercolor: #4c8bf5] {
  restaurant_id uuid [not null, ref: > restaurants.id]
  day_of_week smallint [not null, note: '1 = Monday ... 7 = Sunday']
  opens_at time [not null]
  closes_at time [not null, note: 'Earlier than opens_at means the service runs past midnight']

  indexes {
    (restaurant_id, day_of_week, opens_at) [pk]
  }

  Note: 'Opening hours in the zone timezone. Several rows per day allow a split lunch and dinner service.'
}

// ---------------------------------------------------------------------------
// CUSTOMERS
// ---------------------------------------------------------------------------

Table customers [headercolor: #8bc34a] {
  id uuid [pk]
  email varchar(254) [not null, unique]
  phone varchar(20) [unique, note: 'E.164. Couriers reach the customer through a masked number, never this one directly.']
  first_name varchar(100) [not null]
  last_name varchar(100)
  status account_status [not null, default: 'active']
  created_at timestamptz [not null, default: `now()`]
  Note: 'People who order food.'
}

Table customer_addresses [headercolor: #8bc34a] {
  id uuid [pk]
  customer_id uuid [not null, ref: > customers.id]
  label varchar(60) [note: 'e.g. Home, Office']
  line1 varchar(200) [not null]
  line2 varchar(200) [note: 'Apartment, floor, suite']
  city varchar(120) [not null]
  postal_code varchar(20) [not null]
  country char(2) [not null]
  location geography(Point,4326) [not null, note: 'Geocoded once on save. Zone, distance and fee are computed from it.']
  dropoff_instructions varchar(500) [note: 'e.g. Leave at the door, buzzer 4B']
  is_default boolean [not null, default: false]
  Note: 'Saved delivery addresses. An order copies the address it was delivered to, so editing or deleting this row never rewrites history.'
}

Table payment_methods [headercolor: #8bc34a] {
  id uuid [pk]
  customer_id uuid [not null, ref: > customers.id]
  kind payment_method_kind [not null]
  processor_token varchar(200) [not null, note: 'Card data stays with the payment processor; only its token is stored']
  brand varchar(20)
  last4 char(4)
  expires_on date
  is_default boolean [not null, default: false]
  Note: 'Saved cards and wallets, as processor tokens.'
}

// ---------------------------------------------------------------------------
// ORDERS: the customer and restaurant side, every price snapshotted
// ---------------------------------------------------------------------------

Table promotions [headercolor: #f5b74c] {
  id uuid [pk]
  code varchar(30) [unique, note: 'Null for an automatic promotion that needs no code']
  restaurant_id uuid [ref: > restaurants.id, note: 'Null for a platform-wide promotion']
  kind promotion_kind [not null]
  value integer [not null, note: 'Basis points for percent_off, cents for amount_off']
  min_subtotal_cents integer
  max_discount_cents integer
  funded_by funding_party [not null, note: 'Decides whose ledger the discount is charged to']
  restaurant_share_bps integer [note: 'For a shared promotion, the part of the discount the restaurant pays']
  first_order_only boolean [not null, default: false]
  valid_from timestamptz [not null]
  valid_to timestamptz
  Note: 'Discounts and free-delivery offers. Who funds a promotion matters as much as its size: a restaurant-funded discount reduces the restaurant payout, a platform-funded one does not.'
}

Table orders [headercolor: #f5b74c] {
  id uuid [pk]
  order_number varchar(12) [not null, unique, note: 'Short code read out at the counter, e.g. "4F7K"']
  customer_id uuid [not null, ref: > customers.id]
  restaurant_id uuid [not null, ref: > restaurants.id]
  fulfillment fulfillment_kind [not null]
  status order_status [not null, default: 'placed']
  customer_address_id uuid [ref: > customer_addresses.id, note: 'Where the address was picked from; that row may later change']
  delivery_address varchar(500) [note: 'Snapshot of the address and drop-off instructions at checkout']
  delivery_location geography(Point,4326)
  promotion_id uuid [ref: > promotions.id]
  subtotal_cents integer [not null, note: 'Sum of order_items line totals']
  delivery_fee_cents integer [not null, default: 0]
  service_fee_cents integer [not null, default: 0]
  small_order_fee_cents integer [not null, default: 0]
  discount_cents integer [not null, default: 0]
  tax_cents integer [not null, default: 0]
  tip_cents integer [not null, default: 0, note: 'Passed to the courier in full']
  total_cents integer [not null]
  currency char(3) [not null]
  commission_bps integer [not null, note: 'Restaurant commission rate copied at checkout']
  scheduled_for timestamptz [note: 'Null for as soon as possible']
  estimated_ready_at timestamptz
  placed_at timestamptz [not null, default: `now()`]
  accepted_at timestamptz [note: 'Restaurant confirmed on its tablet']
  ready_at timestamptz [note: 'Food bagged and waiting']
  completed_at timestamptz [note: 'Delivered, or collected by the customer for a pickup order']
  cancelled_at timestamptz

  indexes {
    (restaurant_id, placed_at)
    (customer_id, placed_at)
    (status, placed_at) [note: 'Live operations board: orders stuck in one state too long']
  }

  Note: 'The customer order, as a status machine with a timestamp for each milestone, so prep time and total wait are subtractions. Every fee, rate and the address are copied here at checkout.'
}

Table order_items [headercolor: #f5b74c] {
  id uuid [pk]
  order_id uuid [not null, ref: > orders.id]
  menu_item_id uuid [ref: > menu_items.id, note: 'For reporting only. Null if the item was later deleted; the snapshot still stands.']
  item_name varchar(200) [not null, note: 'Snapshot at checkout']
  base_price_cents integer [not null, note: 'Snapshot of the item price at checkout']
  unit_price_cents integer [not null, note: 'Base price plus the chosen modifier deltas']
  quantity smallint [not null]
  line_total_cents integer [not null]
  special_instructions varchar(300) [note: 'e.g. No ice, sauce on the side']
  Note: 'One line of an order with its name and price SNAPSHOTTED. Editing or deleting a menu item never changes a past order, ticket or receipt.'
}

Table order_item_modifiers [headercolor: #f5b74c] {
  id uuid [pk]
  order_item_id uuid [not null, ref: > order_items.id]
  modifier_option_id uuid [ref: > modifier_options.id, note: 'For reporting only']
  group_name varchar(100) [not null, note: 'Snapshot, e.g. Size']
  option_name varchar(100) [not null, note: 'Snapshot, e.g. Large']
  price_delta_cents integer [not null, note: 'Snapshot; 0 when it fell inside the free selections']
  quantity smallint [not null, default: 1]
  Note: 'The choices made for a line, snapshotted the same way, so the kitchen ticket and the receipt show exactly what was ordered.'
}

Table ratings [headercolor: #f5b74c] {
  id uuid [pk]
  order_id uuid [not null, ref: > orders.id]
  subject rating_subject [not null]
  courier_id uuid [ref: > couriers.id, note: 'Set when the subject is the courier']
  stars smallint [not null, note: '1 to 5']
  comment varchar(1000)
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (order_id, subject) [unique]
  }

  Note: 'The customer rates the food and the delivery separately, so a cold meal from a slow courier is not held against the kitchen.'
}

// ---------------------------------------------------------------------------
// DELIVERY: kept apart from the order, offered before it is assigned
// ---------------------------------------------------------------------------

Table delivery_offers [headercolor: #f07178] {
  id uuid [pk]
  order_id uuid [not null, ref: > orders.id]
  courier_id uuid [not null, ref: > couriers.id]
  offered_pay_cents integer [not null, note: 'Pay shown to the courier before accepting']
  pickup_distance_m integer [not null]
  dropoff_distance_m integer [not null]
  status offer_status [not null, default: 'offered']
  offered_at timestamptz [not null]
  expires_at timestamptz [not null]
  responded_at timestamptz

  indexes {
    (order_id, offered_at)
    (courier_id, offered_at) [note: 'Acceptance rate per courier']
  }

  Note: 'Every offer of an order to a courier and how it ended. Dispatch fires around ready time minus travel time, so the courier arrives as the food does.'
}

Table deliveries [headercolor: #f07178] {
  id uuid [pk]
  order_id uuid [not null, ref: > orders.id]
  courier_id uuid [not null, ref: > couriers.id]
  courier_shift_id uuid [not null, ref: > courier_shifts.id]
  delivery_offer_id uuid [not null, unique, ref: - delivery_offers.id, note: 'The accepted offer that created this assignment']
  status delivery_status [not null, default: 'assigned']
  assigned_at timestamptz [not null]
  at_restaurant_at timestamptz
  picked_up_at timestamptz
  at_customer_at timestamptz
  delivered_at timestamptz
  unassigned_at timestamptz [note: 'Set when the courier drops the job and the order goes back to dispatch']
  distance_m integer [note: 'Restaurant to customer, used for courier pay']
  proof_photo_key varchar(300) [note: 'Photo at the door for a leave-at-door drop-off']

  indexes {
    order_id [name: 'one_live_delivery', note: 'Partial unique index WHERE status NOT IN (unassigned, failed): one live courier per order']
    (courier_id, assigned_at)
  }

  Note: 'A courier assignment, separate from the order. A courier who drops the job ends the row as unassigned and a new delivery is created, so an order can have several deliveries but only one live one.'
}

Table delivery_events [headercolor: #f07178] {
  id uuid [pk]
  delivery_id uuid [not null, ref: > deliveries.id]
  kind delivery_event_kind [not null]
  location geography(Point,4326)
  occurred_at timestamptz [not null]
  detail varchar(300) [note: 'e.g. "Customer not answering, waiting at door"']

  indexes {
    (delivery_id, occurred_at)
  }

  Note: 'Append-only tracking feed behind the live map and the support timeline: status changes, location pings, and problems reported on the way. Partition by occurred_at once volume grows.'
}

// ---------------------------------------------------------------------------
// COURIERS
// ---------------------------------------------------------------------------

Table couriers [headercolor: #90a4ae] {
  id uuid [pk]
  phone varchar(20) [not null, unique]
  email varchar(254) [not null, unique]
  first_name varchar(100) [not null]
  last_name varchar(100) [not null]
  vehicle courier_vehicle [not null, note: 'Limits delivery distance and order size']
  home_zone_id uuid [not null, ref: > delivery_zones.id]
  status courier_status [not null, default: 'applicant']
  background_check_cleared_at timestamptz
  age_verified boolean [not null, default: false, note: 'Required before taking orders with alcohol']
  rating_avg numeric(3,2) [note: 'Cache of courier ratings']
  payout_account_token varchar(200)
  created_at timestamptz [not null, default: `now()`]
  Note: 'Delivery people.'
}

Table courier_shifts [headercolor: #90a4ae] {
  id uuid [pk]
  courier_id uuid [not null, ref: > couriers.id]
  delivery_zone_id uuid [not null, ref: > delivery_zones.id]
  scheduled_start timestamptz [note: 'Null for an unscheduled session; set for a booked block']
  scheduled_end timestamptz
  started_at timestamptz [note: 'When the courier went online']
  ended_at timestamptz
  current_location geography(Point,4326) [note: 'Latest position while online, overwritten every few seconds']
  location_updated_at timestamptz
  status shift_status [not null, default: 'scheduled']

  indexes {
    current_location [type: gist, note: 'Nearest online couriers to a restaurant']
    courier_id [name: 'one_active_shift', note: 'Partial unique index WHERE status = active']
  }

  Note: 'Booked blocks and time online. The active shift carries the latest location, which is what dispatch searches; the trail itself is in delivery_events.'
}

// ---------------------------------------------------------------------------
// MONEY: three sides, three ledgers
// ---------------------------------------------------------------------------

Table payments [headercolor: #b98cf0] {
  id uuid [pk]
  order_id uuid [not null, ref: > orders.id]
  payment_method_id uuid [not null, ref: > payment_methods.id]
  kind payment_kind [not null]
  status payment_status [not null, default: 'pending']
  amount_cents integer [not null]
  currency char(3) [not null]
  parent_payment_id uuid [ref: > payments.id, note: 'A capture or release points at its authorization']
  idempotency_key varchar(100) [not null, unique, note: 'A retry after a timeout can never charge twice']
  processor_reference varchar(100) [unique]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Customer card activity as rows: authorize at checkout, capture on delivery (the tip can still change in between), release on cancellation.'
}

Table refunds [headercolor: #b98cf0] {
  id uuid [pk]
  order_id uuid [not null, ref: > orders.id]
  payment_id uuid [not null, ref: > payments.id, note: 'The capture being refunded']
  order_item_id uuid [ref: > order_items.id, note: 'Set for a missing or wrong item; null for the whole order']
  amount_cents integer [not null]
  reason refund_reason [not null]
  at_fault fault_party [not null, note: 'Decides who absorbs the cost. A restaurant-fault refund is charged back on its ledger.']
  approved_by varchar(120) [note: 'Support agent, or "auto" for rule-based approvals']
  processor_reference varchar(100) [unique]
  created_at timestamptz [not null, default: `now()`]
  Note: 'Money returned to the customer, with the party at fault recorded alongside, because who pays for a refund is the hardest question in delivery support.'
}

Table restaurant_ledger_entries [headercolor: #b98cf0] {
  id uuid [pk]
  restaurant_id uuid [not null, ref: > restaurants.id]
  order_id uuid [ref: > orders.id]
  refund_id uuid [ref: > refunds.id]
  restaurant_payout_id uuid [ref: > restaurant_payouts.id, note: 'Null until swept into a payout']
  kind restaurant_entry_kind [not null]
  amount_cents integer [not null, note: 'Positive when owed to the restaurant, negative when owed by it']
  currency char(3) [not null]
  created_at timestamptz [not null, default: `now()`]

  indexes {
    (restaurant_id, created_at)
    restaurant_payout_id
  }

  Note: 'What the restaurant is owed, line by line: food sales, minus commission, minus restaurant-funded promotions and chargebacks for refunds it caused. Delivery fees and tips never touch this ledger.'
}

Table restaurant_payouts [headercolor: #b98cf0] {
  id uuid [pk]
  restaurant_id uuid [not null, ref: > restaurants.id]
  period_start date [not null]
  period_end date [not null]
  amount_cents bigint [not null, note: 'Sum of the ledger entries it sweeps']
  currency char(3) [not null]
  status payout_status [not null, default: 'pending']
  processor_reference varchar(100) [unique]
  paid_at timestamptz

  indexes {
    (restaurant_id, period_start) [unique]
  }

  Note: 'Periodic transfers to the restaurant. The statement is the list of ledger entries the payout swept.'
}

Table courier_earnings [headercolor: #b98cf0] {
  id uuid [pk]
  courier_id uuid [not null, ref: > couriers.id]
  delivery_id uuid [ref: > deliveries.id, note: 'Null for earnings not tied to one delivery, e.g. a guaranteed-minimum top-up']
  courier_payout_id uuid [ref: > courier_payouts.id, note: 'Null until swept into a payout']
  kind courier_earning_kind [not null]
  amount_cents integer [not null]
  currency char(3) [not null]
  earned_at timestamptz [not null]

  indexes {
    (courier_id, earned_at)
    courier_payout_id
  }

  Note: 'What the courier earned, per delivery and per component. Tips are their own rows and pass through in full.'
}

Table courier_payouts [headercolor: #b98cf0] {
  id uuid [pk]
  courier_id uuid [not null, ref: > couriers.id]
  kind payout_kind [not null]
  period_start date [not null]
  period_end date [not null]
  amount_cents bigint [not null]
  fee_cents integer [not null, default: 0, note: 'Charged for an instant cash-out']
  currency char(3) [not null]
  status payout_status [not null, default: 'pending']
  processor_reference varchar(100) [unique]
  paid_at timestamptz
  Note: 'Transfers to the courier: weekly, or an instant cash-out for a fee.'
}

// ---------------------------------------------------------------------------
// ENUMS
// ---------------------------------------------------------------------------

Enum restaurant_status {
  onboarding
  active
  paused
  churned
}

Enum account_status {
  active
  suspended
  closed
}

Enum payment_method_kind {
  card
  wallet
  gift_card
}

Enum promotion_kind {
  percent_off
  amount_off
  free_delivery
  buy_one_get_one
}

Enum funding_party {
  platform
  restaurant
  shared
}

Enum fulfillment_kind {
  delivery
  pickup
}

Enum order_status {
  placed
  accepted
  preparing
  ready
  out_for_delivery
  completed
  rejected
  cancelled
}

Enum rating_subject {
  restaurant
  courier
}

Enum offer_status {
  offered
  accepted
  declined
  expired
}

Enum delivery_status {
  assigned
  at_restaurant
  picked_up
  at_customer
  delivered
  unassigned
  failed
}

Enum delivery_event_kind {
  status_change
  location_ping
  delay_reported
  customer_unreachable
  item_unavailable
  id_check_passed
  id_check_failed
}

Enum courier_vehicle {
  on_foot
  bicycle
  e_bike
  scooter
  car
}

Enum courier_status {
  applicant
  active
  suspended
  deactivated
}

Enum shift_status {
  scheduled
  active
  completed
  missed
}

Enum payment_kind {
  authorization
  capture
  release
}

Enum payment_status {
  pending
  succeeded
  failed
}

Enum refund_reason {
  missing_item
  wrong_item
  quality_issue
  late_delivery
  never_arrived
  cancelled_by_restaurant
  other
}

Enum fault_party {
  restaurant
  courier
  platform
  customer
}

Enum restaurant_entry_kind {
  food_sales
  commission
  funded_promotion
  refund_chargeback
  adjustment
}

Enum courier_earning_kind {
  base_pay
  distance_pay
  wait_pay
  peak_pay
  tip
  guarantee_top_up
  adjustment
}

Enum payout_kind {
  weekly
  instant
}

Enum payout_status {
  pending
  paid
  failed
}

Food Delivery database schema as SQL

The same schema as CREATE TABLE statements, exported by DB Planner. PostgreSQL is shown first; MySQL and SQL Server are below it.

PostgreSQL
postgresql.sql PostgreSQL
CREATE TYPE "restaurant_status" AS ENUM (
  'onboarding',
  'active',
  'paused',
  'churned'
);

CREATE TYPE "account_status" AS ENUM (
  'active',
  'suspended',
  'closed'
);

CREATE TYPE "payment_method_kind" AS ENUM (
  'card',
  'wallet',
  'gift_card'
);

CREATE TYPE "promotion_kind" AS ENUM (
  'percent_off',
  'amount_off',
  'free_delivery',
  'buy_one_get_one'
);

CREATE TYPE "funding_party" AS ENUM (
  'platform',
  'restaurant',
  'shared'
);

CREATE TYPE "fulfillment_kind" AS ENUM (
  'delivery',
  'pickup'
);

CREATE TYPE "order_status" AS ENUM (
  'placed',
  'accepted',
  'preparing',
  'ready',
  'out_for_delivery',
  'completed',
  'rejected',
  'cancelled'
);

CREATE TYPE "rating_subject" AS ENUM (
  'restaurant',
  'courier'
);

CREATE TYPE "offer_status" AS ENUM (
  'offered',
  'accepted',
  'declined',
  'expired'
);

CREATE TYPE "delivery_status" AS ENUM (
  'assigned',
  'at_restaurant',
  'picked_up',
  'at_customer',
  'delivered',
  'unassigned',
  'failed'
);

CREATE TYPE "delivery_event_kind" AS ENUM (
  'status_change',
  'location_ping',
  'delay_reported',
  'customer_unreachable',
  'item_unavailable',
  'id_check_passed',
  'id_check_failed'
);

CREATE TYPE "courier_vehicle" AS ENUM (
  'on_foot',
  'bicycle',
  'e_bike',
  'scooter',
  'car'
);

CREATE TYPE "courier_status" AS ENUM (
  'applicant',
  'active',
  'suspended',
  'deactivated'
);

CREATE TYPE "shift_status" AS ENUM (
  'scheduled',
  'active',
  'completed',
  'missed'
);

CREATE TYPE "payment_kind" AS ENUM (
  'authorization',
  'capture',
  'release'
);

CREATE TYPE "payment_status" AS ENUM (
  'pending',
  'succeeded',
  'failed'
);

CREATE TYPE "refund_reason" AS ENUM (
  'missing_item',
  'wrong_item',
  'quality_issue',
  'late_delivery',
  'never_arrived',
  'cancelled_by_restaurant',
  'other'
);

CREATE TYPE "fault_party" AS ENUM (
  'restaurant',
  'courier',
  'platform',
  'customer'
);

CREATE TYPE "restaurant_entry_kind" AS ENUM (
  'food_sales',
  'commission',
  'funded_promotion',
  'refund_chargeback',
  'adjustment'
);

CREATE TYPE "courier_earning_kind" AS ENUM (
  'base_pay',
  'distance_pay',
  'wait_pay',
  'peak_pay',
  'tip',
  'guarantee_top_up',
  'adjustment'
);

CREATE TYPE "payout_kind" AS ENUM (
  'weekly',
  'instant'
);

CREATE TYPE "payout_status" AS ENUM (
  'pending',
  'paid',
  'failed'
);

CREATE TABLE "menus" (
  "id" uuid PRIMARY KEY,
  "restaurant_id" uuid NOT NULL,
  "name" varchar(100) NOT NULL,
  "available_from" time,
  "available_to" time,
  "is_active" boolean NOT NULL DEFAULT true
);

CREATE TABLE "menu_categories" (
  "id" uuid PRIMARY KEY,
  "menu_id" uuid NOT NULL,
  "name" varchar(100) NOT NULL,
  "sort_order" smallint NOT NULL DEFAULT 0
);

CREATE TABLE "menu_category_items" (
  "menu_category_id" uuid NOT NULL,
  "menu_item_id" uuid NOT NULL,
  "sort_order" smallint NOT NULL DEFAULT 0,
  PRIMARY KEY ("menu_category_id", "menu_item_id")
);

CREATE TABLE "menu_items" (
  "id" uuid PRIMARY KEY,
  "restaurant_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "description" text,
  "price_cents" integer NOT NULL,
  "image_key" varchar(300),
  "is_alcohol" boolean NOT NULL DEFAULT false,
  "is_available" boolean NOT NULL DEFAULT true,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "modifier_groups" (
  "id" uuid PRIMARY KEY,
  "restaurant_id" uuid NOT NULL,
  "name" varchar(100) NOT NULL,
  "min_selections" smallint NOT NULL DEFAULT 0,
  "max_selections" smallint NOT NULL DEFAULT 1,
  "free_selections" smallint NOT NULL DEFAULT 0
);

CREATE TABLE "modifier_options" (
  "id" uuid PRIMARY KEY,
  "modifier_group_id" uuid NOT NULL,
  "name" varchar(100) NOT NULL,
  "price_delta_cents" integer NOT NULL DEFAULT 0,
  "is_default" boolean NOT NULL DEFAULT false,
  "is_available" boolean NOT NULL DEFAULT true,
  "sort_order" smallint NOT NULL DEFAULT 0
);

CREATE TABLE "menu_item_modifier_groups" (
  "menu_item_id" uuid NOT NULL,
  "modifier_group_id" uuid NOT NULL,
  "sort_order" smallint NOT NULL DEFAULT 0,
  PRIMARY KEY ("menu_item_id", "modifier_group_id")
);

CREATE TABLE "delivery_zones" (
  "id" uuid PRIMARY KEY,
  "name" varchar(120) NOT NULL,
  "city" varchar(120) NOT NULL,
  "timezone" varchar(64) NOT NULL,
  "currency" char(3) NOT NULL,
  "boundary" "geography(MultiPolygon,4326)" NOT NULL,
  "base_delivery_fee_cents" integer NOT NULL,
  "per_km_fee_cents" integer NOT NULL,
  "small_order_threshold_cents" integer,
  "small_order_fee_cents" integer,
  "service_fee_bps" integer NOT NULL,
  "max_delivery_km" numeric(5,2) NOT NULL,
  "is_active" boolean NOT NULL DEFAULT true
);

CREATE TABLE "restaurants" (
  "id" uuid PRIMARY KEY,
  "delivery_zone_id" uuid NOT NULL,
  "name" varchar(200) NOT NULL,
  "slug" varchar(200) UNIQUE NOT NULL,
  "phone" varchar(20) NOT NULL,
  "address" varchar(300) NOT NULL,
  "location" "geography(Point,4326)" NOT NULL,
  "cuisine" varchar(60),
  "commission_bps" integer NOT NULL,
  "avg_prep_minutes" smallint NOT NULL DEFAULT 20,
  "accepts_pickup" boolean NOT NULL DEFAULT true,
  "status" restaurant_status NOT NULL DEFAULT 'onboarding',
  "paused_until" timestamptz,
  "payout_account_token" varchar(200),
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "restaurant_hours" (
  "restaurant_id" uuid NOT NULL,
  "day_of_week" smallint NOT NULL,
  "opens_at" time NOT NULL,
  "closes_at" time NOT NULL,
  PRIMARY KEY ("restaurant_id", "day_of_week", "opens_at")
);

CREATE TABLE "customers" (
  "id" uuid PRIMARY KEY,
  "email" varchar(254) UNIQUE NOT NULL,
  "phone" varchar(20) UNIQUE,
  "first_name" varchar(100) NOT NULL,
  "last_name" varchar(100),
  "status" account_status NOT NULL DEFAULT 'active',
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "customer_addresses" (
  "id" uuid PRIMARY KEY,
  "customer_id" uuid NOT NULL,
  "label" varchar(60),
  "line1" varchar(200) NOT NULL,
  "line2" varchar(200),
  "city" varchar(120) NOT NULL,
  "postal_code" varchar(20) NOT NULL,
  "country" char(2) NOT NULL,
  "location" "geography(Point,4326)" NOT NULL,
  "dropoff_instructions" varchar(500),
  "is_default" boolean NOT NULL DEFAULT false
);

CREATE TABLE "payment_methods" (
  "id" uuid PRIMARY KEY,
  "customer_id" uuid NOT NULL,
  "kind" payment_method_kind NOT NULL,
  "processor_token" varchar(200) NOT NULL,
  "brand" varchar(20),
  "last4" char(4),
  "expires_on" date,
  "is_default" boolean NOT NULL DEFAULT false
);

CREATE TABLE "promotions" (
  "id" uuid PRIMARY KEY,
  "code" varchar(30) UNIQUE,
  "restaurant_id" uuid,
  "kind" promotion_kind NOT NULL,
  "value" integer NOT NULL,
  "min_subtotal_cents" integer,
  "max_discount_cents" integer,
  "funded_by" funding_party NOT NULL,
  "restaurant_share_bps" integer,
  "first_order_only" boolean NOT NULL DEFAULT false,
  "valid_from" timestamptz NOT NULL,
  "valid_to" timestamptz
);

CREATE TABLE "orders" (
  "id" uuid PRIMARY KEY,
  "order_number" varchar(12) UNIQUE NOT NULL,
  "customer_id" uuid NOT NULL,
  "restaurant_id" uuid NOT NULL,
  "fulfillment" fulfillment_kind NOT NULL,
  "status" order_status NOT NULL DEFAULT 'placed',
  "customer_address_id" uuid,
  "delivery_address" varchar(500),
  "delivery_location" "geography(Point,4326)",
  "promotion_id" uuid,
  "subtotal_cents" integer NOT NULL,
  "delivery_fee_cents" integer NOT NULL DEFAULT 0,
  "service_fee_cents" integer NOT NULL DEFAULT 0,
  "small_order_fee_cents" integer NOT NULL DEFAULT 0,
  "discount_cents" integer NOT NULL DEFAULT 0,
  "tax_cents" integer NOT NULL DEFAULT 0,
  "tip_cents" integer NOT NULL DEFAULT 0,
  "total_cents" integer NOT NULL,
  "currency" char(3) NOT NULL,
  "commission_bps" integer NOT NULL,
  "scheduled_for" timestamptz,
  "estimated_ready_at" timestamptz,
  "placed_at" timestamptz NOT NULL DEFAULT (now()),
  "accepted_at" timestamptz,
  "ready_at" timestamptz,
  "completed_at" timestamptz,
  "cancelled_at" timestamptz
);

CREATE TABLE "order_items" (
  "id" uuid PRIMARY KEY,
  "order_id" uuid NOT NULL,
  "menu_item_id" uuid,
  "item_name" varchar(200) NOT NULL,
  "base_price_cents" integer NOT NULL,
  "unit_price_cents" integer NOT NULL,
  "quantity" smallint NOT NULL,
  "line_total_cents" integer NOT NULL,
  "special_instructions" varchar(300)
);

CREATE TABLE "order_item_modifiers" (
  "id" uuid PRIMARY KEY,
  "order_item_id" uuid NOT NULL,
  "modifier_option_id" uuid,
  "group_name" varchar(100) NOT NULL,
  "option_name" varchar(100) NOT NULL,
  "price_delta_cents" integer NOT NULL,
  "quantity" smallint NOT NULL DEFAULT 1
);

CREATE TABLE "ratings" (
  "id" uuid PRIMARY KEY,
  "order_id" uuid NOT NULL,
  "subject" rating_subject NOT NULL,
  "courier_id" uuid,
  "stars" smallint NOT NULL,
  "comment" varchar(1000),
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "delivery_offers" (
  "id" uuid PRIMARY KEY,
  "order_id" uuid NOT NULL,
  "courier_id" uuid NOT NULL,
  "offered_pay_cents" integer NOT NULL,
  "pickup_distance_m" integer NOT NULL,
  "dropoff_distance_m" integer NOT NULL,
  "status" offer_status NOT NULL DEFAULT 'offered',
  "offered_at" timestamptz NOT NULL,
  "expires_at" timestamptz NOT NULL,
  "responded_at" timestamptz
);

CREATE TABLE "deliveries" (
  "id" uuid PRIMARY KEY,
  "order_id" uuid NOT NULL,
  "courier_id" uuid NOT NULL,
  "courier_shift_id" uuid NOT NULL,
  "delivery_offer_id" uuid UNIQUE NOT NULL,
  "status" delivery_status NOT NULL DEFAULT 'assigned',
  "assigned_at" timestamptz NOT NULL,
  "at_restaurant_at" timestamptz,
  "picked_up_at" timestamptz,
  "at_customer_at" timestamptz,
  "delivered_at" timestamptz,
  "unassigned_at" timestamptz,
  "distance_m" integer,
  "proof_photo_key" varchar(300)
);

CREATE TABLE "delivery_events" (
  "id" uuid PRIMARY KEY,
  "delivery_id" uuid NOT NULL,
  "kind" delivery_event_kind NOT NULL,
  "location" "geography(Point,4326)",
  "occurred_at" timestamptz NOT NULL,
  "detail" varchar(300)
);

CREATE TABLE "couriers" (
  "id" uuid PRIMARY KEY,
  "phone" varchar(20) UNIQUE NOT NULL,
  "email" varchar(254) UNIQUE NOT NULL,
  "first_name" varchar(100) NOT NULL,
  "last_name" varchar(100) NOT NULL,
  "vehicle" courier_vehicle NOT NULL,
  "home_zone_id" uuid NOT NULL,
  "status" courier_status NOT NULL DEFAULT 'applicant',
  "background_check_cleared_at" timestamptz,
  "age_verified" boolean NOT NULL DEFAULT false,
  "rating_avg" numeric(3,2),
  "payout_account_token" varchar(200),
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "courier_shifts" (
  "id" uuid PRIMARY KEY,
  "courier_id" uuid NOT NULL,
  "delivery_zone_id" uuid NOT NULL,
  "scheduled_start" timestamptz,
  "scheduled_end" timestamptz,
  "started_at" timestamptz,
  "ended_at" timestamptz,
  "current_location" "geography(Point,4326)",
  "location_updated_at" timestamptz,
  "status" shift_status NOT NULL DEFAULT 'scheduled'
);

CREATE TABLE "payments" (
  "id" uuid PRIMARY KEY,
  "order_id" uuid NOT NULL,
  "payment_method_id" uuid NOT NULL,
  "kind" payment_kind NOT NULL,
  "status" payment_status NOT NULL DEFAULT 'pending',
  "amount_cents" integer NOT NULL,
  "currency" char(3) NOT NULL,
  "parent_payment_id" uuid,
  "idempotency_key" varchar(100) UNIQUE NOT NULL,
  "processor_reference" varchar(100) UNIQUE,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "refunds" (
  "id" uuid PRIMARY KEY,
  "order_id" uuid NOT NULL,
  "payment_id" uuid NOT NULL,
  "order_item_id" uuid,
  "amount_cents" integer NOT NULL,
  "reason" refund_reason NOT NULL,
  "at_fault" fault_party NOT NULL,
  "approved_by" varchar(120),
  "processor_reference" varchar(100) UNIQUE,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "restaurant_ledger_entries" (
  "id" uuid PRIMARY KEY,
  "restaurant_id" uuid NOT NULL,
  "order_id" uuid,
  "refund_id" uuid,
  "restaurant_payout_id" uuid,
  "kind" restaurant_entry_kind NOT NULL,
  "amount_cents" integer NOT NULL,
  "currency" char(3) NOT NULL,
  "created_at" timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE "restaurant_payouts" (
  "id" uuid PRIMARY KEY,
  "restaurant_id" uuid NOT NULL,
  "period_start" date NOT NULL,
  "period_end" date NOT NULL,
  "amount_cents" bigint NOT NULL,
  "currency" char(3) NOT NULL,
  "status" payout_status NOT NULL DEFAULT 'pending',
  "processor_reference" varchar(100) UNIQUE,
  "paid_at" timestamptz
);

CREATE TABLE "courier_earnings" (
  "id" uuid PRIMARY KEY,
  "courier_id" uuid NOT NULL,
  "delivery_id" uuid,
  "courier_payout_id" uuid,
  "kind" courier_earning_kind NOT NULL,
  "amount_cents" integer NOT NULL,
  "currency" char(3) NOT NULL,
  "earned_at" timestamptz NOT NULL
);

CREATE TABLE "courier_payouts" (
  "id" uuid PRIMARY KEY,
  "courier_id" uuid NOT NULL,
  "kind" payout_kind NOT NULL,
  "period_start" date NOT NULL,
  "period_end" date NOT NULL,
  "amount_cents" bigint NOT NULL,
  "fee_cents" integer NOT NULL DEFAULT 0,
  "currency" char(3) NOT NULL,
  "status" payout_status NOT NULL DEFAULT 'pending',
  "processor_reference" varchar(100) UNIQUE,
  "paid_at" timestamptz
);

CREATE INDEX ON "orders" ("restaurant_id", "placed_at");

CREATE INDEX ON "orders" ("customer_id", "placed_at");

CREATE INDEX ON "orders" ("status", "placed_at");

CREATE UNIQUE INDEX ON "ratings" ("order_id", "subject");

CREATE INDEX ON "delivery_offers" ("order_id", "offered_at");

CREATE INDEX ON "delivery_offers" ("courier_id", "offered_at");

CREATE INDEX "one_live_delivery" ON "deliveries" ("order_id");

CREATE INDEX ON "deliveries" ("courier_id", "assigned_at");

CREATE INDEX ON "delivery_events" ("delivery_id", "occurred_at");

CREATE INDEX ON "courier_shifts" USING GIST ("current_location");

CREATE INDEX "one_active_shift" ON "courier_shifts" ("courier_id");

CREATE INDEX ON "restaurant_ledger_entries" ("restaurant_id", "created_at");

CREATE INDEX ON "restaurant_ledger_entries" ("restaurant_payout_id");

CREATE UNIQUE INDEX ON "restaurant_payouts" ("restaurant_id", "period_start");

CREATE INDEX ON "courier_earnings" ("courier_id", "earned_at");

CREATE INDEX ON "courier_earnings" ("courier_payout_id");

COMMENT ON TABLE "menus" IS 'A restaurant can run several menus by time of day. The storefront shows those whose window contains the current local time.';

COMMENT ON COLUMN "menus"."name" IS 'e.g. All day, Breakfast, Late night';

COMMENT ON COLUMN "menus"."available_from" IS 'Null, with available_to, for a menu served whenever the restaurant is open';

COMMENT ON TABLE "menu_categories" IS 'Sections of a menu.';

COMMENT ON COLUMN "menu_categories"."name" IS 'e.g. Starters, Burgers, Drinks';

COMMENT ON TABLE "menu_category_items" IS 'Places an item in a category. The same coffee can sit on the breakfast and the all-day menu without being two items with two prices.';

COMMENT ON TABLE "menu_items" IS 'Dishes and drinks, defined once per restaurant. Changing a price here never touches an order already placed.';

COMMENT ON COLUMN "menu_items"."image_key" IS 'Object storage key. Images never live in the database.';

COMMENT ON COLUMN "menu_items"."is_alcohol" IS 'Requires an ID check at handoff, so only some couriers can take it';

COMMENT ON COLUMN "menu_items"."is_available" IS 'Switched off when sold out; the item stays on the menu, greyed out';

COMMENT ON TABLE "modifier_groups" IS 'A reusable set of choices with its selection rules, defined once and attached to many items.';

COMMENT ON COLUMN "modifier_groups"."name" IS 'e.g. Choose a size, Add toppings, Pick a side';

COMMENT ON COLUMN "modifier_groups"."min_selections" IS '1 or more makes the group required';

COMMENT ON COLUMN "modifier_groups"."free_selections" IS 'Options included before price deltas apply, e.g. two free toppings';

COMMENT ON TABLE "modifier_options" IS 'One choice within a modifier group.';

COMMENT ON COLUMN "modifier_options"."name" IS 'e.g. Large, Extra cheese, No onions';

COMMENT ON COLUMN "modifier_options"."price_delta_cents" IS 'Added to the item price; negative for a cheaper swap';

COMMENT ON TABLE "menu_item_modifier_groups" IS 'Which modifier groups an item offers, in display order. Edit the "Choose a sauce" group once and every item using it changes.';

COMMENT ON TABLE "delivery_zones" IS 'Areas the platform delivers in, each with its fee schedule. Fees are computed from the zone at checkout and then copied onto the order.';

COMMENT ON COLUMN "delivery_zones"."name" IS 'e.g. Downtown, Riverside';

COMMENT ON COLUMN "delivery_zones"."timezone" IS 'IANA zone. Opening hours and menu windows are read in it.';

COMMENT ON COLUMN "delivery_zones"."small_order_threshold_cents" IS 'Orders with a subtotal under this pay the small order fee';

COMMENT ON COLUMN "delivery_zones"."service_fee_bps" IS 'Service fee in basis points of the subtotal';

COMMENT ON TABLE "restaurants" IS 'Merchants on the platform.';

COMMENT ON COLUMN "restaurants"."commission_bps" IS 'Platform commission on the food subtotal, e.g. 2500 for 25 percent';

COMMENT ON COLUMN "restaurants"."avg_prep_minutes" IS 'Feeds the delivery estimate and when to dispatch a courier';

COMMENT ON COLUMN "restaurants"."accepts_pickup" IS 'Customer pickup orders never get a delivery';

COMMENT ON COLUMN "restaurants"."paused_until" IS 'Temporarily not taking orders, e.g. the kitchen is overwhelmed';

COMMENT ON COLUMN "restaurants"."payout_account_token" IS 'Bank account held by the payment processor';

COMMENT ON TABLE "restaurant_hours" IS 'Opening hours in the zone timezone. Several rows per day allow a split lunch and dinner service.';

COMMENT ON COLUMN "restaurant_hours"."day_of_week" IS '1 = Monday ... 7 = Sunday';

COMMENT ON COLUMN "restaurant_hours"."closes_at" IS 'Earlier than opens_at means the service runs past midnight';

COMMENT ON TABLE "customers" IS 'People who order food.';

COMMENT ON COLUMN "customers"."phone" IS 'E.164. Couriers reach the customer through a masked number, never this one directly.';

COMMENT ON TABLE "customer_addresses" IS 'Saved delivery addresses. An order copies the address it was delivered to, so editing or deleting this row never rewrites history.';

COMMENT ON COLUMN "customer_addresses"."label" IS 'e.g. Home, Office';

COMMENT ON COLUMN "customer_addresses"."line2" IS 'Apartment, floor, suite';

COMMENT ON COLUMN "customer_addresses"."location" IS 'Geocoded once on save. Zone, distance and fee are computed from it.';

COMMENT ON COLUMN "customer_addresses"."dropoff_instructions" IS 'e.g. Leave at the door, buzzer 4B';

COMMENT ON TABLE "payment_methods" IS 'Saved cards and wallets, as processor tokens.';

COMMENT ON COLUMN "payment_methods"."processor_token" IS 'Card data stays with the payment processor; only its token is stored';

COMMENT ON TABLE "promotions" IS 'Discounts and free-delivery offers. Who funds a promotion matters as much as its size: a restaurant-funded discount reduces the restaurant payout, a platform-funded one does not.';

COMMENT ON COLUMN "promotions"."code" IS 'Null for an automatic promotion that needs no code';

COMMENT ON COLUMN "promotions"."restaurant_id" IS 'Null for a platform-wide promotion';

COMMENT ON COLUMN "promotions"."value" IS 'Basis points for percent_off, cents for amount_off';

COMMENT ON COLUMN "promotions"."funded_by" IS 'Decides whose ledger the discount is charged to';

COMMENT ON COLUMN "promotions"."restaurant_share_bps" IS 'For a shared promotion, the part of the discount the restaurant pays';

COMMENT ON TABLE "orders" IS 'The customer order, as a status machine with a timestamp for each milestone, so prep time and total wait are subtractions. Every fee, rate and the address are copied here at checkout.';

COMMENT ON COLUMN "orders"."order_number" IS 'Short code read out at the counter, e.g. "4F7K"';

COMMENT ON COLUMN "orders"."customer_address_id" IS 'Where the address was picked from; that row may later change';

COMMENT ON COLUMN "orders"."delivery_address" IS 'Snapshot of the address and drop-off instructions at checkout';

COMMENT ON COLUMN "orders"."subtotal_cents" IS 'Sum of order_items line totals';

COMMENT ON COLUMN "orders"."tip_cents" IS 'Passed to the courier in full';

COMMENT ON COLUMN "orders"."commission_bps" IS 'Restaurant commission rate copied at checkout';

COMMENT ON COLUMN "orders"."scheduled_for" IS 'Null for as soon as possible';

COMMENT ON COLUMN "orders"."accepted_at" IS 'Restaurant confirmed on its tablet';

COMMENT ON COLUMN "orders"."ready_at" IS 'Food bagged and waiting';

COMMENT ON COLUMN "orders"."completed_at" IS 'Delivered, or collected by the customer for a pickup order';

COMMENT ON TABLE "order_items" IS 'One line of an order with its name and price SNAPSHOTTED. Editing or deleting a menu item never changes a past order, ticket or receipt.';

COMMENT ON COLUMN "order_items"."menu_item_id" IS 'For reporting only. Null if the item was later deleted; the snapshot still stands.';

COMMENT ON COLUMN "order_items"."item_name" IS 'Snapshot at checkout';

COMMENT ON COLUMN "order_items"."base_price_cents" IS 'Snapshot of the item price at checkout';

COMMENT ON COLUMN "order_items"."unit_price_cents" IS 'Base price plus the chosen modifier deltas';

COMMENT ON COLUMN "order_items"."special_instructions" IS 'e.g. No ice, sauce on the side';

COMMENT ON TABLE "order_item_modifiers" IS 'The choices made for a line, snapshotted the same way, so the kitchen ticket and the receipt show exactly what was ordered.';

COMMENT ON COLUMN "order_item_modifiers"."modifier_option_id" IS 'For reporting only';

COMMENT ON COLUMN "order_item_modifiers"."group_name" IS 'Snapshot, e.g. Size';

COMMENT ON COLUMN "order_item_modifiers"."option_name" IS 'Snapshot, e.g. Large';

COMMENT ON COLUMN "order_item_modifiers"."price_delta_cents" IS 'Snapshot; 0 when it fell inside the free selections';

COMMENT ON TABLE "ratings" IS 'The customer rates the food and the delivery separately, so a cold meal from a slow courier is not held against the kitchen.';

COMMENT ON COLUMN "ratings"."courier_id" IS 'Set when the subject is the courier';

COMMENT ON COLUMN "ratings"."stars" IS '1 to 5';

COMMENT ON TABLE "delivery_offers" IS 'Every offer of an order to a courier and how it ended. Dispatch fires around ready time minus travel time, so the courier arrives as the food does.';

COMMENT ON COLUMN "delivery_offers"."offered_pay_cents" IS 'Pay shown to the courier before accepting';

COMMENT ON TABLE "deliveries" IS 'A courier assignment, separate from the order. A courier who drops the job ends the row as unassigned and a new delivery is created, so an order can have several deliveries but only one live one.';

COMMENT ON COLUMN "deliveries"."delivery_offer_id" IS 'The accepted offer that created this assignment';

COMMENT ON COLUMN "deliveries"."unassigned_at" IS 'Set when the courier drops the job and the order goes back to dispatch';

COMMENT ON COLUMN "deliveries"."distance_m" IS 'Restaurant to customer, used for courier pay';

COMMENT ON COLUMN "deliveries"."proof_photo_key" IS 'Photo at the door for a leave-at-door drop-off';

COMMENT ON TABLE "delivery_events" IS 'Append-only tracking feed behind the live map and the support timeline: status changes, location pings, and problems reported on the way. Partition by occurred_at once volume grows.';

COMMENT ON COLUMN "delivery_events"."detail" IS 'e.g. "Customer not answering, waiting at door"';

COMMENT ON TABLE "couriers" IS 'Delivery people.';

COMMENT ON COLUMN "couriers"."vehicle" IS 'Limits delivery distance and order size';

COMMENT ON COLUMN "couriers"."age_verified" IS 'Required before taking orders with alcohol';

COMMENT ON COLUMN "couriers"."rating_avg" IS 'Cache of courier ratings';

COMMENT ON TABLE "courier_shifts" IS 'Booked blocks and time online. The active shift carries the latest location, which is what dispatch searches; the trail itself is in delivery_events.';

COMMENT ON COLUMN "courier_shifts"."scheduled_start" IS 'Null for an unscheduled session; set for a booked block';

COMMENT ON COLUMN "courier_shifts"."started_at" IS 'When the courier went online';

COMMENT ON COLUMN "courier_shifts"."current_location" IS 'Latest position while online, overwritten every few seconds';

COMMENT ON TABLE "payments" IS 'Customer card activity as rows: authorize at checkout, capture on delivery (the tip can still change in between), release on cancellation.';

COMMENT ON COLUMN "payments"."parent_payment_id" IS 'A capture or release points at its authorization';

COMMENT ON COLUMN "payments"."idempotency_key" IS 'A retry after a timeout can never charge twice';

COMMENT ON TABLE "refunds" IS 'Money returned to the customer, with the party at fault recorded alongside, because who pays for a refund is the hardest question in delivery support.';

COMMENT ON COLUMN "refunds"."payment_id" IS 'The capture being refunded';

COMMENT ON COLUMN "refunds"."order_item_id" IS 'Set for a missing or wrong item; null for the whole order';

COMMENT ON COLUMN "refunds"."at_fault" IS 'Decides who absorbs the cost. A restaurant-fault refund is charged back on its ledger.';

COMMENT ON COLUMN "refunds"."approved_by" IS 'Support agent, or "auto" for rule-based approvals';

COMMENT ON TABLE "restaurant_ledger_entries" IS 'What the restaurant is owed, line by line: food sales, minus commission, minus restaurant-funded promotions and chargebacks for refunds it caused. Delivery fees and tips never touch this ledger.';

COMMENT ON COLUMN "restaurant_ledger_entries"."restaurant_payout_id" IS 'Null until swept into a payout';

COMMENT ON COLUMN "restaurant_ledger_entries"."amount_cents" IS 'Positive when owed to the restaurant, negative when owed by it';

COMMENT ON TABLE "restaurant_payouts" IS 'Periodic transfers to the restaurant. The statement is the list of ledger entries the payout swept.';

COMMENT ON COLUMN "restaurant_payouts"."amount_cents" IS 'Sum of the ledger entries it sweeps';

COMMENT ON TABLE "courier_earnings" IS 'What the courier earned, per delivery and per component. Tips are their own rows and pass through in full.';

COMMENT ON COLUMN "courier_earnings"."delivery_id" IS 'Null for earnings not tied to one delivery, e.g. a guaranteed-minimum top-up';

COMMENT ON COLUMN "courier_earnings"."courier_payout_id" IS 'Null until swept into a payout';

COMMENT ON TABLE "courier_payouts" IS 'Transfers to the courier: weekly, or an instant cash-out for a fee.';

COMMENT ON COLUMN "courier_payouts"."fee_cents" IS 'Charged for an instant cash-out';

ALTER TABLE "menus" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "menu_categories" ADD FOREIGN KEY ("menu_id") REFERENCES "menus" ("id");

ALTER TABLE "menu_category_items" ADD FOREIGN KEY ("menu_category_id") REFERENCES "menu_categories" ("id");

ALTER TABLE "menu_category_items" ADD FOREIGN KEY ("menu_item_id") REFERENCES "menu_items" ("id");

ALTER TABLE "menu_items" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "modifier_groups" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "modifier_options" ADD FOREIGN KEY ("modifier_group_id") REFERENCES "modifier_groups" ("id");

ALTER TABLE "menu_item_modifier_groups" ADD FOREIGN KEY ("menu_item_id") REFERENCES "menu_items" ("id");

ALTER TABLE "menu_item_modifier_groups" ADD FOREIGN KEY ("modifier_group_id") REFERENCES "modifier_groups" ("id");

ALTER TABLE "restaurants" ADD FOREIGN KEY ("delivery_zone_id") REFERENCES "delivery_zones" ("id");

ALTER TABLE "restaurant_hours" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "customer_addresses" ADD FOREIGN KEY ("customer_id") REFERENCES "customers" ("id");

ALTER TABLE "payment_methods" ADD FOREIGN KEY ("customer_id") REFERENCES "customers" ("id");

ALTER TABLE "promotions" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "orders" ADD FOREIGN KEY ("customer_id") REFERENCES "customers" ("id");

ALTER TABLE "orders" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "orders" ADD FOREIGN KEY ("customer_address_id") REFERENCES "customer_addresses" ("id");

ALTER TABLE "orders" ADD FOREIGN KEY ("promotion_id") REFERENCES "promotions" ("id");

ALTER TABLE "order_items" ADD FOREIGN KEY ("order_id") REFERENCES "orders" ("id");

ALTER TABLE "order_items" ADD FOREIGN KEY ("menu_item_id") REFERENCES "menu_items" ("id");

ALTER TABLE "order_item_modifiers" ADD FOREIGN KEY ("order_item_id") REFERENCES "order_items" ("id");

ALTER TABLE "order_item_modifiers" ADD FOREIGN KEY ("modifier_option_id") REFERENCES "modifier_options" ("id");

ALTER TABLE "ratings" ADD FOREIGN KEY ("order_id") REFERENCES "orders" ("id");

ALTER TABLE "ratings" ADD FOREIGN KEY ("courier_id") REFERENCES "couriers" ("id");

ALTER TABLE "delivery_offers" ADD FOREIGN KEY ("order_id") REFERENCES "orders" ("id");

ALTER TABLE "delivery_offers" ADD FOREIGN KEY ("courier_id") REFERENCES "couriers" ("id");

ALTER TABLE "deliveries" ADD FOREIGN KEY ("order_id") REFERENCES "orders" ("id");

ALTER TABLE "deliveries" ADD FOREIGN KEY ("courier_id") REFERENCES "couriers" ("id");

ALTER TABLE "deliveries" ADD FOREIGN KEY ("courier_shift_id") REFERENCES "courier_shifts" ("id");

ALTER TABLE "deliveries" ADD FOREIGN KEY ("delivery_offer_id") REFERENCES "delivery_offers" ("id");

ALTER TABLE "delivery_events" ADD FOREIGN KEY ("delivery_id") REFERENCES "deliveries" ("id");

ALTER TABLE "couriers" ADD FOREIGN KEY ("home_zone_id") REFERENCES "delivery_zones" ("id");

ALTER TABLE "courier_shifts" ADD FOREIGN KEY ("courier_id") REFERENCES "couriers" ("id");

ALTER TABLE "courier_shifts" ADD FOREIGN KEY ("delivery_zone_id") REFERENCES "delivery_zones" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("order_id") REFERENCES "orders" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("payment_method_id") REFERENCES "payment_methods" ("id");

ALTER TABLE "payments" ADD FOREIGN KEY ("parent_payment_id") REFERENCES "payments" ("id");

ALTER TABLE "refunds" ADD FOREIGN KEY ("order_id") REFERENCES "orders" ("id");

ALTER TABLE "refunds" ADD FOREIGN KEY ("payment_id") REFERENCES "payments" ("id");

ALTER TABLE "refunds" ADD FOREIGN KEY ("order_item_id") REFERENCES "order_items" ("id");

ALTER TABLE "restaurant_ledger_entries" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "restaurant_ledger_entries" ADD FOREIGN KEY ("order_id") REFERENCES "orders" ("id");

ALTER TABLE "restaurant_ledger_entries" ADD FOREIGN KEY ("refund_id") REFERENCES "refunds" ("id");

ALTER TABLE "restaurant_ledger_entries" ADD FOREIGN KEY ("restaurant_payout_id") REFERENCES "restaurant_payouts" ("id");

ALTER TABLE "restaurant_payouts" ADD FOREIGN KEY ("restaurant_id") REFERENCES "restaurants" ("id");

ALTER TABLE "courier_earnings" ADD FOREIGN KEY ("courier_id") REFERENCES "couriers" ("id");

ALTER TABLE "courier_earnings" ADD FOREIGN KEY ("delivery_id") REFERENCES "deliveries" ("id");

ALTER TABLE "courier_earnings" ADD FOREIGN KEY ("courier_payout_id") REFERENCES "courier_payouts" ("id");

ALTER TABLE "courier_payouts" ADD FOREIGN KEY ("courier_id") REFERENCES "couriers" ("id");
MySQL
mysql.sql MySQL
CREATE TABLE `menus` (
  `id` uuid PRIMARY KEY,
  `restaurant_id` uuid NOT NULL,
  `name` varchar(100) NOT NULL COMMENT 'e.g. All day, Breakfast, Late night',
  `available_from` time COMMENT 'Null, with available_to, for a menu served whenever the restaurant is open',
  `available_to` time,
  `is_active` boolean NOT NULL DEFAULT true
);

CREATE TABLE `menu_categories` (
  `id` uuid PRIMARY KEY,
  `menu_id` uuid NOT NULL,
  `name` varchar(100) NOT NULL COMMENT 'e.g. Starters, Burgers, Drinks',
  `sort_order` smallint NOT NULL DEFAULT 0
);

CREATE TABLE `menu_category_items` (
  `menu_category_id` uuid NOT NULL,
  `menu_item_id` uuid NOT NULL,
  `sort_order` smallint NOT NULL DEFAULT 0,
  PRIMARY KEY (`menu_category_id`, `menu_item_id`)
);

CREATE TABLE `menu_items` (
  `id` uuid PRIMARY KEY,
  `restaurant_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL,
  `description` text,
  `price_cents` integer NOT NULL,
  `image_key` varchar(300) COMMENT 'Object storage key. Images never live in the database.',
  `is_alcohol` boolean NOT NULL DEFAULT false COMMENT 'Requires an ID check at handoff, so only some couriers can take it',
  `is_available` boolean NOT NULL DEFAULT true COMMENT 'Switched off when sold out; the item stays on the menu, greyed out',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `modifier_groups` (
  `id` uuid PRIMARY KEY,
  `restaurant_id` uuid NOT NULL,
  `name` varchar(100) NOT NULL COMMENT 'e.g. Choose a size, Add toppings, Pick a side',
  `min_selections` smallint NOT NULL DEFAULT 0 COMMENT '1 or more makes the group required',
  `max_selections` smallint NOT NULL DEFAULT 1,
  `free_selections` smallint NOT NULL DEFAULT 0 COMMENT 'Options included before price deltas apply, e.g. two free toppings'
);

CREATE TABLE `modifier_options` (
  `id` uuid PRIMARY KEY,
  `modifier_group_id` uuid NOT NULL,
  `name` varchar(100) NOT NULL COMMENT 'e.g. Large, Extra cheese, No onions',
  `price_delta_cents` integer NOT NULL DEFAULT 0 COMMENT 'Added to the item price; negative for a cheaper swap',
  `is_default` boolean NOT NULL DEFAULT false,
  `is_available` boolean NOT NULL DEFAULT true,
  `sort_order` smallint NOT NULL DEFAULT 0
);

CREATE TABLE `menu_item_modifier_groups` (
  `menu_item_id` uuid NOT NULL,
  `modifier_group_id` uuid NOT NULL,
  `sort_order` smallint NOT NULL DEFAULT 0,
  PRIMARY KEY (`menu_item_id`, `modifier_group_id`)
);

CREATE TABLE `delivery_zones` (
  `id` uuid PRIMARY KEY,
  `name` varchar(120) NOT NULL COMMENT 'e.g. Downtown, Riverside',
  `city` varchar(120) NOT NULL,
  `timezone` varchar(64) NOT NULL COMMENT 'IANA zone. Opening hours and menu windows are read in it.',
  `currency` char(3) NOT NULL,
  `boundary` geography(MultiPolygon,4326) NOT NULL,
  `base_delivery_fee_cents` integer NOT NULL,
  `per_km_fee_cents` integer NOT NULL,
  `small_order_threshold_cents` integer COMMENT 'Orders with a subtotal under this pay the small order fee',
  `small_order_fee_cents` integer,
  `service_fee_bps` integer NOT NULL COMMENT 'Service fee in basis points of the subtotal',
  `max_delivery_km` numeric(5,2) NOT NULL,
  `is_active` boolean NOT NULL DEFAULT true
);

CREATE TABLE `restaurants` (
  `id` uuid PRIMARY KEY,
  `delivery_zone_id` uuid NOT NULL,
  `name` varchar(200) NOT NULL,
  `slug` varchar(200) UNIQUE NOT NULL,
  `phone` varchar(20) NOT NULL,
  `address` varchar(300) NOT NULL,
  `location` geography(Point,4326) NOT NULL,
  `cuisine` varchar(60),
  `commission_bps` integer NOT NULL COMMENT 'Platform commission on the food subtotal, e.g. 2500 for 25 percent',
  `avg_prep_minutes` smallint NOT NULL DEFAULT 20 COMMENT 'Feeds the delivery estimate and when to dispatch a courier',
  `accepts_pickup` boolean NOT NULL DEFAULT true COMMENT 'Customer pickup orders never get a delivery',
  `status` ENUM ('onboarding', 'active', 'paused', 'churned') NOT NULL DEFAULT 'onboarding',
  `paused_until` timestamptz COMMENT 'Temporarily not taking orders, e.g. the kitchen is overwhelmed',
  `payout_account_token` varchar(200) COMMENT 'Bank account held by the payment processor',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `restaurant_hours` (
  `restaurant_id` uuid NOT NULL,
  `day_of_week` smallint NOT NULL COMMENT '1 = Monday ... 7 = Sunday',
  `opens_at` time NOT NULL,
  `closes_at` time NOT NULL COMMENT 'Earlier than opens_at means the service runs past midnight',
  PRIMARY KEY (`restaurant_id`, `day_of_week`, `opens_at`)
);

CREATE TABLE `customers` (
  `id` uuid PRIMARY KEY,
  `email` varchar(254) UNIQUE NOT NULL,
  `phone` varchar(20) UNIQUE COMMENT 'E.164. Couriers reach the customer through a masked number, never this one directly.',
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100),
  `status` ENUM ('active', 'suspended', 'closed') NOT NULL DEFAULT 'active',
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `customer_addresses` (
  `id` uuid PRIMARY KEY,
  `customer_id` uuid NOT NULL,
  `label` varchar(60) COMMENT 'e.g. Home, Office',
  `line1` varchar(200) NOT NULL,
  `line2` varchar(200) COMMENT 'Apartment, floor, suite',
  `city` varchar(120) NOT NULL,
  `postal_code` varchar(20) NOT NULL,
  `country` char(2) NOT NULL,
  `location` geography(Point,4326) NOT NULL COMMENT 'Geocoded once on save. Zone, distance and fee are computed from it.',
  `dropoff_instructions` varchar(500) COMMENT 'e.g. Leave at the door, buzzer 4B',
  `is_default` boolean NOT NULL DEFAULT false
);

CREATE TABLE `payment_methods` (
  `id` uuid PRIMARY KEY,
  `customer_id` uuid NOT NULL,
  `kind` ENUM ('card', 'wallet', 'gift_card') NOT NULL,
  `processor_token` varchar(200) NOT NULL COMMENT 'Card data stays with the payment processor; only its token is stored',
  `brand` varchar(20),
  `last4` char(4),
  `expires_on` date,
  `is_default` boolean NOT NULL DEFAULT false
);

CREATE TABLE `promotions` (
  `id` uuid PRIMARY KEY,
  `code` varchar(30) UNIQUE COMMENT 'Null for an automatic promotion that needs no code',
  `restaurant_id` uuid COMMENT 'Null for a platform-wide promotion',
  `kind` ENUM ('percent_off', 'amount_off', 'free_delivery', 'buy_one_get_one') NOT NULL,
  `value` integer NOT NULL COMMENT 'Basis points for percent_off, cents for amount_off',
  `min_subtotal_cents` integer,
  `max_discount_cents` integer,
  `funded_by` ENUM ('platform', 'restaurant', 'shared') NOT NULL COMMENT 'Decides whose ledger the discount is charged to',
  `restaurant_share_bps` integer COMMENT 'For a shared promotion, the part of the discount the restaurant pays',
  `first_order_only` boolean NOT NULL DEFAULT false,
  `valid_from` timestamptz NOT NULL,
  `valid_to` timestamptz
);

CREATE TABLE `orders` (
  `id` uuid PRIMARY KEY,
  `order_number` varchar(12) UNIQUE NOT NULL COMMENT 'Short code read out at the counter, e.g. "4F7K"',
  `customer_id` uuid NOT NULL,
  `restaurant_id` uuid NOT NULL,
  `fulfillment` ENUM ('delivery', 'pickup') NOT NULL,
  `status` ENUM ('placed', 'accepted', 'preparing', 'ready', 'out_for_delivery', 'completed', 'rejected', 'cancelled') NOT NULL DEFAULT 'placed',
  `customer_address_id` uuid COMMENT 'Where the address was picked from; that row may later change',
  `delivery_address` varchar(500) COMMENT 'Snapshot of the address and drop-off instructions at checkout',
  `delivery_location` geography(Point,4326),
  `promotion_id` uuid,
  `subtotal_cents` integer NOT NULL COMMENT 'Sum of order_items line totals',
  `delivery_fee_cents` integer NOT NULL DEFAULT 0,
  `service_fee_cents` integer NOT NULL DEFAULT 0,
  `small_order_fee_cents` integer NOT NULL DEFAULT 0,
  `discount_cents` integer NOT NULL DEFAULT 0,
  `tax_cents` integer NOT NULL DEFAULT 0,
  `tip_cents` integer NOT NULL DEFAULT 0 COMMENT 'Passed to the courier in full',
  `total_cents` integer NOT NULL,
  `currency` char(3) NOT NULL,
  `commission_bps` integer NOT NULL COMMENT 'Restaurant commission rate copied at checkout',
  `scheduled_for` timestamptz COMMENT 'Null for as soon as possible',
  `estimated_ready_at` timestamptz,
  `placed_at` timestamptz NOT NULL DEFAULT (now()),
  `accepted_at` timestamptz COMMENT 'Restaurant confirmed on its tablet',
  `ready_at` timestamptz COMMENT 'Food bagged and waiting',
  `completed_at` timestamptz COMMENT 'Delivered, or collected by the customer for a pickup order',
  `cancelled_at` timestamptz
);

CREATE TABLE `order_items` (
  `id` uuid PRIMARY KEY,
  `order_id` uuid NOT NULL,
  `menu_item_id` uuid COMMENT 'For reporting only. Null if the item was later deleted; the snapshot still stands.',
  `item_name` varchar(200) NOT NULL COMMENT 'Snapshot at checkout',
  `base_price_cents` integer NOT NULL COMMENT 'Snapshot of the item price at checkout',
  `unit_price_cents` integer NOT NULL COMMENT 'Base price plus the chosen modifier deltas',
  `quantity` smallint NOT NULL,
  `line_total_cents` integer NOT NULL,
  `special_instructions` varchar(300) COMMENT 'e.g. No ice, sauce on the side'
);

CREATE TABLE `order_item_modifiers` (
  `id` uuid PRIMARY KEY,
  `order_item_id` uuid NOT NULL,
  `modifier_option_id` uuid COMMENT 'For reporting only',
  `group_name` varchar(100) NOT NULL COMMENT 'Snapshot, e.g. Size',
  `option_name` varchar(100) NOT NULL COMMENT 'Snapshot, e.g. Large',
  `price_delta_cents` integer NOT NULL COMMENT 'Snapshot; 0 when it fell inside the free selections',
  `quantity` smallint NOT NULL DEFAULT 1
);

CREATE TABLE `ratings` (
  `id` uuid PRIMARY KEY,
  `order_id` uuid NOT NULL,
  `subject` ENUM ('restaurant', 'courier') NOT NULL,
  `courier_id` uuid COMMENT 'Set when the subject is the courier',
  `stars` smallint NOT NULL COMMENT '1 to 5',
  `comment` varchar(1000),
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `delivery_offers` (
  `id` uuid PRIMARY KEY,
  `order_id` uuid NOT NULL,
  `courier_id` uuid NOT NULL,
  `offered_pay_cents` integer NOT NULL COMMENT 'Pay shown to the courier before accepting',
  `pickup_distance_m` integer NOT NULL,
  `dropoff_distance_m` integer NOT NULL,
  `status` ENUM ('offered', 'accepted', 'declined', 'expired') NOT NULL DEFAULT 'offered',
  `offered_at` timestamptz NOT NULL,
  `expires_at` timestamptz NOT NULL,
  `responded_at` timestamptz
);

CREATE TABLE `deliveries` (
  `id` uuid PRIMARY KEY,
  `order_id` uuid NOT NULL,
  `courier_id` uuid NOT NULL,
  `courier_shift_id` uuid NOT NULL,
  `delivery_offer_id` uuid UNIQUE NOT NULL COMMENT 'The accepted offer that created this assignment',
  `status` ENUM ('assigned', 'at_restaurant', 'picked_up', 'at_customer', 'delivered', 'unassigned', 'failed') NOT NULL DEFAULT 'assigned',
  `assigned_at` timestamptz NOT NULL,
  `at_restaurant_at` timestamptz,
  `picked_up_at` timestamptz,
  `at_customer_at` timestamptz,
  `delivered_at` timestamptz,
  `unassigned_at` timestamptz COMMENT 'Set when the courier drops the job and the order goes back to dispatch',
  `distance_m` integer COMMENT 'Restaurant to customer, used for courier pay',
  `proof_photo_key` varchar(300) COMMENT 'Photo at the door for a leave-at-door drop-off'
);

CREATE TABLE `delivery_events` (
  `id` uuid PRIMARY KEY,
  `delivery_id` uuid NOT NULL,
  `kind` ENUM ('status_change', 'location_ping', 'delay_reported', 'customer_unreachable', 'item_unavailable', 'id_check_passed', 'id_check_failed') NOT NULL,
  `location` geography(Point,4326),
  `occurred_at` timestamptz NOT NULL,
  `detail` varchar(300) COMMENT 'e.g. "Customer not answering, waiting at door"'
);

CREATE TABLE `couriers` (
  `id` uuid PRIMARY KEY,
  `phone` varchar(20) UNIQUE NOT NULL,
  `email` varchar(254) UNIQUE NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `vehicle` ENUM ('on_foot', 'bicycle', 'e_bike', 'scooter', 'car') NOT NULL COMMENT 'Limits delivery distance and order size',
  `home_zone_id` uuid NOT NULL,
  `status` ENUM ('applicant', 'active', 'suspended', 'deactivated') NOT NULL DEFAULT 'applicant',
  `background_check_cleared_at` timestamptz,
  `age_verified` boolean NOT NULL DEFAULT false COMMENT 'Required before taking orders with alcohol',
  `rating_avg` numeric(3,2) COMMENT 'Cache of courier ratings',
  `payout_account_token` varchar(200),
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `courier_shifts` (
  `id` uuid PRIMARY KEY,
  `courier_id` uuid NOT NULL,
  `delivery_zone_id` uuid NOT NULL,
  `scheduled_start` timestamptz COMMENT 'Null for an unscheduled session; set for a booked block',
  `scheduled_end` timestamptz,
  `started_at` timestamptz COMMENT 'When the courier went online',
  `ended_at` timestamptz,
  `current_location` geography(Point,4326) COMMENT 'Latest position while online, overwritten every few seconds',
  `location_updated_at` timestamptz,
  `status` ENUM ('scheduled', 'active', 'completed', 'missed') NOT NULL DEFAULT 'scheduled'
);

CREATE TABLE `payments` (
  `id` uuid PRIMARY KEY,
  `order_id` uuid NOT NULL,
  `payment_method_id` uuid NOT NULL,
  `kind` ENUM ('authorization', 'capture', 'release') NOT NULL,
  `status` ENUM ('pending', 'succeeded', 'failed') NOT NULL DEFAULT 'pending',
  `amount_cents` integer NOT NULL,
  `currency` char(3) NOT NULL,
  `parent_payment_id` uuid COMMENT 'A capture or release points at its authorization',
  `idempotency_key` varchar(100) UNIQUE NOT NULL COMMENT 'A retry after a timeout can never charge twice',
  `processor_reference` varchar(100) UNIQUE,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `refunds` (
  `id` uuid PRIMARY KEY,
  `order_id` uuid NOT NULL,
  `payment_id` uuid NOT NULL COMMENT 'The capture being refunded',
  `order_item_id` uuid COMMENT 'Set for a missing or wrong item; null for the whole order',
  `amount_cents` integer NOT NULL,
  `reason` ENUM ('missing_item', 'wrong_item', 'quality_issue', 'late_delivery', 'never_arrived', 'cancelled_by_restaurant', 'other') NOT NULL,
  `at_fault` ENUM ('restaurant', 'courier', 'platform', 'customer') NOT NULL COMMENT 'Decides who absorbs the cost. A restaurant-fault refund is charged back on its ledger.',
  `approved_by` varchar(120) COMMENT 'Support agent, or "auto" for rule-based approvals',
  `processor_reference` varchar(100) UNIQUE,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `restaurant_ledger_entries` (
  `id` uuid PRIMARY KEY,
  `restaurant_id` uuid NOT NULL,
  `order_id` uuid,
  `refund_id` uuid,
  `restaurant_payout_id` uuid COMMENT 'Null until swept into a payout',
  `kind` ENUM ('food_sales', 'commission', 'funded_promotion', 'refund_chargeback', 'adjustment') NOT NULL,
  `amount_cents` integer NOT NULL COMMENT 'Positive when owed to the restaurant, negative when owed by it',
  `currency` char(3) NOT NULL,
  `created_at` timestamptz NOT NULL DEFAULT (now())
);

CREATE TABLE `restaurant_payouts` (
  `id` uuid PRIMARY KEY,
  `restaurant_id` uuid NOT NULL,
  `period_start` date NOT NULL,
  `period_end` date NOT NULL,
  `amount_cents` bigint NOT NULL COMMENT 'Sum of the ledger entries it sweeps',
  `currency` char(3) NOT NULL,
  `status` ENUM ('pending', 'paid', 'failed') NOT NULL DEFAULT 'pending',
  `processor_reference` varchar(100) UNIQUE,
  `paid_at` timestamptz
);

CREATE TABLE `courier_earnings` (
  `id` uuid PRIMARY KEY,
  `courier_id` uuid NOT NULL,
  `delivery_id` uuid COMMENT 'Null for earnings not tied to one delivery, e.g. a guaranteed-minimum top-up',
  `courier_payout_id` uuid COMMENT 'Null until swept into a payout',
  `kind` ENUM ('base_pay', 'distance_pay', 'wait_pay', 'peak_pay', 'tip', 'guarantee_top_up', 'adjustment') NOT NULL,
  `amount_cents` integer NOT NULL,
  `currency` char(3) NOT NULL,
  `earned_at` timestamptz NOT NULL
);

CREATE TABLE `courier_payouts` (
  `id` uuid PRIMARY KEY,
  `courier_id` uuid NOT NULL,
  `kind` ENUM ('weekly', 'instant') NOT NULL,
  `period_start` date NOT NULL,
  `period_end` date NOT NULL,
  `amount_cents` bigint NOT NULL,
  `fee_cents` integer NOT NULL DEFAULT 0 COMMENT 'Charged for an instant cash-out',
  `currency` char(3) NOT NULL,
  `status` ENUM ('pending', 'paid', 'failed') NOT NULL DEFAULT 'pending',
  `processor_reference` varchar(100) UNIQUE,
  `paid_at` timestamptz
);

CREATE INDEX `orders_index_0` ON `orders` (`restaurant_id`, `placed_at`);

CREATE INDEX `orders_index_1` ON `orders` (`customer_id`, `placed_at`);

CREATE INDEX `orders_index_2` ON `orders` (`status`, `placed_at`);

CREATE UNIQUE INDEX `ratings_index_3` ON `ratings` (`order_id`, `subject`);

CREATE INDEX `delivery_offers_index_4` ON `delivery_offers` (`order_id`, `offered_at`);

CREATE INDEX `delivery_offers_index_5` ON `delivery_offers` (`courier_id`, `offered_at`);

CREATE INDEX `one_live_delivery` ON `deliveries` (`order_id`);

CREATE INDEX `deliveries_index_7` ON `deliveries` (`courier_id`, `assigned_at`);

CREATE INDEX `delivery_events_index_8` ON `delivery_events` (`delivery_id`, `occurred_at`);

CREATE INDEX `courier_shifts_index_9` ON `courier_shifts` (`current_location`) USING GIST;

CREATE INDEX `one_active_shift` ON `courier_shifts` (`courier_id`);

CREATE INDEX `restaurant_ledger_entries_index_11` ON `restaurant_ledger_entries` (`restaurant_id`, `created_at`);

CREATE INDEX `restaurant_ledger_entries_index_12` ON `restaurant_ledger_entries` (`restaurant_payout_id`);

CREATE UNIQUE INDEX `restaurant_payouts_index_13` ON `restaurant_payouts` (`restaurant_id`, `period_start`);

CREATE INDEX `courier_earnings_index_14` ON `courier_earnings` (`courier_id`, `earned_at`);

CREATE INDEX `courier_earnings_index_15` ON `courier_earnings` (`courier_payout_id`);

ALTER TABLE `menus` COMMENT = 'A restaurant can run several menus by time of day. The storefront shows those whose window contains the current local time.';

ALTER TABLE `menu_categories` COMMENT = 'Sections of a menu.';

ALTER TABLE `menu_category_items` COMMENT = 'Places an item in a category. The same coffee can sit on the breakfast and the all-day menu without being two items with two prices.';

ALTER TABLE `menu_items` COMMENT = 'Dishes and drinks, defined once per restaurant. Changing a price here never touches an order already placed.';

ALTER TABLE `modifier_groups` COMMENT = 'A reusable set of choices with its selection rules, defined once and attached to many items.';

ALTER TABLE `modifier_options` COMMENT = 'One choice within a modifier group.';

ALTER TABLE `menu_item_modifier_groups` COMMENT = 'Which modifier groups an item offers, in display order. Edit the "Choose a sauce" group once and every item using it changes.';

ALTER TABLE `delivery_zones` COMMENT = 'Areas the platform delivers in, each with its fee schedule. Fees are computed from the zone at checkout and then copied onto the order.';

ALTER TABLE `restaurants` COMMENT = 'Merchants on the platform.';

ALTER TABLE `restaurant_hours` COMMENT = 'Opening hours in the zone timezone. Several rows per day allow a split lunch and dinner service.';

ALTER TABLE `customers` COMMENT = 'People who order food.';

ALTER TABLE `customer_addresses` COMMENT = 'Saved delivery addresses. An order copies the address it was delivered to, so editing or deleting this row never rewrites history.';

ALTER TABLE `payment_methods` COMMENT = 'Saved cards and wallets, as processor tokens.';

ALTER TABLE `promotions` COMMENT = 'Discounts and free-delivery offers. Who funds a promotion matters as much as its size: a restaurant-funded discount reduces the restaurant payout, a platform-funded one does not.';

ALTER TABLE `orders` COMMENT = 'The customer order, as a status machine with a timestamp for each milestone, so prep time and total wait are subtractions. Every fee, rate and the address are copied here at checkout.';

ALTER TABLE `order_items` COMMENT = 'One line of an order with its name and price SNAPSHOTTED. Editing or deleting a menu item never changes a past order, ticket or receipt.';

ALTER TABLE `order_item_modifiers` COMMENT = 'The choices made for a line, snapshotted the same way, so the kitchen ticket and the receipt show exactly what was ordered.';

ALTER TABLE `ratings` COMMENT = 'The customer rates the food and the delivery separately, so a cold meal from a slow courier is not held against the kitchen.';

ALTER TABLE `delivery_offers` COMMENT = 'Every offer of an order to a courier and how it ended. Dispatch fires around ready time minus travel time, so the courier arrives as the food does.';

ALTER TABLE `deliveries` COMMENT = 'A courier assignment, separate from the order. A courier who drops the job ends the row as unassigned and a new delivery is created, so an order can have several deliveries but only one live one.';

ALTER TABLE `delivery_events` COMMENT = 'Append-only tracking feed behind the live map and the support timeline: status changes, location pings, and problems reported on the way. Partition by occurred_at once volume grows.';

ALTER TABLE `couriers` COMMENT = 'Delivery people.';

ALTER TABLE `courier_shifts` COMMENT = 'Booked blocks and time online. The active shift carries the latest location, which is what dispatch searches; the trail itself is in delivery_events.';

ALTER TABLE `payments` COMMENT = 'Customer card activity as rows: authorize at checkout, capture on delivery (the tip can still change in between), release on cancellation.';

ALTER TABLE `refunds` COMMENT = 'Money returned to the customer, with the party at fault recorded alongside, because who pays for a refund is the hardest question in delivery support.';

ALTER TABLE `restaurant_ledger_entries` COMMENT = 'What the restaurant is owed, line by line: food sales, minus commission, minus restaurant-funded promotions and chargebacks for refunds it caused. Delivery fees and tips never touch this ledger.';

ALTER TABLE `restaurant_payouts` COMMENT = 'Periodic transfers to the restaurant. The statement is the list of ledger entries the payout swept.';

ALTER TABLE `courier_earnings` COMMENT = 'What the courier earned, per delivery and per component. Tips are their own rows and pass through in full.';

ALTER TABLE `courier_payouts` COMMENT = 'Transfers to the courier: weekly, or an instant cash-out for a fee.';

ALTER TABLE `menus` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `menu_categories` ADD FOREIGN KEY (`menu_id`) REFERENCES `menus` (`id`);

ALTER TABLE `menu_category_items` ADD FOREIGN KEY (`menu_category_id`) REFERENCES `menu_categories` (`id`);

ALTER TABLE `menu_category_items` ADD FOREIGN KEY (`menu_item_id`) REFERENCES `menu_items` (`id`);

ALTER TABLE `menu_items` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `modifier_groups` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `modifier_options` ADD FOREIGN KEY (`modifier_group_id`) REFERENCES `modifier_groups` (`id`);

ALTER TABLE `menu_item_modifier_groups` ADD FOREIGN KEY (`menu_item_id`) REFERENCES `menu_items` (`id`);

ALTER TABLE `menu_item_modifier_groups` ADD FOREIGN KEY (`modifier_group_id`) REFERENCES `modifier_groups` (`id`);

ALTER TABLE `restaurants` ADD FOREIGN KEY (`delivery_zone_id`) REFERENCES `delivery_zones` (`id`);

ALTER TABLE `restaurant_hours` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `customer_addresses` ADD FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`);

ALTER TABLE `payment_methods` ADD FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`);

ALTER TABLE `promotions` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `orders` ADD FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`);

ALTER TABLE `orders` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `orders` ADD FOREIGN KEY (`customer_address_id`) REFERENCES `customer_addresses` (`id`);

ALTER TABLE `orders` ADD FOREIGN KEY (`promotion_id`) REFERENCES `promotions` (`id`);

ALTER TABLE `order_items` ADD FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`);

ALTER TABLE `order_items` ADD FOREIGN KEY (`menu_item_id`) REFERENCES `menu_items` (`id`);

ALTER TABLE `order_item_modifiers` ADD FOREIGN KEY (`order_item_id`) REFERENCES `order_items` (`id`);

ALTER TABLE `order_item_modifiers` ADD FOREIGN KEY (`modifier_option_id`) REFERENCES `modifier_options` (`id`);

ALTER TABLE `ratings` ADD FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`);

ALTER TABLE `ratings` ADD FOREIGN KEY (`courier_id`) REFERENCES `couriers` (`id`);

ALTER TABLE `delivery_offers` ADD FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`);

ALTER TABLE `delivery_offers` ADD FOREIGN KEY (`courier_id`) REFERENCES `couriers` (`id`);

ALTER TABLE `deliveries` ADD FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`);

ALTER TABLE `deliveries` ADD FOREIGN KEY (`courier_id`) REFERENCES `couriers` (`id`);

ALTER TABLE `deliveries` ADD FOREIGN KEY (`courier_shift_id`) REFERENCES `courier_shifts` (`id`);

ALTER TABLE `deliveries` ADD FOREIGN KEY (`delivery_offer_id`) REFERENCES `delivery_offers` (`id`);

ALTER TABLE `delivery_events` ADD FOREIGN KEY (`delivery_id`) REFERENCES `deliveries` (`id`);

ALTER TABLE `couriers` ADD FOREIGN KEY (`home_zone_id`) REFERENCES `delivery_zones` (`id`);

ALTER TABLE `courier_shifts` ADD FOREIGN KEY (`courier_id`) REFERENCES `couriers` (`id`);

ALTER TABLE `courier_shifts` ADD FOREIGN KEY (`delivery_zone_id`) REFERENCES `delivery_zones` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`payment_method_id`) REFERENCES `payment_methods` (`id`);

ALTER TABLE `payments` ADD FOREIGN KEY (`parent_payment_id`) REFERENCES `payments` (`id`);

ALTER TABLE `refunds` ADD FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`);

ALTER TABLE `refunds` ADD FOREIGN KEY (`payment_id`) REFERENCES `payments` (`id`);

ALTER TABLE `refunds` ADD FOREIGN KEY (`order_item_id`) REFERENCES `order_items` (`id`);

ALTER TABLE `restaurant_ledger_entries` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `restaurant_ledger_entries` ADD FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`);

ALTER TABLE `restaurant_ledger_entries` ADD FOREIGN KEY (`refund_id`) REFERENCES `refunds` (`id`);

ALTER TABLE `restaurant_ledger_entries` ADD FOREIGN KEY (`restaurant_payout_id`) REFERENCES `restaurant_payouts` (`id`);

ALTER TABLE `restaurant_payouts` ADD FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants` (`id`);

ALTER TABLE `courier_earnings` ADD FOREIGN KEY (`courier_id`) REFERENCES `couriers` (`id`);

ALTER TABLE `courier_earnings` ADD FOREIGN KEY (`delivery_id`) REFERENCES `deliveries` (`id`);

ALTER TABLE `courier_earnings` ADD FOREIGN KEY (`courier_payout_id`) REFERENCES `courier_payouts` (`id`);

ALTER TABLE `courier_payouts` ADD FOREIGN KEY (`courier_id`) REFERENCES `couriers` (`id`);
SQL Server
sql-server.sql SQL Server
CREATE TABLE [menus] (
  [id] uuid PRIMARY KEY,
  [restaurant_id] uuid NOT NULL,
  [name] varchar(100) NOT NULL,
  [available_from] time,
  [available_to] time,
  [is_active] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [menu_categories] (
  [id] uuid PRIMARY KEY,
  [menu_id] uuid NOT NULL,
  [name] varchar(100) NOT NULL,
  [sort_order] smallint NOT NULL DEFAULT (0)
)
GO

CREATE TABLE [menu_category_items] (
  [menu_category_id] uuid NOT NULL,
  [menu_item_id] uuid NOT NULL,
  [sort_order] smallint NOT NULL DEFAULT (0),
  PRIMARY KEY ([menu_category_id], [menu_item_id])
)
GO

CREATE TABLE [menu_items] (
  [id] uuid PRIMARY KEY,
  [restaurant_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [description] text,
  [price_cents] integer NOT NULL,
  [image_key] varchar(300),
  [is_alcohol] boolean NOT NULL DEFAULT (false),
  [is_available] boolean NOT NULL DEFAULT (true),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [modifier_groups] (
  [id] uuid PRIMARY KEY,
  [restaurant_id] uuid NOT NULL,
  [name] varchar(100) NOT NULL,
  [min_selections] smallint NOT NULL DEFAULT (0),
  [max_selections] smallint NOT NULL DEFAULT (1),
  [free_selections] smallint NOT NULL DEFAULT (0)
)
GO

CREATE TABLE [modifier_options] (
  [id] uuid PRIMARY KEY,
  [modifier_group_id] uuid NOT NULL,
  [name] varchar(100) NOT NULL,
  [price_delta_cents] integer NOT NULL DEFAULT (0),
  [is_default] boolean NOT NULL DEFAULT (false),
  [is_available] boolean NOT NULL DEFAULT (true),
  [sort_order] smallint NOT NULL DEFAULT (0)
)
GO

CREATE TABLE [menu_item_modifier_groups] (
  [menu_item_id] uuid NOT NULL,
  [modifier_group_id] uuid NOT NULL,
  [sort_order] smallint NOT NULL DEFAULT (0),
  PRIMARY KEY ([menu_item_id], [modifier_group_id])
)
GO

CREATE TABLE [delivery_zones] (
  [id] uuid PRIMARY KEY,
  [name] varchar(120) NOT NULL,
  [city] varchar(120) NOT NULL,
  [timezone] varchar(64) NOT NULL,
  [currency] char(3) NOT NULL,
  [boundary] geography(MultiPolygon,4326) NOT NULL,
  [base_delivery_fee_cents] integer NOT NULL,
  [per_km_fee_cents] integer NOT NULL,
  [small_order_threshold_cents] integer,
  [small_order_fee_cents] integer,
  [service_fee_bps] integer NOT NULL,
  [max_delivery_km] numeric(5,2) NOT NULL,
  [is_active] boolean NOT NULL DEFAULT (true)
)
GO

CREATE TABLE [restaurants] (
  [id] uuid PRIMARY KEY,
  [delivery_zone_id] uuid NOT NULL,
  [name] varchar(200) NOT NULL,
  [slug] varchar(200) UNIQUE NOT NULL,
  [phone] varchar(20) NOT NULL,
  [address] varchar(300) NOT NULL,
  [location] geography(Point,4326) NOT NULL,
  [cuisine] varchar(60),
  [commission_bps] integer NOT NULL,
  [avg_prep_minutes] smallint NOT NULL DEFAULT (20),
  [accepts_pickup] boolean NOT NULL DEFAULT (true),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('onboarding', 'active', 'paused', 'churned')) DEFAULT 'onboarding',
  [paused_until] timestamptz,
  [payout_account_token] varchar(200),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [restaurant_hours] (
  [restaurant_id] uuid NOT NULL,
  [day_of_week] smallint NOT NULL,
  [opens_at] time NOT NULL,
  [closes_at] time NOT NULL,
  PRIMARY KEY ([restaurant_id], [day_of_week], [opens_at])
)
GO

CREATE TABLE [customers] (
  [id] uuid PRIMARY KEY,
  [email] varchar(254) UNIQUE NOT NULL,
  [phone] varchar(20) UNIQUE,
  [first_name] varchar(100) NOT NULL,
  [last_name] varchar(100),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('active', 'suspended', 'closed')) DEFAULT 'active',
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [customer_addresses] (
  [id] uuid PRIMARY KEY,
  [customer_id] uuid NOT NULL,
  [label] varchar(60),
  [line1] varchar(200) NOT NULL,
  [line2] varchar(200),
  [city] varchar(120) NOT NULL,
  [postal_code] varchar(20) NOT NULL,
  [country] char(2) NOT NULL,
  [location] geography(Point,4326) NOT NULL,
  [dropoff_instructions] varchar(500),
  [is_default] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [payment_methods] (
  [id] uuid PRIMARY KEY,
  [customer_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('card', 'wallet', 'gift_card')),
  [processor_token] varchar(200) NOT NULL,
  [brand] varchar(20),
  [last4] char(4),
  [expires_on] date,
  [is_default] boolean NOT NULL DEFAULT (false)
)
GO

CREATE TABLE [promotions] (
  [id] uuid PRIMARY KEY,
  [code] varchar(30) UNIQUE,
  [restaurant_id] uuid,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('percent_off', 'amount_off', 'free_delivery', 'buy_one_get_one')),
  [value] integer NOT NULL,
  [min_subtotal_cents] integer,
  [max_discount_cents] integer,
  [funded_by] nvarchar(255) NOT NULL CHECK ([funded_by] IN ('platform', 'restaurant', 'shared')),
  [restaurant_share_bps] integer,
  [first_order_only] boolean NOT NULL DEFAULT (false),
  [valid_from] timestamptz NOT NULL,
  [valid_to] timestamptz
)
GO

CREATE TABLE [orders] (
  [id] uuid PRIMARY KEY,
  [order_number] varchar(12) UNIQUE NOT NULL,
  [customer_id] uuid NOT NULL,
  [restaurant_id] uuid NOT NULL,
  [fulfillment] nvarchar(255) NOT NULL CHECK ([fulfillment] IN ('delivery', 'pickup')),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('placed', 'accepted', 'preparing', 'ready', 'out_for_delivery', 'completed', 'rejected', 'cancelled')) DEFAULT 'placed',
  [customer_address_id] uuid,
  [delivery_address] varchar(500),
  [delivery_location] geography(Point,4326),
  [promotion_id] uuid,
  [subtotal_cents] integer NOT NULL,
  [delivery_fee_cents] integer NOT NULL DEFAULT (0),
  [service_fee_cents] integer NOT NULL DEFAULT (0),
  [small_order_fee_cents] integer NOT NULL DEFAULT (0),
  [discount_cents] integer NOT NULL DEFAULT (0),
  [tax_cents] integer NOT NULL DEFAULT (0),
  [tip_cents] integer NOT NULL DEFAULT (0),
  [total_cents] integer NOT NULL,
  [currency] char(3) NOT NULL,
  [commission_bps] integer NOT NULL,
  [scheduled_for] timestamptz,
  [estimated_ready_at] timestamptz,
  [placed_at] timestamptz NOT NULL DEFAULT (now()),
  [accepted_at] timestamptz,
  [ready_at] timestamptz,
  [completed_at] timestamptz,
  [cancelled_at] timestamptz
)
GO

CREATE TABLE [order_items] (
  [id] uuid PRIMARY KEY,
  [order_id] uuid NOT NULL,
  [menu_item_id] uuid,
  [item_name] varchar(200) NOT NULL,
  [base_price_cents] integer NOT NULL,
  [unit_price_cents] integer NOT NULL,
  [quantity] smallint NOT NULL,
  [line_total_cents] integer NOT NULL,
  [special_instructions] varchar(300)
)
GO

CREATE TABLE [order_item_modifiers] (
  [id] uuid PRIMARY KEY,
  [order_item_id] uuid NOT NULL,
  [modifier_option_id] uuid,
  [group_name] varchar(100) NOT NULL,
  [option_name] varchar(100) NOT NULL,
  [price_delta_cents] integer NOT NULL,
  [quantity] smallint NOT NULL DEFAULT (1)
)
GO

CREATE TABLE [ratings] (
  [id] uuid PRIMARY KEY,
  [order_id] uuid NOT NULL,
  [subject] nvarchar(255) NOT NULL CHECK ([subject] IN ('restaurant', 'courier')),
  [courier_id] uuid,
  [stars] smallint NOT NULL,
  [comment] varchar(1000),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [delivery_offers] (
  [id] uuid PRIMARY KEY,
  [order_id] uuid NOT NULL,
  [courier_id] uuid NOT NULL,
  [offered_pay_cents] integer NOT NULL,
  [pickup_distance_m] integer NOT NULL,
  [dropoff_distance_m] integer NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('offered', 'accepted', 'declined', 'expired')) DEFAULT 'offered',
  [offered_at] timestamptz NOT NULL,
  [expires_at] timestamptz NOT NULL,
  [responded_at] timestamptz
)
GO

CREATE TABLE [deliveries] (
  [id] uuid PRIMARY KEY,
  [order_id] uuid NOT NULL,
  [courier_id] uuid NOT NULL,
  [courier_shift_id] uuid NOT NULL,
  [delivery_offer_id] uuid UNIQUE NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('assigned', 'at_restaurant', 'picked_up', 'at_customer', 'delivered', 'unassigned', 'failed')) DEFAULT 'assigned',
  [assigned_at] timestamptz NOT NULL,
  [at_restaurant_at] timestamptz,
  [picked_up_at] timestamptz,
  [at_customer_at] timestamptz,
  [delivered_at] timestamptz,
  [unassigned_at] timestamptz,
  [distance_m] integer,
  [proof_photo_key] varchar(300)
)
GO

CREATE TABLE [delivery_events] (
  [id] uuid PRIMARY KEY,
  [delivery_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('status_change', 'location_ping', 'delay_reported', 'customer_unreachable', 'item_unavailable', 'id_check_passed', 'id_check_failed')),
  [location] geography(Point,4326),
  [occurred_at] timestamptz NOT NULL,
  [detail] varchar(300)
)
GO

CREATE TABLE [couriers] (
  [id] uuid PRIMARY KEY,
  [phone] varchar(20) UNIQUE NOT NULL,
  [email] varchar(254) UNIQUE NOT NULL,
  [first_name] varchar(100) NOT NULL,
  [last_name] varchar(100) NOT NULL,
  [vehicle] nvarchar(255) NOT NULL CHECK ([vehicle] IN ('on_foot', 'bicycle', 'e_bike', 'scooter', 'car')),
  [home_zone_id] uuid NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('applicant', 'active', 'suspended', 'deactivated')) DEFAULT 'applicant',
  [background_check_cleared_at] timestamptz,
  [age_verified] boolean NOT NULL DEFAULT (false),
  [rating_avg] numeric(3,2),
  [payout_account_token] varchar(200),
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [courier_shifts] (
  [id] uuid PRIMARY KEY,
  [courier_id] uuid NOT NULL,
  [delivery_zone_id] uuid NOT NULL,
  [scheduled_start] timestamptz,
  [scheduled_end] timestamptz,
  [started_at] timestamptz,
  [ended_at] timestamptz,
  [current_location] geography(Point,4326),
  [location_updated_at] timestamptz,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('scheduled', 'active', 'completed', 'missed')) DEFAULT 'scheduled'
)
GO

CREATE TABLE [payments] (
  [id] uuid PRIMARY KEY,
  [order_id] uuid NOT NULL,
  [payment_method_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('authorization', 'capture', 'release')),
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'succeeded', 'failed')) DEFAULT 'pending',
  [amount_cents] integer NOT NULL,
  [currency] char(3) NOT NULL,
  [parent_payment_id] uuid,
  [idempotency_key] varchar(100) UNIQUE NOT NULL,
  [processor_reference] varchar(100) UNIQUE,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [refunds] (
  [id] uuid PRIMARY KEY,
  [order_id] uuid NOT NULL,
  [payment_id] uuid NOT NULL,
  [order_item_id] uuid,
  [amount_cents] integer NOT NULL,
  [reason] nvarchar(255) NOT NULL CHECK ([reason] IN ('missing_item', 'wrong_item', 'quality_issue', 'late_delivery', 'never_arrived', 'cancelled_by_restaurant', 'other')),
  [at_fault] nvarchar(255) NOT NULL CHECK ([at_fault] IN ('restaurant', 'courier', 'platform', 'customer')),
  [approved_by] varchar(120),
  [processor_reference] varchar(100) UNIQUE,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [restaurant_ledger_entries] (
  [id] uuid PRIMARY KEY,
  [restaurant_id] uuid NOT NULL,
  [order_id] uuid,
  [refund_id] uuid,
  [restaurant_payout_id] uuid,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('food_sales', 'commission', 'funded_promotion', 'refund_chargeback', 'adjustment')),
  [amount_cents] integer NOT NULL,
  [currency] char(3) NOT NULL,
  [created_at] timestamptz NOT NULL DEFAULT (now())
)
GO

CREATE TABLE [restaurant_payouts] (
  [id] uuid PRIMARY KEY,
  [restaurant_id] uuid NOT NULL,
  [period_start] date NOT NULL,
  [period_end] date NOT NULL,
  [amount_cents] bigint NOT NULL,
  [currency] char(3) NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'paid', 'failed')) DEFAULT 'pending',
  [processor_reference] varchar(100) UNIQUE,
  [paid_at] timestamptz
)
GO

CREATE TABLE [courier_earnings] (
  [id] uuid PRIMARY KEY,
  [courier_id] uuid NOT NULL,
  [delivery_id] uuid,
  [courier_payout_id] uuid,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('base_pay', 'distance_pay', 'wait_pay', 'peak_pay', 'tip', 'guarantee_top_up', 'adjustment')),
  [amount_cents] integer NOT NULL,
  [currency] char(3) NOT NULL,
  [earned_at] timestamptz NOT NULL
)
GO

CREATE TABLE [courier_payouts] (
  [id] uuid PRIMARY KEY,
  [courier_id] uuid NOT NULL,
  [kind] nvarchar(255) NOT NULL CHECK ([kind] IN ('weekly', 'instant')),
  [period_start] date NOT NULL,
  [period_end] date NOT NULL,
  [amount_cents] bigint NOT NULL,
  [fee_cents] integer NOT NULL DEFAULT (0),
  [currency] char(3) NOT NULL,
  [status] nvarchar(255) NOT NULL CHECK ([status] IN ('pending', 'paid', 'failed')) DEFAULT 'pending',
  [processor_reference] varchar(100) UNIQUE,
  [paid_at] timestamptz
)
GO

CREATE INDEX [orders_index_0] ON [orders] ("restaurant_id", "placed_at")
GO

CREATE INDEX [orders_index_1] ON [orders] ("customer_id", "placed_at")
GO

CREATE INDEX [orders_index_2] ON [orders] ("status", "placed_at")
GO

CREATE UNIQUE INDEX [ratings_index_3] ON [ratings] ("order_id", "subject")
GO

CREATE INDEX [delivery_offers_index_4] ON [delivery_offers] ("order_id", "offered_at")
GO

CREATE INDEX [delivery_offers_index_5] ON [delivery_offers] ("courier_id", "offered_at")
GO

CREATE INDEX [one_live_delivery] ON [deliveries] ("order_id")
GO

CREATE INDEX [deliveries_index_7] ON [deliveries] ("courier_id", "assigned_at")
GO

CREATE INDEX [delivery_events_index_8] ON [delivery_events] ("delivery_id", "occurred_at")
GO

CREATE INDEX [courier_shifts_index_9] ON [courier_shifts] ("current_location")
GO

CREATE INDEX [one_active_shift] ON [courier_shifts] ("courier_id")
GO

CREATE INDEX [restaurant_ledger_entries_index_11] ON [restaurant_ledger_entries] ("restaurant_id", "created_at")
GO

CREATE INDEX [restaurant_ledger_entries_index_12] ON [restaurant_ledger_entries] ("restaurant_payout_id")
GO

CREATE UNIQUE INDEX [restaurant_payouts_index_13] ON [restaurant_payouts] ("restaurant_id", "period_start")
GO

CREATE INDEX [courier_earnings_index_14] ON [courier_earnings] ("courier_id", "earned_at")
GO

CREATE INDEX [courier_earnings_index_15] ON [courier_earnings] ("courier_payout_id")
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A restaurant can run several menus by time of day. The storefront shows those whose window contains the current local time.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menus';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. All day, Breakfast, Late night',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menus',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null, with available_to, for a menu served whenever the restaurant is open',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menus',
@level2type = N'Column', @level2name = 'available_from';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Sections of a menu.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_categories';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Starters, Burgers, Drinks',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_categories',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Places an item in a category. The same coffee can sit on the breakfast and the all-day menu without being two items with two prices.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_category_items';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Dishes and drinks, defined once per restaurant. Changing a price here never touches an order already placed.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_items';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Object storage key. Images never live in the database.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_items',
@level2type = N'Column', @level2name = 'image_key';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Requires an ID check at handoff, so only some couriers can take it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_items',
@level2type = N'Column', @level2name = 'is_alcohol';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Switched off when sold out; the item stays on the menu, greyed out',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_items',
@level2type = N'Column', @level2name = 'is_available';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A reusable set of choices with its selection rules, defined once and attached to many items.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'modifier_groups';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Choose a size, Add toppings, Pick a side',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'modifier_groups',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = '1 or more makes the group required',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'modifier_groups',
@level2type = N'Column', @level2name = 'min_selections';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Options included before price deltas apply, e.g. two free toppings',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'modifier_groups',
@level2type = N'Column', @level2name = 'free_selections';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One choice within a modifier group.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'modifier_options';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Large, Extra cheese, No onions',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'modifier_options',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Added to the item price; negative for a cheaper swap',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'modifier_options',
@level2type = N'Column', @level2name = 'price_delta_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Which modifier groups an item offers, in display order. Edit the "Choose a sauce" group once and every item using it changes.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'menu_item_modifier_groups';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Areas the platform delivers in, each with its fee schedule. Fees are computed from the zone at checkout and then copied onto the order.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_zones';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Downtown, Riverside',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_zones',
@level2type = N'Column', @level2name = 'name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'IANA zone. Opening hours and menu windows are read in it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_zones',
@level2type = N'Column', @level2name = 'timezone';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Orders with a subtotal under this pay the small order fee',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_zones',
@level2type = N'Column', @level2name = 'small_order_threshold_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Service fee in basis points of the subtotal',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_zones',
@level2type = N'Column', @level2name = 'service_fee_bps';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Merchants on the platform.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurants';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Platform commission on the food subtotal, e.g. 2500 for 25 percent',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurants',
@level2type = N'Column', @level2name = 'commission_bps';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Feeds the delivery estimate and when to dispatch a courier',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurants',
@level2type = N'Column', @level2name = 'avg_prep_minutes';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Customer pickup orders never get a delivery',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurants',
@level2type = N'Column', @level2name = 'accepts_pickup';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Temporarily not taking orders, e.g. the kitchen is overwhelmed',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurants',
@level2type = N'Column', @level2name = 'paused_until';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Bank account held by the payment processor',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurants',
@level2type = N'Column', @level2name = 'payout_account_token';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Opening hours in the zone timezone. Several rows per day allow a split lunch and dinner service.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_hours';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = '1 = Monday ... 7 = Sunday',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_hours',
@level2type = N'Column', @level2name = 'day_of_week';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Earlier than opens_at means the service runs past midnight',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_hours',
@level2type = N'Column', @level2name = 'closes_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'People who order food.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'customers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'E.164. Couriers reach the customer through a masked number, never this one directly.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'customers',
@level2type = N'Column', @level2name = 'phone';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Saved delivery addresses. An order copies the address it was delivered to, so editing or deleting this row never rewrites history.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'customer_addresses';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Home, Office',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'customer_addresses',
@level2type = N'Column', @level2name = 'label';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Apartment, floor, suite',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'customer_addresses',
@level2type = N'Column', @level2name = 'line2';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Geocoded once on save. Zone, distance and fee are computed from it.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'customer_addresses',
@level2type = N'Column', @level2name = 'location';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. Leave at the door, buzzer 4B',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'customer_addresses',
@level2type = N'Column', @level2name = 'dropoff_instructions';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Saved cards and wallets, as processor tokens.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payment_methods';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Card data stays with the payment processor; only its token is stored',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payment_methods',
@level2type = N'Column', @level2name = 'processor_token';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Discounts and free-delivery offers. Who funds a promotion matters as much as its size: a restaurant-funded discount reduces the restaurant payout, a platform-funded one does not.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promotions';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for an automatic promotion that needs no code',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promotions',
@level2type = N'Column', @level2name = 'code';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for a platform-wide promotion',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promotions',
@level2type = N'Column', @level2name = 'restaurant_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Basis points for percent_off, cents for amount_off',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promotions',
@level2type = N'Column', @level2name = 'value';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Decides whose ledger the discount is charged to',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promotions',
@level2type = N'Column', @level2name = 'funded_by';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For a shared promotion, the part of the discount the restaurant pays',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'promotions',
@level2type = N'Column', @level2name = 'restaurant_share_bps';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The customer order, as a status machine with a timestamp for each milestone, so prep time and total wait are subtractions. Every fee, rate and the address are copied here at checkout.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Short code read out at the counter, e.g. "4F7K"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'order_number';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Where the address was picked from; that row may later change',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'customer_address_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot of the address and drop-off instructions at checkout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'delivery_address';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Sum of order_items line totals',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'subtotal_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Passed to the courier in full',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'tip_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Restaurant commission rate copied at checkout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'commission_bps';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for as soon as possible',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'scheduled_for';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Restaurant confirmed on its tablet',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'accepted_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Food bagged and waiting',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'ready_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Delivered, or collected by the customer for a pickup order',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'orders',
@level2type = N'Column', @level2name = 'completed_at';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'One line of an order with its name and price SNAPSHOTTED. Editing or deleting a menu item never changes a past order, ticket or receipt.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_items';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For reporting only. Null if the item was later deleted; the snapshot still stands.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_items',
@level2type = N'Column', @level2name = 'menu_item_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot at checkout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_items',
@level2type = N'Column', @level2name = 'item_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot of the item price at checkout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_items',
@level2type = N'Column', @level2name = 'base_price_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Base price plus the chosen modifier deltas',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_items',
@level2type = N'Column', @level2name = 'unit_price_cents';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. No ice, sauce on the side',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_items',
@level2type = N'Column', @level2name = 'special_instructions';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The choices made for a line, snapshotted the same way, so the kitchen ticket and the receipt show exactly what was ordered.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_item_modifiers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'For reporting only',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_item_modifiers',
@level2type = N'Column', @level2name = 'modifier_option_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot, e.g. Size',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_item_modifiers',
@level2type = N'Column', @level2name = 'group_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot, e.g. Large',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_item_modifiers',
@level2type = N'Column', @level2name = 'option_name';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Snapshot; 0 when it fell inside the free selections',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'order_item_modifiers',
@level2type = N'Column', @level2name = 'price_delta_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'The customer rates the food and the delivery separately, so a cold meal from a slow courier is not held against the kitchen.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ratings';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when the subject is the courier',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ratings',
@level2type = N'Column', @level2name = 'courier_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = '1 to 5',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'ratings',
@level2type = N'Column', @level2name = 'stars';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Every offer of an order to a courier and how it ended. Dispatch fires around ready time minus travel time, so the courier arrives as the food does.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_offers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Pay shown to the courier before accepting',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_offers',
@level2type = N'Column', @level2name = 'offered_pay_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'A courier assignment, separate from the order. A courier who drops the job ends the row as unassigned and a new delivery is created, so an order can have several deliveries but only one live one.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'deliveries';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The accepted offer that created this assignment',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'deliveries',
@level2type = N'Column', @level2name = 'delivery_offer_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set when the courier drops the job and the order goes back to dispatch',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'deliveries',
@level2type = N'Column', @level2name = 'unassigned_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Restaurant to customer, used for courier pay',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'deliveries',
@level2type = N'Column', @level2name = 'distance_m';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Photo at the door for a leave-at-door drop-off',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'deliveries',
@level2type = N'Column', @level2name = 'proof_photo_key';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Append-only tracking feed behind the live map and the support timeline: status changes, location pings, and problems reported on the way. Partition by occurred_at once volume grows.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_events';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'e.g. "Customer not answering, waiting at door"',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'delivery_events',
@level2type = N'Column', @level2name = 'detail';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Delivery people.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'couriers';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Limits delivery distance and order size',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'couriers',
@level2type = N'Column', @level2name = 'vehicle';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Required before taking orders with alcohol',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'couriers',
@level2type = N'Column', @level2name = 'age_verified';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Cache of courier ratings',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'couriers',
@level2type = N'Column', @level2name = 'rating_avg';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Booked blocks and time online. The active shift carries the latest location, which is what dispatch searches; the trail itself is in delivery_events.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_shifts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for an unscheduled session; set for a booked block',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_shifts',
@level2type = N'Column', @level2name = 'scheduled_start';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'When the courier went online',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_shifts',
@level2type = N'Column', @level2name = 'started_at';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Latest position while online, overwritten every few seconds',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_shifts',
@level2type = N'Column', @level2name = 'current_location';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Customer card activity as rows: authorize at checkout, capture on delivery (the tip can still change in between), release on cancellation.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A capture or release points at its authorization',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments',
@level2type = N'Column', @level2name = 'parent_payment_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'A retry after a timeout can never charge twice',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'payments',
@level2type = N'Column', @level2name = 'idempotency_key';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Money returned to the customer, with the party at fault recorded alongside, because who pays for a refund is the hardest question in delivery support.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'refunds';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'The capture being refunded',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'refunds',
@level2type = N'Column', @level2name = 'payment_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Set for a missing or wrong item; null for the whole order',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'refunds',
@level2type = N'Column', @level2name = 'order_item_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Decides who absorbs the cost. A restaurant-fault refund is charged back on its ledger.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'refunds',
@level2type = N'Column', @level2name = 'at_fault';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Support agent, or "auto" for rule-based approvals',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'refunds',
@level2type = N'Column', @level2name = 'approved_by';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What the restaurant is owed, line by line: food sales, minus commission, minus restaurant-funded promotions and chargebacks for refunds it caused. Delivery fees and tips never touch this ledger.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_ledger_entries';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null until swept into a payout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_ledger_entries',
@level2type = N'Column', @level2name = 'restaurant_payout_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Positive when owed to the restaurant, negative when owed by it',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_ledger_entries',
@level2type = N'Column', @level2name = 'amount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Periodic transfers to the restaurant. The statement is the list of ledger entries the payout swept.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_payouts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Sum of the ledger entries it sweeps',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'restaurant_payouts',
@level2type = N'Column', @level2name = 'amount_cents';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'What the courier earned, per delivery and per component. Tips are their own rows and pass through in full.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_earnings';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null for earnings not tied to one delivery, e.g. a guaranteed-minimum top-up',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_earnings',
@level2type = N'Column', @level2name = 'delivery_id';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Null until swept into a payout',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_earnings',
@level2type = N'Column', @level2name = 'courier_payout_id';
GO

EXEC sp_addextendedproperty
@name = N'Table_Description',
@value = 'Transfers to the courier: weekly, or an instant cash-out for a fee.',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_payouts';
GO

EXEC sp_addextendedproperty
@name = N'Column_Description',
@value = 'Charged for an instant cash-out',
@level0type = N'Schema', @level0name = 'dbo',
@level1type = N'Table',  @level1name = 'courier_payouts',
@level2type = N'Column', @level2name = 'fee_cents';
GO

ALTER TABLE [menus] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [menu_categories] ADD FOREIGN KEY ([menu_id]) REFERENCES [menus] ([id])
GO

ALTER TABLE [menu_category_items] ADD FOREIGN KEY ([menu_category_id]) REFERENCES [menu_categories] ([id])
GO

ALTER TABLE [menu_category_items] ADD FOREIGN KEY ([menu_item_id]) REFERENCES [menu_items] ([id])
GO

ALTER TABLE [menu_items] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [modifier_groups] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [modifier_options] ADD FOREIGN KEY ([modifier_group_id]) REFERENCES [modifier_groups] ([id])
GO

ALTER TABLE [menu_item_modifier_groups] ADD FOREIGN KEY ([menu_item_id]) REFERENCES [menu_items] ([id])
GO

ALTER TABLE [menu_item_modifier_groups] ADD FOREIGN KEY ([modifier_group_id]) REFERENCES [modifier_groups] ([id])
GO

ALTER TABLE [restaurants] ADD FOREIGN KEY ([delivery_zone_id]) REFERENCES [delivery_zones] ([id])
GO

ALTER TABLE [restaurant_hours] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [customer_addresses] ADD FOREIGN KEY ([customer_id]) REFERENCES [customers] ([id])
GO

ALTER TABLE [payment_methods] ADD FOREIGN KEY ([customer_id]) REFERENCES [customers] ([id])
GO

ALTER TABLE [promotions] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [orders] ADD FOREIGN KEY ([customer_id]) REFERENCES [customers] ([id])
GO

ALTER TABLE [orders] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [orders] ADD FOREIGN KEY ([customer_address_id]) REFERENCES [customer_addresses] ([id])
GO

ALTER TABLE [orders] ADD FOREIGN KEY ([promotion_id]) REFERENCES [promotions] ([id])
GO

ALTER TABLE [order_items] ADD FOREIGN KEY ([order_id]) REFERENCES [orders] ([id])
GO

ALTER TABLE [order_items] ADD FOREIGN KEY ([menu_item_id]) REFERENCES [menu_items] ([id])
GO

ALTER TABLE [order_item_modifiers] ADD FOREIGN KEY ([order_item_id]) REFERENCES [order_items] ([id])
GO

ALTER TABLE [order_item_modifiers] ADD FOREIGN KEY ([modifier_option_id]) REFERENCES [modifier_options] ([id])
GO

ALTER TABLE [ratings] ADD FOREIGN KEY ([order_id]) REFERENCES [orders] ([id])
GO

ALTER TABLE [ratings] ADD FOREIGN KEY ([courier_id]) REFERENCES [couriers] ([id])
GO

ALTER TABLE [delivery_offers] ADD FOREIGN KEY ([order_id]) REFERENCES [orders] ([id])
GO

ALTER TABLE [delivery_offers] ADD FOREIGN KEY ([courier_id]) REFERENCES [couriers] ([id])
GO

ALTER TABLE [deliveries] ADD FOREIGN KEY ([order_id]) REFERENCES [orders] ([id])
GO

ALTER TABLE [deliveries] ADD FOREIGN KEY ([courier_id]) REFERENCES [couriers] ([id])
GO

ALTER TABLE [deliveries] ADD FOREIGN KEY ([courier_shift_id]) REFERENCES [courier_shifts] ([id])
GO

ALTER TABLE [deliveries] ADD FOREIGN KEY ([delivery_offer_id]) REFERENCES [delivery_offers] ([id])
GO

ALTER TABLE [delivery_events] ADD FOREIGN KEY ([delivery_id]) REFERENCES [deliveries] ([id])
GO

ALTER TABLE [couriers] ADD FOREIGN KEY ([home_zone_id]) REFERENCES [delivery_zones] ([id])
GO

ALTER TABLE [courier_shifts] ADD FOREIGN KEY ([courier_id]) REFERENCES [couriers] ([id])
GO

ALTER TABLE [courier_shifts] ADD FOREIGN KEY ([delivery_zone_id]) REFERENCES [delivery_zones] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([order_id]) REFERENCES [orders] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([payment_method_id]) REFERENCES [payment_methods] ([id])
GO

ALTER TABLE [payments] ADD FOREIGN KEY ([parent_payment_id]) REFERENCES [payments] ([id])
GO

ALTER TABLE [refunds] ADD FOREIGN KEY ([order_id]) REFERENCES [orders] ([id])
GO

ALTER TABLE [refunds] ADD FOREIGN KEY ([payment_id]) REFERENCES [payments] ([id])
GO

ALTER TABLE [refunds] ADD FOREIGN KEY ([order_item_id]) REFERENCES [order_items] ([id])
GO

ALTER TABLE [restaurant_ledger_entries] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [restaurant_ledger_entries] ADD FOREIGN KEY ([order_id]) REFERENCES [orders] ([id])
GO

ALTER TABLE [restaurant_ledger_entries] ADD FOREIGN KEY ([refund_id]) REFERENCES [refunds] ([id])
GO

ALTER TABLE [restaurant_ledger_entries] ADD FOREIGN KEY ([restaurant_payout_id]) REFERENCES [restaurant_payouts] ([id])
GO

ALTER TABLE [restaurant_payouts] ADD FOREIGN KEY ([restaurant_id]) REFERENCES [restaurants] ([id])
GO

ALTER TABLE [courier_earnings] ADD FOREIGN KEY ([courier_id]) REFERENCES [couriers] ([id])
GO

ALTER TABLE [courier_earnings] ADD FOREIGN KEY ([delivery_id]) REFERENCES [deliveries] ([id])
GO

ALTER TABLE [courier_earnings] ADD FOREIGN KEY ([courier_payout_id]) REFERENCES [courier_payouts] ([id])
GO

ALTER TABLE [courier_payouts] ADD FOREIGN KEY ([courier_id]) REFERENCES [couriers] ([id])
GO

How to use this template

  1. Open the ER diagram to see the tables and how they relate.
  2. Copy it into your workspace. You get your own editable copy, in DBML.
  3. Export it as PostgreSQL, MySQL, or SQL Server DDL, or as Prisma, Drizzle, SQLAlchemy, TypeScript, Zod or C# models.

The copy opens in DB Planner’s ER diagram tool, with the schema as text in the DBML editor beside it. Have a database already? Turn its SQL into an ER diagram instead.

Frequently asked questions

Which table is at the centre of the Food Delivery database schema?
restaurants. It is referenced by 8 other tables: menu_items, menus, modifier_groups, orders, promotions and 3 more.
How is menu_items related to restaurants?
menu_items.restaurant_id references restaurants.id, a many to one relationship. All 49 relationships in the schema are listed on this page.
Which table in the Food Delivery database schema has the most columns?
orders, with 27 columns, followed by restaurants (15) and deliveries (14). The schema has 269 columns across 29 tables.
Can I export it to PostgreSQL or MySQL?
Yes. Every DB Planner template exports as DBML, as PostgreSQL, MySQL, or SQL Server DDL, and as C# models.
Is this template free?
Yes. You can open it in the browser without an account, and copy it into your own workspace with a free DB Planner account.
Can I change it after copying it?
Yes. A copy is yours: you can rename tables, add columns, and export it. Changes the author makes later do not affect your copy.