Skip to content

Project codespace compatibility#4

Open
Mqhele-dot wants to merge 195 commits into
mainfrom
cursor/project-codespace-compatibility-b14c
Open

Project codespace compatibility#4
Mqhele-dot wants to merge 195 commits into
mainfrom
cursor/project-codespace-compatibility-b14c

Conversation

@Mqhele-dot
Copy link
Copy Markdown
Owner

Add GitHub Codespaces support by restoring project files, configuring the devcontainer, and fixing environment-specific runtime issues.

The repository's main branch was found to be empty, necessitating a restoration of the last complete project snapshot. Furthermore, the original project contained Replit-specific configurations, including a Neon WebSocket database driver and hardcoded hostnames, which prevented it from running correctly in a standard Codespaces environment. This PR addresses these issues to ensure seamless operation.


Open in Cursor Open in Web

cursoragent and others added 3 commits February 13, 2026 08:06
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
@cursor
Copy link
Copy Markdown

cursor Bot commented Feb 13, 2026

Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch.
Learn more about Cursor Agents

cursoragent and others added 26 commits February 13, 2026 19:52
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
…ceptions

Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
…tions

Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
…_URL

Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
…cript

Co-authored-by: Mqhele-dot <Mqhele-dot@users.noreply.github.com>
Mqhele Sithole and others added 7 commits May 16, 2026 19:10
Standardize legacy procurement routes on sendOk/sendError, align logistics list filters via shared normalization (meta.appliedFilters vs client query), harden KPI deeplink script with test-http CSRF login, and document memStorage Tier-B plus production PO email warning.

Co-authored-by: Cursor <cursoragent@cursor.com>
fix(test): return after fatal exitTest in procurement flow script

- Run ALTER TYPE user_role ADD VALUE for planner so db:seed succeeds on older DBs
- Stop main() after exitTest(1) to avoid reading undefined inventory rows
- Unwrap GET /api/user envelope for createdBy

Co-authored-by: Cursor <cursoragent@cursor.com>
- Add purchase_orders.currency_code (schema, migration, seed ZAR, validation on commercial PATCH)
- Register PO list routes before operational mount so /records is not captured by /:po
- Extend PO detail commercial UI, master-data cache invalidation, diagnostics buffer
- Client: PurchaseOrderRecordSummary.currencyCode normalization
- Tests: purchase-order-endpoints currency assertion; functional-audit adjustments

Co-authored-by: Cursor <cursoragent@cursor.com>
…al_exceptions; CI smoke and reports e2e

- Unwrap POST purchase-requisition and convert responses in test-procurement-flow and test-ap-workflow; clearer truncated JSON errors
- register-analytics-routes: query operational_exceptions (not ops_exceptions)
- test-smoke: assert GET /api/reports/analytics returns exceptionSummary array
- e2e/reports: match inventory preview header (filtered rows + total value)
- Include prior branch work: billing invoices, reference banners, analytics shell/KPI registry, reports charts/load-more, PO signed PDF currency, requisition date/tests, training panel, operations-routes

Co-authored-by: Cursor <cursoragent@cursor.com>
…on script

Co-authored-by: Cursor <cursoragent@cursor.com>
… RBAC catalog

- Receive: validate putaway from warehouse master data; wire inventory adjustment and movements/batches/serials to resolved warehouse_id
- AP: admin-only submit/approve/reject; withdraw PENDING_APPROVAL to DRAFT; admin bypass configured approver user ID; audit action for withdraw
- RBAC: GET /api/rbac/permission-catalog; Role Manager search + collapsible groups from catalog
- Plus: shared master currency fetch, supplier portal/PO commercial term alignment where touched

Co-authored-by: Cursor <cursoragent@cursor.com>
… currency, requisitions)

- AP: validate policy approver user; map policy errors to 4xx on invoice/batch routes

- Invoices: domain invalidation + PO when linked

- PO: shipment-aware send/receive client and receive panel wiring

- PDF: format PO amounts in order currency with fallback

- Reports: canonical query key for procurement PO records

- Requisitions: commercial hint card, master fetches; convert copies dept + supplier currency

- Approval policies: invalidate approval-suggestions queries

- Master data integration migration, evidence doc, and test script

Co-authored-by: Cursor <cursoragent@cursor.com>
Copy link
Copy Markdown
Owner Author

Logistics integration audit required

User feedback: the logistics module still does not make business sense as an end-to-end workflow. The app has a Logistics page, but the structure feels disconnected: users need to be able to create/manage deliveries/shipments from POs, capture transport details, link shipments to receiving, and see logistics reflected in POs, inventory, AP, analytics, and reports.

Current repo evidence to inspect

  • client/src/pages/logistics.tsx
  • client/src/features/purchase-orders/api/operational-purchase-orders.api.ts
  • client/src/features/purchase-orders/hooks/use-purchase-order-mutations.ts
  • server/modules/operations/operations-core.ts
  • server/modules/operations/register-operations-routes.ts
  • server/operations-routes.ts
  • shared/schema.ts
  • scripts/test-logistics-filters.ts
  • scripts/test-purchase-order-endpoints.ts

Key questions

  1. Can a user create a delivery/shipment from an approved/sent PO?
  2. Can a user capture carrier, carrier ID, transport mode, freight cost, tracking number, delivery note reference, vehicle, driver, ETA, and status?
  3. Can logistics be initiated from the PO send action and also from the Logistics page?
  4. Can receiving link to a shipment/delivery note through shipmentId?
  5. Does receiving update PO, inventory, shipment status, AP matching readiness, analytics, and reports?
  6. Are carriers treated as master data and connected to logistics forms?
  7. Are warehouses/bins and shipment/delivery details visible where receiving happens?
  8. Do logistics mutations use invalidateLogisticsDomain() and refresh POs, inventory, analytics, reports, and control tower?
  9. Are users shown clear workflow states such as planned, in transit, delivered, received, delayed, cancelled?
  10. Do logistics tests prove the full workflow, not only filters?

Required build plan

  • Audit the full logistics data flow: PO approval/send → shipment creation → transport tracking → delivery note → receive against shipment → inventory update → AP match readiness → reports/analytics.
  • Separate shipment, delivery, delivery note, and goods receipt concepts if the schema currently mixes them.
  • Add missing UI for delivery/shipment creation if the current form is too basic.
  • Connect carriers and warehouses from Master Data.
  • Ensure PO send can create/link shipment, and PO receive can select/link an existing shipment.
  • Add tests proving: create shipment from PO, update shipment status, receive against shipment, inventory updates, PO status/received qty updates, logistics reports refresh, and analytics/control tower refresh.

Do not weaken existing tests or release gates. Start with an evidence report before editing.

Copy link
Copy Markdown
Owner Author

Cursor build prompt: fix ERP-style logistics, carriers, deliveries, receipts, and payments

Use the following as the implementation prompt for the next Cursor/Composer pass.

You are working on the ISSSourcing / InvTrack repo.

Goal:
Fix the logistics module so it behaves like a real basic ERP logistics workflow, not just a loose shipment table. The current build has partial shipment tracking, but the business process is incomplete and inconsistent.

Do not start by editing code.
First inspect the actual repo files and produce an evidence report.
Then implement in small phases.
Do not weaken tests or release gates.
Do not remove existing passing functionality.
Do not add Kafka, Redis, SSE, WebSockets, CQRS, or event bus in this pass.
Keep the implementation relational, testable, and compatible with the current Node/Express + React/TanStack Query app.

Current problem summary:
1. Logistics currently feels like PO shipment tracking, not full logistics.
2. Direct Logistics page shipment creation is too thin: PO number, carrier, ETA, tracking only.
3. PO send can create richer shipment data than the Logistics page can, causing inconsistent shipment creation paths.
4. Carrier is sometimes a text field and sometimes an ID. This causes weak data quality.
5. Carriers should be connected to supplier/business-partner/service-provider master data, not isolated free text.
6. Shipments/deliveries do not clearly differentiate inbound, outbound, transfer, and return flows.
7. Receiving stock is stronger than delivery creation, but receiving should link clearly to shipment/delivery note/GRN.
8. There is no clear outbound delivery/dispatch workflow.
9. Carrier/freight payment flow is not clearly modeled.
10. Reports, analytics, control tower, AP, inventory, and PO screens must reflect delivery and receipt updates.

Business target:
Upgrade from:
PO shipment tracking

to:
ERP-style inbound/outbound delivery management.

Use this conceptual model:

Master Data:
- parties / business partners where possible
- suppliers
- carriers / logistics service providers
- carrier profiles
- warehouses
- transport modes
- payment terms
- currencies
- tax codes

Operational documents:
- purchase order
- delivery order / shipment
- delivery order lines
- shipment events / delivery timeline
- goods receipt / GRN
- stock movements
- supplier invoice
- carrier/freight invoice where possible
- payment records / payment batches

Core ERP-like flows to support:

Inbound purchase flow:
Purchase Order
→ Send/confirm PO
→ Create inbound shipment/delivery
→ Capture carrier/transport/tracking/ETA/delivery note
→ Receive goods against shipment/delivery note
→ Create or update GRN/receipt
→ Update inventory and stock movements
→ Enable AP 3-way match
→ Supplier invoice approval/payment
→ Reports/analytics/control tower update

Outbound flow, if the app has customer/sales/order concepts:
Inventory
→ Pick/pack/dispatch
→ Outbound delivery
→ Carrier/tracking/POD
→ Stock issue movement
→ Customer invoice/payment if supported

If the app does not yet have sales/customer orders, implement outbound support as a safe foundation only:
- delivery direction = outbound
- source type = manual/transfer/customer_order if supported
- stock movement = ISSUE/DISPATCH
- do not fake sales-order data that does not exist.

Important design decisions:
1. Carriers are not necessarily product suppliers, but they are service providers/business partners.
2. A carrier should have a canonical master record, not only free text on a shipment.
3. Shipments should store both:
   - carrier_id for data integrity
   - carrier_name_snapshot for historical display
4. Transaction documents should snapshot commercial/logistics values at document time.
5. Master data changes should affect new records, not silently mutate closed historical records.
6. Direct Logistics page creation and PO-send shipment creation must use one shared backend service.
7. Receiving must link to shipment/delivery note and produce receipt/stock movement/AP readiness.

Files to inspect first:
- shared/schema.ts
- server/operations-routes.ts
- server/modules/operations/operations-core.ts
- server/modules/operations/operational-ddl.ts
- server/modules/master-data/register-master-data-routes.ts
- server/modules/accounts-payable/service.ts
- server/modules/accounts-payable/register-accounts-payable-routes.ts
- server/modules/procurement/register-procurement-routes.ts
- server/database-storage.ts
- client/src/pages/logistics.tsx
- client/src/api/client.ts
- client/src/features/purchase-orders/api/operational-purchase-orders.api.ts
- client/src/features/purchase-orders/hooks/use-purchase-order-mutations.ts
- client/src/pages/orders/purchase-order-detail-view.tsx
- client/src/pages/orders/po-receive-panel.tsx
- client/src/lib/domain-invalidation.ts
- client/src/lib/query-keys.ts
- scripts/test-logistics-filters.ts
- scripts/test-purchase-order-endpoints.ts
- scripts/test-ap-workflow.ts
- scripts/test-data-propagation.ts if present
- scripts/test-master-data-propagation.ts if present

Evidence report required before editing:
1. Current logistics tables found.
2. Current shipment fields in schema/DDL.
3. Current carrier tables or carrier-like master data found.
4. Whether carriers link to suppliers/parties/business partners or are standalone.
5. Current direct shipment creation route and payload.
6. Current PO-send shipment creation service and payload.
7. Differences between direct shipment create and PO-send shipment create.
8. Current shipment update fields.
9. Current shipment status transitions.
10. Whether direction/type exists: inbound/outbound/transfer/return.
11. Whether delivery order / delivery lines / GRN / receipt records exist separately.
12. How PO receive links to shipmentId.
13. Whether PO receive creates stock movements and AP receipt bridge.
14. Whether outbound stock movement/dispatch exists.
15. Whether carrier/freight invoices or freight costs connect to AP.
16. Which UI fields exist on Logistics page.
17. Which UI fields are missing for a basic logistics workflow.
18. Which mutation invalidations exist after shipment/receive changes.
19. Minimal phased implementation plan.

Phase 1 — Normalize carrier and shipment creation without broad schema rewrite
Objective:
Make direct Logistics page shipment creation and PO-send shipment creation consistent.

Tasks:
1. Create or identify a shared backend function such as createOperationalShipment(input).
2. Both POST /api/logistics/shipments and PO send shipment creation must call this shared function.
3. Validate the PO exists for inbound PO-linked shipments.
4. Save purchase_order_id when source is a PO.
5. Support these fields consistently where schema already supports them:
   - poNumber
   - purchaseOrderId
   - carrierId
   - carrier / carrierNameSnapshot
   - transportMode
   - freightCost
   - trackingNumber
   - deliveryNoteRef
   - vehicle
   - driver
   - eta
   - status
6. If the existing schema only has carrier text, do not fake carrierId. Either add a safe nullable carrier_id field or clearly snapshot carrier name while preserving compatibility.
7. Update client createShipment() to accept the same richer payload.
8. Update Logistics page New Shipment form to expose the same fields as PO-send shipment creation.

Phase 2 — Treat carriers as master data / service providers
Objective:
Carriers should be selectable from master data and not only typed as text.

Tasks:
1. Inspect whether carriers table exists.
2. If it exists, use it consistently.
3. If carriers are currently managed inside logistics only, integrate them with master-data invalidation and query keys.
4. Recommended minimum carrier fields:
   - id
   - code
   - name
   - active
   - contactName/contactEmail/contactPhone if already supported
   - defaultTransportMode if supported
   - paymentTermsId if supported
   - currencyCode if supported
   - taxCodeId if supported
5. Do not force carriers into product suppliers if schema is not ready. Model them as logistics service providers/business partners where possible.
6. Logistics forms should select carrierId and display carrier name.
7. Store carrier name snapshot on shipment for history.
8. If carrier is inactive, prevent new shipment usage but keep old shipment history readable.

Phase 3 — Add delivery direction and source type safely
Objective:
Differentiate incoming vs outgoing stock and delivery types.

Add or use fields if available:
- direction: inbound | outbound | transfer | return
- sourceType: purchase_order | manual | transfer | customer_order | return
- sourceId / sourceRef

Rules:
1. PO-linked shipments default to direction=inbound and sourceType=purchase_order.
2. Manual outbound should only be enabled if there is a safe stock issue path.
3. Transfer should only be enabled if warehouses/locations exist.
4. Do not fake customer/sales order support if the app does not have those modules.
5. UI must show direction clearly.
6. Filters must include direction and source type.

Phase 4 — Strengthen shipment update and status workflow
Objective:
A user must be able to update delivery information after creation.

Update patchShipmentMeta/backend patch route to support existing schema fields:
- carrierId
- carrier / carrierNameSnapshot
- transportMode
- freightCost
- trackingNumber
- deliveryNoteRef
- vehicle
- driver
- eta
- status handled by status endpoint

Improve statuses if compatible:
- planned/created
- booked
- in_transit
- delayed
- delivered
- received
- cancelled
- closed

If changing statuses is risky, preserve existing statuses and add aliases/labels in UI.
Do not break old tests.

Phase 5 — Delivery note, GRN, and receiving linkage
Objective:
Receiving should not feel disconnected from logistics.

Tasks:
1. In PO receive UI, allow selecting an existing shipment/delivery note for that PO.
2. Display shipment carrier/tracking/ETA/deliveryNoteRef while receiving.
3. Backend already accepts shipmentId; preserve validation that shipment must belong to PO.
4. When receiving against shipment:
   - update PO received quantities
   - update inventory positions
   - create stock movement with type RECEIPT
   - update batches/serials if provided
   - update shipment status to delivered or received depending on model
   - create shipment event
   - sync AP receipt bridge
5. If GRN/receipt tables exist, expose GRN number in UI. If they do not exist, use AP receipt bridge/stock movement as current receipt proof and note schema gap.

Phase 6 — Outbound stock foundation
Objective:
Differentiate incoming and outgoing stock movements.

Tasks:
1. Confirm stock_movements supports movement type.
2. Ensure inbound receiving uses RECEIPT.
3. Add or confirm outbound issue/dispatch movement types:
   - ISSUE
   - DISPATCH
   - TRANSFER_OUT
   - TRANSFER_IN
   - RETURN
4. If no sales/customer module exists, only add backend-safe foundation and tests for manual outbound adjustment/dispatch if current product allows it.
5. Do not create fake customer invoices or sales order data.

Phase 7 — Freight/carrier payment foundation
Objective:
Payments should make sense both for goods suppliers and logistics carriers.

Tasks:
1. Existing AP supplier invoice flow should remain for goods suppliers.
2. If freightCost exists on shipment, show it clearly and include currency if available.
3. If accounts payable can handle service invoices, allow carrier freight invoice linkage to shipment/carrier.
4. If not feasible in this pass, add explicit TODO and test coverage that freight cost remains informational and does not enter AP falsely.
5. Do not mix goods supplier invoice and carrier invoice without clear source type.

Phase 8 — Reports, analytics, and control tower propagation
Objective:
Logistics must update the rest of the app.

Tasks:
1. After shipment create/update/delete/status change, call invalidateLogisticsDomain and related domain invalidations.
2. If shipment affects PO, invalidate purchase order domain.
3. If receiving affects inventory/AP, invalidate inventory and invoice/AP domains.
4. Reports should show inbound/outbound/direction where available.
5. Analytics should show logistics status distribution, late risk, carrier performance, inbound/outbound counts.
6. Control tower should show late/no ETA/exception shipments.

Phase 9 — UI restructure
Objective:
Logistics page must make sense to a basic logistics user.

Recommended UI structure:
Tabs:
1. Overview
   - shipments by status
   - late/no ETA/due soon
   - inbound vs outbound counts
   - carrier performance summary
2. Inbound Deliveries
   - PO-linked inbound shipments
   - create inbound shipment from PO
   - receive against shipment
3. Outbound / Dispatch
   - only enable if safe stock issue flow exists
   - otherwise show foundation/coming soon with no fake data
4. Carriers
   - carrier master records
5. Delivery Exceptions
   - late/no ETA/delayed shipments
6. Timeline / Activity
   - shipment events

Forms:
- Create delivery/shipment form with all supported fields.
- Edit delivery info form with all supported editable fields.
- Status update action.
- Delivery note PDF action.
- Receive against shipment action for inbound PO shipments.

Phase 10 — Tests
Add or update tests proving real logistics workflow, not only filters.

Required tests:
1. Create inbound shipment from Logistics page/API with PO and rich transport fields.
2. Create shipment from PO send with same service and same fields.
3. Direct create rejects missing/nonexistent PO for inbound PO shipment.
4. CarrierId/name snapshot is stored/displayed consistently.
5. Update shipment info updates carrier/transport/tracking/delivery note/vehicle/driver/freight where supported.
6. Shipment status transitions work and invalid transitions fail.
7. Receive against shipment updates PO received quantity, inventory, stock movements, shipment event/status, and AP receipt bridge.
8. Inbound/outbound direction appears in filters/UI/API if implemented.
9. Logistics page can create a delivery and then find it through filters.
10. Reports/analytics/control tower queries refetch after logistics mutations.

Suggested commands:
npm run check
npm run build
npm run test:logistics-filters
npm run test:purchase-order-endpoints
npm run test:ap-workflow
npm run test:functional-e2e
npm run verify:release
npm run release:gate:delta

If new scripts are added, run them too.

Final response required:
1. Files inspected.
2. Current logistics model summary.
3. Confirmed gaps.
4. Schema changes, if any.
5. Backend service changes.
6. API route changes.
7. Frontend UI changes.
8. Carrier/master-data changes.
9. Receiving/GRN/AP changes.
10. Outbound/direction changes.
11. Tests added/updated.
12. Tests run and results.
13. Remaining risks.
14. Whether logistics is now basic-ERP coherent.

Acceptance criteria

  • Logistics is no longer just a shipment table.
  • Direct logistics shipment creation and PO-send shipment creation use the same backend logic.
  • Carriers are not free-text-only where carrier master data exists.
  • Inbound vs outbound/transfer/return direction is represented or clearly planned if schema cannot safely support it yet.
  • Receiving can link to shipment/delivery note and update inventory/AP readiness.
  • Tests prove the logistics workflow end-to-end.

Mqhele Sithole and others added 2 commits May 19, 2026 21:16
Single createOperationalShipment path, richer DTOs and PATCH, direction/source DDL and filters, carrier master on forms, receive GRN and cross-domain invalidation; logistics tabs and extended filter tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
Collapsible secondary filters and dialog for new shipments. Single logistics-create-shipment-button on submit; e2e opens More filters for advanced controls.

Co-authored-by: Cursor <cursoragent@cursor.com>
Copy link
Copy Markdown
Owner Author

Security build plan: npm supply-chain and vibe-coded app hardening

This build plan is based on the npm supply-chain hardening research. The goal is to protect ISSSourcing / InvTrack against malicious npm packages, install-script malware, dependency confusion, typosquatting, leaked secrets, poisoned CI, unsafe AI-suggested dependencies, and weak runtime security.

Build objective

Upgrade the app from normal CI security to a stricter supply-chain security posture without breaking development velocity.

Priority outcomes:

  1. Deterministic installs only.
  2. No silent dependency drift.
  3. Dependency changes reviewed before build execution.
  4. Malicious lifecycle scripts detected or blocked.
  5. CI tokens and secrets least-privilege.
  6. GitHub Actions hardened.
  7. SBOM generated on protected builds.
  8. Release artifacts traceable to trusted workflows.
  9. App-layer security tightened for Express/React/Postgres.
  10. AI/vibe-coded dependency additions gated.

Phase 0 — Repo security evidence report

Before editing, inspect:

  • package.json
  • package-lock.json
  • .npmrc if present
  • .github/workflows/*
  • .github/dependabot.yml if present
  • Dockerfile / compose files if present
  • server security middleware files
  • auth/session/RBAC files
  • file upload routes
  • API validation utilities
  • environment/secrets documentation

Report:

  1. Package manager and lockfile type.
  2. Whether CI uses npm ci or unsafe npm install.
  3. Whether any workflows run installs before dependency review/security scanning.
  4. Whether third-party GitHub Actions are pinned to tags or full SHAs.
  5. Current workflow permissions: blocks.
  6. Whether Dependabot/dependency review/security workflows exist.
  7. Whether npm audit, npm audit signatures, SBOM, Snyk/OSV, CodeQL, secret scanning, or container scanning exist.
  8. Whether install lifecycle scripts are audited.
  9. Whether production Docker image omits dev dependencies and runs non-root.
  10. Current Express security middleware: Helmet, CORS, rate limits, CSRF, session cookies, validation.
  11. Risk summary and minimal patch plan.

Phase 1 — Quick-win CI supply-chain guardrails

Implement without changing runtime app behavior:

  1. Ensure CI uses deterministic install:

    • use npm ci, not npm install
    • add a manifest drift check: git diff --exit-code -- package.json package-lock.json
  2. Add a security scan workflow using scriptless install:

    • npm ci --ignore-scripts
    • npm audit --audit-level=high
    • npm audit signatures where supported
    • SBOM generation: npm sbom --sbom-format cyclonedx --package-lock-only > sbom.cdx.json
  3. Add lifecycle-script audit:

    • create scripts/list-lifecycle-scripts.mjs
    • fail when dependencies contain preinstall, install, postinstall, or prepare hooks unless allowlisted
    • document every allowed lifecycle package and why it is allowed
  4. Add GitHub dependency review workflow:

    • fail on high/critical vulnerable dependency additions
    • fail or warn on license policies if repo already has license policy
  5. Add Dependabot config:

    • weekly npm updates
    • GitHub Actions updates
    • security labels
    • limited open PRs to avoid noise
  6. Add repository docs:

    • docs/security/supply-chain-baseline.md
    • include dependency approval rules and emergency compromise response.

Phase 2 — Harden GitHub Actions

Update workflows safely:

  1. Add top-level default:

    • permissions: contents: read
  2. For each job, grant only required permissions.

  3. Pin third-party Actions to immutable full commit SHAs where practical.

    • At minimum, produce a report listing unpinned actions.
    • If full-SHA conversion is too disruptive, add a TODO and workflow policy check.
  4. Avoid secrets in pull_request jobs from forks.

  5. Separate scan/review jobs from build/test/release jobs.

  6. Add branch protection recommendation doc:

    • required CI
    • required dependency review
    • required security scan
    • require review for workflow changes
    • restrict who can edit .github/workflows/*

Phase 3 — App-layer hardening

Inspect Express/React/Postgres security and patch only real gaps.

Server requirements:

  1. Helmet enabled with safe defaults.
  2. CORS allowlist, not wildcard in production.
  3. CSRF protection for state-changing routes if cookie/session auth is used.
  4. Rate limiting on auth, upload, admin, and mutation-heavy routes.
  5. Zod/body validation for API inputs.
  6. Clear auth/RBAC middleware per sensitive module.
  7. Tenant/org isolation checked on all org-scoped queries.
  8. SQL queries parameterized; no unsafe string concatenation.
  9. Uploads restricted by file type, size, path, and scanning placeholder if malware scanning is not available.
  10. Errors are structured but do not leak secrets or stack traces in production.

Frontend requirements:

  1. No unsafe dynamic eval / new Function usage.
  2. Avoid raw HTML injection; sanitize any unavoidable rich text.
  3. Add or document CSP strategy.
  4. Avoid storing tokens in localStorage if app uses cookies/sessions.
  5. Avoid leaking sensitive payloads into diagnostics logs.

Phase 4 — SBOM, artifact integrity, and release provenance

For protected branches/releases:

  1. Upload SBOM as workflow artifact.
  2. Add artifact attestation where available:
    • id-token: write
    • attestations: write
  3. Package built assets once and promote that artifact; do not rebuild different outputs per environment.
  4. Add verification instructions:
    • how to inspect SBOM
    • how to verify artifact provenance

Phase 5 — Optional private registry/proxy foundation

Do not force this if deployment environment is not ready.

Plan and document:

  1. .npmrc registry strategy.
  2. Scoped internal package rules such as @invtrack/*.
  3. Verdaccio/Artifactory/GitHub Packages proxy option.
  4. Dependency confusion prevention.
  5. Rule: never commit registry tokens.

Phase 6 — Super security mode for vibe-coded development

Add a developer gate for AI-generated or rapidly added dependencies.

Create docs/checklist:

  • docs/security/ai-code-security-checklist.md

Rules:

  1. No new npm package without justification.
  2. Check package name for typosquatting/slopsquatting risk.
  3. Prefer existing dependencies already in repo.
  4. Verify package age, maintainer, downloads, repo, license, recent compromise notices.
  5. Avoid packages with unnecessary install scripts.
  6. All dependency changes must pass dependency review and lifecycle audit.
  7. AI-generated code touching auth, payments, approvals, SQL, file upload, admin, CI, or package config requires human review.

Phase 7 — Tests and verification

Run:

  • npm run check
  • npm run build
  • npm audit --audit-level=high
  • npm audit signatures
  • npm sbom --sbom-format cyclonedx --package-lock-only > sbom.cdx.json
  • npm ci --ignore-scripts
  • node scripts/list-lifecycle-scripts.mjs
  • existing release gates:
    • npm run verify:release
    • npm run release:gate:delta

Add test cases:

  1. Changing package.json without lockfile update fails CI.
  2. Adding a dependency with lifecycle script fails unless allowlisted.
  3. Dependency review workflow exists and runs on PRs.
  4. Security workflow uploads SBOM artifact.
  5. Workflows use least-privilege permissions.
  6. Build still passes after security workflow changes.

Acceptance criteria

  • CI does not use unsafe dependency installation for scan jobs.
  • Lockfile drift is blocked.
  • Lifecycle scripts are visible and gated.
  • Dependency Review and Dependabot are configured.
  • GitHub Actions permissions are least-privilege.
  • SBOM is generated on protected builds.
  • App security middleware and validation gaps are documented and patched where safe.
  • A clear npm compromise response plan exists.
  • The build remains green.

Mqhele Sithole and others added 4 commits May 24, 2026 12:27
Add Dependabot, dependency review, lifecycle/SBOM workflows with weekly cron; pin official actions to immutable SHAs (including Codespaces). Upgrade Electron/drizzle/cloudinary/express/nodemailer/sqlite3; streamline Cloudinary multer uploads; tighten production CSP script-src; document audit backlog and npm legacy-peer policy.

Co-authored-by: Cursor <cursoragent@cursor.com>
Resolve Dependency Review blocker via filelist/readdir-glob overrides; npm audit fix clears high advisories. Add CI security-supply-chain-gate, PR dependency-review, and pr-security-merge-gate before release-gate; consolidate DR workflow; blocking npm audit in supply-chain. Node 24 in Actions; attestation after successful supply-chain workflow. Remove unused sharp. Update security docs and verification results.

Co-authored-by: Cursor <cursoragent@cursor.com>
…r-data routes

Extend suppliers UI/schema with defaultCarrierId; invoice paymentTermsId and currencyCode. Expand AP, operations, and procurement route registration; strengthen master-data propagation tests and HTTP test helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
Copy link
Copy Markdown
Owner Author

Codex instruction: Suppliers integration + Diagnostics rebuild

Use this as the Codex implementation instruction for the next build pass.

You are working on the ISSSourcing / InvTrack repository.

Goal:
Rebuild the Suppliers page into a true supplier master-data command centre and upgrade System Diagnostics so it detects and surfaces more real app errors through the existing user notification/error system.

Do not start by editing immediately.
First inspect the current repo and produce an evidence report.
Then implement in small, safe, testable phases.

Primary business requirements:
1. The Suppliers page must be integrated throughout the app.
2. Supplier data entered once must flow into downstream modules.
3. Supplier commercial defaults must become the source of truth for new transactions.
4. If a supplier has a selected currency, every new PO for that supplier must default to that supplier currency.
5. Supplier currency should be enforced by backend service logic, not only frontend dropdowns.
6. Draft POs may be updated/warned when supplier defaults change.
7. Approved/sent/received/invoiced POs must not be silently rewritten. They must keep historical snapshot values and show mismatch/amendment warnings.
8. Supplier payment terms, tax code, incoterm, default department, default contract, preferred carrier, and sites should propagate to requisitions, POs, contracts, AP/invoices, logistics, reports, analytics, and exports where relevant.
9. The Diagnostics page must detect frontend, backend, API, business-rule, integration, data-consistency, security, and notification errors.
10. Diagnostics must connect to the function/system that notifies users of errors.

Hard rules:
- Do not weaken tests.
- Do not remove release gates.
- Do not fake data.
- Do not silently mutate historical procurement/financial documents.
- Preserve org/tenant isolation.
- Use supplier master data as defaults for new documents.
- Snapshot supplier defaults onto transaction documents at creation.
- Use controlled warning/amendment flow for locked documents.
- Use existing app patterns: TypeScript, React, TanStack Query, Express, Drizzle, Zod, current response envelopes, current auth/RBAC/org-isolation patterns.
- Do not introduce Kafka, Redis, SSE, WebSockets, or an event bus in this pass.
- Do not add new dependencies unless absolutely necessary.

Files to inspect first:
- shared/schema.ts
- client/src/pages/suppliers.tsx
- client/src/pages/master-data.tsx
- client/src/pages/orders/purchase-order-detail-view.tsx
- client/src/pages/orders/po-commercial-terms-card.tsx
- client/src/pages/requisitions/use-requisition-form.ts
- client/src/pages/contracts.tsx
- client/src/pages/invoices.tsx
- client/src/pages/logistics.tsx
- client/src/pages/diagnostics.tsx
- client/src/lib/query-keys.ts
- client/src/lib/domain-invalidation.ts
- client/src/lib/queryClient.ts
- client/src/components/**/*toast*
- client/src/components/**/*notification*
- client/src/hooks/**/*toast*
- client/src/hooks/**/*notification*
- client/src/**/*ErrorBoundary*
- server/modules/master-data/register-master-data-routes.ts
- server/modules/procurement/register-procurement-routes.ts
- server/modules/accounts-payable/register-accounts-payable-routes.ts
- server/modules/accounts-payable/service.ts
- server/modules/operations/operations-core.ts
- server/modules/operations/register-operations-routes.ts
- server/bootstrap/security-middleware.ts
- server/index.ts
- server/routes.ts
- server/**/*diagnostic*
- server/**/*notification*
- scripts/test-master-data-propagation.ts
- scripts/test-master-data-integration.ts
- scripts/test-purchase-order-endpoints.ts
- scripts/test-ap-workflow.ts
- scripts/test-diagnostics-self-checks.ts
- scripts/test-route-diagnostics.ts

PHASE 0 — Evidence report before editing

Produce a report with:
1. Current Suppliers page tabs.
2. Current fields in each supplier tab.
3. Current supplier DB/schema fields.
4. Supplier fields displayed in UI but not persisted.
5. Supplier fields persisted but not used downstream.
6. Supplier APIs and payloads.
7. Whether supplier currency currently applies to new POs.
8. Whether supplier payment terms apply to POs/invoices.
9. Whether supplier tax code applies to POs/invoices.
10. Whether supplier incoterm applies to POs/logistics.
11. Whether supplier preferred carrier applies to logistics.
12. Whether supplier sites flow to logistics/receiving.
13. Whether supplier updates invalidate PO/requisition/contract/invoice/logistics/report/analytics queries.
14. Current Diagnostics tabs.
15. Which errors Diagnostics currently detects.
16. Which errors Diagnostics currently misses.
17. Current frontend global error handling.
18. Current API/query/mutation error handling.
19. Current backend error middleware.
20. Current notification/toast system and how to trigger it.
21. Current diagnostic event persistence, if any.
22. Minimal safe patch plan.

PHASE 1 — Rebuild Suppliers page information architecture

Reorganize Suppliers into these tabs:

1. Overview
- supplier status
- open POs
- open invoices
- total spend
- active contracts
- unpaid amount
- risk/compliance summary
- recent supplier activity

2. Profile
- supplier code
- supplier name
- legal name
- supplier type
- active/inactive/blocked/pending status
- registration number
- tax/VAT number
- category
- notes

3. Commercial Defaults
- currencyCode or currencyId
- paymentTermsId
- taxCodeId
- incotermId
- defaultDepartmentId
- defaultContractId
- preferredCarrierId
- defaultTransportMode
- billControlPolicy: ordered_quantities or received_quantities
- allowCurrencyOverride
- requireApprovalForOverride

4. Contacts & Sites
- primary contact
- finance contact
- logistics contact
- billing address
- remit-to address
- pickup site
- delivery site
- supplier site list

5. Contracts & Pricing
- active contracts
- contract currency
- contract payment terms
- contract incoterm
- contract lines/catalogues where supported

6. Procurement History
- requisitions
- POs
- received quantities
- cancelled/rejected orders
- supplier performance

7. Logistics
- preferred carrier
- transport mode
- supplier pickup sites
- delivery terms
- inbound delivery history

8. AP & Payments
- invoices
- payment status
- credit notes
- unmatched invoices
- 3-way match status
- bank/remit details if supported

9. Risk & Compliance
- required documents
- compliance status
- expiry dates
- blocked supplier reason
- policy exceptions

10. Audit Trail
- supplier changes
- old value/new value
- user
- timestamp
- affected downstream documents

PHASE 2 — Make supplier commercial defaults real

Implement supplier defaults as source-of-truth for new transactions.

When creating or editing a draft PO and supplier is selected:
- set PO currency from supplier currency
- set payment terms from supplier
- set tax code from supplier
- set incoterm from supplier
- set preferred carrier if shipment/logistics section exists
- set default department/contract if available

Contract override rule:
- Contract terms override supplier defaults only where the contract explicitly has values.
- Missing contract terms fall back to supplier defaults.

Currency override rule:
- If user overrides supplier currency, allow only if supplier.allowCurrencyOverride = true.
- If supplier.requireApprovalForOverride = true, flag/block until approved depending on existing approval architecture.

Existing document rules:
- draft PO: may auto-update or prompt user
- open/unapproved PO: warn and require confirmation
- approved/sent/received/invoiced PO: do not silently mutate; show mismatch warning and require controlled amendment

Snapshot fields on PO where schema supports it:
- supplierId
- supplierNameSnapshot
- currencyCode
- paymentTermsId
- paymentTermsSnapshot
- taxCodeId
- incotermId
- incotermSnapshot
- supplierDefaultsVersion or supplierUpdatedAtSnapshot if available

PHASE 3 — Backend enforcement

Do not rely on frontend only.

Add/update backend service functions:
- resolveSupplierCommercialDefaults(orgId, supplierId, contractId?)
- applySupplierDefaultsToPurchaseOrder(input)
- validateSupplierCurrencyOverride(input)
- detectSupplierDocumentMismatches(orgId, supplierId)

Backend PO create/update must:
1. Resolve supplier by supplierId and orgId.
2. Reject cross-org supplier usage.
3. Apply supplier defaults server-side.
4. Validate currency exists and is active.
5. Validate payment terms/tax/incoterm exist and are active.
6. Validate override policy.
7. Save snapshot fields.
8. Return structured errors for invalid supplier defaults or override attempts.
9. Create diagnostic event for blocked business-rule attempts where diagnostic storage exists.

PHASE 4 — Cross-module supplier propagation

Supplier data must flow into:

1. Requisitions
- supplier defaults visible when supplier selected
- conversion to PO carries supplier defaults

2. Purchase Orders
- new PO uses supplier currency
- PO detail displays supplier defaults used
- PO PDF/export uses PO snapshot currency

3. Contracts
- contract defaults can be created from supplier defaults
- contract terms can override supplier defaults only where explicit

4. Invoices/AP
- invoice currency defaults from PO
- if no PO, invoice currency defaults from supplier
- payment terms default from PO/supplier
- 3-way match uses PO/receipt/invoice consistency

5. Logistics
- preferred carrier defaults from supplier
- supplier sites available for inbound delivery
- incoterm visible on shipment/delivery

6. Reports/Analytics
- show supplier currency
- group spend by supplier and currency
- flag mixed-currency supplier spend where no exchange rate exists

PHASE 5 — Domain invalidation and query keys

Expand query keys where safe:
- qk.suppliers.list(filters)
- qk.suppliers.detail(id)
- qk.suppliers.defaults(id)
- qk.purchaseOrders.bySupplier(supplierId)
- qk.purchaseOrders.detail(poNumber)
- qk.invoices.bySupplier(supplierId)
- qk.contracts.bySupplier(supplierId)
- qk.logistics.bySupplier(supplierId)
- qk.reports.supplierSpend(filters)
- qk.analytics.supplierPerformance(filters)
- qk.diagnostics.list(filters)
- qk.notifications.list(filters)

After supplier create/update/delete:
Call or create invalidateSupplierDomain(queryClient, supplierId), refreshing:
- suppliers
- master data
- requisitions
- purchase orders
- contracts
- invoices/AP
- logistics
- reports
- analytics
- diagnostics if consistency errors are generated

PHASE 6 — Rebuild Diagnostics page tabs

Reorganize Diagnostics into:

1. Overview
- health score
- open errors
- highest-risk modules
- latest incidents
- unresolved business-rule failures

2. User-Visible Errors
- errors that triggered toasts/notifications
- user ID
- route/page
- action attempted

3. Frontend Errors
- React render errors
- route errors
- failed API calls
- query failures
- component stack if available

4. Backend Errors
- Express route errors
- database errors
- failed service calls
- unhandled rejection monitor events
- uncaught exception monitor events

5. Business Rule Failures
- invalid approver blocked
- PO status transition rejected
- supplier currency mismatch
- invoice/PO/receipt mismatch
- over-receipt attempt
- blocked supplier transaction attempt

6. Integration Health
- supplier defaults not matching PO
- PO without supplier snapshot
- invoice currency mismatch
- receipt without shipment/PO
- orphan shipment
- AP receipt missing after receiving

7. Data Consistency
- stale supplier defaults
- missing master-data references
- inactive currency used on draft PO
- invalid supplier/site/carrier links

8. Notifications
- notification records
- read/unread
- severity
- linked diagnostic event

9. Security & Supply Chain
- npm audit status
- dependency review status
- lifecycle script audit
- SBOM status

10. Audit Timeline
- chronological event stream
- filter by module, user, severity, supplier, PO, invoice

PHASE 7 — Connect Diagnostics to global errors and notifications

Backend:
1. Express global error middleware logs every handled route error.
2. Async route wrapper catches rejected promises.
3. process.on('uncaughtExceptionMonitor') records fatal diagnostic event.
4. process.on('unhandledRejection') records diagnostic event.
5. Business-rule errors create diagnostic events.
6. Diagnostic events can create notification records for relevant users/admins.
7. Production responses do not leak stack traces.

Frontend:
1. Add or improve app-level ErrorBoundary.
2. ErrorBoundary reports errors to backend diagnostics endpoint.
3. queryClient catches failed API calls and triggers toast/notification.
4. Mutation failures create user-visible error notifications.
5. Diagnostics page reads from the same source as notifications.

If data model is missing, add safely:

diagnostic_events:
- id
- orgId
- severity
- source: frontend/backend/business_rule/integration/security
- module
- code
- message
- safeMessage
- stackHash
- contextJson
- userId
- route
- entityType
- entityId
- createdAt
- resolvedAt

notifications:
- id
- orgId
- userId nullable
- severity
- title
- message
- sourceDiagnosticEventId
- readAt
- createdAt

PHASE 8 — Supplier consistency diagnostics

Add diagnostics checks:
1. Supplier has inactive currency.
2. Supplier has no currency.
3. Draft PO currency does not match supplier currency.
4. Invoice currency does not match PO currency.
5. Supplier default payment term missing.
6. Supplier default carrier inactive.
7. PO missing supplier snapshot.
8. Contract currency differs from supplier currency without override flag.
9. AP invoice missing supplier/PO link.
10. Supplier is blocked but has open draft transactions.

PHASE 9 — Tests

Add/update tests:

Supplier tests:
- create supplier with currency/payment terms/incoterm/tax/default carrier
- create PO for supplier and assert PO currency equals supplier currency
- supplier currency override blocked unless allowed
- draft PO updates or warns after supplier currency change
- approved PO is not silently mutated after supplier currency change
- requisition conversion creates PO with supplier defaults
- invoice defaults currency from PO/supplier
- contract terms override supplier defaults only where explicit
- supplier update invalidates PO/invoice/logistics/report/analytics queries

Diagnostics tests:
- frontend API error creates toast and diagnostic event
- backend route error creates diagnostic event
- business rule failure creates diagnostic event
- supplier currency mismatch appears in Diagnostics
- notification created from high-severity diagnostic event
- diagnostics page shows frontend/backend/business/integration tabs
- error boundary catches render failure and reports event
- production error response does not leak stack trace

Run:
- npm run check
- npm run build
- npm run test:master-data-propagation
- npm run test:master-data-integration
- npm run test:purchase-order-endpoints
- npm run test:ap-workflow
- npm run test:diagnostics
- npm run test:route-diagnostics
- npm run verify:release
- npm run release:gate:delta

If a listed script does not exist, do not fake it. Report it and add the minimal appropriate test script only if needed.

Final response required:
1. Files inspected.
2. Current Suppliers tab setup found.
3. Current Diagnostics setup found.
4. New Suppliers tab structure implemented.
5. New Diagnostics tab structure implemented.
6. Supplier fields added/changed.
7. Supplier default propagation logic.
8. Backend enforcement rules.
9. Query invalidation changes.
10. Diagnostics/error notification changes.
11. Tests added/updated.
12. Commands run and results.
13. Remaining risks.
14. Whether supplier defaults now propagate end-to-end.
15. Whether diagnostics now detects and notifies missed errors.

Acceptance criteria:

  • Supplier currency controls all new POs for that supplier.
  • Supplier defaults flow into requisitions, POs, contracts, invoices/AP, logistics, reports, analytics, and exports where relevant.
  • Locked historical documents are not silently mutated.
  • Supplier mismatch issues are visible in Diagnostics.
  • Frontend/backend/API/business-rule errors create diagnostic events where applicable.
  • Diagnostics and user notifications are connected.
  • Release gates remain intact.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants