תפעול החברה
טיוטה: ניהול ואוטומציה
מפרט מוצע לתפעול החברה, תורים חריגים, תפקידים ותהליכים אוטומטיים.
בעמוד הזה
Status: proposed implementation specification, 21 November 2026. This document changes no runtime behavior, permissions, screens or assets. The source inventory covers the current Development work; source availability is not evidence of a configured or deployed integration.
1. Operating model#
Build a company that processes routine work automatically and gives three human roles a small, actionable exception queue: CEO, operations manager and external accountant. Automation owns execution within approved policies. Humans own commercial commitments, policy changes, accounting judgments and exceptional outcomes. The objective is fewer interventions per completed customer journey, with measured reliability and recoverability.
Every automated outcome must answer: what happened, for which customer, under which rule, against which evidence, and how can it be corrected? Missing evidence produces a pending or exception state. It must not produce a fabricated successful payment, connected supplier or completed deletion.
The internal admin is the operational control plane. Customer fleet administration remains in the existing product. The first internal release should expose operational evidence and bounded recovery actions before adding broader autonomous agents.
2. Existing foundations and actual gaps#
| Area | Available in repository | Gap before an operational company admin |
|---|---|---|
| Surface isolation | Server-selected APP_SURFACE=website/product/admin; admin currently exposes its closed entry page and limited public infrastructure routes | Staff authentication, staff authorization, internal APIs and operational screens |
| Customer workspace | Fleet, drivers, providers, policy, energy, billing, team and tenant audit routes | Cross-company operational views must use separate staff access, never reuse customer admin authority |
| Billing | HYP checkout and renewal service, atomic attempts/refund reservation, recovery and reconciliation listing | Verified provider configuration, scheduled execution, operational exception ownership and settlement evidence |
| Provider integration | Typed adapter contract, explicit registration, authorization boundary and deterministic sandbox adapter | First certified supplier connection, real processors, reconciled transactions and verified command capabilities |
| Jobs | BullMQ queues for provider sync, webhook reconciliation and billing reconciliation; bounded retries and deterministic enqueue IDs | Production business processors and durable operation ledgers; the Railway worker currently processes system-smoke only |
| Identity | Clerk organization provisioning; new Development session-policy, verified webhook and lifecycle worker code | Deployment configuration, customer IdP/SCIM activation, staff-specific policy and real end-to-end evidence |
| Privacy/support | Authenticated account deletion request queue; private company contact submissions | Full deletion fulfillment, support case management and approved notification delivery |
| Audit | Tenant mutation audit events and restricted tenant audit reads | Company operation audit, approval history, export controls and retention implementation |
Sources: surface rules, closed company admin, customer routes, billing service, billing safety migration, provider boundary, queue contracts, smoke worker, identity webhook, identity worker, deletion workflow.
3. Company access boundary#
Preserve the existing three surfaces and approved visual state. APP_SURFACE selects a deployment surface; it is not a staff permission. A customer owner, admin, Clerk organization role or verified email domain must never grant company access.
Introduce a server-owned staff membership registry with explicit, revocable grants. Every internal endpoint checks staff status, session assurance, operation permission and resource scope. Staff authentication configuration must be separate from customer tenant policy. Require strong MFA for staff; connect a staff IdP when available. Device biometrics can protect the local device but cannot replace server verification.
The operations manager receives customer health and necessary case metadata. Access to detailed customer information requires a recorded purpose and a short-lived, tenant-scoped support grant. There is no default customer impersonation or unrestricted database console. The accountant receives finance records and exports, with customer fleet/location data excluded unless explicitly necessary. CEO access includes policy and approval authority; routine support access is still audited.
Service identities receive named commands and minimum data access for their jobs. A provider sync identity cannot refund payments, and a billing identity cannot grant staff privileges. AI agents receive constrained tools, never browser-exposed service keys or arbitrary SQL. Customer text, provider payloads and uploaded documents are untrusted data, never operational instructions.
4. Module map#
All modules below are proposed internal capabilities. Existing customer screens remain in place.
| Module | Purpose and primary actions | Automation / human owner |
|---|---|---|
| Company overview — תמונת מצב | Service health, backlog, cash collection, unresolved risk, customer activation funnel | Aggregate continuously; CEO reviews trends |
| Exception queue — חריגים לטיפול | One case per unresolved operation, evidence, impact, owner, next action and retry eligibility | Deduplicate and prioritize; operations resolves exceptions |
| Customers and subscriptions — לקוחות ומנויים | Tenant lifecycle, entitlements, onboarding state, renewal/cancellation and commercial exceptions | Standard lifecycle automatic; bespoke terms need CEO approval |
| Suppliers and connections — ספקים וחיבורים | Capability matrix, credentials expiry metadata, consent, sync freshness and certification state | Refresh approved feeds; operations manages certification and incidents |
| Energy reconciliation — התאמת עסקאות אנרגיה | Match supplier transaction, vehicle, tenant, session, tariff and invoice; show provenance | Deterministic matching; ambiguous ownership or amount enters review |
| Finance — חיובים והתחשבנות | Obligations, attempts, collections, refunds, supplier settlement, document references and closing exports | Existing safe state machines; accountant owns closing and classification |
| Service and customer care — שירות ותמיכה | Contact/deletion requests, support history, verified notifications and incident communication | Approved templates and case routing; operations handles exceptions |
| Identity and security — זהות ואבטחה | Staff grants, tenant assurance status, lifecycle failures, revocation evidence and access reviews | Immediate defensive denial; privileged restoration requires approval |
| Automation operations — אוטומציות | Workflow versions, schedules, leases, retries, dead letters, pause switches and run history | Workers execute; operations controls bounded recovery |
| Commercial analytics — כלכלת יחידה | Revenue definitions, margin, acquisition/servicing cost, retention and supplier concentration | Reproducible calculations; CEO and accountant approve definitions |
| Governance and documents — בקרה ומסמכים | Agreements, policy versions, retention schedules, consent evidence and audit exports | Reminders and evidence collection; authorized humans approve commitments |
5. End-to-end workflows#
Customer activation#
- Verify identity and consent, create/recover the tenant idempotently, and provision the correct organization relationship for Business/Enterprise.
- Apply commercial entitlements independently of identity roles. Provisioning retries must not create a second tenant or organization.
- Collect the customer's provider selections and record what is merely selected versus technically connected.
- Activate paid capabilities only after verified billing evidence and required tenant policy checks. Uncertain steps remain recoverable pending operations.
- Route prolonged pending activation to one exception case. Customer communication uses an approved template and verified destination when a delivery integration is activated.
Supplier data to financial evidence#
Fetch only authorized provider capabilities, with bounded pages and durable checkpoints. Validate source IDs, timestamps, currency and integer quantities. Preserve the original provenance and canonical transaction reference; deduplicate by provider, customer scope and external event identity.
Match against the customer's vehicles and existing sessions. Imported customer files remain distinguishable from supplier-verified events. Unmatched vehicles, conflicting duplicates, missing tariff evidence and unusual amounts enter the exception queue. Only verified, nonconflicting records can produce commission obligations. Supplier settlement needs its own verified statement/payment evidence; customer collection alone does not prove settlement.
No live connector is implied by this workflow. The current adapter boundary is read-only; charging start/stop or fuel authorization needs a separately verified command contract and durable idempotency controls.
Billing and collection#
Reuse existing obligations, attempts, atomic reservations and reconciliation states. Due work obtains a database claim before calling HYP. Confirmed provider results update the authoritative ledger. Lost responses, timeouts after dispatch or uncertain persistence remain on hold and are reconciled before another charge or refund is considered.
A general queue retry must never blindly resend a financial command. Automated reminders and collection schedules need approved policies and verified delivery. Refund authority is configured explicitly; the current refund enablement flag is not an authorization decision. Closing exports reconcile opening balance, obligations, collections, refunds, adjustments and closing balance, with discrepancies visible to the accountant.
Employee and account lifecycle#
Verify webhook signatures and instance identity; apply organization/user scope checks, ordering rules and idempotent processing. Organization removal blocks that organization's access without automatically revoking access to unrelated tenants. Global bans/deprovisioning can require account-wide session revocation. Reconciliation detects missed events, with stale observations unable to restore revoked access.
Deletion requests become a controlled workflow: verify request identity, resolve tenant ownership, stop applicable future billing, determine required retained records, erase eligible data across processors, verify completion and notify the requester. The existing request queue does not implement this entire workflow. Restoration, ownership disputes and retention exceptions require a human decision.
6. Exceptions, approvals and escalation#
An exception contains an immutable operation reference, environment, tenant/provider scope, category, severity, first/last occurrence, evidence links, attempts, assigned role and allowed next actions. Identical retries update the same case. Cases close only when a verified terminal result or documented compensating action exists.
| Situation | Automatic behavior | Decision owner |
|---|---|---|
| Read-only transient provider failure | Retry with bounded backoff, checkpoint and circuit breaker | Operations after retry exhaustion |
| Uncertain charge/refund result | Hold funds/attempt state, reconcile; block duplicate dispatch | Operations gathers evidence; accountant resolves finance discrepancy |
| Refund within an approved policy | Execute only when evidence, budget and permission all match | Operations within delegated limit; CEO above limit |
| New supplier, contract or price override | Prepare review package; keep capability disabled | CEO; accountant reviews financial treatment |
| Suspicious identity or revoked employee | Deny affected access, record evidence and notify designated staff | Operations investigates; CEO approves privileged restoration |
| Staff privilege, payout destination or automation spending-limit change | Require fresh assurance and independent approval; audit before/after | CEO plus a second authorized reviewer |
| Retention conflict or account ownership dispute | Pause irreversible deletion, preserve case evidence | CEO with accountant where finance records are involved |
Approval binds to the exact command, version, resource and maximum amount; it expires and cannot authorize a different payload. The proposer cannot approve their own high-impact change. If only one authorized person is available, hold the operation. Initial limits, support hours and escalation deadlines must be agreed before activation; this document does not invent spending authority or round-the-clock staffing.
Critical security events page operations with CEO as backup. Routine exceptions are grouped into a daily work list. The accountant receives a scheduled closing packet and unresolved finance cases. Notification routes require verified delivery and an escalation fallback; a failed notification must itself remain observable.
7. Execution and data contracts#
Use Supabase/Postgres as the authoritative state; Redis holds queue/cache state. Record business state and outbox intent atomically. Queue delivery is at least once; each consumer produces idempotent effects using durable uniqueness constraints and operation state. An opaque BullMQ job ID alone is insufficient once queue retention removes the job.
Proposed shared records:
- Operation: operation ID, schema/workflow version, environment, tenant/provider, actor/service identity, correlation/causation IDs, canonical idempotency key, request digest and status.
- Execution: attempt, claim/lease token, start/end times, checkpoint, outcome classification, provider reference and retry deadline. Stale leases cannot finalize newer work.
- Approval: exact operation digest, approver, authority scope, amount/currency ceiling, expiry and consumption state.
- Exception: typed reason, safe evidence references, owner, severity, resolution and linked executions.
- Audit: actor, assurance context, purpose, target, rule version, result and approved redacted before/after values. Exports are permission-checked and themselves audited.
Keep money in integer minor units and energy/fuel quantities in their existing milli-unit conventions. Currency is mandatory. Store UTC instants and retain the customer timezone for reporting periods. Never place payment tokens, provider secrets or raw sensitive webhook bodies in queue payloads, logs or AI prompts.
Retries distinguish safe reads, definitely unsubmitted writes and uncertain external effects. Use bounded attempts, jitter, dead letters and provider circuit breakers. Workflow changes are versioned; pause by tenant/provider/workflow without losing evidence. Compensation creates a new linked operation rather than rewriting history. AI may classify, summarize and propose actions; execution still passes deterministic authorization, schema, budget and approval checks.
8. Control center and unit economics#
Show confirmed values, pending values and freshness separately. Core operational measures are oldest unprocessed event, sync lag, retry/dead-letter count, reconciliation age, unknown payment/refund exposure, onboarding completion, revocation lag and exceptions per completed workflow.
Commercial measures include recurring subscription revenue, recognized commissions, churn, collection success, supplier cost, payment/identity/infrastructure cost per active customer and contribution margin. Do not equate gross energy payments with company revenue. The accountant approves revenue recognition, taxes and pass-through treatment before these definitions drive management reporting.
Measure automation coverage alongside error and reopening rates. A high automatically closed percentage is unhealthy if cases later reopen or financial mismatches grow. Report customer-impacting failures and total financial exposure, not just worker uptime. Initial service targets are set from pilot measurements and then versioned as operational policy.
9. Delivery sequence and acceptance#
- Finish Development readiness: isolated Clerk/API/database, tenant assurance and lifecycle tests, provider sandbox, billing reconciliation tests, signed-device identity QA and release gates. External Apple/IdP/provider dependencies remain explicit blockers.
- Final mobile UI/design: only the user's approved scoped changes; retain working flows and assets. Validate accessibility, RTL, loading/error states and physical-device behavior.
- Finish website: complete agreed content, legal/customer journeys and verified form routing while preserving surface separation.
- Internal admin foundation: staff identity, permissions and audit; read-only overview plus exception inbox. Prove customer administrators cannot enter.
- Bounded operations: ship one workflow at a time, starting with onboarding/lifecycle reconciliation and billing exception visibility. Add approved recovery commands and notification delivery.
- Supplier and finance automation: certify the first supplier, prove ingestion/reconciliation, then settlement and accounting exports. Expand autonomous execution only from observed success and explicit policies.
Acceptance for each executable workflow: two-tenant isolation and staff-role denial tests pass; duplicate/out-of-order events do not duplicate effects; crash/retry and lease races are exercised; unknown financial outcomes stay held; every command and approval is traceable; secrets stay out of client/log/export surfaces; pause and recovery are demonstrated; failure produces one owned exception; and environment, configuration, deployment and live verification status are documented separately.
This sequence preserves the approved product while making automation an accountable part of the business, with human attention concentrated on the decisions that actually require it.