Merge remote-tracking branch 'origin/dev' into staff_recurring_permanent_order

This commit is contained in:
José Salazar
2026-02-19 14:56:59 -05:00

View File

@@ -0,0 +1,183 @@
# Backend Cloud Run / Functions Guide
## 1) Validate Shift Acceptance (Worker)
**Best fit:** Cloud Run
**Why backend logic is required**
- Shift acceptance must be enforced serverside to prevent bypassing the client.
- It must be racecondition safe (two accepts at the same time).
- It needs to be extensible for future eligibility rules.
**Proposed backend solution**
Add a single command endpoint:
- `POST /shifts/:shiftId/accept`
**Backend flow**
- Verify Firebase Auth token + permissions (worker identity).
- Run an extensible validation pipeline (pluggable rules):
- `NoOverlapRule` (M4)
- Future rules can be added without changing core logic.
- Apply acceptance in a DB transaction (atomic).
- Return a clear error payload on rejection:
- `409 CONFLICT` (overlap) with `{ code, message, conflictingShiftIds }`
---
## 2) Validate Shift Creation by a Client (Minimum Hours — soft check)
**Best fit:** Cloud Run
**Why backend logic is required**
- Creation rules must be enforced serverside so clients cant bypass validations by skipping the UI or calling APIs directly.
- We want a scalable rule system so new creation checks can be added without rewriting core logic.
**Proposed backend solution**
Add/route creation through a backend validation layer (Cloud Run endpoint or a dedicated “create order” command).
**On create**
- Compute shift duration and compare against vendor minimum (current: **5 hours**).
- Return a consistent validation response when below minimum, e.g.:
- `200 OK` with `{ valid: false, severity: "SOFT", code: "MIN_HOURS", message, minHours: 5 }`
- (or `400` only if we decide it should block creation; for now its a soft check)
**FE note**
- Show the same message before submission (UX feedback), but backend remains the source of truth.
---
## 3) Enforce Cancellation Policy (no cancellations within 24 hours)
**Best fit:** Cloud Run
**Why backend logic is required**
- Cancellation restrictions must be enforced serverside to prevent policy bypass.
- Ensures consistent behavior across web/mobile and future clients.
**Proposed backend solution**
Add a backend command endpoint for cancel:
- `POST /shifts/:shiftId/cancel` (or `/orders/:id/cancel` depending on ownership model)
**Backend checks**
- If `now >= shiftStart - 24h`, reject cancellation.
**Error response**
- `403 FORBIDDEN` (or `409 CONFLICT`) with `{ code: "CANCEL_WINDOW_LOCKED", message, windowHours: 24, penalty: <TBD> }`
- Once penalty is finalized, include it in the response and logs/audit trail.
---
## 4) Implement Worker Documentation Upload Process
**Best fit:** Cloud Functions v2 + Cloud Storage
**Why backend logic is required**
- Uploads must be stored securely and reliably linked to the correct worker profile.
- Requires serverside auth and auditing.
**Proposed backend solution**
- HTTP/Callable Function: `uploadInit(workerId, docType)` → returns signed upload URL + `documentId`.
- Client uploads directly to Cloud Storage.
- Storage trigger (`onFinalize`) or `uploadComplete(documentId)`:
- Validate uploader identity/ownership.
- Store metadata in DB (type, path, status, timestamps).
- Link document to worker profile.
- Enforce access control (worker/self, admins, authorized client reviewers).
---
## 5) Parse Uploaded Documentation for Verification
**Best fit:** Cloud Functions (eventdriven) or Cloud Run worker (async)
**Why backend logic is required**
- Parsing should run asynchronously.
- Store structured results for review while keeping manual verification as the final authority.
**Proposed backend solution**
- Trigger on Storage upload finalize:
- OCR/AI extract key fields → store structured output (`parsedFields`, `confidence`, `aiStatus`).
- Keep manual review:
- Client can approve/override AI results.
- Persist reviewer decision + audit trail.
---
## 6) Support Attire Upload for Workers
**Best fit:** Cloud Functions v2 + Cloud Storage
**Why backend logic is required**
- Attire images must be securely stored and linked to the correct worker profile.
- Requires serverside authorization.
**Proposed backend solution**
- HTTP/Callable Function: `attireUploadInit(workerId)` → signed upload URL + `attireAssetId`.
- Client uploads to Cloud Storage.
- Storage trigger (`onFinalize`) or `attireUploadComplete(attireAssetId)`:
- Validate identity/ownership.
- Store metadata and link to worker profile.
---
## 7) Verify Attire Images Against Shift Dress Code
**Best fit:** Cloud Functions (trigger) or Cloud Run worker (async)
**Why backend logic is required**
- Verification must be enforced serverside.
- Must remain reviewable/overrideable by the client even if AI passes.
**Proposed backend solution**
- Async verification triggered after upload or when tied to a shift:
- Evaluate dress code rules (and optional AI).
- Store results `{ status, reasons, evidence, confidence }`.
- Client can manually approve/override; audit every decision.
---
## 8) Support Shifts Requiring “Awaiting Confirmation” Status
**Best fit:** Cloud Run (domain state transitions)
**Why backend logic is required**
- State transitions must be enforced serverside.
- Prevent invalid bookings and support future workflow rules.
**Proposed backend solution**
- Add status flow: `AWAITING_CONFIRMATION → BOOKED/ACTIVE` (per lifecycle).
- Command endpoint: `POST /shifts/:id/confirm`.
**Backend validates**
- Caller is the assigned worker.
- Shift is still eligible (not started/canceled/overlapped, etc.).
- Persist transition + audit event.
---
## 9) Enable NFCBased ClockIn and ClockOut
**Best fit:** Cloud Run (secure API) + optional Cloud Functions for downstream events
**Why backend logic is required**
- Clockin/out is securitysensitive and must be validated serverside.
- Requires strong auditing and antifraud checks.
**Proposed backend solution**
API endpoints:
- `POST /attendance/clock-in`
- `POST /attendance/clock-out`
**Validate**
- Firebase identity.
- NFC tag legitimacy (mapped to hub/location).
- Time window rules + prevent duplicates/inconsistent sequences.
**Persist**
- Store immutable events + derived attendance record.
- Emit audit logs/alerts if needed.
---
## 10) Update Recurring & Permanent Orders (Backend)
**Best fit:** Cloud Run
**Why backend logic is required**
Updating a recurring or permanent order is not a single update. It may affect **N shifts** and **M shift roles**, and requires extra validations, such as:
- Prevent editing shifts that already started.
- Prevent removing or reducing roles with assigned staff.
- Control whether changes apply to future only, from a given date, or all.
- Ensure data consistency (allornothing updates).
These operations can take time and must be enforced serverside, even if the client is bypassed.