Compare commits

...

37 commits

Author SHA1 Message Date
dependabot[bot]
c5867c27eb
Merge 9d9f4a89df into dfbd0562ee 2026-05-20 22:30:22 +00:00
Adam Moussa
dfbd0562ee
Merge pull request #48 from Sea-Haven-Industries/mobile/fix-react-version-and-ui
Fix React version, mobile auth, web/API bugs, and admin UX hardening
2026-05-20 18:29:15 -04:00
Adam Moussa
a978fdd292 Update retrospective with session 5: automated QA and 18-bug fix sweep
Documents the parallel 4-agent QA run (~145 test cases), the 18 bugs
found, and all fixes applied in the preceding 4 commits. Adds session 5
changelog and QA coverage summary table.
2026-05-20 18:10:02 -04:00
Adam Moussa
5e89e42e6a Extract shared constants and format utils, wire admin dashboard filters
Move STATUS_COLORS and PRIORITY_COLORS to constants/index.ts and
formatCurrency/formatDate/formatDateTime to lib/format.ts — previously
duplicated across 5 and 4 files respectively.

AdminDashboard: Wire Category and Priority filter dropdowns to
usePaginatedList extraParams (were no-op onChange handlers).

ProposalDetailPage: Add 'Revised' to STATUS_ORDER so the stepper
renders correctly for revised proposals.
2026-05-20 18:09:11 -04:00
Adam Moussa
4d72b63547 Add frontend role guards, fix dashboard data exposure, and harden UX
RoleGuard: New component wrapping admin routes — dispatchers navigating
to /admin/* by URL now redirect to / instead of seeing error states.

Dashboard: Add mine=true filter so dispatchers only see their own
proposals and stats, not all users' data.

AdminWorkspace: Auto-save dirty changes before approving so edits to
refined scope and line items aren't silently discarded.

ProposalFormPage: Add onError toast and 300ms debounce on customer
search (was firing an API call per keystroke).

admin.ts: Stop swallowing errors in getPdf — let them propagate to the
mutation's onError handler. Fix AuditEntry.details type to string|null.

LoginPage: Fix pre-existing TS error with noUncheckedIndexedAccess.
2026-05-20 18:09:04 -04:00
Adam Moussa
866601025d Validate dev-login input: reject empty email and invalid role
Empty-string email passed model binding but created a ghost user with no
identity. Invalid role strings (e.g. "SuperHero") silently defaulted to
Admin, granting unintended elevated access.

Now returns 400 for both cases. Default role changed from Admin to
Dispatcher (least privilege).
2026-05-20 18:08:55 -04:00
Adam Moussa
d00c552497 Fix admin dashboard LINQ crash, revise unique constraint, and mutation response data
AdminController: Rewrite avgTurnaround query to fetch approved times to
memory before computing TotalHours — EF Core/Npgsql cannot translate
TimeSpan.TotalHours to SQL, causing a 409 on every dashboard load.

ProposalService.ReviseAsync: Append -R{n} suffix to revision's
ProposalNumber so it doesn't violate the unique index. Previously copied
the parent's number verbatim, causing a DbUpdateException (500).

ProposalService Update/Approve/MarkSent: Add .Include(p => p.SubmittedBy)
(and ApprovedBy where relevant) so MapToResponse returns submittedByName
instead of null. GetByIdAsync already had these includes.
2026-05-20 18:08:50 -04:00
Adam Moussa
0b1af71166 Add retrospective covering mobile and web testing sessions
Documents findings from all four sessions (2026-05-18 through 2026-05-20):
mobile CI/CD, device testing, and web dev-mode testing. Includes
standards compliance audit, lessons learned, and prioritized follow-ups.
2026-05-20 17:30:48 -04:00
Adam Moussa
2645d970ed Fix customer name not binding from Autocomplete free text input
The freeSolo Autocomplete only updated customerName on dropdown
selection, not on typed input. Update form state on onInputChange
so validation passes when typing a new customer name.
2026-05-20 17:24:14 -04:00
Adam Moussa
9b97b7b578 Fix proposal workflow: scoped My Proposals, idempotent state transitions
Add Mine filter to ProposalFilterRequest so My Proposals page shows
only the current user's submissions regardless of role. Create
proposals directly as InReview (skip Draft) since form submission is
the review request. Make Approve, MarkSent, and Revise idempotent —
repeat calls return current state instead of throwing. Wrap line item
audit logging in try/catch so audit failures don't mask successful
saves.
2026-05-20 17:24:09 -04:00
Adam Moussa
f37c2aa3f0 Fix dev-login role switching, distinct users, and user resolution races
Dev-login now updates the role when an existing user logs in as a
different role. Each dev role maps to a distinct email/name so
sessions don't collide. CognitoSub is deterministic (email-based)
to prevent mismatch between dev-login and CurrentUserService.
CurrentUserService catches DbUpdateException on concurrent user
creation and retries the lookup instead of crashing.
2026-05-20 17:24:01 -04:00
Adam Moussa
f44caba906 Fix JSON enum serialization and audit log jsonb format
Add JsonStringEnumConverter so string enum values (ServiceCategory,
Priority, PricingMode, LineItemSource) deserialize correctly from
frontend requests. Wrap AuditService detail strings in a JSON object
to satisfy the Postgres jsonb column type. Relax global.json SDK
version to match installed 8.0.1xx feature band.
2026-05-20 17:23:55 -04:00
Adam Moussa
686b42330c Fix React version mismatch, auth fallback, and UI polish
Pin React to 19.2.3 (exact version RN 0.85.3's bundled renderer
requires — 19.2.6 caused "Cannot read property 'default' of
undefined" crash at getPaperRenderer).

Auth: fall back to parsing user info from Cognito ID token when
backend API is unreachable, removing the hard dependency on
localhost:5000 for credential login.

UI fixes:
- Safe area insets on Settings screen (top edge was missing)
- Separate refresh indicator from filter-triggered loading on
  proposal queue (chips no longer trigger pull-to-refresh animation)
- Dashboard welcome shows first name instead of full email
- Dashboard/AdminDashboard remove duplicate top safe area when
  navigation header already provides it
- Service category selector uses wrapping chips instead of
  cramped SegmentedButtons
- Add ErrorBoundary to App root for crash visibility
2026-05-20 13:34:08 -04:00
Adam Moussa
bd9fbb4da5 Fix launch crash: lazy-load amazon-cognito-identity-js
Some checks are pending
Deploy Mobile (iOS) / Build & Upload to TestFlight (push) Waiting to run
Deploy / Deploy to AWS (push) Waiting to run
The library's module graph eagerly initializes native module bindings
(RNAWSCognito) during import, causing a TypeError on startup since the
native pod isn't linked. Dynamic import defers loading until the user
actually taps "Sign In" with credentials, keeping it off the critical
startup path entirely.
2026-05-20 12:14:29 -04:00
Adam Moussa
a9c157dc95 Fix iOS 26 launch crash: patch netinfo removed CoreTelephony APIs
netinfo v12.0.1 calls subscriberCellularProvider and
currentRadioAccessTechnology which were removed in iOS 26. No newer
version exists. Add patch-package with respondsToSelector guards so
the app gracefully returns nil for carrier info and skips cellular
generation detection on iOS 26+ instead of crashing on launch.
2026-05-20 11:52:43 -04:00
Adam Moussa
da00d27049 Add email/password login, fix Cognito config, enable mobile auto-deploy
Apple review requires a test account login path that doesn't depend on
Google OAuth. Add amazon-cognito-identity-js for direct SRP auth with a
native email/password form on the login screen. Fill in the empty Cognito
client ID and pool ID, fix the Cognito domain prefix, and align CDK
callback URLs with the app's actual URL scheme. Enable push-triggered
mobile deploys, add CDK outputs for client IDs, fix stale README
references, and add mobile/README.md.
2026-05-20 11:36:51 -04:00
Adam Moussa
a9b720ee08 Fix launch crash on iOS 26: update netinfo and add error handling
Crash log showed RCTFatal from an unhandled promise rejection during
startup. The NetInfo listener fires immediately and processOfflineQueue
had no .catch() — fatal in production RN.

Also updated @react-native-community/netinfo from 11.x to 12.x because
11.x uses subscriberCellularProvider (deprecated iOS 12, likely removed
in iOS 26).
2026-05-19 19:54:13 -04:00
Adam Moussa
042339948c Add app icons and CFBundleIconName for TestFlight validation
Some checks are pending
Deploy / Deploy to AWS (push) Waiting to run
App Store Connect rejected the upload because:
- Missing 120x120px app icon (and other required sizes)
- Missing CFBundleIconName in Info.plist

Added placeholder solid-color icons at all required sizes.
These should be replaced with the actual Sea Haven logo.
2026-05-19 19:32:38 -04:00
Adam Moussa
fa93870a99 Fix RN bundle phase: align metro-config and babel-preset with RN 0.85
The "Bundle React Native code and images" Xcode build phase failed
because @react-native/metro-config and @react-native/babel-preset were
pinned to 0.79.x while react-native is 0.85.3. The 0.79 metro-config
API is incompatible with the 0.85 bundler script.

Also fixes xcodebuild_formatter from "" to "cat" to avoid empty pipe.
2026-05-19 19:21:33 -04:00
Adam Moussa
ddb1e52e68 Fix .xcode.env.local path: Fastlane runs from fastlane/ not mobile/ 2026-05-19 18:57:05 -04:00
Adam Moussa
8b997b9086 Fix NODE_BINARY for Xcode build phases in CI
Write .xcode.env.local with explicit node path so the "Bundle React
Native code and images" build phase can find node. Xcode build phases
don't inherit the GitHub Actions PATH. Also disable xcbeautify for
this run to see raw xcodebuild output for debugging.
2026-05-19 18:54:42 -04:00
Adam Moussa
0326909e51 Add verbose match output and keychain diagnostics for signing issue
Certificate installs to keychain but security find-identity shows
no signing identities. Added verbose match, explicit keychain params,
setup_ci force, profile_name in update_code_signing_settings, and
diagnostic security find-identity commands to diagnose the import.
2026-05-19 18:47:09 -04:00
Adam Moussa
69f582f0b3 Configure manual code signing for CI builds
Add update_code_signing_settings to disable automatic signing and
set development team (9KAQYC653W) + Apple Distribution identity.
Fixes Xcode error "Signing requires a development team" in CI.
2026-05-19 18:43:53 -04:00
Adam Moussa
a1f2e22562 Add headerless-body and DER-wrap strategies to ASC key normalizer
The .p8 file from Apple has no PEM headers, just the raw base64
body. Add strategies for: headerless body wrapped with PEM headers,
base64-decoded DER re-wrapped as PEM, and double-decoded DER. Also
show hex bytes in diagnostics for better binary data analysis.
Secret has been re-set with properly PEM-wrapped + base64-encoded
content matching the reusable workflow's expected format.
2026-05-19 18:40:29 -04:00
Adam Moussa
279cd6c94a Robust ASC key normalization with diagnostics for TestFlight deploy
Replace fragile BEGIN/base64 branch with multi-strategy key parser
that handles raw PEM, escaped newlines, base64-encoded PEM, mangled
line wrapping, CR/LF issues, and double-encoding. Validates key with
OpenSSL::PKey.read before passing to Fastlane via key_filepath (temp
file) instead of key_content to bypass Fastlane's own parsing. Prints
safe diagnostics (no key material) if all strategies fail.
2026-05-19 18:32:46 -04:00
Adam Moussa
9cd12ceb79 Fix ASC key format detection: handle both raw PEM and base64
The secret may contain either raw PEM text (with BEGIN header) or
base64-encoded PEM. Detect format and pass appropriately to fastlane
instead of blindly base64-decoding (which corrupts raw PEM content).
2026-05-18 19:30:56 -04:00
Adam Moussa
a0ccf676b8 Use prepend to fix OpenSSL::PKey::EC.new on OpenSSL 3.x
alias_method doesn't reliably wrap C-extension class methods. Switch to
singleton_class.prepend which correctly intercepts the call chain. Falls
back to OpenSSL::PKey.read when EC.new raises on PKCS#8 format keys.
2026-05-18 19:27:26 -04:00
Adam Moussa
e355809b58 Fix OpenSSL 3.x EC key parsing in Fastfile
Fastlane 2.234.0 uses OpenSSL::PKey::EC.new which fails with "invalid
curve name" on PKCS#8 keys under OpenSSL 3.x. Add monkey-patch to fall
back to OpenSSL::PKey.read which handles both formats.
2026-05-18 19:22:46 -04:00
Adam Moussa
efa77c6ce7 Fix ASC key parsing: decode base64 before passing to Fastlane
Some checks are pending
Deploy / Deploy to AWS (push) Waiting to run
The app_store_connect_api_key action fails with "invalid curve name"
when is_key_content_base64 is true on macOS runners with OpenSSL 3.x.
Decoding the key manually and passing the raw PEM content avoids the
OpenSSL incompatibility. Also reverts the Fastlane version pin since
2.235.0 doesn't exist.
2026-05-18 18:52:15 -04:00
Adam Moussa
a4c78048ed Bump Fastlane >= 2.235.0 to fix OpenSSL curve name error
Fastlane 2.234.0 fails with "invalid curve name" on macos-latest
runners due to an OpenSSL 3.x incompatibility in the ASC API key
parsing. Fixed in 2.235.0. Removed lockfile so CI regenerates it
with the correct Ruby/bundler version.
2026-05-18 18:49:28 -04:00
Adam Moussa
68f77a6c0a Add missing RN CLI deps, exclude mobile from AWS deploy
react-native 0.79 requires @react-native-community/cli as an
explicit dev dependency for CocoaPods autolinking. Also adds
paths-ignore for mobile/ on the AWS deploy workflow so mobile-only
changes don't trigger unnecessary infrastructure deploys.
2026-05-18 18:42:36 -04:00
dependabot[bot]
ed6aed9aa7
Bump react-native from 0.79.7 to 0.85.3 in /mobile (#35)
Bumps [react-native](https://github.com/facebook/react-native/tree/HEAD/packages/react-native) from 0.79.7 to 0.85.3.
- [Release notes](https://github.com/facebook/react-native/releases)
- [Changelog](https://github.com/facebook/react-native/blob/main/CHANGELOG-0.7x.md)
- [Commits](https://github.com/facebook/react-native/commits/v0.85.3/packages/react-native)

---
updated-dependencies:
- dependency-name: react-native
  dependency-version: 0.85.3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-18 22:40:56 +00:00
Adam Moussa
e64da7ecd7 Revert babel-preset to 0.79 to match React Native version
Dependabot bumped @react-native/babel-preset from 0.79 to 0.85,
which is incompatible with react-native 0.79. The 0.85 preset
expects CLI infrastructure that doesn't exist in 0.79, breaking
pod install during the mobile deploy.
2026-05-18 18:38:03 -04:00
Adam Moussa
e96c80c78a Add OIDC permissions to mobile deploy workflow
Startup failure — caller workflow needs id-token: write for the
reusable workflow's OIDC credential step to function.
2026-05-18 18:35:00 -04:00
Adam Moussa
28475d8529 Revert suggestions log group from foundation stack
The log group already exists — created by the compute stack's
logRetention setting on the suggestions Lambda. Adding it to the
foundation stack caused a duplicate resource error on deploy.
2026-05-18 18:32:04 -04:00
Adam Moussa
fdaaf5ed4a Fix compliance violations: Lambda defaults, CI node-version, dead code
oss-index-creator Lambda was missing functionName, arm64 architecture,
and explicit log retention — all required by the engineering handbook.
CI workflow was not passing node-version to reusable workflows, risking
drift. Removed unused _api_request helper from all four main Lambdas.
Added missing suggestions log group to foundation stack.
2026-05-18 18:28:31 -04:00
dependabot[bot]
69c989847f
Update requests-aws4auth requirement in /lambdas/oss-index-creator (#41)
Updates the requirements on [requests-aws4auth](https://github.com/tedder/requests-aws4auth) to permit the latest version.
- [Release notes](https://github.com/tedder/requests-aws4auth/releases)
- [Changelog](https://github.com/tedder/requests-aws4auth/blob/main/HISTORY.md)
- [Commits](https://github.com/tedder/requests-aws4auth/compare/v1.2.0...v1.3.2)

---
updated-dependencies:
- dependency-name: requests-aws4auth
  dependency-version: 1.3.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-18 22:14:39 +00:00
62 changed files with 4915 additions and 2676 deletions

View file

@ -21,6 +21,7 @@ jobs:
with:
working-directory: web
cache-dependency-path: web/package-lock.json
node-version: "24"
run-cdk-synth: false
run-conventions-check: false
@ -38,6 +39,7 @@ jobs:
with:
working-directory: mobile
cache-dependency-path: mobile/package-lock.json
node-version: "24"
run-cdk-synth: false
run-conventions-check: false
@ -47,6 +49,7 @@ jobs:
with:
working-directory: infra
cache-dependency-path: infra/package-lock.json
node-version: "24"
dotnet-version: "8.0.x"
dotnet-publish-project: api/src/ProposalSystem.Api/ProposalSystem.Api.csproj
run-typecheck: false

View file

@ -1,17 +1,19 @@
name: Deploy Mobile (iOS)
# Disabled during development. To activate for V1 release, change to:
# on:
# push:
# branches: [main]
# paths: ["mobile/**"]
on:
push:
branches: [main]
paths: ["mobile/**"]
workflow_dispatch:
concurrency:
group: deploy-mobile
cancel-in-progress: false
permissions:
id-token: write
contents: read
jobs:
deploy-ios:
name: Build & Upload to TestFlight

View file

@ -3,6 +3,8 @@ name: Deploy
on:
push:
branches: [main]
paths-ignore:
- "mobile/**"
concurrency:
group: deploy-backend

1
.gitignore vendored
View file

@ -44,6 +44,7 @@ TestResults/
# React Native / Mobile
mobile/ios/Pods/
mobile/ios/build/
mobile/ios/.xcode.env.local
mobile/android/.gradle/
mobile/android/app/build/
mobile/android/build/

View file

@ -18,7 +18,7 @@ Monorepo with five primary services:
proposal-system/
├── api/ .NET 8 Web API (Lambda-hosted, EF Core + PostgreSQL)
├── web/ React 19 + MUI v7 + Vite frontend
├── mobile/ React Native 0.79 iOS app
├── mobile/ React Native 0.85 iOS app
├── lambdas/ Python 3.12 processing functions (arm64)
├── infra/ CDK TypeScript (3 stacks)
├── shared/ TypeScript API contracts (shared between web + mobile)
@ -33,7 +33,7 @@ proposal-system/
|---|---|
| API | .NET 8, ASP.NET Core, EF Core + Npgsql, FluentValidation, Cognito JWT, Amazon.Lambda.AspNetCoreServer |
| Web | React 19, TypeScript, MUI v7, Vite, Redux Toolkit, TanStack Query, axios |
| Mobile | React Native CLI 0.79, React 19, React Native Paper, React Navigation, react-native-app-auth (PKCE), Keychain, offline draft queue |
| Mobile | React Native CLI 0.85, React 19, React Native Paper, React Navigation, react-native-app-auth (PKCE), amazon-cognito-identity-js (SRP), Keychain, offline draft queue |
| Lambdas | Python 3.12, arm64, pdfplumber, reportlab, httpx, boto3 |
| Infrastructure | CDK TypeScript (aws-cdk-lib 2.253.1) |
| AI/RAG | Bedrock Knowledge Base (Titan Embeddings v2), OpenSearch Serverless, Claude via Bedrock Runtime |
@ -127,11 +127,13 @@ Calls `cd-cdk.yaml` reusable workflow:
Deploy uses OIDC role `githubdeploy-proposal-system`. Concurrency group prevents parallel deploys.
### Mobile Deploy (currently disabled)
### Mobile Deploy
Workflow: `deploy-mobile.yaml` -- triggered by `workflow_dispatch` only (manual).
Workflow: `deploy-mobile.yaml` -- builds and uploads to TestFlight via `cd-mobile-ios.yaml` reusable workflow on `macos-26`.
To activate for release, change the trigger to push on main with path filter `mobile/**`.
Triggers:
- **Automatic**: push to `main` with changes in `mobile/**`
- **Manual**: `workflow_dispatch` for on-demand builds
## Mobile iOS
@ -147,15 +149,6 @@ Build and upload to TestFlight is handled by the `cd-mobile-ios.yaml` reusable w
| `ASC_ISSUER_ID` | App Store Connect issuer |
| `ASC_KEY_CONTENT` | App Store Connect API key (base64) |
To activate automatic deploys, update `deploy-mobile.yaml` trigger from `workflow_dispatch` to:
```yaml
on:
push:
branches: [main]
paths: ["mobile/**"]
```
## Data Flow
1. Dispatcher submits proposal request (web or mobile)

228
RETROSPECTIVE-2026-05-19.md Normal file
View file

@ -0,0 +1,228 @@
# Proposal System — Retrospective (2026-05-19, updated 2026-05-20, session 5 added 2026-05-20)
## Executive Summary
Across four sessions (2026-05-18, 2026-05-19, and two on 2026-05-20), the project progressed from a broken mobile CI pipeline to a functional mobile app on device AND a fully tested web frontend with working dev-mode authentication, proposal lifecycle, and admin workflows.
**Sessions 1-3 (Mobile):** The mobile app went from a broken CI pipeline to a functional app running on a physical device with working email/password authentication. Three distinct launch crashes were resolved, Cognito SRP login was validated end-to-end, and multiple UI issues were fixed. The app boots, authenticates, and renders on iOS 26 hardware. However, it cannot communicate with the backend API from a device, Google OAuth crashes the app, and the branch has not been merged to main.
**Session 4 (Web):** Full local web testing exposed six bugs in the API and frontend: enum serialization failures, identity/role confusion in dev-login, incorrect proposal ownership filtering, Autocomplete binding issues, audit log format errors on Postgres jsonb columns, and missing API idempotency. All were fixed in four logical commits. The web app's core workflow — submit as dispatcher, review/edit/approve/send as admin — is now functional end-to-end in dev mode.
**Session 5 (Automated QA):** Ran 4 parallel test agents covering ~145 test cases across every API endpoint and every frontend page. Found 18 bugs (2 critical, 4 high, 7 medium, 5 low). All 16 actionable bugs fixed in 4 commits. Critical: admin dashboard LINQ crash (EF Core can't translate TimeSpan.TotalHours to SQL) and revision endpoint 500 (unique constraint on ProposalNumber). High: dispatcher dashboard data exposure (missing mine filter), no frontend role guards on admin routes, submittedByName null on mutation responses, invalid role silently defaulting to Admin. Also extracted duplicated STATUS_COLORS and format utilities into shared modules, wired the admin dashboard filter dropdowns, and added debounce to customer search.
**Systemic findings:** The web session revealed two architectural gaps: (1) audit logging was fragile — a format error in a non-critical audit write could roll back an otherwise successful save, and (2) state machine transitions lacked idempotency, meaning retries or UI double-clicks could produce 500 errors instead of graceful no-ops. Both are patterns that would have surfaced in production under real load. Session 5 added a third: the frontend had no authorization enforcement — `ProtectedRoute` checked authentication but not role, so any logged-in user could navigate to admin pages by URL.
## Standards Compliance Status
| Rule | Status | Detail |
|------|--------|--------|
| Naming conventions | PASS | kebab-case throughout, branch name follows pattern |
| CI/CD pipeline exists | PASS | `deploy-mobile.yaml` and `deploy.yaml` both trigger on push to main |
| OIDC deploy role | PASS | `githubdeploy-proposal-system` |
| README accurate | **PARTIAL** | Root README updated (0.85, deploy status). `mobile/README.md` incomplete (no auth/device docs). Web dev mode not documented. |
| Confluence updated | **FAIL** | No Atlassian MCP. Architecture Map missing mobile pipeline, Cognito auth flow, and web dev-mode setup |
| Memory updated | **UPDATED** | Project memory updated with session 4 web fixes. New feedback memories created for API patterns. |
| Git workflow | PASS | All sessions used feature branch `mobile/fix-react-version-and-ui` |
| Commit messages | PASS | Imperative mood, explains "why", logically grouped changes |
| CDK callback URL fix | PASS | Fixed in CDK + live Cognito via AWS CLI |
| Pre-push lint/typecheck | NOT VERIFIED | Did not run typecheck before pushing — should have per CLAUDE.md hook |
| Dev secrets excluded | PASS | `appsettings.Development.json` (dev signing key) kept untracked, not committed |
| API idempotency | **FIXED** | Approve, MarkSent, Revise transitions now idempotent. Audit failures isolated from saves. |
## Required Memory Updates
### Completed this session
1. **`project_proposal_system.md`** — Updated with session 4 web fixes: dev-mode setup, enum serialization, audit log format, idempotent transitions, scoped My Proposals filtering.
2. **`feedback_mobile_deploy_lessons.md`** — All three session-3 lessons added (React pinning, import type, dev API URL). Done in session 3.
3. **`feedback_react_version_pinning.md`** — Created in session 3. Done.
4. **`feedback_api_idempotency.md`** — NEW: State machine transitions must be idempotent. Audit writes must not roll back successful saves.
5. **`feedback_jsonb_audit_format.md`** — NEW: Postgres jsonb columns require valid JSON, not plain strings. Audit details must be wrapped.
### Still outstanding
6. **`reference_mobile_testflight.md`** — The ⚠️ note about "username/password flow needs to be added" is now resolved but not yet updated in the file.
## Required Documentation Updates
| Doc | Status | Action |
|-----|--------|--------|
| Root `README.md` | Updated (session 2) | Needs update: add web dev-mode setup instructions (DevMode, dev-login, local Postgres) |
| `mobile/README.md` | Exists but incomplete | Add: email/password auth via Cognito SRP, `patch-package` for netinfo iOS 26 fix, React version pinning requirement, local device testing setup |
| `api/` dev setup | **MISSING** | No documentation for local API development: `appsettings.Development.json` template (without secrets), Docker Compose for Postgres, dev-login endpoint usage |
| Confluence "AWS Architecture Map" | **OUTSTANDING** | Still blocked — no Atlassian MCP. Needs: mobile CI/CD pipeline, Cognito auth flow, web dev-mode architecture |
| CDK `foundation-stack.ts` | Updated (session 2) | Callback URLs fixed, CfnOutputs added for client IDs |
## Reusable Skills / Automations
| Candidate | Type | ROI | Description |
|-----------|------|-----|-------------|
| React version coherence check | CI step | **CRITICAL** | `node -e` script that reads `node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js`, extracts the hardcoded version string, and compares against `node_modules/react/package.json`. Fails if mismatch. Would have caught the exact crash from session 3. |
| API idempotency test suite | Integration test | **HIGH** | For each state-machine endpoint (approve, markSent, revise), call twice with same input and assert both return 200 with matching response. Would have caught all three idempotency bugs from session 4. Pattern: assert `f(f(x)) == f(x)` for all mutation endpoints. |
| Audit isolation pattern | Code pattern | **HIGH** | Wrap all non-critical audit writes in try/catch so they never roll back the primary operation. Consider a `SafeAuditService` decorator or middleware. Session 4's bulk update 500 error was caused by audit failure after a successful save. |
| iOS device smoke test script | Script / Runbook | HIGH | Checklist for post-build device testing: connect device, Metro `--host <LAN_IP>`, build with automatic signing, verify login, test auth flow. |
| `patch-package` audit CI step | CI check | MEDIUM | Verify patches in `mobile/patches/` still apply cleanly and patched packages haven't been updated. |
| Dev-mode login test harness | Script | MEDIUM | Script that exercises all three dev-login roles (SysAdmin, Admin, Dispatcher) and verifies each returns a distinct user identity with correct role. Would have caught the role/identity confusion bugs immediately. |
| Cognito ID token user extraction | Utility | LOW | `parseUserFromIdToken()` in `auth.ts` — reusable for any Cognito-backed app. |
## Key Lessons Learned
### React Native Runtime (Sessions 1-3)
1. **React version MUST be pinned exactly, not with semver range.** RN 0.85.3's bundled `ReactNativeRenderer-dev.js` has a hard check: `if ("19.2.3" !== isomorphicReactPackageVersion)`. The peer dependency says `^19.2.3`, npm resolves to 19.2.6, and the app crashes with an opaque "Cannot read property 'default' of undefined" in `getPaperRenderer`. Pin `"react": "19.2.3"` in package.json.
2. **`import type` is not reliably erased for modules with native initialization.** `import type { CognitoUserSession } from 'amazon-cognito-identity-js'` was NOT stripped by Babel in RN's build pipeline. The module eagerly initialized native crypto at import time, causing a crash. Fix: remove the import entirely and use `any`, or use dynamic `await import()`.
3. **`localhost` in dev config is the phone, not the Mac.** `API_URL: 'http://localhost:5000/api'` in dev mode is unreachable from a physical device. Need either LAN IP or a fallback strategy.
### iOS 26 Specific (Sessions 1-3)
4. **CoreTelephony APIs removed without replacement.** `@react-native-community/netinfo` v12.0.1 still calls deprecated APIs. Required `patch-package` with `respondsToSelector:` guards.
5. **iPhone Mirroring is the fastest way to test on device.** Built into macOS 26, gives full touch control. Developer Mode on the phone is under Settings > Privacy & Security.
### .NET API / Web Frontend (Session 4)
6. **Postgres jsonb columns reject plain strings.** The `details` column on `AuditLogs` is typed `jsonb`. Writing a bare string like `"Added: Widget repair"` produces Postgres error 22P02. Wrap in a JSON object: `JsonSerializer.Serialize(new { message = details })`. This is easy to miss because SQLite and SQL Server `nvarchar` accept anything.
7. **System.Text.Json requires explicit `JsonStringEnumConverter` for enum round-tripping.** Without it, sending `"ServiceCategory": "Plumbing"` from the frontend produces a validation error because the default deserializer expects an integer. Must add `options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter())` in `AddJsonOptions`.
8. **State machine transitions must be idempotent.** Approve, MarkSent, and Revise all threw `InvalidOperationException` on repeat calls (e.g., from network retries or UI double-clicks). Fix: if already in the target state, return current entity instead of throwing. This is especially critical for mobile clients with unreliable connectivity.
9. **Audit writes must never roll back successful business operations.** `BulkUpdateAsync` saved line items successfully, then `_audit.LogAsync` threw (due to the jsonb format bug), and the entire request returned 500. The user saw "unexpected error" even though their data was saved. Fix: wrap non-critical audit calls in try/catch.
10. **Dev-login must produce deterministic, distinct identities per role.** Using `Guid.NewGuid()` for CognitoSub meant the same email produced different identities across logins. Using a single hardcoded email for all roles meant switching roles didn't actually switch users. Fix: deterministic sub (`dev-{email}`), distinct email/name per role, and update role on existing user if changed.
11. **"My Proposals" means ownership, not role-based filtering.** Initial implementation filtered by role (show all for admins, filter for dispatchers). The correct behavior: "My Proposals" always shows only proposals the current user submitted, regardless of role. Admins see all proposals in the separate Admin Queue.
### Process (All Sessions)
12. **Feature branch for iterative debugging works.** Session 2 pushed 10+ commits to main. Sessions 3-4 used `mobile/fix-react-version-and-ui` — all fixes stay off main until ready.
13. **User testing catches what type systems and linters can't.** Session 4's six bugs all passed TypeScript compilation and would pass unit tests. They were logic errors in business rules, serialization config, and identity management that only surfaced through manual workflow testing. Interactive testing with role-switching is essential before any deploy.
## Highest ROI Improvements
Ranked by impact-to-effort:
1. **Add API idempotency integration tests** (1 hr) — For each state-machine endpoint, call twice with same input and assert both return 200. Pattern: `assert f(f(x)) == f(x)`. Would have caught 3 of session 4's bugs automatically. Generalizable to any future endpoint.
2. **Add React version coherence CI check** (30 min) — A 10-line node script that extracts the expected version from the bundled renderer and compares to installed React. Prevents the most time-consuming crash from session 3.
3. **Isolate audit writes from business operations** (30 min) — Create a `SafeAuditService` wrapper or add try/catch to all audit calls in services. The pattern already exists in `LineItemService` but should be systematic, not ad-hoc. A single audit format bug caused a 500 on an otherwise successful operation.
4. **Add `.gitignore` to API project** (5 min) — `appsettings.Development.json` contains dev signing keys and must not be committed. Currently relying on manual exclusion. Add it to `.gitignore` with a template file (`.example`) that documents the required keys without values.
5. **Document web dev-mode setup** (15 min) — No docs exist for running the API locally: Docker Compose for Postgres, `appsettings.Development.json` template, dev-login endpoint, role switching. This will block any new developer.
6. **Merge `mobile/fix-react-version-and-ui` and deploy** (5 min) — Branch has 8 commits of critical fixes (sessions 3-4). Current TestFlight build crashes. Must merge before next submission.
7. **Fix dev API_URL for physical devices** (10 min) — `localhost:5000` is unreachable from iPhone. Blocks all API-dependent mobile features during device testing.
8. **Pin all RN ecosystem versions exactly** (5 min) — Already done for React; extend to all `@react-native/*` packages.
## Outstanding Risks or Follow-Ups
| Priority | Item | Risk | Branch/Location |
|----------|------|------|-----------------|
| **BLOCKING** | Feature branch not merged — TestFlight build still crashes | Any TestFlight tester or Apple reviewer will see a crash | `mobile/fix-react-version-and-ui` |
| **BLOCKING** | Google OAuth crashes the app on tap | Apple reviewer may try both login methods | `auth.ts` → `react-native-app-auth` → Cognito Hosted UI |
| **HIGH** | `appsettings.Development.json` not in `.gitignore` | Dev signing key could be accidentally committed | `api/src/ProposalSystem.Api/` |
| **HIGH** | Dev API_URL is `localhost:5000` — all API calls fail on device | Proposals can't be created, viewed, or searched on device | `config.ts` |
| **HIGH** | Placeholder app icons (solid blue squares) | Unprofessional for TestFlight / App Store | `ios/ProposalSystem/Images.xcassets` |
| **HIGH** | No web dev-mode setup documentation | New developer can't run the system locally | Root README / api/ docs |
| ~~HIGH~~ | ~~Audit isolation is ad-hoc, not systematic~~ | ~~Fixed session 4; session 5 verified via testing~~ | ~~LineItemService, ProposalService~~ |
| **MEDIUM** | Confluence Architecture Map still missing mobile pipeline | Documentation debt per CLAUDE.md | Page 1540098 |
| **MEDIUM** | `react-native-paper` has known issues with RN 0.85 | May surface as bugs in production | GitHub issues #4889, #4905 |
| **MEDIUM** | netinfo patch needs monitoring for upstream fix | Patches can silently break on version bumps | `patches/@react-native-community+netinfo+12.0.1.patch` |
| **MEDIUM** | `DeleteAsync` in `LineItemService` doesn't update `TotalBidAmount` | Deleting a line item leaves the proposal total stale | `LineItemService.cs:113` |
| **LOW** | `no-floating-promises` ESLint rule still not added | Class of crash from session 2 can recur | `mobile/.eslintrc` |
| **LOW** | Cognito test user password in memory file | Acceptable for internal test account | `reference_mobile_testflight.md` |
| **LOW** | 4 Dependabot vulnerabilities open | Adam deferred these | GitHub Security tab |
## Session 5 Changelog — Automated QA & Bug Fixes (2026-05-20)
All fixes on `mobile/fix-react-version-and-ui` (4 commits, not yet on main):
### `d00c552` Fix admin dashboard LINQ crash, revise unique constraint, and mutation response data
- **`AdminController.cs`** — Rewrote avgTurnaround query to fetch approved times to memory before computing TotalHours (EF Core/Npgsql cannot translate TimeSpan.TotalHours)
- **`ProposalService.cs` ReviseAsync** — Append `-R{n}` suffix to revision ProposalNumber to avoid unique index violation
- **`ProposalService.cs` Update/Approve/MarkSent** — Added `.Include(p => p.SubmittedBy)` so mutation responses return submittedByName
### `8666010` Validate dev-login input: reject empty email and invalid role
- **`AuthController.cs`** — Return 400 for empty/whitespace email and invalid role strings; default role changed from Admin to Dispatcher (least privilege)
### `4d72b63` Add frontend role guards, fix dashboard data exposure, and harden UX
- **`ProtectedRoute.tsx`** — New `RoleGuard` component for role-based route protection
- **`App.tsx`** — Wrapped admin routes with `RoleGuard`; `/admin/*` requires Admin/SysAdmin, `/admin/users` requires SysAdmin
- **`Dashboard.tsx`** — Added `mine: true` to dashboard query so dispatchers only see their own proposals
- **`AdminWorkspace.tsx`** — Auto-save dirty changes before approving (was silently discarding edits)
- **`ProposalFormPage.tsx`** — Added onError toast handler; added 300ms debounce on customer autocomplete search
- **`admin.ts`** — Stopped swallowing errors in getPdf; fixed AuditEntry.details type to `string | null`
- **`LoginPage.tsx`** — Fixed pre-existing TS error with noUncheckedIndexedAccess
### `5e89e42` Extract shared constants and format utils, wire admin dashboard filters
- **`constants/index.ts`** — Added shared `STATUS_COLORS` and `PRIORITY_COLORS` (removed from 5 files)
- **`lib/format.ts`** — New shared `formatCurrency`, `formatDate`, `formatDateTime` (removed from 4 files)
- **`AdminDashboard.tsx`** — Wired Category and Priority filter dropdowns to `usePaginatedList` extraParams
- **`ProposalDetailPage.tsx`** — Added 'Revised' to STATUS_ORDER so stepper renders correctly
### QA Coverage Summary
| Test Area | Tests | Pass | Fail | Agent |
|-----------|-------|------|------|-------|
| Auth & RBAC | 35 | 31 | 4 | Auth agent |
| Proposal CRUD & State Machine | 38 | 35 | 3 | Proposal agent |
| Line Items, Customers & Misc | 42 | 39 | 3 | Misc agent |
| Web Frontend Code Review + API | ~30 | ~25 | ~5 | Frontend agent |
| **Total** | **~145** | **~130** | **~15** | — |
## Session 3 Changelog — Mobile Device Testing (2026-05-20)
Fixes on `mobile/fix-react-version-and-ui` (not yet on main):
- **Pin React 19.2.3** — fixes renderer version mismatch crash
- **Remove `import type` from cognito-auth.ts** — fixes eager module init crash
- **Auth fallback to ID token** — `loginWithCredentials` parses user from JWT when backend API unreachable
- **Safe area fixes** — Settings gets top+bottom edges; Dashboard/AdminDashboard use bottom-only (nav header handles top)
- **Pull-to-refresh separation** — filter chip taps no longer trigger refresh animation on proposal queue
- **Welcome name** — shows first name or email prefix instead of full email
- **Service category chips** — wrapping `Chip` components replace truncated `SegmentedButtons`
- **ErrorBoundary** — added to App root for crash visibility
Already on main (sessions 2-3):
- **Email/password login screen** — TextInput form + Cognito SRP via `amazon-cognito-identity-js`
- **Cognito config populated** — real values from AWS CLI
- **CDK callback URL fix** — `com.seahavenind.proposals://auth/callback`
- **netinfo iOS 26 patch** — `patch-package` with `respondsToSelector:` guards
- **Auto-deploy enabled** — `deploy-mobile.yaml` triggers on `mobile/**` push to main
- **Root README updated** — RN 0.85, deploy status corrected
- **`mobile/README.md` created** — local dev, signing, CI/CD docs
## Session 4 Changelog — Web Local Testing (2026-05-20)
All fixes on `mobile/fix-react-version-and-ui` (4 commits, not yet on main):
### `f44caba` Fix JSON enum serialization and audit log jsonb format
- **`Program.cs`** — Added `JsonStringEnumConverter` to `AddJsonOptions` so frontend string enums deserialize correctly
- **`AuditService.cs`** — Wrapped plain-string audit details in `JsonSerializer.Serialize(new { message = details })` for Postgres jsonb column
- **`global.json`** — Relaxed SDK version from 8.0.400 to 8.0.100 to match installed .NET SDK
### `f37c2aa` Fix dev-login role switching, distinct users, and user resolution races
- **`AuthController.cs`** — Dev-login now updates role on existing user; CognitoSub is deterministic (`dev-{email}`)
- **`CurrentUserService.cs`** — Added `DbUpdateException` catch on concurrent user creation with retry lookup
- **`LoginPage.tsx`** — Distinct dev user per role (SysAdmin=Adam, Admin=Sarah, Dispatcher=Mike)
### `9b97b7b` Fix proposal workflow: scoped My Proposals, idempotent state transitions
- **`ProposalService.cs`** — New proposals created as `InReview` (not `Draft`); My Proposals filters by `Mine` parameter (not role); `ApproveAsync`, `MarkSentAsync`, `ReviseAsync` all idempotent
- **`LineItemService.cs`** — Audit writes wrapped in try/catch so failures don't roll back successful saves
- **`ProposalDtos.cs`** — Added `bool Mine` filter parameter
- **`proposals.ts` / `ProposalListPage.tsx`** — Frontend passes `mine: true` for My Proposals page
### `2645d97` Fix customer name not binding from Autocomplete free text input
- **`ProposalFormPage.tsx`** — `onInputChange` with `reason === 'input'` now calls `handleChange('customerName', value)` alongside search

View file

@ -1,6 +1,6 @@
{
"sdk": {
"version": "8.0.400",
"version": "8.0.100",
"rollForward": "latestFeature"
}
}

View file

@ -29,11 +29,14 @@ public class AdminController : ControllerBase
var approvedThisWeek = await _db.Proposals
.CountAsync(p => p.ApprovedAt >= weekStart, ct);
var avgTurnaround = await _db.Proposals
var approvedTimes = await _db.Proposals
.Where(p => p.ApprovedAt.HasValue)
.Select(p => (p.ApprovedAt!.Value - p.SubmittedAt).TotalHours)
.DefaultIfEmpty(0)
.AverageAsync(ct);
.Select(p => new { p.ApprovedAt, p.SubmittedAt })
.ToListAsync(ct);
var avgTurnaround = approvedTimes.Count > 0
? approvedTimes.Average(p => (p.ApprovedAt!.Value - p.SubmittedAt).TotalHours)
: 0;
var totalProposals = await _db.Proposals.CountAsync(ct);

View file

@ -99,7 +99,13 @@ public class AuthController : ControllerBase
if (string.IsNullOrEmpty(signingKey))
return StatusCode(500, new { message = "Dev signing key not configured" });
var role = Enum.TryParse<UserRole>(request.Role, true, out var parsed) ? parsed : UserRole.Admin;
if (string.IsNullOrWhiteSpace(request.Email))
return BadRequest(new { message = "Email is required" });
if (!string.IsNullOrEmpty(request.Role) && !Enum.TryParse<UserRole>(request.Role, true, out _))
return BadRequest(new { message = $"Invalid role: '{request.Role}'. Valid roles are: Dispatcher, Admin, SysAdmin" });
var role = Enum.TryParse<UserRole>(request.Role, true, out var parsed) ? parsed : UserRole.Dispatcher;
var user = await _db.Users.FirstOrDefaultAsync(u => u.Email == request.Email, ct);
if (user == null)
@ -107,7 +113,7 @@ public class AuthController : ControllerBase
user = new User
{
Id = Guid.NewGuid(),
CognitoSub = $"dev-{Guid.NewGuid():N}",
CognitoSub = $"dev-{request.Email}",
Email = request.Email,
DisplayName = request.DisplayName ?? request.Email.Split('@')[0],
Role = role,
@ -118,6 +124,12 @@ public class AuthController : ControllerBase
_db.Users.Add(user);
await _db.SaveChangesAsync(ct);
}
else if (user.Role != role)
{
user.Role = role;
user.UpdatedAt = DateTime.UtcNow;
await _db.SaveChangesAsync(ct);
}
var claims = new List<Claim>
{

View file

@ -137,6 +137,9 @@ builder.Services.AddValidatorsFromAssemblyContaining<CreateProposalValidator>();
builder.Services.AddControllers(options =>
{
options.Filters.Add<ValidationFilter>();
}).AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});
// Middleware

View file

@ -80,7 +80,16 @@ public class CurrentUserService : ICurrentUserService
};
_db.Users.Add(_cachedUser);
await _db.SaveChangesAsync();
try
{
await _db.SaveChangesAsync();
}
catch (DbUpdateException)
{
_db.Entry(_cachedUser).State = EntityState.Detached;
_cachedUser = await _db.Users.FirstOrDefaultAsync(u => u.Email == email)
?? throw new UnauthorizedAccessException("Could not resolve current user");
}
}
private User GetOrThrow()

View file

@ -67,6 +67,7 @@ public record ProposalFilterRequest(
DateTime? FromDate,
DateTime? ToDate,
string? Search,
bool Mine = false,
int Page = 1,
int PageSize = 25
);

View file

@ -1,3 +1,4 @@
using System.Text.Json;
using ProposalSystem.Application.Interfaces;
using ProposalSystem.Domain.Entities;
using ProposalSystem.Infrastructure.Data;
@ -17,13 +18,17 @@ public class AuditService : IAuditService
public async Task LogAsync(AuditAction action, Guid? proposalId, string? details = null, CancellationToken ct = default)
{
var jsonDetails = details != null
? JsonSerializer.Serialize(new { message = details })
: null;
var entry = new AuditLog
{
Id = Guid.NewGuid(),
ProposalId = proposalId,
UserId = _currentUser.UserId,
Action = action,
Details = details,
Details = jsonDetails,
Timestamp = DateTime.UtcNow,
IpAddress = _currentUser.IpAddress,
};

View file

@ -54,7 +54,11 @@ public class LineItemService : ILineItemService
_db.LineItems.Add(lineItem);
await _db.SaveChangesAsync(ct);
await _audit.LogAsync(AuditAction.EditLineItem, proposalId, $"Added: {request.Description}", ct);
try
{
await _audit.LogAsync(AuditAction.EditLineItem, proposalId, $"Added: {request.Description}", ct);
}
catch { /* audit failure should not roll back a successful save */ }
return MapToResponse(lineItem);
}
@ -97,7 +101,11 @@ public class LineItemService : ILineItemService
await _db.SaveChangesAsync(ct);
await _audit.LogAsync(AuditAction.EditLineItem, proposalId, $"Bulk update: {newItems.Count} items", ct);
try
{
await _audit.LogAsync(AuditAction.EditLineItem, proposalId, $"Bulk update: {newItems.Count} items", ct);
}
catch { /* audit failure should not roll back a successful save */ }
return newItems.OrderBy(li => li.SortOrder).Select(MapToResponse).ToList();
}

View file

@ -43,7 +43,7 @@ public class ProposalService : IProposalService
ScopeOfWork = request.ScopeOfWork,
ServiceCategory = request.ServiceCategory,
Priority = request.Priority,
Status = ProposalStatus.Draft,
Status = ProposalStatus.InReview,
Notes = request.Notes ?? string.Empty,
SubmittedById = _currentUser.UserId,
SubmittedAt = now,
@ -79,7 +79,7 @@ public class ProposalService : IProposalService
.Include(p => p.AssignedAdmin)
.AsQueryable();
if (_currentUser.Role == UserRole.Dispatcher)
if (filter.Mine)
{
query = query.Where(p => p.SubmittedById == _currentUser.UserId);
}
@ -135,7 +135,11 @@ public class ProposalService : IProposalService
public async Task<ProposalResponse> UpdateAsync(Guid id, UpdateProposalRequest request, CancellationToken ct = default)
{
var proposal = await _db.Proposals.FindAsync(new object[] { id }, ct)
var proposal = await _db.Proposals
.Include(p => p.SubmittedBy)
.Include(p => p.AssignedAdmin)
.Include(p => p.ApprovedBy)
.FirstOrDefaultAsync(p => p.Id == id, ct)
?? throw new KeyNotFoundException($"Proposal {id} not found");
if (request.RefinedScope != null)
@ -163,9 +167,14 @@ public class ProposalService : IProposalService
{
var proposal = await _db.Proposals
.Include(p => p.LineItems)
.Include(p => p.SubmittedBy)
.Include(p => p.ApprovedBy)
.FirstOrDefaultAsync(p => p.Id == id, ct)
?? throw new KeyNotFoundException($"Proposal {id} not found");
if (proposal.Status == ProposalStatus.Approved)
return MapToResponse(proposal);
if (proposal.Status != ProposalStatus.InReview)
throw new InvalidOperationException("Only proposals in review can be approved");
@ -186,9 +195,15 @@ public class ProposalService : IProposalService
public async Task<ProposalResponse> MarkSentAsync(Guid id, CancellationToken ct = default)
{
var proposal = await _db.Proposals.FindAsync(new object[] { id }, ct)
var proposal = await _db.Proposals
.Include(p => p.SubmittedBy)
.Include(p => p.ApprovedBy)
.FirstOrDefaultAsync(p => p.Id == id, ct)
?? throw new KeyNotFoundException($"Proposal {id} not found");
if (proposal.Status == ProposalStatus.Sent)
return MapToResponse(proposal);
if (proposal.Status != ProposalStatus.Approved)
throw new InvalidOperationException("Only approved proposals can be marked as sent");
@ -211,13 +226,21 @@ public class ProposalService : IProposalService
.FirstOrDefaultAsync(p => p.Id == id, ct)
?? throw new KeyNotFoundException($"Proposal {id} not found");
if (proposal.Status == ProposalStatus.Revised)
{
var existingRevision = await _db.Proposals
.FirstOrDefaultAsync(p => p.ParentProposalId == proposal.Id, ct);
if (existingRevision != null)
return MapToResponse(existingRevision);
}
if (proposal.Status != ProposalStatus.Sent)
throw new InvalidOperationException("Only sent proposals can be revised");
var revision = new Proposal
{
Id = Guid.NewGuid(),
ProposalNumber = proposal.ProposalNumber,
ProposalNumber = $"{proposal.ProposalNumber}-R{proposal.CurrentRevision + 1}",
WorkOrderNumber = proposal.WorkOrderNumber,
CustomerName = proposal.CustomerName,
CustomerAddress = proposal.CustomerAddress,

View file

@ -93,7 +93,9 @@ export class ComputeStack extends cdk.Stack {
// Lambda to pre-create the vector index (retries until AOSS access policy propagates)
const indexCreatorFn = new lambda.Function(this, 'OssIndexCreator', {
functionName: 'proposal-system-oss-index-creator',
runtime: lambda.Runtime.PYTHON_3_12,
architecture: lambda.Architecture.ARM_64,
handler: 'app.handler',
code: lambda.Code.fromAsset('../lambdas/oss-index-creator', {
bundling: {
@ -105,6 +107,7 @@ export class ComputeStack extends cdk.Stack {
},
}),
timeout: cdk.Duration.minutes(6),
logRetention: logs.RetentionDays.TWO_MONTHS,
});
indexCreatorFn.addToRolePolicy(new iam.PolicyStatement({

View file

@ -210,7 +210,7 @@ export class FoundationStack extends cdk.Stack {
});
// Web App Client (PKCE)
userPool.addClient('WebClient', {
const webClient = userPool.addClient('WebClient', {
userPoolClientName: 'proposal-system-web',
generateSecret: false,
authFlows: {
@ -235,7 +235,7 @@ export class FoundationStack extends cdk.Stack {
});
// Mobile App Client (PKCE)
userPool.addClient('MobileClient', {
const mobileClient = userPool.addClient('MobileClient', {
userPoolClientName: 'proposal-system-mobile',
generateSecret: false,
authFlows: {
@ -248,8 +248,8 @@ export class FoundationStack extends cdk.Stack {
cognito.OAuthScope.EMAIL,
cognito.OAuthScope.PROFILE,
],
callbackUrls: ['proposalsystem://callback'],
logoutUrls: ['proposalsystem://logout'],
callbackUrls: ['com.seahavenind.proposals://auth/callback'],
logoutUrls: ['com.seahavenind.proposals://auth/logout'],
},
});
@ -278,5 +278,7 @@ export class FoundationStack extends cdk.Stack {
new cdk.CfnOutput(this, 'LibraryBucketName', { value: this.libraryBucket.bucketName });
new cdk.CfnOutput(this, 'JobsQueueUrl', { value: this.jobsQueue.queueUrl });
new cdk.CfnOutput(this, 'DbSecretArn', { value: this.dbSecret.secretArn });
new cdk.CfnOutput(this, 'WebClientId', { value: webClient.userPoolClientId });
new cdk.CfnOutput(this, 'MobileClientId', { value: mobileClient.userPoolClientId });
}
}

View file

@ -8,7 +8,6 @@ then triggers a KB sync.
import json
import logging
import os
import time
from datetime import datetime
import boto3
@ -199,27 +198,3 @@ def _api_headers() -> dict:
if api_key:
headers["X-Internal-Api-Key"] = api_key
return headers
def _api_request(method: str, url: str, retries: int = 3, **kwargs) -> httpx.Response:
kwargs.setdefault("headers", _api_headers())
kwargs.setdefault("timeout", 10)
for attempt in range(retries):
try:
resp = httpx.request(method, url, **kwargs)
if resp.status_code < 500:
return resp
logger.warning(
"API returned %s on attempt %d for %s",
resp.status_code,
attempt + 1,
url,
)
except httpx.TransportError as e:
logger.warning(
"Transport error on attempt %d for %s: %s", attempt + 1, url, e
)
if attempt == retries - 1:
raise
time.sleep(min(2**attempt, 4))
return resp # type: ignore[possibly-undefined]

View file

@ -37,9 +37,7 @@ def handler(event, context):
)
index_body = {
"settings": {
"index": {"knn": True, "knn.algo_param.ef_search": 512}
},
"settings": {"index": {"knn": True, "knn.algo_param.ef_search": 512}},
"mappings": {
"properties": {
vector_field: {

View file

@ -1,3 +1,3 @@
opensearch-py>=3.2.0
requests-aws4auth>=1.2.0
requests-aws4auth>=1.3.2
requests>=2.34.2

View file

@ -9,7 +9,6 @@ import json
import logging
import os
import tempfile
import time
import boto3
import httpx
@ -339,27 +338,3 @@ def _api_headers() -> dict:
if api_key:
headers["X-Internal-Api-Key"] = api_key
return headers
def _api_request(method: str, url: str, retries: int = 3, **kwargs) -> httpx.Response:
kwargs.setdefault("headers", _api_headers())
kwargs.setdefault("timeout", 10)
for attempt in range(retries):
try:
resp = httpx.request(method, url, **kwargs)
if resp.status_code < 500:
return resp
logger.warning(
"API returned %s on attempt %d for %s",
resp.status_code,
attempt + 1,
url,
)
except httpx.TransportError as e:
logger.warning(
"Transport error on attempt %d for %s: %s", attempt + 1, url, e
)
if attempt == retries - 1:
raise
time.sleep(min(2**attempt, 4))
return resp # type: ignore[possibly-undefined]

View file

@ -7,7 +7,6 @@ Triggered via SQS when an admin requests PDF generation.
import json
import logging
import os
import time
from datetime import datetime
from io import BytesIO
@ -543,27 +542,3 @@ def _api_headers() -> dict:
if api_key:
headers["X-Internal-Api-Key"] = api_key
return headers
def _api_request(method: str, url: str, retries: int = 3, **kwargs) -> httpx.Response:
kwargs.setdefault("headers", _api_headers())
kwargs.setdefault("timeout", 10)
for attempt in range(retries):
try:
resp = httpx.request(method, url, **kwargs)
if resp.status_code < 500:
return resp
logger.warning(
"API returned %s on attempt %d for %s",
resp.status_code,
attempt + 1,
url,
)
except httpx.TransportError as e:
logger.warning(
"Transport error on attempt %d for %s: %s", attempt + 1, url, e
)
if attempt == retries - 1:
raise
time.sleep(min(2**attempt, 4))
return resp # type: ignore[possibly-undefined]

View file

@ -7,7 +7,6 @@ to generate line item suggestions for new proposals.
import json
import logging
import os
import time
import boto3
import httpx
@ -320,27 +319,3 @@ def _api_headers() -> dict:
if api_key:
headers["X-Internal-Api-Key"] = api_key
return headers
def _api_request(method: str, url: str, retries: int = 3, **kwargs) -> httpx.Response:
kwargs.setdefault("headers", _api_headers())
kwargs.setdefault("timeout", 10)
for attempt in range(retries):
try:
resp = httpx.request(method, url, **kwargs)
if resp.status_code < 500:
return resp
logger.warning(
"API returned %s on attempt %d for %s",
resp.status_code,
attempt + 1,
url,
)
except httpx.TransportError as e:
logger.warning(
"Transport error on attempt %d for %s: %s", attempt + 1, url, e
)
if attempt == retries - 1:
raise
time.sleep(min(2**attempt, 4))
return resp # type: ignore[possibly-undefined]

92
mobile/README.md Normal file
View file

@ -0,0 +1,92 @@
# Proposal System — Mobile (iOS)
React Native 0.85 iOS app for Sea Haven Industries field dispatchers. Submit proposals, capture vendor documents, and manage drafts with offline support.
## Prerequisites
- Node.js 24+
- Ruby 3.x (for Fastlane)
- Xcode 26+ with iOS 26 SDK
- CocoaPods (installed via Bundler)
## Local Development
```bash
# Install JS dependencies
npm install
# Install Ruby dependencies (Fastlane, CocoaPods)
bundle install
# Install native pods
cd ios && bundle exec pod install && cd ..
# Start Metro bundler
npm start
# Run on iOS simulator
npm run ios
```
### Environment
The app reads configuration from `src/config.ts`. In development mode (`__DEV__`), the API URL points to `http://localhost:5000/api`. Run the .NET API locally or use the development proxy.
### Authentication
Two login methods are supported:
- **Email/Password** — direct Cognito SRP auth via `amazon-cognito-identity-js`
- **Google OAuth** — Cognito Hosted UI PKCE flow via `react-native-app-auth`
The iOS URL scheme `com.seahavenind.proposals` is registered in `Info.plist` for OAuth callbacks.
## Code Signing
Certificates and provisioning profiles are managed by **Fastlane Match** using S3 storage:
- **Bucket**: `seahaven-ios-certificates` (us-east-1)
- **Bundle ID**: `com.seahavenind.proposals`
- **Team ID**: `9KAQYC653W`
Match is configured in `fastlane/Matchfile`. The `MATCH_PASSWORD` secret decrypts signing assets.
## CI/CD
The `deploy-mobile.yaml` workflow triggers on push to `main` (with `mobile/**` path filter) or manual `workflow_dispatch`. It calls the `cd-mobile-ios.yaml` reusable workflow which:
1. Sets up `macos-26` runner with Xcode 26
2. Installs dependencies and pods
3. Retrieves signing assets via Match (S3)
4. Builds the IPA with Fastlane
5. Uploads to TestFlight
### Required GitHub Secrets
| Secret | Purpose |
|---|---|
| `AWS_DEPLOY_ROLE_ARN` | OIDC role for Match S3 access |
| `MATCH_PASSWORD` | Signing asset decryption passphrase |
| `ASC_KEY_ID` | App Store Connect API key ID |
| `ASC_ISSUER_ID` | App Store Connect API issuer |
| `ASC_KEY_CONTENT` | App Store Connect `.p8` key (base64) |
## Project Structure
```
mobile/
├── src/
│ ├── screens/ Auth, dispatcher, and admin screens
│ ├── lib/api/ API clients (auth, proposals, line items, admin)
│ ├── store/ Redux Toolkit (auth slice)
│ ├── navigation/ React Navigation (RootNavigator)
│ ├── components/ Reusable UI components
│ ├── hooks/ useAuth, useOfflineDraft, usePaginatedList
│ ├── theme/ Material Design 3 theming
│ ├── constants/ App-wide constants
│ └── config.ts Cognito + API configuration
├── ios/ Xcode project, assets, Info.plist
├── fastlane/ Fastfile, Matchfile, Appfile
├── Gemfile Ruby dependencies
└── package.json React Native 0.85.3
```

View file

@ -1,18 +1,137 @@
require 'openssl'
require 'base64'
require 'tempfile'
# OpenSSL 3.x rejects PKCS#8 keys via EC.new ("invalid curve name").
# Prepend a wrapper that falls back to PKey.read for both formats.
module OpenSSLECNewFix
def new(arg = nil, *rest)
super
rescue OpenSSL::PKey::ECError
raise if arg.nil? || !arg.is_a?(String)
OpenSSL::PKey.read(arg)
end
end
OpenSSL::PKey::EC.singleton_class.prepend(OpenSSLECNewFix)
def normalize_p8_key(raw)
candidates = []
cleaned = raw.gsub("\r", "")
with_newlines = cleaned.gsub('\n', "\n")
candidates << ["raw (newlines normalized)", with_newlines]
if with_newlines.include?("BEGIN")
b64_body = with_newlines.gsub(/-----(?:BEGIN|END)[^-]+-----/, '').gsub(/\s+/, '')
rewrapped = "-----BEGIN PRIVATE KEY-----\n#{b64_body.scan(/.{1,64}/).join("\n")}\n-----END PRIVATE KEY-----\n"
candidates << ["rewrapped PEM", rewrapped]
end
unless with_newlines.include?("BEGIN")
body = cleaned.strip.gsub(/\s+/, '')
pem = "-----BEGIN PRIVATE KEY-----\n#{body.scan(/.{1,64}/).join("\n")}\n-----END PRIVATE KEY-----\n"
candidates << ["headerless body → PEM", pem]
end
begin
decoded = Base64.decode64(cleaned.strip)
if decoded.include?("BEGIN")
decoded_clean = decoded.gsub("\r", "").gsub('\n', "\n")
candidates << ["base64→PEM", decoded_clean]
b64_body = decoded_clean.gsub(/-----(?:BEGIN|END)[^-]+-----/, '').gsub(/\s+/, '')
rewrapped = "-----BEGIN PRIVATE KEY-----\n#{b64_body.scan(/.{1,64}/).join("\n")}\n-----END PRIVATE KEY-----\n"
candidates << ["base64→PEM rewrapped", rewrapped]
elsif decoded.length.between?(32, 256)
candidates << ["base64→DER", decoded]
der_pem = "-----BEGIN PRIVATE KEY-----\n#{Base64.strict_encode64(decoded).scan(/.{1,64}/).join("\n")}\n-----END PRIVATE KEY-----\n"
candidates << ["base64→DER→PEM", der_pem]
end
rescue StandardError
# not valid base64
end
begin
double = Base64.decode64(Base64.decode64(cleaned.strip).strip)
if double.include?("BEGIN")
candidates << ["double-base64→PEM", double.gsub("\r", "")]
elsif double.length.between?(32, 256)
der_pem = "-----BEGIN PRIVATE KEY-----\n#{Base64.strict_encode64(double).scan(/.{1,64}/).join("\n")}\n-----END PRIVATE KEY-----\n"
candidates << ["double-base64→DER→PEM", der_pem]
end
rescue StandardError
# not double-encoded
end
candidates.each do |name, content|
begin
OpenSSL::PKey.read(content)
UI.success("ASC key parsed with strategy: #{name}")
return content
rescue StandardError => e
UI.message("Strategy '#{name}' failed: #{e.class} — #{e.message}")
end
end
UI.error("=== ASC KEY DIAGNOSTIC (no key material shown) ===")
UI.error("Raw byte length: #{raw.bytesize}")
UI.error("Starts with BEGIN: #{raw.strip.start_with?('-----BEGIN')}")
UI.error("Ends with -----: #{raw.strip.end_with?('-----')}")
UI.error("Has real newlines: #{raw.include?("\n")}")
UI.error("Has literal backslash-n: #{raw.include?('\\n')}")
UI.error("Has carriage returns: #{raw.include?("\r")}")
UI.error("Printable ASCII ratio: #{(raw.count(' -~').to_f / raw.bytesize * 100).round(1)}%")
UI.error("Header (first 27 chars): #{raw[0..26]}")
begin
d = Base64.decode64(raw.strip)
hex = d.bytes[0..15].map { |b| format('%02x', b) }.join(' ')
UI.error("After base64 decode — length: #{d.bytesize}, first 16 bytes hex: #{hex}")
rescue StandardError
UI.error("base64 decode raised an exception")
end
UI.error("=== END DIAGNOSTIC ===")
raise "Could not parse ASC_KEY_CONTENT in any known format. See diagnostics above."
end
default_platform(:ios)
platform :ios do
desc "Build and upload to TestFlight"
lane :beta do
setup_ci
setup_ci(force: true)
key_pem = normalize_p8_key(ENV["ASC_KEY_CONTENT"])
key_path = File.join(Dir.tmpdir, "asc_api_key.p8")
File.write(key_path, key_pem)
app_store_connect_api_key(
key_id: ENV["ASC_KEY_ID"],
issuer_id: ENV["ASC_ISSUER_ID"],
key_content: ENV["ASC_KEY_CONTENT"],
is_key_content_base64: true
key_filepath: key_path
)
match(type: "appstore", readonly: true)
File.delete(key_path) if File.exist?(key_path)
match(
type: "appstore",
readonly: true,
keychain_name: "fastlane_tmp_keychain",
keychain_password: ""
)
update_code_signing_settings(
use_automatic_signing: false,
team_id: "9KAQYC653W",
code_sign_identity: "Apple Distribution",
profile_name: "match AppStore com.seahavenind.proposals",
path: "ios/ProposalSystem.xcodeproj"
)
node_path = sh("which node").strip
xcode_env_path = File.join(__dir__, "..", "ios", ".xcode.env.local")
File.write(xcode_env_path, "export NODE_BINARY=#{node_path}\n")
UI.message("NODE_BINARY set to #{node_path} at #{xcode_env_path}")
increment_build_number(
build_number: ENV["GITHUB_RUN_NUMBER"],
@ -24,8 +143,10 @@ platform :ios do
scheme: "ProposalSystem",
configuration: "Release",
export_method: "app-store",
export_team_id: "9KAQYC653W",
output_directory: "build",
output_name: "ProposalSystem.ipa"
output_name: "ProposalSystem.ipa",
xcodebuild_formatter: "cat"
)
upload_to_testflight(skip_waiting_for_build_processing: true)

File diff suppressed because it is too large Load diff

View file

@ -1,46 +1,55 @@
{
"images" : [
{
"filename" : "Icon-40.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"filename" : "Icon-60.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"filename" : "Icon-58.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"filename" : "Icon-87.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"filename" : "Icon-80.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"filename" : "Icon-120.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"filename" : "Icon-120.png",
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"filename" : "Icon-180.png",
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"filename" : "Icon-1024.png",
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"

Binary file not shown.

After

Width:  |  Height:  |  Size: 6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 292 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 695 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 B

View file

@ -8,6 +8,8 @@
<string>Sea Haven Proposals</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconName</key>
<string>AppIcon</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
@ -20,6 +22,17 @@
<string>$(MARKETING_VERSION)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.seahavenind.proposals</string>
<key>CFBundleURLSchemes</key>
<array>
<string>com.seahavenind.proposals</string>
</array>
</dict>
</array>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
@ -31,35 +44,14 @@
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>com.seahavenind.proposals</string>
</array>
<key>CFBundleURLName</key>
<string>com.seahavenind.proposals</string>
</dict>
</array>
<key>NSCameraUsageDescription</key>
<string>Sea Haven Proposals needs camera access to capture vendor proposal documents.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Sea Haven Proposals needs photo library access to attach vendor proposal images.</string>
<key>NSFaceIDUsageDescription</key>
<string>Sea Haven Proposals uses Face ID to secure your login session.</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSPhotoLibraryUsageDescription</key>
<string>Sea Haven Proposals needs photo library access to attach vendor proposal images.</string>
<key>RCTNewArchEnabled</key>
<true/>
<key>UIAppFonts</key>
<array>
<string>MaterialCommunityIcons.ttf</string>
@ -82,6 +74,18 @@
<string>FontAwesome6_Brands.ttf</string>
<string>MaterialIcons.ttf</string>
</array>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>

4360
mobile/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -6,20 +6,22 @@
"start": "react-native start",
"ios": "react-native run-ios",
"android": "react-native run-android",
"typecheck": "tsc --noEmit"
"typecheck": "tsc --noEmit",
"postinstall": "patch-package"
},
"dependencies": {
"@proposal-system/api-contracts": "file:../shared/api-contracts",
"@react-native-async-storage/async-storage": "^2.1.0",
"@react-native-community/netinfo": "^11.4.0",
"@react-native-community/netinfo": "^12.0.1",
"@react-navigation/bottom-tabs": "^7.2.0",
"@react-navigation/native": "^7.0.0",
"@react-navigation/native-stack": "^7.2.0",
"@reduxjs/toolkit": "^2.11.2",
"@tanstack/react-query": "^5.100.10",
"amazon-cognito-identity-js": "^6.3.0",
"axios": "^1.16.0",
"react": "^19.0.0",
"react-native": "^0.79.0",
"react": "19.2.3",
"react-native": "^0.85.3",
"react-native-app-auth": "^8.0.0",
"react-native-document-picker": "^9.3.0",
"react-native-haptic-feedback": "^2.3.0",
@ -33,10 +35,13 @@
"react-redux": "^9.2.0"
},
"devDependencies": {
"@react-native-community/cli": "^20.1.3",
"@react-native-community/cli-platform-ios": "^20.1.3",
"@react-native/babel-preset": "^0.85.3",
"@react-native/metro-config": "^0.79.0",
"@react-native/metro-config": "^0.85.3",
"@types/react": "^19.0.0",
"@types/react-native-vector-icons": "^6.4.18",
"patch-package": "^8.0.1",
"typescript": "~5.7.0"
}
}

View file

@ -0,0 +1,65 @@
diff --git a/node_modules/@react-native-community/netinfo/ios/RNCConnectionState.m b/node_modules/@react-native-community/netinfo/ios/RNCConnectionState.m
index 5a807a4..94e53f8 100644
--- a/node_modules/@react-native-community/netinfo/ios/RNCConnectionState.m
+++ b/node_modules/@react-native-community/netinfo/ios/RNCConnectionState.m
@@ -47,24 +47,28 @@
_expensive = true;
CTTelephonyNetworkInfo *netinfo = [[CTTelephonyNetworkInfo alloc] init];
- if (netinfo) {
- if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyGPRS] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyEdge] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
+ if (netinfo && [netinfo respondsToSelector:@selector(currentRadioAccessTechnology)]) {
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+ NSString *radio = netinfo.currentRadioAccessTechnology;
+#pragma clang diagnostic pop
+ if ([radio isEqualToString:CTRadioAccessTechnologyGPRS] ||
+ [radio isEqualToString:CTRadioAccessTechnologyEdge] ||
+ [radio isEqualToString:CTRadioAccessTechnologyCDMA1x]) {
_cellularGeneration = RNCCellularGeneration2g;
- } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyWCDMA] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSDPA] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyHSUPA] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyeHRPD]) {
+ } else if ([radio isEqualToString:CTRadioAccessTechnologyWCDMA] ||
+ [radio isEqualToString:CTRadioAccessTechnologyHSDPA] ||
+ [radio isEqualToString:CTRadioAccessTechnologyHSUPA] ||
+ [radio isEqualToString:CTRadioAccessTechnologyCDMAEVDORev0] ||
+ [radio isEqualToString:CTRadioAccessTechnologyCDMAEVDORevA] ||
+ [radio isEqualToString:CTRadioAccessTechnologyCDMAEVDORevB] ||
+ [radio isEqualToString:CTRadioAccessTechnologyeHRPD]) {
_cellularGeneration = RNCCellularGeneration3g;
- } else if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyLTE]) {
+ } else if ([radio isEqualToString:CTRadioAccessTechnologyLTE]) {
_cellularGeneration = RNCCellularGeneration4g;
} else if (@available(iOS 14.1, *)) {
- if ([netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNRNSA] ||
- [netinfo.currentRadioAccessTechnology isEqualToString:CTRadioAccessTechnologyNR]) {
+ if ([radio isEqualToString:CTRadioAccessTechnologyNRNSA] ||
+ [radio isEqualToString:CTRadioAccessTechnologyNR]) {
_cellularGeneration = RNCCellularGeneration5g;
}
}
diff --git a/node_modules/@react-native-community/netinfo/ios/RNCNetInfo.mm b/node_modules/@react-native-community/netinfo/ios/RNCNetInfo.mm
index baa2de0..6b75224 100644
--- a/node_modules/@react-native-community/netinfo/ios/RNCNetInfo.mm
+++ b/node_modules/@react-native-community/netinfo/ios/RNCNetInfo.mm
@@ -190,7 +190,13 @@ RCT_EXPORT_METHOD(configure:(NSDictionary *)config)
return nil;
#else
CTTelephonyNetworkInfo *netinfo = [[CTTelephonyNetworkInfo alloc] init];
+ if (![netinfo respondsToSelector:@selector(subscriberCellularProvider)]) {
+ return nil;
+ }
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
CTCarrier *carrier = [netinfo subscriberCellularProvider];
+#pragma clang diagnostic pop
return carrier.carrierName;
#endif
}

View file

@ -1,10 +1,10 @@
import React, { useEffect } from 'react';
import React, { useEffect, Component, ErrorInfo, ReactNode } from 'react';
import { Provider as ReduxProvider, useDispatch } from 'react-redux';
import { PaperProvider } from 'react-native-paper';
import { QueryClientProvider } from '@tanstack/react-query';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import NetInfo from '@react-native-community/netinfo';
import { Alert } from 'react-native';
import { Alert, Text, View } from 'react-native';
import { store } from './store';
import { theme } from './theme';
@ -15,6 +15,26 @@ import { setUser, setLoading } from './store/slices/authSlice';
import { processOfflineQueue } from './hooks/useOfflineDraft';
import { proposalsApi, CreateProposalRequest } from './lib/api/proposals';
class ErrorBoundary extends Component<{ children: ReactNode }, { error: Error | null }> {
state = { error: null as Error | null };
static getDerivedStateFromError(error: Error) { return { error }; }
componentDidCatch(error: Error, info: ErrorInfo) {
console.error('ErrorBoundary caught:', error, info.componentStack);
}
render() {
if (this.state.error) {
return (
<View style={{ flex: 1, justifyContent: 'center', padding: 32, backgroundColor: '#fff' }}>
<Text style={{ fontSize: 18, fontWeight: 'bold', color: 'red', marginBottom: 8 }}>App Error</Text>
<Text style={{ fontSize: 14, color: '#333' }}>{this.state.error.message}</Text>
<Text style={{ fontSize: 12, color: '#666', marginTop: 8 }}>{this.state.error.stack?.slice(0, 500)}</Text>
</View>
);
}
return this.props.children;
}
}
function AuthBootstrap({ children }: { children: React.ReactNode }) {
const dispatch = useDispatch();
@ -41,14 +61,16 @@ function AuthBootstrap({ children }: { children: React.ReactNode }) {
if (state.isConnected) {
processOfflineQueue((data) =>
proposalsApi.create(data as CreateProposalRequest),
).then((count) => {
if (count > 0) {
Alert.alert(
'Synced',
`${count} offline proposal${count > 1 ? 's' : ''} submitted.`,
);
}
});
)
.then((count) => {
if (count > 0) {
Alert.alert(
'Synced',
`${count} offline proposal${count > 1 ? 's' : ''} submitted.`,
);
}
})
.catch(() => {});
}
});
return unsubscribe;
@ -59,16 +81,18 @@ function AuthBootstrap({ children }: { children: React.ReactNode }) {
export default function App() {
return (
<ReduxProvider store={store}>
<QueryClientProvider client={queryClient}>
<PaperProvider theme={theme}>
<SafeAreaProvider>
<AuthBootstrap>
<RootNavigator />
</AuthBootstrap>
</SafeAreaProvider>
</PaperProvider>
</QueryClientProvider>
</ReduxProvider>
<ErrorBoundary>
<ReduxProvider store={store}>
<QueryClientProvider client={queryClient}>
<PaperProvider theme={theme}>
<SafeAreaProvider>
<AuthBootstrap>
<RootNavigator />
</AuthBootstrap>
</SafeAreaProvider>
</PaperProvider>
</QueryClientProvider>
</ReduxProvider>
</ErrorBoundary>
);
}

View file

@ -2,9 +2,9 @@ const Config = {
API_URL: __DEV__
? 'http://localhost:5000/api'
: 'https://api.proposals.seahaven.com/api',
COGNITO_DOMAIN: 'proposal-system.auth.us-east-1.amazoncognito.com',
COGNITO_CLIENT_ID: '',
COGNITO_USER_POOL_ID: '',
COGNITO_DOMAIN: 'proposal-system-seahaven.auth.us-east-1.amazoncognito.com',
COGNITO_CLIENT_ID: '3egjbljml6o9qg3q155t784018',
COGNITO_USER_POOL_ID: 'us-east-1_DfWcl2q5z',
COGNITO_REDIRECT_URI: 'com.seahavenind.proposals://auth/callback',
COGNITO_SCOPES: ['openid', 'email', 'profile'],
};

View file

@ -21,6 +21,7 @@ export function usePaginatedList<T>(
const [pageSize, setPageSize] = useState(DEFAULT_PAGE_SIZE);
const [totalCount, setTotalCount] = useState(0);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [err, setErr] = useState('');
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@ -37,8 +38,7 @@ export function usePaginatedList<T>(
};
}, [search]);
const reload = useCallback(() => {
setLoading(true);
const fetchData = useCallback(() => {
setErr('');
fetchFn({ search: debouncedSearch, page, pageSize, ...extraParams })
.then(({ items, totalCount: total }) => {
@ -46,13 +46,22 @@ export function usePaginatedList<T>(
setTotalCount(total);
})
.catch((e: Error) => setErr(e.message || 'Failed to load'))
.finally(() => setLoading(false));
.finally(() => {
setLoading(false);
setRefreshing(false);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fetchFn, debouncedSearch, page, pageSize, extraKey]);
useEffect(() => {
reload();
}, [reload]);
setLoading(true);
fetchData();
}, [fetchData]);
const reload = useCallback(() => {
setRefreshing(true);
fetchData();
}, [fetchData]);
return useMemo(
() => ({
@ -65,9 +74,10 @@ export function usePaginatedList<T>(
setPageSize,
totalCount,
loading,
refreshing,
err,
reload,
}),
[rows, search, page, pageSize, totalCount, loading, err, reload],
[rows, search, page, pageSize, totalCount, loading, refreshing, err, reload],
);
}

View file

@ -1,6 +1,7 @@
import { authorize, refresh, revoke } from 'react-native-app-auth';
import Config from '../../config';
import apiClient from './client';
import { authenticateWithCredentials } from './cognito-auth';
import {
tokenStorage,
userStorage,
@ -8,6 +9,22 @@ import {
StoredUser,
} from '../storage';
function parseUserFromIdToken(idToken: string): StoredUser {
const base64Url = idToken.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const payload = JSON.parse(atob(base64));
const groups: string[] = payload['cognito:groups'] || [];
const role = groups.includes('admins') || groups.includes('sysadmins')
? 'Admin'
: 'Dispatcher';
return {
id: payload.sub,
email: payload.email,
displayName: payload.name || payload.email,
role: role as StoredUser['role'],
};
}
const cognitoConfig = {
clientId: Config.COGNITO_CLIENT_ID,
redirectUrl: Config.COGNITO_REDIRECT_URI,
@ -38,6 +55,30 @@ export const authApi = {
return profile;
},
loginWithCredentials: async (
email: string,
password: string,
): Promise<StoredUser> => {
const cognitoTokens = await authenticateWithCredentials(email, password);
const tokens: StoredTokens = {
accessToken: cognitoTokens.accessToken,
idToken: cognitoTokens.idToken,
refreshToken: cognitoTokens.refreshToken,
expiresAt: cognitoTokens.expiresAt,
};
await tokenStorage.save(tokens);
let profile: StoredUser;
try {
profile = await authApi.getMe();
} catch {
profile = parseUserFromIdToken(cognitoTokens.idToken);
}
await userStorage.save(profile);
return profile;
},
refreshTokens: async (): Promise<void> => {
const stored = await tokenStorage.get();
if (!stored?.refreshToken) throw new Error('No refresh token');

View file

@ -0,0 +1,67 @@
import Config from '../../config';
export interface CognitoTokens {
accessToken: string;
idToken: string;
refreshToken: string;
expiresAt: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function extractTokens(session: any): CognitoTokens {
const accessToken = session.getAccessToken();
return {
accessToken: accessToken.getJwtToken(),
idToken: session.getIdToken().getJwtToken(),
refreshToken: session.getRefreshToken().getToken(),
expiresAt: new Date(accessToken.getExpiration() * 1000).toISOString(),
};
}
export async function authenticateWithCredentials(
email: string,
password: string,
): Promise<CognitoTokens> {
const {
CognitoUserPool,
CognitoUser,
AuthenticationDetails,
} = await import('amazon-cognito-identity-js');
const userPool = new CognitoUserPool({
UserPoolId: Config.COGNITO_USER_POOL_ID,
ClientId: Config.COGNITO_CLIENT_ID,
});
return new Promise((resolve, reject) => {
const cognitoUser = new CognitoUser({
Username: email,
Pool: userPool,
});
const authDetails = new AuthenticationDetails({
Username: email,
Password: password,
});
cognitoUser.authenticateUser(authDetails, {
onSuccess: (session) => {
resolve(extractTokens(session));
},
onFailure: (err) => {
if (err.code === 'NotAuthorizedException') {
reject(new Error('Incorrect email or password.'));
} else if (err.code === 'UserNotFoundException') {
reject(new Error('No account found with that email.'));
} else if (err.code === 'UserNotConfirmedException') {
reject(new Error('Account not confirmed. Contact your administrator.'));
} else {
reject(new Error(err.message || 'Authentication failed.'));
}
},
newPasswordRequired: () => {
reject(new Error('Password change required. Contact your administrator.'));
},
});
});
}

View file

@ -8,7 +8,7 @@ export function SettingsScreen() {
const { user, logout } = useAuth();
return (
<SafeAreaView style={styles.container} edges={['bottom']}>
<SafeAreaView style={styles.container} edges={['top', 'bottom']}>
<View style={styles.content}>
<Card style={styles.card} mode="elevated">
<Card.Content>

View file

@ -30,6 +30,7 @@ export function ProposalQueueScreen() {
search,
setSearch,
loading,
refreshing,
reload,
} = usePaginatedList<ProposalListItem>(
(params) =>
@ -90,7 +91,7 @@ export function ProposalQueueScreen() {
<ProposalCard proposal={item} onPress={() => handlePress(item)} />
)}
refreshControl={
<RefreshControl refreshing={loading} onRefresh={reload} />
<RefreshControl refreshing={refreshing} onRefresh={reload} />
}
contentContainerStyle={rows.length === 0 ? styles.empty : styles.list}
ListEmptyComponent={

View file

@ -1,23 +1,67 @@
import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { Button, Text, Surface } from 'react-native-paper';
import {
View,
StyleSheet,
KeyboardAvoidingView,
Platform,
ScrollView,
} from 'react-native';
import {
Button,
Text,
Surface,
TextInput,
Divider,
HelperText,
} from 'react-native-paper';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useDispatch } from 'react-redux';
import { authApi } from '../../lib/api/auth';
import { setUser, setError } from '../../store/slices/authSlice';
import { setUser, setError, clearError } from '../../store/slices/authSlice';
export function LoginScreen() {
const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [localError, setLocalError] = useState('');
const handleLogin = async () => {
const handleGoogleLogin = async () => {
setLoading(true);
setLocalError('');
dispatch(clearError());
try {
const user = await authApi.login();
dispatch(setUser(user));
} catch (err) {
const message =
err instanceof Error ? err.message : 'Login failed. Please try again.';
setLocalError(message);
dispatch(setError(message));
} finally {
setLoading(false);
}
};
const handleCredentialLogin = async () => {
if (!email.trim() || !password) {
setLocalError('Email and password are required.');
return;
}
setLoading(true);
setLocalError('');
dispatch(clearError());
try {
const user = await authApi.loginWithCredentials(
email.trim().toLowerCase(),
password,
);
dispatch(setUser(user));
} catch (err) {
const message =
err instanceof Error ? err.message : 'Login failed. Please try again.';
setLocalError(message);
dispatch(setError(message));
} finally {
setLoading(false);
@ -26,28 +70,92 @@ export function LoginScreen() {
return (
<SafeAreaView style={styles.container}>
<View style={styles.content}>
<Surface style={styles.logoContainer} elevation={0}>
<Text variant="headlineLarge" style={styles.brand}>
Sea Haven
</Text>
<Text variant="titleMedium" style={styles.brandSub}>
Industries
</Text>
</Surface>
<KeyboardAvoidingView
style={styles.flex}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<ScrollView
contentContainerStyle={styles.content}
keyboardShouldPersistTaps="handled"
>
<Surface style={styles.logoContainer} elevation={0}>
<Text variant="headlineLarge" style={styles.brand}>
Sea Haven
</Text>
<Text variant="titleMedium" style={styles.brandSub}>
Industries
</Text>
</Surface>
<Text variant="headlineSmall" style={styles.title}>
Proposal System
</Text>
<Text variant="bodyLarge" style={styles.subtitle}>
Submit and manage proposals from anywhere
</Text>
<Text variant="headlineSmall" style={styles.title}>
Proposal System
</Text>
<Text variant="bodyLarge" style={styles.subtitle}>
Submit and manage proposals from anywhere
</Text>
<View style={styles.form}>
<TextInput
label="Email"
value={email}
onChangeText={setEmail}
autoCapitalize="none"
autoComplete="email"
keyboardType="email-address"
textContentType="emailAddress"
mode="outlined"
disabled={loading}
style={styles.input}
/>
<TextInput
label="Password"
value={password}
onChangeText={setPassword}
secureTextEntry={!showPassword}
autoCapitalize="none"
autoComplete="password"
textContentType="password"
mode="outlined"
disabled={loading}
style={styles.input}
right={
<TextInput.Icon
icon={showPassword ? 'eye-off' : 'eye'}
onPress={() => setShowPassword(!showPassword)}
/>
}
/>
{localError ? (
<HelperText type="error" visible>
{localError}
</HelperText>
) : null}
<Button
mode="contained"
onPress={handleCredentialLogin}
loading={loading}
disabled={loading}
contentStyle={styles.buttonContent}
style={styles.button}
>
Sign In
</Button>
</View>
<View style={styles.dividerRow}>
<Divider style={styles.dividerLine} />
<Text variant="bodySmall" style={styles.dividerText}>
OR
</Text>
<Divider style={styles.dividerLine} />
</View>
<View style={styles.actions}>
<Button
mode="contained"
mode="outlined"
icon="google"
onPress={handleLogin}
onPress={handleGoogleLogin}
loading={loading}
disabled={loading}
contentStyle={styles.buttonContent}
@ -55,12 +163,12 @@ export function LoginScreen() {
>
Sign in with Google
</Button>
</View>
<Text variant="bodySmall" style={styles.footer}>
Use your Sea Haven Workspace account
</Text>
</View>
<Text variant="bodySmall" style={styles.footer}>
Use your Sea Haven email to sign in
</Text>
</ScrollView>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
@ -70,11 +178,15 @@ const styles = StyleSheet.create({
flex: 1,
backgroundColor: '#FAFAFA',
},
content: {
flex: {
flex: 1,
},
content: {
flexGrow: 1,
justifyContent: 'center',
alignItems: 'center',
paddingHorizontal: 32,
paddingVertical: 24,
},
logoContainer: {
alignItems: 'center',
@ -97,16 +209,33 @@ const styles = StyleSheet.create({
subtitle: {
color: '#757575',
textAlign: 'center',
marginBottom: 48,
marginBottom: 32,
},
actions: {
form: {
width: '100%',
},
input: {
marginBottom: 12,
},
buttonContent: {
paddingVertical: 8,
},
button: {
borderRadius: 8,
width: '100%',
},
dividerRow: {
flexDirection: 'row',
alignItems: 'center',
width: '100%',
marginVertical: 20,
},
dividerLine: {
flex: 1,
},
dividerText: {
color: '#9E9E9E',
marginHorizontal: 16,
},
footer: {
color: '#9E9E9E',

View file

@ -52,7 +52,7 @@ export function DashboardScreen() {
}
>
<Text variant="headlineSmall" style={styles.welcome}>
Welcome, {user?.displayName?.split(' ')[0] || 'there'}
Welcome, {user?.displayName?.includes('@') ? user.displayName.split('@')[0] : user?.displayName?.split(' ')[0] || 'there'}
</Text>
{stats && (

View file

@ -11,6 +11,7 @@ import {
TextInput,
Button,
Text,
Chip,
SegmentedButtons,
Snackbar,
} from 'react-native-paper';
@ -146,16 +147,19 @@ export function NewProposalScreen() {
<Text variant="labelLarge" style={styles.label}>
Service Category
</Text>
<SegmentedButtons
value={draft.serviceCategory}
onValueChange={(v) => updateDraft({ serviceCategory: v })}
buttons={SERVICE_CATEGORIES.map((c) => ({
value: c,
label: c,
}))}
style={styles.segmented}
density="small"
/>
<View style={styles.chipRow}>
{SERVICE_CATEGORIES.map((c) => (
<Chip
key={c}
selected={draft.serviceCategory === c}
showSelectedOverlay
onPress={() => updateDraft({ serviceCategory: c })}
style={styles.chip}
>
{c}
</Chip>
))}
</View>
<Text variant="labelLarge" style={styles.label}>
Priority
@ -247,6 +251,15 @@ const styles = StyleSheet.create({
segmented: {
marginBottom: 16,
},
chipRow: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: 8,
marginBottom: 16,
},
chip: {
marginBottom: 0,
},
hint: {
color: '#9E9E9E',
marginBottom: 12,

View file

@ -3,7 +3,7 @@ import { useSelector } from 'react-redux';
import { Box, Toolbar, Typography } from '@mui/material';
import { selectSidebarOpen } from './app/slices/uiSlice';
import type { RootState } from './app/store';
import ProtectedRoute from './components/ProtectedRoute';
import ProtectedRoute, { RoleGuard } from './components/ProtectedRoute';
import Topbar from './components/Topbar';
import Sidebar from './components/Sidebar';
import LoginPage from './pages/auth/LoginPage';
@ -50,10 +50,10 @@ export default function App() {
<Route path="/proposals/:id" element={<ProposalDetailPage />} />
{/* Admin Routes */}
<Route path="/admin" element={<AdminDashboard />} />
<Route path="/admin/proposals" element={<AdminDashboard />} />
<Route path="/admin/proposals/:id" element={<AdminWorkspace />} />
<Route path="/admin/users" element={<Typography variant="h5" sx={{ p: 2 }}>User Management — Coming Soon</Typography>} />
<Route path="/admin" element={<RoleGuard roles={['Admin', 'SysAdmin']}><AdminDashboard /></RoleGuard>} />
<Route path="/admin/proposals" element={<RoleGuard roles={['Admin', 'SysAdmin']}><AdminDashboard /></RoleGuard>} />
<Route path="/admin/proposals/:id" element={<RoleGuard roles={['Admin', 'SysAdmin']}><AdminWorkspace /></RoleGuard>} />
<Route path="/admin/users" element={<RoleGuard roles={['SysAdmin']}><Typography variant="h5" sx={{ p: 2 }}>User Management — Coming Soon</Typography></RoleGuard>} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>

View file

@ -10,3 +10,13 @@ export default function ProtectedRoute({ children }: { children: React.ReactNode
return <>{children}</>;
}
export function RoleGuard({ roles, children }: { roles: string[]; children: React.ReactNode }) {
const { user } = useAuth();
if (!user || !roles.includes(user.role)) {
return <Navigate to="/" replace />;
}
return <>{children}</>;
}

View file

@ -19,3 +19,17 @@ export const STORAGE_KEY_SIDEBAR = 'sidebarOpen';
export const PROPOSAL_STATUSES = ['Draft', 'InReview', 'Approved', 'Sent', 'Revised'] as const;
export const SERVICE_CATEGORIES = ['HVAC', 'Plumbing', 'Electrical', 'General', 'Renovation'] as const;
export const PRIORITIES = ['Standard', 'Urgent', 'Emergency'] as const;
export const STATUS_COLORS: Record<string, 'default' | 'info' | 'warning' | 'success' | 'error'> = {
Draft: 'default',
InReview: 'info',
Approved: 'success',
Sent: 'success',
Revised: 'warning',
};
export const PRIORITY_COLORS: Record<string, 'default' | 'warning' | 'error'> = {
Standard: 'default',
Urgent: 'warning',
Emergency: 'error',
};

View file

@ -19,7 +19,7 @@ export interface AuditEntry {
userId: string;
userName: string;
action: string;
details: Record<string, unknown>;
details: string | null;
timestamp: string;
ipAddress: string | null;
}
@ -66,11 +66,8 @@ export const adminApi = {
},
getPdf: async (id: string): Promise<{ downloadUrl: string; expiresAt: string } | null> => {
try {
const res = await apiClient.get(`/proposals/${id}/pdf`);
return res.data;
} catch {
return null;
}
const res = await apiClient.get(`/proposals/${id}/pdf`);
if (res.status === 202) return null;
return res.data;
},
};

View file

@ -67,6 +67,7 @@ export interface ProposalFilters {
priority?: string;
fromDate?: string;
toDate?: string;
mine?: boolean;
}
export const proposalsApi = {
@ -83,6 +84,7 @@ export const proposalsApi = {
if (filters.status) params.append('status', filters.status);
if (filters.serviceCategory) params.append('serviceCategory', filters.serviceCategory);
if (filters.priority) params.append('priority', filters.priority);
if (filters.mine) params.append('mine', 'true');
const res = await apiClient.get(`/proposals?${params.toString()}`);
return res.data;

18
web/src/lib/format.ts Normal file
View file

@ -0,0 +1,18 @@
export function formatCurrency(amount: number): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}
export function formatDate(iso: string): string {
return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}
export function formatDateTime(iso: string | null): string {
if (!iso) return '-';
return new Date(iso).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
});
}

View file

@ -1,3 +1,4 @@
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import {
@ -28,29 +29,8 @@ import { usePaginatedList } from '../../../hooks/usePaginatedList';
import { proposalsApi, type ProposalListItem } from '../../../lib/api/proposals';
import { adminApi, type DashboardStats } from '../../../lib/api/admin';
import { QUERY_KEYS } from '../../../constants/queryKeys';
import { SERVICE_CATEGORIES, PRIORITIES } from '../../../constants';
const STATUS_COLORS: Record<string, 'default' | 'info' | 'warning' | 'success'> = {
Draft: 'default',
InReview: 'info',
Approved: 'success',
Sent: 'success',
Revised: 'warning',
};
const PRIORITY_COLORS: Record<string, 'default' | 'warning' | 'error'> = {
Standard: 'default',
Urgent: 'warning',
Emergency: 'error',
};
function formatCurrency(amount: number): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}
function formatDate(iso: string): string {
return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}
import { SERVICE_CATEGORIES, PRIORITIES, STATUS_COLORS, PRIORITY_COLORS } from '../../../constants';
import { formatCurrency, formatDate } from '../../../lib/format';
function StatCard({ icon, label, value, color }: { icon: React.ReactNode; label: string; value: string; color: string }) {
return (
@ -76,6 +56,9 @@ export default function AdminDashboard() {
queryFn: adminApi.getDashboard,
});
const [categoryFilter, setCategoryFilter] = useState('');
const [priorityFilter, setPriorityFilter] = useState('');
const {
rows,
search,
@ -87,7 +70,10 @@ export default function AdminDashboard() {
totalCount,
loading,
err,
} = usePaginatedList<ProposalListItem>(proposalsApi.getAll);
} = usePaginatedList<ProposalListItem>(proposalsApi.getAll, {
...(categoryFilter && { serviceCategory: categoryFilter }),
...(priorityFilter && { priority: priorityFilter }),
});
return (
<Box>
@ -167,9 +153,9 @@ export default function AdminDashboard() {
size="small"
select
label="Category"
value=""
value={categoryFilter}
sx={{ width: 160 }}
onChange={() => {}}
onChange={(e) => setCategoryFilter(e.target.value)}
>
<MenuItem value="">All</MenuItem>
{SERVICE_CATEGORIES.map((c) => (
@ -180,9 +166,9 @@ export default function AdminDashboard() {
size="small"
select
label="Priority"
value=""
value={priorityFilter}
sx={{ width: 140 }}
onChange={() => {}}
onChange={(e) => setPriorityFilter(e.target.value)}
>
<MenuItem value="">All</MenuItem>
{PRIORITIES.map((p) => (

View file

@ -34,14 +34,7 @@ import { QUERY_KEYS } from '../../../constants/queryKeys';
import LineItemEditor, { type EditableLineItem } from '../../../components/admin/LineItemEditor';
import VendorDataPanel from '../../../components/admin/VendorDataPanel';
import SimilarProposalsPanel from '../../../components/admin/SimilarProposalsPanel';
const STATUS_COLORS: Record<string, 'default' | 'info' | 'warning' | 'success'> = {
Draft: 'default',
InReview: 'info',
Approved: 'success',
Sent: 'success',
Revised: 'warning',
};
import { STATUS_COLORS } from '../../../constants';
export default function AdminWorkspace() {
const { id } = useParams<{ id: string }>();
@ -115,10 +108,17 @@ export default function AdminWorkspace() {
});
const approveMutation = useMutation({
mutationFn: () => adminApi.approveProposal(id!),
mutationFn: async () => {
if (dirty) {
await saveMutation.mutateAsync();
}
await adminApi.approveProposal(id!);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.proposals, id] });
queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.proposalLineItems, id] });
setApproveDialogOpen(false);
setDirty(false);
toast.success('Proposal approved');
},
});

View file

@ -39,10 +39,17 @@ export default function LoginPage() {
}
}, [isAuthenticated, navigate]);
const devUsers: Record<string, { email: string; name: string }> = {
SysAdmin: { email: 'adam@seahavenind.com', name: 'Adam Moussa' },
Admin: { email: 'sarah@seahavenind.com', name: 'Sarah Chen' },
Dispatcher: { email: 'mike@seahavenind.com', name: 'Mike Torres' },
};
const handleDevLogin = async (role: string) => {
setLoading(true);
try {
const user = await authApi.devLogin('adam@seahavenind.com', 'Adam Moussa', role);
const dev = devUsers[role] ?? devUsers['SysAdmin']!;
const user = await authApi.devLogin(dev.email, dev.name, role);
dispatch(setUser(user));
navigate('/', { replace: true });
} catch (err) {

View file

@ -23,22 +23,8 @@ import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import SendIcon from '@mui/icons-material/Send';
import { proposalsApi, type ProposalListItem, type ProposalStats } from '../../lib/api/proposals';
import { QUERY_KEYS } from '../../constants/queryKeys';
const STATUS_COLORS: Record<string, 'default' | 'info' | 'warning' | 'success' | 'error'> = {
Draft: 'default',
InReview: 'info',
Approved: 'success',
Sent: 'success',
Revised: 'warning',
};
function formatCurrency(amount: number): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}
function formatDate(iso: string): string {
return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}
import { STATUS_COLORS } from '../../constants';
import { formatCurrency, formatDate } from '../../lib/format';
function KpiCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
return (
@ -61,7 +47,7 @@ export default function Dashboard() {
const { data: recentData, isLoading: recentLoading } = useQuery<{ items: ProposalListItem[]; totalCount: number }>({
queryKey: [QUERY_KEYS.proposals, 'dashboard-recent'],
queryFn: () => proposalsApi.getAll({ page: 1, pageSize: 5 }),
queryFn: () => proposalsApi.getAll({ page: 1, pageSize: 5, mine: true }),
});
const { data: stats, isLoading: statsLoading } = useQuery<ProposalStats>({

View file

@ -16,30 +16,10 @@ import {
} from '@mui/material';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import { proposalsApi, type ProposalDetail } from '../../../lib/api/proposals';
import { STATUS_COLORS } from '../../../constants';
import { formatCurrency, formatDateTime } from '../../../lib/format';
const STATUS_ORDER = ['Draft', 'InReview', 'Approved', 'Sent'];
const STATUS_COLORS: Record<string, 'default' | 'info' | 'warning' | 'success' | 'error'> = {
Draft: 'default',
InReview: 'info',
Approved: 'success',
Sent: 'success',
Revised: 'warning',
};
function formatCurrency(amount: number): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}
function formatDateTime(iso: string | null): string {
if (!iso) return '-';
return new Date(iso).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
});
}
const STATUS_ORDER = ['Draft', 'InReview', 'Approved', 'Sent', 'Revised'];
function InfoRow({ label, value }: { label: string; value: React.ReactNode }) {
return (

View file

@ -1,4 +1,4 @@
import { useState, useCallback } from 'react';
import { useState, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useMutation } from '@tanstack/react-query';
import {
@ -37,6 +37,7 @@ export default function ProposalFormPage() {
const [customerLoading, setCustomerLoading] = useState(false);
const [addresses, setAddresses] = useState<string[]>([]);
const [vendorFile, setVendorFile] = useState<File | null>(null);
const searchDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleChange = (field: keyof CreateProposalRequest, value: string) => {
setForm((prev) => ({ ...prev, [field]: value }));
@ -90,6 +91,9 @@ export default function ProposalFormPage() {
toast.success(`Proposal ${proposal.proposalNumber} submitted`);
navigate(`/proposals/${proposal.id}`);
},
onError: (error: Error) => {
toast.error(error.message || 'Failed to submit proposal');
},
});
const handleSubmit = (e: React.FormEvent) => {
@ -130,7 +134,13 @@ export default function ProposalFormPage() {
options={customers}
getOptionLabel={(opt) => (typeof opt === 'string' ? opt : opt.name)}
loading={customerLoading}
onInputChange={(_, value) => searchCustomers(value)}
onInputChange={(_, value, reason) => {
if (reason === 'input') {
handleChange('customerName', value);
}
if (searchDebounceRef.current) clearTimeout(searchDebounceRef.current);
searchDebounceRef.current = setTimeout(() => searchCustomers(value), 300);
}}
onChange={handleCustomerSelect}
renderInput={(params) => (
<TextField

View file

@ -21,25 +21,12 @@ import SearchIcon from '@mui/icons-material/Search';
import AddCircleIcon from '@mui/icons-material/AddCircle';
import { usePaginatedList } from '../../../hooks/usePaginatedList';
import { proposalsApi, type ProposalListItem } from '../../../lib/api/proposals';
const STATUS_COLORS: Record<string, 'default' | 'info' | 'warning' | 'success' | 'error'> = {
Draft: 'default',
InReview: 'info',
Approved: 'success',
Sent: 'success',
Revised: 'warning',
};
function formatCurrency(amount: number): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(amount);
}
function formatDate(iso: string): string {
return new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
}
import { STATUS_COLORS } from '../../../constants';
import { formatCurrency, formatDate } from '../../../lib/format';
export default function ProposalListPage() {
const navigate = useNavigate();
const mineParams = { mine: true };
const {
rows,
search,
@ -51,7 +38,7 @@ export default function ProposalListPage() {
totalCount,
loading,
err,
} = usePaginatedList<ProposalListItem>(proposalsApi.getAll);
} = usePaginatedList<ProposalListItem>(proposalsApi.getAll, mineParams);
return (
<Box>