# ספר מערכת הנתונים

> תיעוד מקור. מקור: docs/data-system/handbook.md · 6a466bf.

תכנון, מקור אמת בקוד וראיות ביצוע; אינו אישור מוכנות להפעלה מסחרית.

תאריך: 2026-11-08. מקור: lib/systems/data.json.

מצבים: deployed = רכיב פרוס עם ראיה מוגדרת; foundation = בסיס בקוד; planned = תכנון; blocked = תלות פתוחה. אף אחד מהם אינו אישור פרודקשן מלא.

## עקרונות ובעלות

### D01 · מקור אמת ובעלות

מצב: foundation. אחריות: Data.

נתון עסקי שייך ל־tenant, עם חריגים מפורשים לקטלוג ציבורי ולסודות.

- קטלוג רכבים ומידע תחנות ציבורי אינם כוללים פרטי לקוחות.
- User הוא זהות גלובלית; membership מחבר אותו ל־tenant אישי או עסקי.
- הדגמה מקומית אינה מועתקת אוטומטית למסד; יבוא עתידי דורש מיפוי ובדיקות.

מקורות: lib/platform/types.ts.

### D02 · יחידות וזמן

מצב: foundation. אחריות: Data.

כסף באגורות, אנרגיה ב־Wh, זמנים ב־timestamptz.

- ILS הוא המטבע הממומש כיום; אין לטעון לתמיכת ריבוי מטבעות.
- תעריף דורש דיוק עשרוני וחוק עיגול מאושר. אין חשבון כספי עם float בדפדפן.
- אירועים נשמרים בזמן מוחלט; חלונות דוחות עסקיים לפי Asia/Jerusalem כולל שעון קיץ.
- bigint ב־JSON מוגבל ל־safe integer בחוזה או מועבר כמחרוזת עשרונית בגרסה עתידית.

מקורות: supabase/migrations/20261107211048_platform_foundation.sql.

## מילון הנתונים

### D15 · מילון שמופק מהקוד

מצב: foundation. אחריות: Data.

רשימת הטבלאות, השדות, האילוצים והקשרים מופקת מקובצי המיגרציות.

- הספרייה מציגה סכימת מקור, לא מידע של לקוחות או סודות.
- שינוי מיגרציה מחייב הפקה מחדש ובדיקת drift. טבלאות מוצעות מופיעות בנפרד ולא מוצגות כממומשות.
- פריסת הסכימה בענן אומתה בנפרד; שדות אינם הוכחה שתהליך התפעול המשתמש בהם קיים.

מקורות: scripts/generate-systems.mjs.

## קשרים ובידוד

### D03 · שיוכים בתוך אותו ארגון

מצב: foundation. אחריות: Security.

מפתחות זרים מורכבים מונעים חיבור רכב לנהג מארגון אחר.

- tenant_id,id הוא יעד לקשרים בין נהג, רכב, מרכז עלות, דלקן וטעינה.
- מזהה tenant ומשאב אינם ניתנים לשינוי גם למשתמש שחבר בשני הארגונים.
- בדיקות RLS עם משתמשים אמיתיים בענן נדרשות בנוסף למבחני SQL המקומיים.

מקורות: scripts/test-tenant-isolation.mjs.

### D04 · היסטוריית שיוך וגורם משלם

מצב: planned. אחריות: Fleet.

שיוך בזמן הפעולה חייב להישאר ניתן להסבר אחרי שינוי צי.

- טעינה כיום שומרת driver_id,vehicle_id והנחות צריכה; חסרים snapshot מלא של מרכז עלות וגורם משלם.
- טבלת assignment_periods עתידית תמנע תקופות חופפות ותאפשר אירועי מעבר רכב.
- אין להסיק הרשאה להיסטוריה רק מהנהג שמשויך לרכב היום.

מקורות: lib/platform/types.ts.

## כסף ומדידה

### D05 · יומן כספי והחזרים

מצב: planned. אחריות: Finance.

רישומים בלתי משתנים עם פעולות תיקון מפורשות.

- ה־payments הקיים הוא תשתית סטטוסים; אין כיום ledger חשבונאי מלא.
- הצעה: ledger_transactions ו־ledger_entries עם איזון חיוב/זיכוי לפי tenant ומטבע.
- תיקון או החזר יוצרים רישום מקושר, ולא מחיקה של חיוב היסטורי.
- מאמת האיזון בקוד הוא חוזה בדיקה; אכיפה אטומית במסד והקשר חשבונאי עדיין נדרשים.
- ספר החברה אינו ledger של הלקוח: מזהה ישות משפטית וספר, ממד tenant, בקרה פיננסית של staff והתאמה למערכת החשבונאית.

מקורות: lib/systems/contracts.ts.

### D06 · שריון תקציב במקביל

מצב: planned. אחריות: Charging.

בדיקת יתרה ושריון צריכים להתרחש באותה טרנזקציה.

- בדוק used + reserved + requested מול מסגרות ארגון, מרכז עלות, נהג ורכב.
- נעילת שורות בסדר קבוע מפחיתה deadlocks; אין check-then-write בשתי בקשות נפרדות.
- reservation נשאר תפוס כשמצב הפקודה לא ידוע. שחרור מותנה בראיה או בתהליך בירור.
- שדות monthly_budget קיימים לתכנון; אכיפה מצטברת עדיין אינה ממומשת.

מקורות: lib/platform/domain.ts.

### D07 · תעריף קפוא ומדידה

מצב: planned. אחריות: Charging & Finance.

התחשבנות מבוססת על מדידה מאומתת ועל תעריף שנשמר בזמן האישור.

- לשמור גרסת מחיר, מטבע, רכיבים, מסים, rounding ומזהה ספק ב־tariff_snapshot.
- meter_samples דורשים מקור, session, יחידה, sequence, occurred_at ו־received_at.
- תיקון מדידה מאוחר או מונה שהתאפס נכנסים לבירור; אין להניח שהמדידה האחרונה שהגיעה היא האחרונה בזמן.

מקורות: תכנון — טרם מומש.

### D17 · נתוני מנוי, עמלה והסכם מסחרי

מצב: foundation. אחריות: Data & Finance.

חוזי סכומים באגורות, אחוזים בנקודות בסיס וגרסת הסכם למרחב; הרחבת הסכימה עדיין בתכנון.

- billing_accounts, plan_price_revisions, customer_agreements, subscriptions/cycles ו־billing_obligations/lines הוגדרו כישויות מוצעות, לא כטבלאות מותקנות.
- ev1_payments הקיים דורש session_id ואינו מתאים לחיוב מנוי. ההרחבה חייבת להפריד מקור התחייבות והקצאת תשלום בלי לשנות תשלומים היסטוריים.
- צילום חיוב שומר מחיר ספק, בסיס ואחוז עמלה, מס, עיגול, הסכם ומקור CDR. עמלה מתווספת ללקוח; אינה קיזוז אוטומטי מספק.
- ספרי חברה מוגבלים לפי ישות משפטית ומטבע; רישומים, מסמכים והתחשבנות בלתי משתנים, עם תיקון מקושר ו־idempotency.

מקורות: lib/commercial-system/pricing.ts, lib/commercial-system/spec.json, docs/commercial-system/architecture.md.

## איכות ואנליטיקה

### D08 · הגדרות מדדים עסקיים

מצב: foundation. אחריות: Analytics.

הוצאות וצריכה מטעות אם לא מגדירים מקור וחלון זמן.

- הדוח הקיים משתמש בטעינות completed ולפי ended_at; אינו דוח התחשבנות סופית מול PSP.
- עלות לקוט״ש = amount_minor / (energy_wh / 1000) כאשר המכנה גדול מאפס.
- חיסכון = עלות ייחוס פחות עלות חשמל; תוצאה שלילית נשמרת.
- אומדן קילומטרים ו־CO₂ תלוי בצריכת הדגם ובהנחות, ואינו טלמטריה או מדידה מוסמכת.

מקורות: lib/platform/domain.ts.

### D09 · איכות, lineage וגרסאות

מצב: planned. אחריות: Data.

לכל מדד מקור, טרנספורמציה ובדיקת איכות.

- Freshness לתחנות, שלמות מזהי ספק, כפילויות אירוע ומדידות חסרות נמדדים בנפרד.
- שמור גרסת מתאם ו־payload hash; מזהה פקודה חוצה לוגים ללא מידע אישי.
- הנחות הדוחות כיום מחושבות מחדש מהגדרות tenant. דוח כספי סגור ידרוש snapshot גרסאות.

מקורות: תכנון — טרם מומש.

### D10 · שאילתות וביצועים

מצב: planned. אחריות: Data.

גישה מתחילה בסינון tenant ובהרשאה, לפני aggregation.

- להוסיף cursor ויצוא אסינכרוני במקום הרחבת מגבלת התוצאה ללא גבול.
- לבחון EXPLAIN ANALYZE על נפח דמוי פיילוט; אינדקסים לפי tenant_id,ended_at,id ושדות FK לפי תוכניות אמיתיות.
- RLS יכול להוסיף עבודה לכל שורה; לשמר SELECT auth.jwt, חיפוש חברות מאונדקס ו־security_invoker לדוחות.
- אין cache משותף ללא tenant/user/permission context ופסילה עם שינוי חברות.

מקורות: תכנון — טרם מומש.

## שימור ומחזור חיים

### D11 · סיווג מידע ושימור

מצב: planned. אחריות: Privacy.

שימור נקבע לפי צורך עסקי וחובה חוקית, ולא לפי ברירת מחדל של כלי.

- קטלוג ציבורי; פרטי קשר ולוחיות כמידע אישי; טעינות וכסף כמידע רגיש; token/hash כסוד.
- לוח שימור לפי מחלקת מידע עדיין טעון אישור. אין TTL מומצא למסמכים כספיים.
- סיום לקוח: חסימת פעולות, הסדרת יתרות, יצוא מאומת, מחיקה/פסאודונימיזציה לפי מדיניות ולוג ביקורת.

מקורות: תכנון — טרם מומש.

### D12 · מחיקה וגיבויים

מצב: planned. אחריות: Operations.

בקשת מחיקה אינה מחיקה עיוורת של עובדות כספיות.

- להפריד מחיקת זהות, נתונים אישיים ורשומות שחובה לשמור. legal hold מונע מחיקה אוטומטית.
- גיבויים כפופים ללוח שימור; שחזור חייב לשחזר גם הוראות מחיקה רלוונטיות.
- קובצי יצוא יישמרו ב־Storage פרטי עם בדיקת הרשאה וקישור קצר־חיים.

מקורות: תכנון — טרם מומש.

## הרחבות ומיגרציות

### D13 · תוכנית הרחבת הסכימה

מצב: planned. אחריות: Data.

שינויים תוספתיים עם מיגרציה ובדיקת תאימות.

- להוסיף tariff_snapshots, meter_samples, budget_reservations, assignment_periods, ledger_transactions, ledger_entries ו־subscription_entitlements רק עם חוזי ביצוע מאושרים.
- Outbox ו־provider_events כבר קיימים כסכימה; חסרים relay, claim/lease, חוזה payload ו־retry/DLQ.
- מתאם ספק יקבע תחום uniqueness נכון ומצבי timeout נוספים; אין לפתוח live charging לפני כן.

מקורות: תכנון — טרם מומש.

### D14 · תאימות ומעבר מהדגמה

מצב: planned. אחריות: Platform.

שמות ev1 פנימיים נשמרים כדי לא לשבור מזהים קיימים.

- מיתוג ציבורי LinkNodes Energy נפרד ממזהי SQL ו־storage.
- כל מיגרציה נבדקת על בסיס ריק ועל גרסה קיימת; rollback של אפליקציה אינו מבטל מיגרציה אוטומטית.
- יש ארבע טבלאות legacy של ממשק הנהג; אין dual-write או מעבר שקט למודל tenant. נדרש מתאם נתונים ומיפוי מפורש.

מקורות: supabase/migrations/0001_ev1.sql.

### D16 · נתוני ייחוס ורשתות בישראל

מצב: deployed. אחריות: Data Platform.

1,316 רשומות יישובים, 2,261 אתרי טעינה עם מיקום ו־26 רשומות מפעילים וכינויים; קטלוג דגמים ממשלתי בשאילתה חיה.

- נתוני הייחוס משותפים ונגישים לקריאה בלבד. קשר בין רכב לאדם או לארגון נשאר נתון פרטי במרחב שלו.
- מועד קליטה אינו מועד עדכון מקור. מאגר העמדות עודכן במרץ 2026; אין טענה לכיסוי מלא, זמינות או תעריף חי.
- מספר רישוי נבדק רק לאחר התחברות ובכפוף למכסה אטומית של 30 בקשות ביום. מוחזר מפרט טכני מצומצם; אין אימות בעלות ואין שמירת תוצאות.
- יבוא מכין נתונים לבדיקה, בודק שלמות ומזהים ומפיק UPSERT. פרסום כל המנות בעסקה אחת; אין מחיקה אוטומטית של רשומות חסרות.

מקורות: supabase/migrations/20261107232238_israel_reference_data.sql, scripts/import-israel-reference.py, lib/reference/manifest.json, app/api/reference/\[kind]/route.ts.

### D18 · פרופיל ארגון ולוגו פרטי

מצב: deployed. אחריות: Platform & Data.

ev1_workspace_profiles ו־workspace-logos נפרסו עם בידוד לפי מרחב; פרטי התחברות אישיים נשארים ב־Clerk.

- שם משפטי ומספר חברה נשמרים ב־ev1_tenants; איש קשר, טלפון, אתר וכתובת בפרופיל מרחב נפרד.
- שם החברה וגרסת הפרופיל נקראים באותה תמונת נתונים. שינוי הפרופיל והשם אטומיים, עם בדיקת revision ו־audit ללא תוכן השדות.
- הלוגו מוגבל לתמונה סטטית עד 2MB ו־16 מיליון פיקסלים; השרת ממיר ל־WebP עד 512px ומסיר מטא־דאטה. צפייה ב־API דורשת חברות פעילה.

מקורות: supabase/migrations/20261108013050_workspace_profiles.sql, lib/platform/profile-server.ts, lib/platform/logo.ts, scripts/test-workspace-profile-isolation.mjs.

## סכימה מתוך המיגרציות

### public.stations

מקור: supabase/migrations/0001_ev1.sql. היקף: catalog.

| שדה        | הגדרת SQL                                                        |
| ---------- | ---------------------------------------------------------------- |
| id         | text primary key                                                 |
| name       | text not null check (length(trim(name)) > 0)                     |
| address    | text not null                                                    |
| city       | text not null                                                    |
| lat        | double precision not null check (lat between -90 and 90)         |
| lng        | double precision not null check (lng between -180 and 180)       |
| available  | integer not null default 0 check (available >= 0)                |
| total      | integer not null check (total > 0)                               |
| power      | integer not null check (power > 0)                               |
| price      | numeric(8, 3) not null check (price >= 0)                        |
| connector  | text not null check (connector in ('CCS2', 'Type 2', 'CHAdeMO')) |
| rating     | numeric(2, 1) check (rating between 0 and 5)                     |
| amenities  | text\[] not null default '{}'                                    |
| tag        | text                                                             |
| updated_at | timestamptz not null default now()                               |

אילוצים: constraint available_connectors_within_total check (available <= total)

קשרים:

### public.favorites

מקור: supabase/migrations/0001_ev1.sql. היקף: user.

| שדה        | הגדרת SQL                                                                      |
| ---------- | ------------------------------------------------------------------------------ |
| user_id    | text not null default (auth.jwt() ->> 'sub') check (length(trim(user_id)) > 0) |
| station_id | text not null references public.stations(id) on delete cascade                 |
| created_at | timestamptz not null default now()                                             |

אילוצים: primary key (user_id, station_id)

קשרים: station_id → public.stations(id)

### public.vehicles

מקור: supabase/migrations/0001_ev1.sql. היקף: user.

| שדה                  | הגדרת SQL                                                                                |
| -------------------- | ---------------------------------------------------------------------------------------- |
| id                   | uuid primary key default gen_random_uuid()                                               |
| user_id              | text not null default (auth.jwt() ->> 'sub') check (length(trim(user_id)) > 0)           |
| name                 | text not null check (length(trim(name)) between 1 and 100)                               |
| battery_capacity_kwh | numeric(7, 2) not null check (battery_capacity_kwh > 0 and battery_capacity_kwh <= 1000) |
| connector            | text not null check (connector in ('CCS2', 'Type 2', 'CHAdeMO'))                         |
| created_at           | timestamptz not null default now()                                                       |

אילוצים:

קשרים:

### public.charging_sessions

מקור: supabase/migrations/0001_ev1.sql. היקף: user.

| שדה                  | הגדרת SQL                                                                                                  |
| -------------------- | ---------------------------------------------------------------------------------------------------------- |
| id                   | uuid primary key default gen_random_uuid()                                                                 |
| user_id              | text not null check (length(trim(user_id)) > 0)                                                            |
| station_id           | text not null references public.stations(id)                                                               |
| connector_identifier | text not null                                                                                              |
| status               | text not null check (status in ('requested', 'authorized', 'charging', 'stopping', 'completed', 'failed')) |
| energy_kwh           | numeric(12, 3) not null default 0 check (energy_kwh >= 0)                                                  |
| amount_minor         | bigint not null default 0 check (amount_minor >= 0)                                                        |
| currency             | text not null default 'ILS' check (currency = 'ILS')                                                       |
| tariff_per_kwh       | numeric(8, 3) not null check (tariff_per_kwh >= 0)                                                         |
| idempotency_key      | uuid not null unique                                                                                       |
| requested_at         | timestamptz not null default now()                                                                         |
| started_at           | timestamptz                                                                                                |
| ended_at             | timestamptz                                                                                                |
| updated_at           | timestamptz not null default now()                                                                         |

אילוצים: constraint valid_session_times check (ended_at is null or (started_at is not null and ended_at >= started_at))

קשרים: station_id → public.stations(id)

### public.ev1_tenants

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                        | הגדרת SQL                                                                          |
| -------------------------- | ---------------------------------------------------------------------------------- |
| id                         | uuid primary key default gen_random_uuid()                                         |
| kind                       | text not null check(kind in ('personal','business'))                               |
| name                       | text not null check(length(trim(name)) between 2 and 100)                          |
| legal_name                 | text check(length(legal_name)<=160)                                                |
| tax_id                     | text check(tax_id \~ '^\[0-9]{5,20}$')                                             |
| owner_user_id              | text not null check(length(owner_user_id)>0)                                       |
| provision_key              | uuid not null                                                                      |
| clerk_org_id               | text unique                                                                        |
| currency                   | text not null default 'ILS' check(currency='ILS')                                  |
| timezone                   | text not null default 'Asia/Jerusalem' check(timezone='Asia/Jerusalem')            |
| status                     | text not null default 'active' check(status in ('active','suspended'))             |
| fuel_price_minor_per_litre | integer not null default 750 check(fuel_price_minor_per_litre between 0 and 10000) |
| fuel_kg_co2_per_litre      | numeric(8,4) not null default 2.31 check(fuel_kg_co2_per_litre between 0 and 10)   |
| grid_kg_co2_per_kwh        | numeric(8,4) not null default 0.45 check(grid_kg_co2_per_kwh between 0 and 5)      |
| accepted_terms_version     | text not null default 'platform-preview-1'                                         |
| created_at                 | timestamptz not null default now()                                                 |
| plan_code                  | text                                                                               |

אילוצים: unique(owner_user_id,provision_key); constraint lne_account_plan_kind check (
(kind='personal' and plan_code in ('personal','family')) or
(kind='business' and plan_code in ('business','enterprise'))
)

קשרים:

### public.ev1_memberships

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה          | הגדרת SQL                                                                         |
| ------------ | --------------------------------------------------------------------------------- |
| tenant_id    | uuid not null references public.ev1_tenants(id)                                   |
| user_id      | text not null check(length(user_id)>0)                                            |
| role         | text not null check(role in ('owner','admin','fleet_manager','finance','driver')) |
| status       | text not null default 'active' check(status in ('active','suspended'))            |
| display_name | text not null default '' check(length(display_name)<=100)                         |
| created_at   | timestamptz not null default now()                                                |

אילוצים: primary key(tenant_id,user_id)

קשרים: tenant_id → public.ev1_tenants(id)

### public.ev1_vehicle_models

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: catalog.

| שדה                        | הגדרת SQL                                                                 |
| -------------------------- | ------------------------------------------------------------------------- |
| id                         | text primary key                                                          |
| make                       | text not null                                                             |
| model                      | text not null                                                             |
| category                   | text not null check(category in ('car','suv','van','truck','bus'))        |
| powertrain                 | text not null check(powertrain in ('BEV','PHEV'))                         |
| battery_kwh                | numeric(8,2) not null check(battery_kwh>0)                                |
| connector                  | text not null check(connector in ('CCS2','Type 2','CHAdeMO'))             |
| consumption_wh_per_km      | integer not null check(consumption_wh_per_km between 50 and 3000)         |
| reference_fuel_l_per_100km | numeric(8,3) not null check(reference_fuel_l_per_100km between 0 and 100) |

אילוצים:

קשרים:

### public.ev1_cost_centers

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                  | הגדרת SQL                                                   |
| -------------------- | ----------------------------------------------------------- |
| id                   | uuid primary key default gen_random_uuid()                  |
| tenant_id            | uuid not null references public.ev1_tenants(id)             |
| name                 | text not null check(length(trim(name)) between 2 and 100)   |
| code                 | text not null check(code \~ '^\[A-Za-z0-9\_-]{1,24}$')      |
| monthly_budget_minor | integer check(monthly_budget_minor between 0 and 100000000) |
| created_at           | timestamptz not null default now()                          |

אילוצים: unique(tenant_id,id); unique(tenant_id,code)

קשרים: tenant_id → public.ev1_tenants(id)

### public.ev1_drivers

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                  | הגדרת SQL                                                                                                   |
| -------------------- | ----------------------------------------------------------------------------------------------------------- |
| id                   | uuid primary key default gen_random_uuid()                                                                  |
| tenant_id            | uuid not null references public.ev1_tenants(id)                                                             |
| name                 | text not null check(length(trim(name)) between 2 and 100)                                                   |
| email                | text not null check(length(email)<=254 and email \~ '^\[^\[:space:]@]+@\[^\[:space:]@]+.\[^\[:space:]@]+$') |
| user_id              | text                                                                                                        |
| cost_center_id       | uuid                                                                                                        |
| status               | text not null default 'active' check(status in ('active','suspended'))                                      |
| monthly_budget_minor | integer check(monthly_budget_minor between 0 and 100000000)                                                 |
| created_at           | timestamptz not null default now()                                                                          |

אילוצים: unique(tenant_id,id); foreign key(tenant_id,cost_center_id) references public.ev1_cost_centers(tenant_id,id); foreign key(tenant_id,user_id) references public.ev1_memberships(tenant_id,user_id)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,cost_center_id → public.ev1_cost_centers(tenant_id,id); tenant_id,user_id → public.ev1_memberships(tenant_id,user_id)

### public.ev1_fleet_vehicles

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                  | הגדרת SQL                                                                        |
| -------------------- | -------------------------------------------------------------------------------- |
| id                   | uuid primary key default gen_random_uuid()                                       |
| tenant_id            | uuid not null references public.ev1_tenants(id)                                  |
| model_id             | text references public.ev1_vehicle_models(id)                                    |
| plate                | text not null check(plate \~ '^\[0-9A-Za-z -]{4,16}$')                           |
| label                | text not null default '' check(length(label)<=100)                               |
| driver_id            | uuid                                                                             |
| cost_center_id       | uuid                                                                             |
| status               | text not null default 'active' check(status in ('active','suspended','retired')) |
| monthly_budget_minor | integer check(monthly_budget_minor between 0 and 100000000)                      |
| created_at           | timestamptz not null default now()                                               |
| catalog_vehicle      | jsonb                                                                            |
| revision             | bigint not null default 0 check (revision >= 0)                                  |

אילוצים: unique(tenant_id,id); unique(tenant_id,plate); foreign key(tenant_id,driver_id) references public.ev1_drivers(tenant_id,id); foreign key(tenant_id,cost_center_id) references public.ev1_cost_centers(tenant_id,id); constraint vehicle_model_selection check ((
(model_id is not null and catalog_vehicle is null) or
(model_id is null and catalog_vehicle is not null and
jsonb_typeof(catalog_vehicle)='object' and
catalog_vehicle ?& array\['id','make','model','year','fuel','trim','source'] and
catalog_vehicle->>'id' \~ '^\[1-9]\[0-9]{0,11}$' and
jsonb_typeof(catalog_vehicle->'id')='number' and
length(catalog_vehicle->>'make') between 1 and 160 and
length(catalog_vehicle->>'model') between 1 and 160 and
catalog_vehicle->>'year' \~ '^\[12]\[0-9]{3}$' and
catalog_vehicle->>'source'='142afde2-6228-49f9-8a29-9b6c3a0cbe40' and
length(catalog_vehicle::text)<2500)
) is true)

קשרים: tenant_id → public.ev1_tenants(id); model_id → public.ev1_vehicle_models(id); tenant_id,driver_id → public.ev1_drivers(tenant_id,id); tenant_id,cost_center_id → public.ev1_cost_centers(tenant_id,id)

### public.ev1_charging_policies

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                  | הגדרת SQL                                                                                                                                |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| tenant_id            | uuid primary key references public.ev1_tenants(id)                                                                                       |
| monthly_budget_minor | integer check(monthly_budget_minor between 0 and 100000000)                                                                              |
| max_session_minor    | integer not null default 20000 check(max_session_minor between 100 and 100000000)                                                        |
| max_power_kw         | integer not null default 350 check(max_power_kw between 1 and 2000)                                                                      |
| allow_public         | boolean not null default true                                                                                                            |
| allow_home           | boolean not null default true                                                                                                            |
| allowed_days         | integer\[] not null default '{0,1,2,3,4,5,6}' check(cardinality(allowed_days) between 1 and 7 and allowed_days <@ array\[0,1,2,3,4,5,6]) |
| start_hour           | integer not null default 0 check(start_hour between 0 and 23)                                                                            |
| end_hour             | integer not null default 0 check(end_hour between 0 and 23)                                                                              |

אילוצים:

קשרים: tenant_id → public.ev1_tenants(id)

### public.ev1_charge_credentials

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה        | הגדרת SQL                                                                                   |
| ---------- | ------------------------------------------------------------------------------------------- |
| id         | uuid primary key default gen_random_uuid()                                                  |
| tenant_id  | uuid not null references public.ev1_tenants(id)                                             |
| driver_id  | uuid not null                                                                               |
| vehicle_id | uuid                                                                                        |
| label      | text not null check(length(trim(label)) between 2 and 100)                                  |
| last_four  | text not null check(length(last_four)=4)                                                    |
| kind       | text not null check(kind in ('virtual','rfid'))                                             |
| status     | text not null default 'pending' check(status in ('pending','active','suspended','revoked')) |
| created_at | timestamptz not null default now()                                                          |

אילוצים: unique(tenant_id,id); foreign key(tenant_id,driver_id) references public.ev1_drivers(tenant_id,id); foreign key(tenant_id,vehicle_id) references public.ev1_fleet_vehicles(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,driver_id → public.ev1_drivers(tenant_id,id); tenant_id,vehicle_id → public.ev1_fleet_vehicles(tenant_id,id)

### ev1_private.credential_secrets

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: private.

| שדה           | הגדרת SQL                                                     |
| ------------- | ------------------------------------------------------------- |
| credential_id | uuid primary key references public.ev1_charge_credentials(id) |
| token_hash    | text not null unique check(token_hash \~ '^\[0-9a-f]{64}$')   |

אילוצים:

קשרים: credential_id → public.ev1_charge_credentials(id)

### public.ev1_fleet_sessions

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                          | הגדרת SQL                                                                                                                                  |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| id                           | uuid primary key default gen_random_uuid()                                                                                                 |
| tenant_id                    | uuid not null references public.ev1_tenants(id)                                                                                            |
| driver_id                    | uuid                                                                                                                                       |
| vehicle_id                   | uuid not null                                                                                                                              |
| station_name                 | text not null                                                                                                                              |
| provider                     | text                                                                                                                                       |
| provider_session_id          | text                                                                                                                                       |
| connector_key                | text                                                                                                                                       |
| status                       | text not null check(status in ('requested','authorized','charging','stopping','completed','failed','cancelled','reconciliation_required')) |
| energy_wh                    | bigint not null default 0 check(energy_wh between 0 and 100000000)                                                                         |
| amount_minor                 | bigint not null default 0 check(amount_minor between 0 and 100000000)                                                                      |
| currency                     | text not null default 'ILS' check(currency='ILS')                                                                                          |
| consumption_wh_per_km        | integer not null check(consumption_wh_per_km between 50 and 3000)                                                                          |
| reference_fuel_l_per_100km   | numeric(8,3) not null check(reference_fuel_l_per_100km between 0 and 100)                                                                  |
| reserved_minor               | integer not null default 0 check(reserved_minor between 0 and 100000000)                                                                   |
| idempotency_key              | uuid not null                                                                                                                              |
| created_at                   | timestamptz not null default now()                                                                                                         |
| started_at                   | timestamptz                                                                                                                                |
| ended_at                     | timestamptz                                                                                                                                |
| provider_amount_finalized_at | timestamptz                                                                                                                                |

אילוצים: unique(tenant_id,id); unique(tenant_id,idempotency_key); unique(provider,provider_session_id); foreign key(tenant_id,driver_id) references public.ev1_drivers(tenant_id,id); foreign key(tenant_id,vehicle_id) references public.ev1_fleet_vehicles(tenant_id,id); check(ended_at is null or (started_at is not null and ended_at>=started_at)); check(status<>'completed' or ended_at is not null)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,driver_id → public.ev1_drivers(tenant_id,id); tenant_id,vehicle_id → public.ev1_fleet_vehicles(tenant_id,id)

### public.ev1_payment_methods

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה          | הגדרת SQL                                                     |
| ------------ | ------------------------------------------------------------- |
| id           | uuid primary key default gen_random_uuid()                    |
| tenant_id    | uuid not null references public.ev1_tenants(id)               |
| brand        | text not null                                                 |
| last_four    | text not null check(last_four \~ '^\[0-9]{4}$')               |
| expiry_month | integer not null check(expiry_month between 1 and 12)         |
| expiry_year  | integer not null check(expiry_year between 2020 and 2100)     |
| status       | text not null check(status in ('active','expired','removed')) |
| is_default   | boolean not null default false                                |

אילוצים: unique(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id)

### ev1_private.payment_tokens

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: private.

| שדה                   | הגדרת SQL                                                  |
| --------------------- | ---------------------------------------------------------- |
| payment_method_id     | uuid primary key references public.ev1_payment_methods(id) |
| provider              | text not null                                              |
| provider_customer_ref | text not null                                              |
| provider_method_ref   | text not null                                              |

אילוצים: unique(provider,provider_method_ref)

קשרים: payment_method_id → public.ev1_payment_methods(id)

### public.ev1_invoices

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה          | הגדרת SQL                                                     |
| ------------ | ------------------------------------------------------------- |
| id           | uuid primary key default gen_random_uuid()                    |
| tenant_id    | uuid not null references public.ev1_tenants(id)               |
| number       | text not null                                                 |
| period_start | date not null                                                 |
| period_end   | date not null                                                 |
| amount_minor | bigint not null check(amount_minor between 0 and 100000000)   |
| currency     | text not null default 'ILS' check(currency='ILS')             |
| status       | text not null check(status in ('draft','open','paid','void')) |

אילוצים: unique(tenant_id,id); unique(tenant_id,number); check(period_end>=period_start)

קשרים: tenant_id → public.ev1_tenants(id)

### public.ev1_payments

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                  | הגדרת SQL                                                                                                           |
| -------------------- | ------------------------------------------------------------------------------------------------------------------- |
| id                   | uuid primary key default gen_random_uuid()                                                                          |
| tenant_id            | uuid not null references public.ev1_tenants(id)                                                                     |
| session_id           | uuid not null                                                                                                       |
| provider             | text not null                                                                                                       |
| provider_payment_ref | text                                                                                                                |
| idempotency_key      | uuid not null                                                                                                       |
| amount_minor         | bigint not null check(amount_minor between 0 and 100000000)                                                         |
| refunded_minor       | bigint not null default 0 check(refunded_minor>=0 and refunded_minor<=amount_minor)                                 |
| currency             | text not null default 'ILS' check(currency='ILS')                                                                   |
| status               | text not null check(status in ('requires_method','authorized','captured','failed','partially_refunded','refunded')) |

אילוצים: unique(tenant_id,idempotency_key); unique(provider,provider_payment_ref); foreign key(tenant_id,session_id) references public.ev1_fleet_sessions(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,session_id → public.ev1_fleet_sessions(tenant_id,id)

### public.ev1_invitations

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה                 | הגדרת SQL                                                                         |
| ------------------- | --------------------------------------------------------------------------------- |
| id                  | uuid primary key default gen_random_uuid()                                        |
| tenant_id           | uuid not null references public.ev1_tenants(id)                                   |
| email               | text not null check(length(email)<=254)                                           |
| role                | text not null check(role in ('admin','fleet_manager','finance','driver'))         |
| status              | text not null default 'pending' check(status in ('pending','accepted','revoked')) |
| invited_by          | text not null                                                                     |
| expires_at          | timestamptz not null default now()+interval '7 days'                              |
| created_at          | timestamptz not null default now()                                                |
| accepted_by_user_id | text                                                                              |
| accepted_at         | timestamptz                                                                       |

אילוצים: unique(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id)

### ev1_private.invitation_secrets

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: private.

| שדה           | הגדרת SQL                                                   |
| ------------- | ----------------------------------------------------------- |
| invitation_id | uuid primary key references public.ev1_invitations(id)      |
| token_hash    | text not null unique check(token_hash \~ '^\[0-9a-f]{64}$') |

אילוצים:

קשרים: invitation_id → public.ev1_invitations(id)

### public.ev1_audit_events

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: tenant.

| שדה           | הגדרת SQL                                       |
| ------------- | ----------------------------------------------- |
| id            | uuid primary key default gen_random_uuid()      |
| tenant_id     | uuid not null references public.ev1_tenants(id) |
| actor_user_id | text                                            |
| action        | text not null                                   |
| resource_type | text not null                                   |
| resource_id   | text not null                                   |
| created_at    | timestamptz not null default now()              |

אילוצים:

קשרים: tenant_id → public.ev1_tenants(id)

### ev1_private.outbox

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: private.

| שדה               | הגדרת SQL                                       |
| ----------------- | ----------------------------------------------- |
| id                | uuid primary key default gen_random_uuid()      |
| tenant_id         | uuid not null references public.ev1_tenants(id) |
| session_id        | uuid not null                                   |
| event_type        | text not null                                   |
| payload           | jsonb not null default '{}'                     |
| deduplication_key | text not null unique                            |
| attempts          | integer not null default 0 check(attempts>=0)   |
| available_at      | timestamptz not null default now()              |
| published_at      | timestamptz                                     |

אילוצים: foreign key(tenant_id,session_id) references public.ev1_fleet_sessions(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,session_id → public.ev1_fleet_sessions(tenant_id,id)

### ev1_private.provider_events

מקור: supabase/migrations/20261107211048_platform_foundation.sql. היקף: private.

| שדה          | הגדרת SQL                          |
| ------------ | ---------------------------------- |
| provider     | text not null                      |
| event_id     | text not null                      |
| received_at  | timestamptz not null default now() |
| payload_hash | text not null                      |

אילוצים: primary key(provider,event_id)

קשרים:

### public.lne_data_sources

מקור: supabase/migrations/20261107232238_israel_reference_data.sql. היקף: catalog.

| שדה                | הגדרת SQL                            |
| ------------------ | ------------------------------------ |
| id                 | text primary key                     |
| title              | text not null                        |
| publisher          | text not null                        |
| url                | text not null                        |
| license            | text not null                        |
| source_modified_at | timestamptz                          |
| fetched_at         | timestamptz not null                 |
| coverage           | text not null                        |
| row_count          | integer not null check(row_count>=0) |
| content_sha256     | text not null                        |

אילוצים:

קשרים:

### public.lne_localities

מקור: supabase/migrations/20261107232238_israel_reference_data.sql. היקף: catalog.

| שדה       | הגדרת SQL                                            |
| --------- | ---------------------------------------------------- |
| code      | text primary key                                     |
| name_he   | text not null                                        |
| name_en   | text                                                 |
| region    | text                                                 |
| source_id | text not null references public.lne_data_sources(id) |

אילוצים:

קשרים: source_id → public.lne_data_sources(id)

### public.lne_operators

מקור: supabase/migrations/20261107232238_israel_reference_data.sql. היקף: catalog.

| שדה                | הגדרת SQL                                                                                                                               |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| id                 | text primary key                                                                                                                        |
| name               | text not null                                                                                                                           |
| aliases            | text\[] not null default '{}'                                                                                                           |
| website            | text                                                                                                                                    |
| identity_status    | text not null check(identity_status in ('verified','source_only','review'))                                                             |
| integration_status | text not null default 'not_connected' check(integration_status in ('not_connected','sandbox','live'))                                   |
| note               | text not null                                                                                                                           |
| source_url         | text not null                                                                                                                           |
| capabilities       | jsonb not null default '{"availability":false,"tariffs":false,"remote_start":false,"remote_stop":false,"cdr":false,"settlement":false}' |
| energy_sources     | text\[] not null default array\['electricity']::text\[]                                                                                 |

אילוצים: constraint lne_operator_energy_sources check (
array_ndims(energy_sources)=1
and cardinality(energy_sources) between 1 and 4
and array_position(energy_sources,null) is null
and energy_sources <@ array\['electricity','petrol','diesel','lpg']::text\[]
)

קשרים:

### public.lne_charging_locations

מקור: supabase/migrations/20261107232238_israel_reference_data.sql. היקף: catalog.

| שדה              | הגדרת SQL                                                     |
| ---------------- | ------------------------------------------------------------- |
| id               | text primary key                                              |
| source_id        | text not null references public.lne_data_sources(id)          |
| source_record_id | text not null                                                 |
| operator_id      | text not null references public.lne_operators(id)             |
| source_operator  | text not null                                                 |
| name             | text not null                                                 |
| address          | text                                                          |
| latitude         | double precision                                              |
| longitude        | double precision                                              |
| reported_points  | integer check(reported_points>=0)                             |
| reported_fast    | integer check(reported_fast>=0)                               |
| reported_slow    | integer check(reported_slow>=0)                               |
| availability     | text not null default 'unknown' check(availability='unknown') |

אילוצים: unique(source_id,source_record_id); check((latitude is null and longitude is null) or (latitude between -90 and 90 and longitude between -180 and 180))

קשרים: source_id → public.lne_data_sources(id); operator_id → public.lne_operators(id)

### ev1_private.vehicle_lookup_limits

מקור: supabase/migrations/20261107232238_israel_reference_data.sql. היקף: private.

| שדה      | הגדרת SQL                                         |
| -------- | ------------------------------------------------- |
| user_id  | text not null                                     |
| day      | date not null                                     |
| attempts | integer not null check(attempts between 1 and 30) |

אילוצים: primary key(user_id,day)

קשרים:

### public.ev1_provider_preferences

מקור: supabase/migrations/20261108003309_customer_provider_preferences.sql. היקף: tenant.

| שדה        | הגדרת SQL                                          |
| ---------- | -------------------------------------------------- |
| tenant_id  | uuid primary key references public.ev1_tenants(id) |
| revision   | integer not null check (revision > 0)              |
| updated_by | text not null                                      |
| updated_at | timestamptz not null default now()                 |

אילוצים:

קשרים: tenant_id → public.ev1_tenants(id)

### public.ev1_tenant_providers

מקור: supabase/migrations/20261108003309_customer_provider_preferences.sql. היקף: tenant.

| שדה         | הגדרת SQL                                                           |
| ----------- | ------------------------------------------------------------------- |
| tenant_id   | uuid not null references public.ev1_provider_preferences(tenant_id) |
| operator_id | text not null references public.lne_operators(id)                   |
| approved_by | text not null                                                       |
| approved_at | timestamptz not null default now()                                  |

אילוצים: primary key (tenant_id, operator_id)

קשרים: tenant_id → public.ev1_provider_preferences(tenant_id); operator_id → public.lne_operators(id)

### public.ev1_workspace_profiles

מקור: supabase/migrations/20261108013050_workspace_profiles.sql. היקף: tenant.

| שדה           | הגדרת SQL                                                                                                                                                    |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| tenant_id     | uuid primary key references public.ev1_tenants(id)                                                                                                           |
| contact_name  | text not null default '' check(length(contact_name)<=100)                                                                                                    |
| contact_email | text not null default '' check(length(contact_email)<=254 and (contact_email='' or contact_email \~ '^\[^\[:space:]@]+@\[^\[:space:]@]+.\[^\[:space:]@]+$')) |
| phone         | text not null default '' check(phone='' or phone \~ '^+?\[0-9 ()-]{7,25}$')                                                                                  |
| website       | text not null default '' check(length(website)<=300 and (website='' or website \~ '^https\://\[^\[:space:]@]+$'))                                            |
| industry      | text not null default '' check(industry in ('','transport','logistics','leasing','services','retail','public','technology','other'))                         |
| address_line  | text not null default '' check(length(address_line)<=180)                                                                                                    |
| city          | text not null default '' check(length(city)<=100)                                                                                                            |
| postal_code   | text not null default '' check(postal_code='' or postal_code \~ '^\[0-9]{5,7}$')                                                                             |
| country_code  | text not null default 'IL' check(country_code='IL')                                                                                                          |
| logo_path     | text check(logo_path is null or (split_part(logo_path,'/',1)=tenant_id::text and logo_path \~ '^\[0-9a-f-]{36}/\[0-9a-f-]{36}.webp$'))                       |
| revision      | integer not null default 1 check(revision>0)                                                                                                                 |
| updated_by    | text not null                                                                                                                                                |
| updated_at    | timestamptz not null default now()                                                                                                                           |

אילוצים:

קשרים: tenant_id → public.ev1_tenants(id)

### ev1_private.verified_member_emails

מקור: supabase/migrations/20261109190551_invitation_driver_lifecycle.sql. היקף: private.

| שדה         | הגדרת SQL                                                                                                                                    |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| tenant_id   | uuid not null                                                                                                                                |
| user_id     | text not null                                                                                                                                |
| email       | text not null check ( email=lower(btrim(email)) and length(email)<=254 and email \~ '^\[^\[:space:]@]+@\[^\[:space:]@]+.\[^\[:space:]@]+$' ) |
| verified_at | timestamptz not null default now()                                                                                                           |
| is_current  | boolean not null default true                                                                                                                |

אילוצים: primary key(tenant_id,email); foreign key(tenant_id,user_id) references public.ev1_memberships(tenant_id,user_id)

קשרים: tenant_id,user_id → public.ev1_memberships(tenant_id,user_id)

### ev1_private.billing_catalog

מקור: supabase/migrations/20261110203000_hyp_billing_foundation.sql. היקף: private.

| שדה                 | הגדרת SQL                                                                          |
| ------------------- | ---------------------------------------------------------------------------------- |
| version             | text not null                                                                      |
| plan_code           | text not null check (plan_code in ('personal','family','business','enterprise'))   |
| monthly_price_minor | bigint                                                                             |
| annual_price_minor  | bigint                                                                             |
| price_includes_vat  | boolean not null                                                                   |
| trial_days          | integer not null default 0 check (trial_days between 0 and 365)                    |
| commission_rate_bps | integer check (commission_rate_bps between 0 and 10000)                            |
| commission_basis    | text not null default 'charging_gross' check (commission_basis = 'charging_gross') |
| vat_rate_bps        | integer not null check (vat_rate_bps between 0 and 10000)                          |
| active              | boolean not null default false                                                     |
| created_at          | timestamptz not null default now()                                                 |

אילוצים: primary key (version, plan_code); check (monthly_price_minor is null or monthly_price_minor > 0); check (annual_price_minor is null or annual_price_minor > 0)

קשרים:

### public.ev1_subscriptions

מקור: supabase/migrations/20261110203000_hyp_billing_foundation.sql. היקף: tenant.

| שדה                  | הגדרת SQL                                                                                                                                                                   |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id                   | uuid primary key default gen_random_uuid()                                                                                                                                  |
| tenant_id            | uuid not null references public.ev1_tenants(id)                                                                                                                             |
| plan_code            | text not null check (plan_code in ('personal','family','business','enterprise'))                                                                                            |
| billing_interval     | text not null check (billing_interval in ('monthly','annual'))                                                                                                              |
| status               | text not null default 'pending_payment' check (status in ('pending_payment','trialing','active','past_due','canceled','expired'))                                           |
| catalog_version      | text not null                                                                                                                                                               |
| terms_version        | text not null                                                                                                                                                               |
| billing_name         | text not null check (length(trim(billing_name)) between 2 and 160)                                                                                                          |
| billing_email        | text not null check ( length(billing_email)<=254 and billing_email=lower(trim(billing_email)) and billing_email \~ '^\[^\[:space:]@]+@\[^\[:space:]@]+.\[^\[:space:]@]+$' ) |
| billing_tax_id       | text check (billing_tax_id is null or billing_tax_id \~ '^\[0-9]{5,20}$')                                                                                                   |
| price_minor          | bigint not null check (price_minor > 0 and price_minor <= 100000000)                                                                                                        |
| price_includes_vat   | boolean not null                                                                                                                                                            |
| vat_rate_bps         | integer not null check (vat_rate_bps between 0 and 10000)                                                                                                                   |
| commission_rate_bps  | integer check (commission_rate_bps between 0 and 10000)                                                                                                                     |
| commission_basis     | text not null check (commission_basis = 'charging_gross')                                                                                                                   |
| payment_method_id    | uuid                                                                                                                                                                        |
| accepted_at          | timestamptz not null default now()                                                                                                                                          |
| current_period_start | timestamptz                                                                                                                                                                 |
| current_period_end   | timestamptz                                                                                                                                                                 |
| next_charge_at       | timestamptz                                                                                                                                                                 |
| cancel_at_period_end | boolean not null default false                                                                                                                                              |
| failed_attempts      | integer not null default 0 check (failed_attempts >= 0)                                                                                                                     |
| retry_after          | timestamptz                                                                                                                                                                 |
| created_at           | timestamptz not null default now()                                                                                                                                          |
| updated_at           | timestamptz not null default now()                                                                                                                                          |

אילוצים: unique (tenant_id,id); foreign key (tenant_id,payment_method_id)
references public.ev1_payment_methods(tenant_id,id); check (current_period_end is null or current_period_start is not null); check (current_period_end is null or current_period_end >= current_period_start)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,payment_method_id → public.ev1_payment_methods(tenant_id,id)

### public.ev1_billing_obligations

מקור: supabase/migrations/20261110203000_hyp_billing_foundation.sql. היקף: tenant.

| שדה                       | הגדרת SQL                                                                                                          |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| id                        | uuid primary key default gen_random_uuid()                                                                         |
| tenant_id                 | uuid not null references public.ev1_tenants(id)                                                                    |
| subscription_id           | uuid not null                                                                                                      |
| session_id                | uuid                                                                                                               |
| payment_method_id         | uuid                                                                                                               |
| kind                      | text not null check (kind in ('subscription','charging_commission'))                                               |
| logical_key               | text not null check (length(logical_key) between 1 and 180)                                                        |
| description               | text not null check (length(description) between 1 and 300)                                                        |
| net_minor                 | bigint not null check (net_minor >= 0 and net_minor <= 100000000)                                                  |
| tax_minor                 | bigint not null check (tax_minor >= 0 and tax_minor <= 100000000)                                                  |
| amount_minor              | bigint not null check (amount_minor > 0 and amount_minor <= 100000000)                                             |
| currency                  | text not null default 'ILS' check (currency='ILS')                                                                 |
| status                    | text not null default 'open' check (status in ('open','processing','paid','void','partially_refunded','refunded')) |
| commission_base_minor     | bigint                                                                                                             |
| commission_rate_bps       | integer                                                                                                            |
| commission_tax_rate_bps   | integer                                                                                                            |
| due_at                    | timestamptz not null                                                                                               |
| paid_at                   | timestamptz                                                                                                        |
| lease_owner               | uuid                                                                                                               |
| lease_until               | timestamptz                                                                                                        |
| created_at                | timestamptz not null default now()                                                                                 |
| updated_at                | timestamptz not null default now()                                                                                 |
| commission_policy_version | text                                                                                                               |

אילוצים: unique (tenant_id,id); unique (tenant_id,logical_key); foreign key (tenant_id,subscription_id)
references public.ev1_subscriptions(tenant_id,id); foreign key (tenant_id,session_id)
references public.ev1_fleet_sessions(tenant_id,id); foreign key (tenant_id,payment_method_id)
references public.ev1_payment_methods(tenant_id,id); check (amount_minor = net_minor + tax_minor); check (
(kind='subscription' and session_id is null and commission_base_minor is null)
or
(kind='charging_commission' and session_id is not null and commission_base_minor is not null
and commission_rate_bps between 0 and 10000
and commission_tax_rate_bps between 0 and 10000)
)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,subscription_id → public.ev1_subscriptions(tenant_id,id); tenant_id,session_id → public.ev1_fleet_sessions(tenant_id,id); tenant_id,payment_method_id → public.ev1_payment_methods(tenant_id,id)

### public.ev1_payment_attempts

מקור: supabase/migrations/20261110203000_hyp_billing_foundation.sql. היקף: tenant.

| שדה                         | הגדרת SQL                                                                                                                    |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| id                          | uuid primary key default gen_random_uuid()                                                                                   |
| tenant_id                   | uuid not null references public.ev1_tenants(id)                                                                              |
| obligation_id               | uuid not null                                                                                                                |
| provider                    | text not null default 'hyp' check (provider='hyp')                                                                           |
| action                      | text not null check (action in ('checkout','card_verification','token_charge'))                                              |
| status                      | text not null default 'created' check (status in ('created','pending_customer','processing','succeeded','failed','unknown')) |
| idempotency_key             | uuid not null                                                                                                                |
| attempt_no                  | integer not null default 1 check (attempt_no > 0)                                                                            |
| amount_minor                | bigint not null check (amount_minor > 0 and amount_minor <= 100000000)                                                       |
| provider_payment_ref        | text                                                                                                                         |
| provider_authorization_code | text                                                                                                                         |
| provider_code               | text                                                                                                                         |
| provider_message            | text                                                                                                                         |
| provider_brand              | text                                                                                                                         |
| provider_last_four          | text check (provider_last_four is null or provider_last_four \~ '^\[0-9]{4}$')                                               |
| provider_expiry_month       | integer check (provider_expiry_month is null or provider_expiry_month between 1 and 12)                                      |
| provider_expiry_year        | integer check (provider_expiry_year is null or provider_expiry_year between 2020 and 2100)                                   |
| provider_document_ref       | text                                                                                                                         |
| redirect_verified           | boolean not null default false                                                                                               |
| created_at                  | timestamptz not null default now()                                                                                           |
| verified_at                 | timestamptz                                                                                                                  |
| completed_at                | timestamptz                                                                                                                  |

אילוצים: unique (tenant_id,id); unique (tenant_id,idempotency_key); foreign key (tenant_id,obligation_id)
references public.ev1_billing_obligations(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,obligation_id → public.ev1_billing_obligations(tenant_id,id)

### public.ev1_financial_documents

מקור: supabase/migrations/20261110203000_hyp_billing_foundation.sql. היקף: tenant.

| שדה                   | הגדרת SQL                                                                                    |
| --------------------- | -------------------------------------------------------------------------------------------- |
| id                    | uuid primary key default gen_random_uuid()                                                   |
| tenant_id             | uuid not null references public.ev1_tenants(id)                                              |
| obligation_id         | uuid not null                                                                                |
| payment_attempt_id    | uuid not null                                                                                |
| provider              | text not null default 'hyp' check (provider='hyp')                                           |
| document_type         | text not null check (document_type in ('invoice_receipt','receipt','credit_note','unknown')) |
| provider_document_ref | text not null check (length(provider_document_ref) between 1 and 120)                        |
| amount_minor          | bigint not null check (amount_minor >= 0 and amount_minor <= 100000000)                      |
| currency              | text not null default 'ILS' check (currency='ILS')                                           |
| status                | text not null default 'issued' check (status in ('issued','pending','failed','void'))        |
| issued_at             | timestamptz not null default now()                                                           |
| created_at            | timestamptz not null default now()                                                           |

אילוצים: unique (tenant_id,id); unique (provider,provider_document_ref); foreign key (tenant_id,obligation_id)
references public.ev1_billing_obligations(tenant_id,id); foreign key (tenant_id,payment_attempt_id)
references public.ev1_payment_attempts(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,obligation_id → public.ev1_billing_obligations(tenant_id,id); tenant_id,payment_attempt_id → public.ev1_payment_attempts(tenant_id,id)

### public.ev1_refunds

מקור: supabase/migrations/20261110203000_hyp_billing_foundation.sql. היקף: tenant.

| שדה                | הגדרת SQL                                                                                    |
| ------------------ | -------------------------------------------------------------------------------------------- |
| id                 | uuid primary key default gen_random_uuid()                                                   |
| tenant_id          | uuid not null references public.ev1_tenants(id)                                              |
| payment_attempt_id | uuid not null                                                                                |
| idempotency_key    | uuid not null                                                                                |
| provider           | text not null default 'hyp' check (provider='hyp')                                           |
| provider_ref       | text                                                                                         |
| amount_minor       | bigint not null check (amount_minor > 0 and amount_minor <= 100000000)                       |
| status             | text not null default 'pending' check (status in ('pending','succeeded','failed','unknown')) |
| provider_code      | text                                                                                         |
| provider_message   | text                                                                                         |
| document_ref       | text                                                                                         |
| created_at         | timestamptz not null default now()                                                           |
| completed_at       | timestamptz                                                                                  |

אילוצים: unique (tenant_id,id); unique (tenant_id,idempotency_key); foreign key (tenant_id,payment_attempt_id)
references public.ev1_payment_attempts(tenant_id,id)

קשרים: tenant_id → public.ev1_tenants(id); tenant_id,payment_attempt_id → public.ev1_payment_attempts(tenant_id,id)

### public.lne_account_deletion_requests

מקור: supabase/migrations/20261111155528_mobile_onboarding_and_deletion_requests.sql. היקף: catalog.

| שדה               | הגדרת SQL                                                                                 |
| ----------------- | ----------------------------------------------------------------------------------------- |
| id                | uuid primary key default gen_random_uuid()                                                |
| clerk_user_id     | text not null check (clerk_user_id \~ '^user\_\[A-Za-z0-9]{5,100}$')                      |
| status            | text not null default 'requested' check (status in ('requested','in_review','completed')) |
| requested_at      | timestamptz not null default now()                                                        |
| updated_at        | timestamptz not null default now()                                                        |
| completed_at      | timestamptz                                                                               |
| retention_summary | text check (retention_summary is null or length(retention_summary) <= 2000)               |

אילוצים: constraint lne_deletion_completed_state check (
(status = 'completed') = (completed_at is not null)
)

קשרים:

### public.lne_clerk_org_provision_claims

מקור: supabase/migrations/20261111161830_clerk_org_provision_claims.sql. היקף: tenant.

| שדה           | הגדרת SQL                                                                         |
| ------------- | --------------------------------------------------------------------------------- |
| tenant_id     | uuid primary key references public.ev1_tenants(id)                                |
| owner_user_id | text not null check (length(owner_user_id) > 0)                                   |
| status        | text not null default 'creating' check (status in ('creating', 'linked'))         |
| clerk_org_id  | text check (clerk_org_id is null or clerk_org_id \~ '^org\_\[A-Za-z0-9]{5,100}$') |
| created_at    | timestamptz not null default now()                                                |
| updated_at    | timestamptz not null default now()                                                |

אילוצים: constraint lne_org_claim_linked_state check (
(status = 'linked') = (clerk_org_id is not null)
)

קשרים: tenant_id → public.ev1_tenants(id)

### ev1_private.charging_fee_queue

מקור: supabase/migrations/20261121230000_uniform_charging_commission.sql. היקף: private.

| שדה                  | הגדרת SQL                                                                                                                  |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| tenant_id            | uuid not null                                                                                                              |
| session_id           | uuid not null                                                                                                              |
| policy_version       | text not null default '1.4.0' check(policy_version='1.4.0')                                                                |
| provider_gross_minor | bigint check(provider_gross_minor between 0 and 100000000)                                                                 |
| status               | text not null check(status in ('waiting_completion','pending','waiting_payment','created','no_charge','ignored','review')) |
| obligation_id        | uuid                                                                                                                       |
| attempts             | integer not null default 0 check(attempts>=0)                                                                              |
| last_error_code      | text                                                                                                                       |
| next_attempt_at      | timestamptz not null default now()                                                                                         |
| created_at           | timestamptz not null default now()                                                                                         |
| updated_at           | timestamptz not null default now()                                                                                         |

אילוצים: primary key(tenant_id,session_id); foreign key(tenant_id,session_id) references public.ev1_fleet_sessions(tenant_id,id) on delete cascade; foreign key(tenant_id,obligation_id) references public.ev1_billing_obligations(tenant_id,id); check((status='created')=(obligation_id is not null))

קשרים: tenant_id,session_id → public.ev1_fleet_sessions(tenant_id,id); tenant_id,obligation_id → public.ev1_billing_obligations(tenant_id,id)
