Compare commits

...

163 commits

Author SHA1 Message Date
Alexandre Brandizzi
1a76f270ea
Merge branch 'dev' into fix/ab/sh-339-wizard-complete-image 2026-09-17 14:34:46 -03:00
Alexandre Brandizzi
6420b0d091
Merge pull request #214 from Sea-Haven-Industries/feat/ab/sh-325-add-team-member
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-325: add team member form
2026-09-17 14:32:23 -03:00
Alexandre Brandizzi
09c2447094
Merge branch 'dev' into fix/ab/sh-339-wizard-complete-image 2026-09-17 14:26:43 -03:00
Alexandre Brandizzi
a81fd14d7d
Merge branch 'dev' into feat/ab/sh-325-add-team-member 2026-09-17 14:20:16 -03:00
Alexandre Brandizzi
c0b511ed12
Merge pull request #218 from Sea-Haven-Industries/fix/ab/sh-375-edit-error-copy
SH-375: keep backend validation text out of work-order edit errors
2026-09-17 14:18:12 -03:00
Alexandre Brandizzi
8d2adb4472
Merge branch 'dev' into fix/ab/sh-375-edit-error-copy 2026-09-17 14:04:19 -03:00
Codex Review Integration
a65f282b51 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-325-add-team-member 2026-09-17 13:47:06 -03:00
Alexandre Brandizzi
1e1b58c560
Merge pull request #211 from Sea-Haven-Industries/feat/ab/sh-324-team-members-list
SH-324: add searchable team member registry
2026-09-17 13:42:13 -03:00
Alexandre Brandizzi
d6518bc065
Merge branch 'dev' into feat/ab/sh-324-team-members-list 2026-09-17 13:28:10 -03:00
Alexandre Brandizzi
04a248fd53
Merge pull request #210 from Sea-Haven-Industries/feat/ab/sh-187-service-picker
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-187: Use Services registry in work-order picker
2026-09-17 13:14:09 -03:00
Alexandre Brandizzi
c991c9e89f
Merge branch 'dev' into feat/ab/sh-187-service-picker 2026-09-17 13:02:18 -03:00
Alexandre Brandizzi
56a7895950
Merge pull request #206 from Sea-Haven-Industries/fix/ab/sh-320-inline-sh-prefix-wo-number
SH-320: accept SH-prefixed placeholder work-order numbers
2026-09-17 13:00:19 -03:00
Alexandre Brandizzi
8427182209
Merge branch 'dev' into feat/ab/sh-187-service-picker 2026-09-17 12:58:17 -03:00
Alexandre Brandizzi
a9247a1997
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-17 12:50:18 -03:00
Codex Review Integration
b551421115 fix(work-orders): show duplicate-WO copy for edit conflicts (SH-375)
A duplicate work order number edit returns 422 DuplicateWoNumber from the
board PATCH endpoint, which mapped to the generic save-failed copy. Add the
code to the known validation copy map so edits reuse the same duplicate-WO
product text as create, and share the message constant across both paths.
2026-09-17 06:15:23 -03:00
Codex Review Integration
5c093e8c26 Merge remote-tracking branch 'origin/dev' into fix/ab/sh-375-edit-error-copy 2026-09-17 05:59:25 -03:00
Codex Review Integration
824001dc5e fix(work-orders): make service picker search placeholder type-neutral 2026-09-17 01:40:58 -03:00
Codex Review Integration
7cef338e34 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-324-team-members-list
# Conflicts:
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-add.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-detail.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-edit.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-empty.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-error.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-filter.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-inactive.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-list.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-mobile-navigation.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-detail.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-empty.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-error.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-filters.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-list.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-new.png
2026-09-17 00:49:09 -03:00
Alexandre Brandizzi
6972972afe test(visual): regenerate visual baselines for team members nav group 2026-09-17 00:30:36 -03:00
Codex Review Integration
16a2ab5511 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-325-add-team-member 2026-09-17 00:06:18 -03:00
Codex Review Integration
1207df6ed8 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-325-add-team-member
# Conflicts:
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-add.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-detail.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-edit.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-empty.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-error.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-filter.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-inactive.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-list.png
#	e2e/__screenshots__/vendors/vendors.visual.spec.ts/vendor-mobile-navigation.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-detail.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-empty.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-error.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-filters.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-list.png
#	e2e/__screenshots__/work-orders/work-orders.visual.spec.ts/wo-new.png
2026-09-17 00:04:46 -03:00
Alexandre Brandizzi
5e4999b4f2
Merge pull request #207 from Sea-Haven-Industries/fix/ab/sh-359-wo-board-column-order
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-359: place Completed Date before Comp Doc
2026-09-16 23:54:15 -03:00
Alexandre Brandizzi
bc40c17285
Merge branch 'dev' into fix/ab/sh-359-wo-board-column-order 2026-09-16 23:44:07 -03:00
Codex Review Integration
a24b43b219 test(team-members): refresh visual baselines (SH-325) 2026-09-16 23:15:17 -03:00
Codex Review Integration
0ac8c4473e fix(team-members): harden team member flows (SH-325) 2026-09-16 23:14:51 -03:00
Codex Review Integration
ae255f59a6 fix(team-members): destructure load error prop (SH-324) 2026-09-16 22:58:46 -03:00
Codex Review Integration
9160dd472a test(work-orders): refresh startup visual baselines (SH-324) 2026-09-16 22:53:03 -03:00
Codex Review Integration
a4ce537ed6 test(work-orders): tolerate cold visual page startup (SH-324) 2026-09-16 22:50:55 -03:00
Codex Review Integration
4bee428c71 test(team-members): refresh sidebar visual baselines (SH-324) 2026-09-16 22:39:09 -03:00
Codex Review Integration
1df3e5d292 fix(team-members): render load failures distinctly (SH-324) 2026-09-16 22:38:53 -03:00
Codex Review Integration
49923c9a02 test(work-orders): target the Insert WO # placeholder in the SH number e2e
The inline create row now renders the empty WO # cell as a required
"Insert WO # *" field instead of "-", so the spec waited for a cell that
no longer exists.
2026-09-16 22:07:46 -03:00
Alexandre Brandizzi
e6f5199da9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 21:56:20 -03:00
Alexandre Brandizzi
ffaa91bb1b
Merge pull request #194 from Sea-Haven-Industries/feat/ab/sh-222-create-error-copy
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-222: keep backend validation text out of create error toasts
2026-09-16 21:54:18 -03:00
Codex Review Integration
2d54ff12f8 fix(work-orders): show fixed copy for edit conflict toasts (SH-375) 2026-09-16 21:22:07 -03:00
Codex Review Integration
afc98a9daa fix(work-orders): normalize partial-save and generic edit error toasts (SH-375) 2026-09-16 21:20:16 -03:00
Codex Review Integration
fc25d8f7c7 fix(work-orders): show generic copy for unknown edit errors (SH-375) 2026-09-16 21:14:25 -03:00
Alexandre Brandizzi
440a3d0112
Merge branch 'dev' into feat/ab/sh-222-create-error-copy 2026-09-16 20:56:26 -03:00
Alexandre Brandizzi
c0d3300ab1
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:48:14 -03:00
Alexandre Brandizzi
9fb2cc9702
Merge pull request #208 from Sea-Haven-Industries/fix/ab/sh-369-completion-doc-service-gate
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-369: keep completion document disabled until a service is selected
2026-09-16 20:44:14 -03:00
Alexandre Brandizzi
6682fcd7c2
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:30:17 -03:00
Alexandre Brandizzi
5d5581209a
Merge branch 'dev' into fix/ab/sh-369-completion-doc-service-gate 2026-09-16 20:30:14 -03:00
Alexandre Brandizzi
f25aea8bac
Merge pull request #200 from Sea-Haven-Industries/feat/ab/sh-278-vendor-service-area
SH-278: add vendor Service Area assignment, filter and column
2026-09-16 20:26:17 -03:00
Alexandre Brandizzi
fc21321148
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 20:16:18 -03:00
Alexandre Brandizzi
7aa964aa0f
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:16:15 -03:00
Alexandre Brandizzi
20662b57c1
Merge branch 'dev' into fix/ab/sh-369-completion-doc-service-gate 2026-09-16 20:16:13 -03:00
Alexandre Brandizzi
b9535e1484
Merge pull request #199 from Sea-Haven-Industries/feat/ab/sh-195-date-header-tooltips
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-195: Date column header tooltips
2026-09-16 20:12:13 -03:00
Codex Review Integration
9722805300 Merge remote-tracking branch 'origin/dev' into fix/ab/sh-369-completion-doc-service-gate
# Conflicts:
#	src/app/(protected)/workorders/_components/detail/tabs/slide-over-completion-tab.tsx
2026-09-16 20:03:04 -03:00
Alexandre Brandizzi
bbc955e6fe
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 20:00:20 -03:00
Alexandre Brandizzi
e272cabe34
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 20:00:16 -03:00
Alexandre Brandizzi
85a6dad0f9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 20:00:13 -03:00
Alexandre Brandizzi
4f661813d1
Merge pull request #197 from Sea-Haven-Industries/fix/ab/sh-341-generate-completes-work-order
SH-341: complete the work order when the completion document is generated
2026-09-16 19:56:11 -03:00
Codex Review Integration
b6f4590bfa feat(team-members): add member creation form (SH-325) 2026-09-16 19:49:27 -03:00
Alexandre Brandizzi
12d4a0c4b8
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 19:46:33 -03:00
Alexandre Brandizzi
c6ed6072ff
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 19:46:30 -03:00
Alexandre Brandizzi
1c1c6b5670
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 19:46:26 -03:00
Alexandre Brandizzi
ace66f52e5
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:46:22 -03:00
Alexandre Brandizzi
c0a20e74ac
Merge pull request #192 from Sea-Haven-Industries/fix/ab/sh-194-week-scoped-search
SH-194: Keep keyword search week-scoped and Advanced Filters global
2026-09-16 19:42:24 -03:00
Alexandre Brandizzi
ef199e19b6
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:34:20 -03:00
Codex Review Integration
71756ca3a5 fix(work-orders): clear registry service when WO type changes
Selecting a work-order type on wizard step 1 only patched type and
severity, leaving pm, serviceId, extraServices, and the vendor filtered
by that service in the draft. Switching type (e.g. PM -> Reactive) then
submitted a serviceId that is not in the new type's registry list, which
backend ResolveServiceAsync (SH-187/#131) rejects as ServiceInvalid and
the create toast renders as the generic "Unable to create the work
order". Clear the service and its vendor whenever the type actually
changes; re-selecting the same type leaves the selection untouched.
2026-09-16 19:33:08 -03:00
Alexandre Brandizzi
aeb6f7d224
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 19:32:26 -03:00
Alexandre Brandizzi
f752ced38d
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 19:32:23 -03:00
Alexandre Brandizzi
40301e23ab
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 19:32:20 -03:00
Alexandre Brandizzi
3ec6540271
Merge branch 'dev' into fix/ab/sh-194-week-scoped-search 2026-09-16 19:30:44 -03:00
Alexandre Brandizzi
d40090a5c0
Merge pull request #201 from Sea-Haven-Industries/feat/ab/sh-235-severity-badge
SH-235: guard severity tooltip and escalation toast rules with tests
2026-09-16 19:30:23 -03:00
Alexandre Brandizzi
68c4809a16
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 19:18:28 -03:00
Alexandre Brandizzi
331de59f97
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 19:18:25 -03:00
Alexandre Brandizzi
638e33af72
Merge branch 'dev' into feat/ab/sh-235-severity-badge 2026-09-16 19:18:21 -03:00
Alexandre Brandizzi
a793e1c2d9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:18:18 -03:00
Codex Review Integration
04f8b51eab refactor(work-orders): use Tailwind tokens for search scope label
Swap the inline fontSize/color on the week-scope status label for the
text-(length:--text-xs) and text-muted-foreground classes already used
across the header, so it tracks future token changes. --text-xs is 11px
and text-muted-foreground resolves to --muted-foreground, so rendering is
unchanged.
2026-09-16 19:17:28 -03:00
Alexandre Brandizzi
9cce2966f1
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 19:16:15 -03:00
Alexandre Brandizzi
dabdc86c69
Merge pull request #204 from Sea-Haven-Industries/fix/ab/sh-356-due-date-after-schedule
SH-356: keep Due Date on or after Schedule On
2026-09-16 19:14:18 -03:00
Alexandre Brandizzi
33a979c79d
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 19:04:30 -03:00
Alexandre Brandizzi
0ca032ef8f
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 19:04:26 -03:00
Alexandre Brandizzi
0b219311b5
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 19:04:23 -03:00
Alexandre Brandizzi
448ba70d87
Merge branch 'dev' into feat/ab/sh-235-severity-badge 2026-09-16 19:04:20 -03:00
Alexandre Brandizzi
51739fd155
Merge branch 'dev' into fix/ab/sh-356-due-date-after-schedule 2026-09-16 19:04:17 -03:00
Alexandre Brandizzi
b120b43b0f
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 19:04:14 -03:00
Alexandre Brandizzi
2583ad63d1
Merge pull request #198 from Sea-Haven-Industries/feat/ab/sh-197-inline-create-fields
Some checks are pending
Frontend checks / Build and test (push) Waiting to run
Frontend checks / governance (push) Waiting to run
Frontend checks / Visual regression (push) Waiting to run
Deploy dev content / Deploy shoc-frontend-new-dev through Terraform (push) Waiting to run
SH-197: inline create cells as fields with persistent required asterisks
2026-09-16 19:00:20 -03:00
Codex Review Integration
de79daefb1 feat(team-members): add searchable team member registry (SH-324) 2026-09-16 18:54:33 -03:00
Alexandre Brandizzi
f33580972d
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 18:52:33 -03:00
Alexandre Brandizzi
7876b6ca42
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 18:52:29 -03:00
Alexandre Brandizzi
dd34e79e19
Merge branch 'dev' into fix/ab/sh-356-due-date-after-schedule 2026-09-16 18:52:26 -03:00
Alexandre Brandizzi
cd611fd09c
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 18:52:23 -03:00
Alexandre Brandizzi
79f9e52870
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 18:50:23 -03:00
Alexandre Brandizzi
5d1b6e5aa0
Merge branch 'dev' into feat/ab/sh-197-inline-create-fields 2026-09-16 18:50:20 -03:00
Alexandre Brandizzi
1e15eab573
Merge branch 'dev' into feat/ab/sh-235-severity-badge 2026-09-16 18:50:17 -03:00
Alexandre Brandizzi
77b679b8f6
Merge pull request #209 from Sea-Haven-Industries/fix/ab/sh-371-pm-extra-media-gallery
SH-371: show extra media in the gallery on PM work orders
2026-09-16 18:48:17 -03:00
Alexandre Brandizzi
55723a1cfd
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 18:38:38 -03:00
Alexandre Brandizzi
8b5b5903fa
Merge branch 'dev' into feat/ab/sh-197-inline-create-fields 2026-09-16 18:38:35 -03:00
Alexandre Brandizzi
c081ea8d97
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 18:38:32 -03:00
Alexandre Brandizzi
42b5642fec
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 18:38:29 -03:00
Alexandre Brandizzi
d3b74afe5a
Merge branch 'dev' into feat/ab/sh-235-severity-badge 2026-09-16 18:38:26 -03:00
Alexandre Brandizzi
b746087d0b
Merge branch 'dev' into fix/ab/sh-356-due-date-after-schedule 2026-09-16 18:38:23 -03:00
Alexandre Brandizzi
551ed863f4
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 18:38:20 -03:00
Alexandre Brandizzi
2152d2d31c
Merge branch 'dev' into fix/ab/sh-369-completion-doc-service-gate 2026-09-16 18:38:17 -03:00
Alexandre Brandizzi
0f34e8c7c6
Merge branch 'dev' into fix/ab/sh-371-pm-extra-media-gallery 2026-09-16 18:38:14 -03:00
Alexandre Brandizzi
e2a81e3ff8
Merge pull request #195 from Sea-Haven-Industries/fix/ab/sh-357-sh-358-status-transitions
SH-357, SH-358: offer only valid manual status transitions inline
2026-09-16 18:34:26 -03:00
Alexandre Brandizzi
ac2642d5b9
Merge branch 'dev' into fix/ab/sh-320-inline-sh-prefix-wo-number 2026-09-16 18:28:25 -03:00
Alexandre Brandizzi
c135605c87
Merge branch 'dev' into fix/ab/sh-369-completion-doc-service-gate 2026-09-16 18:28:22 -03:00
Alexandre Brandizzi
754912c643
Merge branch 'dev' into fix/ab/sh-371-pm-extra-media-gallery 2026-09-16 18:28:19 -03:00
Codex Review Integration
3a902bfebe feat(work-orders): use services registry picker 2026-09-16 18:26:55 -03:00
Alexandre Brandizzi
daaf588793
Merge branch 'dev' into feat/ab/sh-278-vendor-service-area 2026-09-16 18:26:26 -03:00
Alexandre Brandizzi
f2df213965
Merge branch 'dev' into feat/ab/sh-235-severity-badge 2026-09-16 18:26:23 -03:00
Alexandre Brandizzi
49fd0b039c
Merge branch 'dev' into fix/ab/sh-356-due-date-after-schedule 2026-09-16 18:26:20 -03:00
Alexandre Brandizzi
99f57b9c89
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 18:24:22 -03:00
Alexandre Brandizzi
baf16501cc
Merge branch 'dev' into feat/ab/sh-197-inline-create-fields 2026-09-16 18:24:20 -03:00
Alexandre Brandizzi
ae6ba6978f
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 18:24:17 -03:00
Alexandre Brandizzi
632d01f373
Merge branch 'dev' into fix/ab/sh-357-sh-358-status-transitions 2026-09-16 18:22:16 -03:00
Alexandre Brandizzi
785e112f63
Merge pull request #196 from Sea-Haven-Industries/fix/ab/sh-361-sh-363-audit-log-entries
SH-361, SH-363: full audit timestamps and previous type values
2026-09-16 18:20:19 -03:00
Alexandre Brandizzi
92fa61ad57
Merge branch 'dev' into feat/ab/sh-195-date-header-tooltips 2026-09-16 18:20:16 -03:00
Alexandre Brandizzi
46f90abf8a
Merge branch 'dev' into feat/ab/sh-197-inline-create-fields 2026-09-16 18:18:14 -03:00
Alexandre Brandizzi
d872e08a2b
Merge branch 'dev' into fix/ab/sh-341-generate-completes-work-order 2026-09-16 18:16:14 -03:00
Alexandre Brandizzi
71432ac586
Merge branch 'dev' into fix/ab/sh-357-sh-358-status-transitions 2026-09-16 18:08:14 -03:00
Alexandre Brandizzi
ad1fd7ebf9
Merge branch 'dev' into fix/ab/sh-361-sh-363-audit-log-entries 2026-09-16 18:08:11 -03:00
Adam Moussa
e95a720630
Merge branch 'dev' into feat/ab/sh-222-create-error-copy 2026-09-16 16:46:27 -04:00
Codex Review Integration
e65049691c chore(work-orders): remove ticket keys from lifecycle docs 2026-09-16 17:01:58 -03:00
Codex Review Integration
196ec8a836 fix(work-orders): make date help controls accessible 2026-09-16 16:56:26 -03:00
Codex Review Integration
4e54aa7cfe chore(work-orders): remove ticket keys from completion docs 2026-09-16 16:56:26 -03:00
Codex Review Integration
c75f8b6239 chore(work-orders): remove ticket keys from audit docs 2026-09-16 16:56:26 -03:00
Codex Review Integration
38ea40d6ca Merge origin/dev into feat/ab/sh-278-vendor-service-area 2026-09-16 16:08:12 -03:00
Codex Review Integration
2b2b24f2e3 fix(work-orders): clarify search scope with advanced filters 2026-09-16 15:42:01 -03:00
Codex Review Integration
8774b2e0a6 fix(work-orders): render PM extra media in the gallery (SH-371)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 15:23:24 -03:00
Codex Review Integration
9225f2345c fix(work-orders): gate completion document button on service selection (SH-369)
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 15:23:17 -03:00
Codex Review Integration
4eb929e1c8 test(work-orders): remove query devtools overlay after navigation
Also drops ticket keys from shipped comments and test names.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 15:15:52 -03:00
Alexandre Brandizzi
2d8a35a08a
Merge branch 'dev' into fix/ab/sh-359-wo-board-column-order 2026-09-16 15:08:07 -03:00
Codex Review Integration
62825d2c70 chore(workorders): remove ticket keys from column comments 2026-09-16 15:05:25 -03:00
Alexandre Brandizzi
1f405bbcaf
Merge branch 'dev' into fix/ab/sh-356-due-date-after-schedule 2026-09-16 15:03:34 -03:00
Codex Review Integration
96a066e98f fix(workorders): satisfy SH-356 maintainability gate 2026-09-16 14:30:39 -03:00
Codex Review Integration
49be7ffbc6 test(work-orders): avoid unsupported array at helper 2026-09-16 13:59:22 -03:00
Codex Review Integration
fdc275ab9a test(work-orders): cover the Due Date floor in the wizard 2026-09-16 13:35:12 -03:00
Codex Review Integration
b4d2d69abe fix(work-orders): keep Due Date on or after Schedule On 2026-09-16 13:32:44 -03:00
Codex Review Integration
4649fd00da fix(work-orders): place Completed Date before Comp Doc on the board 2026-09-16 13:21:48 -03:00
Codex Review Integration
050e3f5134 test(work-orders): cover SH placeholder WO numbers on the board 2026-09-16 13:13:35 -03:00
Codex Review Integration
45b988c522 fix(work-orders): accept SH placeholder numbers in the inline WO number field 2026-09-16 13:12:24 -03:00
Codex Review Integration
dace388633 test(work-orders): update empty-state baseline for week search scope label 2026-09-16 12:30:17 -03:00
Codex Review Integration
e13dede629 feat(work-orders): add date column header tooltips
Add a help icon with hover/focus tooltip copy to the Schedule On, Due
Date, and Completed Date board table headers so dispatchers can see
what each date drives without opening a row (SH-195).
2026-09-16 12:05:50 -03:00
Codex Review Integration
88ba480522 test(vendors): refresh visual baselines for Service Area 2026-09-16 12:05:07 -03:00
Codex Review Integration
2bff7176be feat(vendors): add Service Area assignment, filter and column
Replace the free-text vendor State with a closed 50-state list, add an
admin-only Service Area select below Notes, a Service Area advanced filter
(stable ids plus Unassigned) and a Service Area directory column.
2026-09-16 11:55:40 -03:00
Codex Review Integration
f6a22a9096 fix(work-orders): offer only valid manual status transitions inline (SH-357, SH-358)
The inline status control no longer offers the automatic Incomplete and
Scheduled states or the work order's current status. Inline create keeps its
explicit Incomplete/Pending/Scheduled creation list.
2026-09-16 11:43:34 -03:00
Codex Review Integration
e46e42df69 fix(work-orders): show full audit timestamps and previous type values (SH-361, SH-363)
Audit Log entries now show date and time for every entry instead of a
time-only stamp for manual changes. Type and Severity entries read
'Changed Type from X to Y', a severity cleared by a type correction reads
'from SEV N to —', and the generic fallback no longer renders a raw
FieldChanged action name.
2026-09-16 11:43:34 -03:00
Codex Review Integration
09636ef590 fix(work-orders): complete the work order when its completion document is generated (SH-341)
Generating or uploading the completion document now moves a closable work
order to Completed without the manual confirmation, as SH-115 requires. The
SH-114 closability gate is evaluated on the row the server returned after the
document save; Save draft, Not required, Past Due, Completed and Canceled rows
are never auto-completed. The follow-up status patch uses that row's
rowVersion so it does not conflict with the document save.
2026-09-16 11:43:33 -03:00
Codex Review Integration
aa583858ba fix(work-orders): scope keyword search to the week and keep filters global
Show the Searching within [week] indicator while a keyword is typed and
stop sending the week-scoped keyword to Advanced Filters search. Refs SH-194.
2026-09-16 11:18:12 -03:00
Codex Review Integration
3ad07c9e10 fix(work-orders): keep backend validation text out of create error toasts
Board create failures toasted the backend message verbatim, exposing
field names such as siteCode and vendorId from the inline row and the
wizard. Map known codes to product copy and fall back to generic copy
for every other failure.
2026-09-16 11:17:37 -03:00
Codex Review Integration
bd69350a7c feat(work-orders): render inline create cells as fields with required asterisks
Wrap every inline creation cell in the bordered field box used by Site and
WO #, top-aligned like the prototype inline row. Show a persistent asterisk
on the empty WO # placeholder, the Site label in the create site dialog,
and the POC name and phone inputs in the create site dialog and wizard.
2026-09-16 11:13:17 -03:00
Codex Review Integration
f48342f268 test(work-orders): guard SH-235 severity tooltip and escalation toast rules 2026-09-16 11:01:06 -03:00
Codex Review Integration
83df262ab6 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-281-company-directory 2026-09-15 19:12:21 -03:00
Codex Review Integration
b83514a240 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-281-company-directory
# Conflicts:
#	e2e/vendors/vendors.spec.ts
#	src/app/(protected)/vendors/_components/vendors-table.tsx
#	src/test/app/(protected)/vendors/vendors-list.test.tsx
2026-09-15 19:08:53 -03:00
Codex Review Integration
1f3a8f939f test(vendors): refresh combined visual snapshots 2026-09-15 16:40:59 -03:00
Codex Review Integration
fa1f4467e2 feat(vendors): merge dev after address changes 2026-09-15 16:15:04 -03:00
Codex Review Integration
158e1740df Merge remote-tracking branch 'origin/dev' into feat/ab/sh-281-company-directory 2026-09-15 16:04:42 -03:00
Codex Review Integration
c8c7533ee7 Merge remote-tracking branch 'origin/dev' into feat/ab/sh-281-company-directory 2026-09-15 14:07:08 -03:00
Codex Review Integration
af6616ca65 test(vendors): follow grouped directory endpoint 2026-09-14 15:51:00 -03:00
Codex Review Integration
99253587ef fix(vendors): use grouped directory endpoint 2026-09-14 15:24:55 -03:00
Codex Review Integration
b1ae5085e7 test(vendors): align centered empty baseline 2026-09-14 13:34:57 -03:00
Codex Review Integration
5cadc26fce fix(vendors): keep empty states in viewport 2026-09-14 13:31:06 -03:00
Codex Review Integration
886a9f522a test(vendors): complete company visual baselines 2026-09-14 13:23:06 -03:00
Codex Review Integration
26d50f90b6 test(vendors): align company directory visuals 2026-09-14 13:19:50 -03:00
Codex Review Integration
472d7f734b chore(vendors): trigger SH-281 review checks 2026-09-14 13:14:07 -03:00
Codex Review Integration
2eb707a522 chore(vendors): stack SH-281 on SH-279 2026-09-14 13:10:33 -03:00
Codex Review Integration
1c90aa60f3 feat(vendors): group directory rows by company 2026-09-14 13:07:00 -03:00
Codex Review Integration
7eb3308a06 refactor(vendors): satisfy row maintainability gate 2026-09-14 13:04:35 -03:00
Codex Review Integration
0b4dafc868 fix(vendors): add accessible trade overflow tooltip 2026-09-14 12:36:31 -03:00
Codex Review Integration
c587122b16 fix(vendors): add accessible trade overflow tooltip 2026-09-14 12:26:05 -03:00
160 changed files with 4894 additions and 261 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 137 KiB

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 98 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 108 KiB

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

After

Width:  |  Height:  |  Size: 144 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 144 KiB

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 185 KiB

After

Width:  |  Height:  |  Size: 189 KiB

View file

@ -29,6 +29,8 @@ const activeVendors = [
TotalJobs: 72,
IsActive: true,
PreferredContact: "Email",
AreaId: 1 as number | null,
AreaName: "East",
},
{
Id: 2,
@ -47,9 +49,16 @@ const activeVendors = [
Notes: "",
TotalJobs: 18,
IsActive: true,
AreaId: null as number | null,
AreaName: "",
},
];
const SERVICE_AREAS = [
{ id: 2, name: "Central" },
{ id: 1, name: "East" },
];
const inactiveVendors = [
{
...activeVendors[0],
@ -135,6 +144,7 @@ async function mockVendorApi(
googleMapsUrl: vendor.GoogleMapsUrl,
})),
trades: ["Plumbing", "Backflow Preventers", "HVAC"],
areas: SERVICE_AREAS,
locations: [
{ city: "St. Louis", state: "MO", label: "St. Louis, MO" },
{ city: "Clayton", state: "MO", label: "Clayton, MO" },
@ -160,13 +170,20 @@ async function mockVendorApi(
const source = vendorRecords.filter((vendor) => vendor.IsActive === isActive);
const search = (url.searchParams.get("search") ?? "").toLowerCase();
const company = url.searchParams.get("companies[0]");
const areas = [...url.searchParams.entries()]
.filter(([key]) => key.startsWith("areas["))
.map(([, value]) => value);
const filtered = source.filter(
(vendor) =>
(!search ||
`${vendor.CompanyName} ${vendor.ContactName} ${vendor.TradeSpecialties} ${vendor.City} ${vendor.State}`
.toLowerCase()
.includes(search)) &&
(!company || vendor.CompanyName === company),
(!company || vendor.CompanyName === company) &&
(areas.length === 0 ||
areas.some((area) =>
area === "__unassigned__" ? vendor.AreaId == null : String(vendor.AreaId) === area,
)),
);
const isCount = url.searchParams.get("pageSize") === "1";
const responseRows = filtered.map((vendor) => {
@ -244,6 +261,8 @@ async function mockVendorApi(
zip: anchor.Zip,
googleMapsUrl: anchor.GoogleMapsUrl,
notes: anchor.Notes,
areaId: anchor.AreaId,
areaName: anchor.AreaName,
technicians: [
...vendorRecords
.filter((vendor) => vendor.CompanyId === anchor.CompanyId)
@ -307,6 +326,8 @@ async function mockVendorApi(
zip: anchor.Zip,
googleMapsUrl: anchor.GoogleMapsUrl,
notes: anchor.Notes,
areaId: anchor.AreaId,
areaName: anchor.AreaName,
technicians: vendorRecords
.filter((vendor) => vendor.CompanyId === anchor.CompanyId)
.map((vendor) => ({
@ -410,6 +431,7 @@ test.describe("Vendor directory prototype parity", () => {
"Street Address",
"City",
"State",
"Service Area",
"Trade",
"Technician",
"Technician Phone",
@ -461,6 +483,7 @@ test.describe("Vendor directory prototype parity", () => {
"Street Address",
"City",
"State",
"Service Area",
"Trade",
"Technician",
"Technician Phone",
@ -474,7 +497,7 @@ test.describe("Vendor directory prototype parity", () => {
const tableContainerBox = await page.locator("table").locator("..").boundingBox();
expect(tableContainerBox).toMatchObject({ x: 260, y: 212.5, width: 1164 });
expect(tableContainerBox?.height).toBeCloseTo(738, 0);
expect((await page.locator("table").boundingBox())?.width).toBe(2050);
expect((await page.locator("table").boundingBox())?.width).toBe(2200);
expect(
(await page.getByRole("columnheader", { name: "Company", exact: true }).boundingBox())
?.height,
@ -540,8 +563,8 @@ test.describe("Vendor directory prototype parity", () => {
{ cellIndex: 0, testId: "vendor-text-company", value: LONG_TEXT_VENDOR.CompanyName },
{ cellIndex: 2, testId: "vendor-text-company-email", value: LONG_TEXT_VENDOR.Email },
{ cellIndex: 3, testId: "vendor-text-street-address", value: LONG_TEXT_VENDOR.Address },
{ cellIndex: 7, testId: "vendor-text-technician", value: LONG_TEXT_VENDOR.ContactName },
{ cellIndex: 8, testId: "vendor-text-technician-phone", value: LONG_TEXT_VENDOR.Phone },
{ cellIndex: 8, testId: "vendor-text-technician", value: LONG_TEXT_VENDOR.ContactName },
{ cellIndex: 9, testId: "vendor-text-technician-phone", value: LONG_TEXT_VENDOR.Phone },
];
for (const expected of fields) {
@ -675,7 +698,8 @@ test.describe("Vendor directory prototype parity", () => {
"1 Market St",
);
await expect(page.getByLabel("City (required)")).toHaveValue("St. Louis");
await expect(page.getByLabel("State (required)")).toHaveValue("MO");
await expect(page.getByLabel("State (required)")).toHaveValue("Missouri (MO)");
await expect(page.getByLabel("Service Area (optional)")).toHaveValue("East");
await expect(page.getByLabel("Google Maps URL (optional)")).toHaveCount(0);
await expect(page.getByLabel("Address (optional)")).toHaveCount(0);
await expect(page.getByLabel("Preferred Contact")).toHaveCount(0);
@ -748,6 +772,55 @@ test.describe("Vendor directory prototype parity", () => {
await expect.poll(() => state.updatedBody?.notes).toBe("Updated in browser E2E");
});
test("filters by Service Area and lets an admin assign one", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
const state = await mockVendorApi(page);
await page.goto("/vendors");
const gatewayRow = page.getByRole("button", {
name: "Open vendor details for Gateway Plumbing",
});
const metroRow = page.getByRole("button", { name: "Open vendor details for Metro HVAC" });
await expect(gatewayRow.getByTestId("vendor-text-service-area")).toHaveText("East");
await expect(metroRow.getByTestId("vendor-text-service-area")).toHaveText("Unassigned");
await page.getByRole("button", { name: "Open vendor filters" }).click();
await page.getByRole("button", { name: "Service Area" }).click();
await page.getByPlaceholder("All areas").click();
await expect(page.getByRole("option")).toHaveText(["Unassigned", "Central", "East"]);
await page.getByRole("option", { name: "East" }).click();
await page.getByRole("button", { name: "Apply filters" }).click();
await expect(
page.getByRole("button", { name: "Remove filter Service Area: East" }),
).toBeVisible();
await expect(gatewayRow).toBeVisible();
await expect(metroRow).toHaveCount(0);
expect(state.listUrls.some((url) => new URL(url).searchParams.get("areas[0]") === "1")).toBe(
true,
);
await page.getByRole("button", { name: "Open vendor filters" }).click();
await page.getByRole("button", { name: "Service Area" }).click();
await page.getByRole("button", { name: "Clear all" }).last().click();
await page.getByPlaceholder("All areas").click();
await page.getByRole("option", { name: "Unassigned" }).click();
await page.getByRole("button", { name: "Apply filters" }).click();
await expect(page.getByText("Service Area: Unassigned")).toBeVisible();
await expect(metroRow).toBeVisible();
await expect(gatewayRow).toHaveCount(0);
await page.getByRole("button", { name: "Edit vendor Metro HVAC" }).click();
const detailDrawer = page.locator(".MuiDrawer-paper").last();
const areaField = detailDrawer.getByRole("combobox", { name: "Service Area (optional)" });
await expect(areaField).toBeEnabled();
await areaField.click();
await page.getByRole("option", { name: "Central" }).click();
await detailDrawer.getByRole("button", { name: "Save changes" }).click();
await expect.poll(() => state.updatedBody?.areaId).toBe(2);
expect(state.updatedBody?.state).toBe("MO");
});
test("reactivates a legacy inactive vendor with an exact sparse update", async ({ page }) => {
const state = await mockVendorApi(page, { legacyGateway: true });
await page.goto("/vendors");
@ -791,11 +864,14 @@ test.describe("Vendor directory prototype parity", () => {
// leave those as the only things it is exercising.
await page.getByRole("combobox", { name: "Street Address (required)" }).fill("1 Market St");
await page.getByLabel("City (required)").fill("St. Louis");
await page.getByLabel("State (required)").fill("MO");
await page.getByLabel("State (required)").fill("Missouri");
await page.getByRole("option", { name: "Missouri (MO)" }).click();
await page.getByRole("button", { name: "Add Vendor", exact: true }).last().click();
await expect.poll(() => state.createdBody?.name).toBe("Independent Vendor LLC");
expect(state.createdBody?.technicians).toEqual([]);
expect(state.createdBody?.state).toBe("MO");
expect(state.createdBody?.areaId).toBeNull();
});
test("closes vendor details with Escape and keeps only Edit in the footer", async ({ page }) => {

View file

@ -0,0 +1,80 @@
import { expect, test, type Route } from "@playwright/test";
const FROZEN_NOW = "2026-08-19T15:00:00.000Z";
const TEST_USER = {
token: "due-date-floor-e2e-token",
expiration: "2030-01-01T00:00:00.000Z",
email: "admin@seahavenind.com",
userRoles: "Admin",
phoneNumber: "5551234567",
fullname: "Work Order E2E Admin",
id: "1",
};
async function fulfillJson(route: Route, body: unknown, status = 200) {
await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
}
test.describe("Due Date floor in the Create WO wizard (SH-356)", () => {
test.setTimeout(60_000);
test("disables days before Schedule On and clears Due Date when Schedule On passes it", async ({
page,
}) => {
await page.clock.install({ time: new Date(FROZEN_NOW) });
await page.clock.resume();
await page.addInitScript((user) => {
localStorage.setItem("auth", JSON.stringify(user));
const style = document.createElement("style");
style.textContent = ".tsqd-parent-container { display: none !important; }";
document.documentElement.appendChild(style);
}, TEST_USER);
await page.route(
(url) => url.pathname.startsWith("/api/"),
async (route) => {
if (route.request().method() !== "GET") {
await fulfillJson(route, {}, 500);
return;
}
await fulfillJson(route, {
data: [],
items: [],
weekStart: "2026-08-17",
weekEnd: "2026-08-21",
counts: { returned: 0, total: 0 },
unscheduled: [],
scheduled: [],
});
},
);
await page.goto("/workorders");
await page.getByRole("button", { name: "New WO" }).click();
await expect(page.getByRole("heading", { name: "Type & schedule" })).toBeVisible({
timeout: 20_000,
});
await page.getByRole("button", { name: /Pick a date/ }).click();
const dateTab = page.getByRole("button", { name: "Date", exact: true });
if (await dateTab.isVisible()) {
await dateTab.click();
}
await page.getByRole("button", { name: "20", exact: true }).click();
await page.getByRole("button", { name: /No due date/ }).click();
await expect(page.getByRole("button", { name: "19", exact: true })).toBeDisabled();
await expect(page.getByRole("button", { name: "20", exact: true })).toBeEnabled();
await page.getByRole("button", { name: "21", exact: true }).click();
await expect(page.getByRole("button", { name: /No due date/ })).toHaveCount(0);
await page.getByRole("button", { name: /Aug 20/ }).click();
const dateTabAgain = page.getByRole("button", { name: "Date", exact: true });
if (await dateTabAgain.isVisible()) {
await dateTabAgain.click();
}
await page.getByRole("button", { name: "25", exact: true }).click();
await expect(page.getByRole("button", { name: /No due date/ })).toBeVisible();
});
});

View file

@ -0,0 +1,121 @@
import { expect, test, type Page, type Route } from "@playwright/test";
const FROZEN_NOW = "2026-08-19T15:00:00.000Z";
const TEST_USER = {
token: "wo-number-sh-placeholder-e2e-token",
expiration: "2030-01-01T00:00:00.000Z",
email: "admin@seahavenind.com",
userRoles: "Admin",
phoneNumber: "5551234567",
fullname: "Work Order E2E Admin",
id: "1",
};
async function fulfillJson(route: Route, body: unknown, status = 200) {
await route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
}
async function hideQueryDevtools(page: Page) {
await page.addStyleTag({
content:
".tsqd-parent-container { display: none !important; pointer-events: none !important; }",
});
await page.locator(".tsqd-parent-container").evaluateAll((nodes) => {
for (const node of nodes) {
node.remove();
}
});
}
const REAL_ROW = {
id: 1000,
woNumber: "12345678901",
workOrderType: 2,
siteCode: "DAL1",
lifecycleStatusLabel: "Scheduled",
scheduledDate: "2026-08-19",
dispatcherId: "1",
dispatcherName: "Pat Dispatcher",
pm: "HVAC",
};
async function mockBoard(page: Page, patches: unknown[]) {
await page.route(
(url) => url.pathname.startsWith("/api/"),
async (route) => {
const request = route.request();
const url = request.url();
if (request.method() !== "GET") {
patches.push({ url, body: request.postDataJSON() });
await fulfillJson(route, {}, 500);
return;
}
if (url.includes("workorders/board/search")) {
await fulfillJson(route, { items: [REAL_ROW], totalCount: 1, page: 0, pageSize: 50 });
return;
}
if (url.includes("workorders/board")) {
await fulfillJson(route, {
weekStart: "2026-08-17",
weekEnd: "2026-08-21",
counts: { returned: 1, total: 1 },
unscheduled: [],
scheduled: [REAL_ROW],
});
return;
}
await fulfillJson(route, { data: [], items: [] });
},
);
}
test.describe("inline WO number SH placeholder", () => {
test.setTimeout(60_000);
test.beforeEach(async ({ page }) => {
await page.clock.install({ time: new Date(FROZEN_NOW) });
await page.clock.resume();
await page.addInitScript((user) => {
localStorage.setItem("auth", JSON.stringify(user));
}, TEST_USER);
});
test("keeps a typed SH number on a new inline row and blocks downgrading a saved real number", async ({
page,
}) => {
const mutations: unknown[] = [];
await mockBoard(page, mutations);
await page.goto("/workorders");
await hideQueryDevtools(page);
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible({
timeout: 20_000,
});
await expect(page.getByText("12345678901").first()).toBeVisible();
await page
.getByRole("button", { name: /Add WO/ })
.first()
.click();
await page
.getByText(/^Insert WO #/)
.first()
.click();
const draftInput = page.getByLabel("Work order number");
await draftInput.fill("SH00001");
await draftInput.press("Enter");
await expect(draftInput).toHaveCount(0);
await expect(page.getByText("SH00001", { exact: true })).toBeVisible();
await expect(page.getByText(/must be 11 digits/)).toHaveCount(0);
await page.getByText("12345678901", { exact: true }).first().click();
const savedInput = page.getByLabel("Work order number");
await savedInput.fill("SH00009");
await savedInput.press("Enter");
await expect(
page.getByText("Cannot replace an APM work order number with an internal number"),
).toBeVisible();
await expect(page.getByText("12345678901", { exact: true }).first()).toBeVisible();
expect(mutations).toEqual([]);
});
});

View file

@ -204,6 +204,12 @@ async function openWorkOrderPage(page: Page, mode: "default" | "empty" | "error"
});
}
async function expectWorkOrderPageReady(page: Page) {
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible({
timeout: 90_000,
});
}
async function expectStableScreenshot(page: Page, name: string) {
await page.waitForTimeout(250);
await page.evaluate(
@ -217,15 +223,18 @@ async function expectStableScreenshot(page: Page, name: string) {
}
test.describe("Work Orders deterministic pixel regression", () => {
test.setTimeout(120_000);
test("list", async ({ page }) => {
await openWorkOrderPage(page);
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
await expectWorkOrderPageReady(page);
await expect(page.getByText("WO-501").first()).toBeVisible();
await expectStableScreenshot(page, "wo-list.png");
});
test("filters", async ({ page }) => {
await openWorkOrderPage(page);
await expectWorkOrderPageReady(page);
await page.getByRole("button", { name: "Advanced Filters" }).click();
await expect(page.getByRole("dialog", { name: "Advanced Filters" })).toBeVisible();
await expectStableScreenshot(page, "wo-filters.png");
@ -233,6 +242,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
test("new", async ({ page }) => {
await openWorkOrderPage(page);
await expectWorkOrderPageReady(page);
await page.getByRole("button", { name: "New WO" }).click();
await expect(page.getByRole("heading", { name: "Type & schedule" })).toBeVisible();
await expectStableScreenshot(page, "wo-new.png");
@ -240,6 +250,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
test("detail", async ({ page }) => {
await openWorkOrderPage(page);
await expectWorkOrderPageReady(page);
const row = page.locator("#wo-row-1");
await row.hover();
await row.getByRole("button", { name: "View details" }).click();
@ -249,7 +260,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
test("empty", async ({ page }) => {
await openWorkOrderPage(page, "empty");
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
await expectWorkOrderPageReady(page);
await page.getByLabel("Search work orders").fill("zz");
await expect(page.getByText("No work orders match your search")).toBeVisible();
await expectStableScreenshot(page, "wo-empty.png");
@ -257,7 +268,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
test("error", async ({ page }) => {
await openWorkOrderPage(page, "error");
await expect(page.getByRole("heading", { name: "Work Orders" })).toBeVisible();
await expectWorkOrderPageReady(page);
const alert = page.getByRole("main").getByRole("alert");
await expect(alert).toBeVisible();
await expect(alert).toContainText(/server error/i);
@ -267,6 +278,7 @@ test.describe("Work Orders deterministic pixel regression", () => {
test("mobile", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await openWorkOrderPage(page);
await expectWorkOrderPageReady(page);
await expect(page.getByText("WO-501").first()).toBeVisible();
await expectStableScreenshot(page, "wo-mobile.png");

View file

@ -77,6 +77,10 @@ export const API_PATHS = {
deleteEmployees: "Employee/DeleteEmployees",
dropdown: "Employee/Dropdown",
},
teamMember: {
getList: "User",
create: "team-members",
},
contact: {
getList: "Contact/GetContactList",
getContacts: "Contact/GetContacts",
@ -155,6 +159,9 @@ export const API_PATHS = {
update: "DropdownOptions/Update",
delete: "DropdownOptions",
},
services: {
list: "services",
},
user: {
list: "User",
},

View file

@ -0,0 +1,473 @@
import { useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from "react";
import {
Accordion,
AccordionDetails,
AccordionSummary,
Alert,
Box,
Button,
Checkbox,
CircularProgress,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
FormControl,
FormControlLabel,
FormHelperText,
InputLabel,
MenuItem,
Select,
Stack,
TextField,
Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { AREA_ZONES } from "@/data/areas";
import { useCreateTeamMember } from "@/domain/team-members/use-cases/use-create-team-member";
import type {
CreateTeamMemberInput,
TeamMemberRole,
} from "@/domain/team-members/types/team-member";
const ROLES: TeamMemberRole[] = ["Dispatcher", "Scheduler", "Admin"];
const COLORS = [
"#F59E0B",
"#0D9488",
"#6366F1",
"#F43F5E",
"#7C3AED",
"#0EA5E9",
"#16A34A",
"#EA580C",
"#0891B2",
"#C026D3",
] as const;
const PERMISSION_GROUPS = [
{
label: "Team Members",
keys: ["manageTeamMembers", "changeTeamMemberRole"],
},
{
label: "Vendors",
keys: ["createVendors", "editVendors", "deactivateVendors"],
},
{
label: "Sites",
keys: ["createSites", "editSites", "deleteSites"],
},
{
label: "Services",
keys: ["createServices", "editServices", "deactivateServices"],
},
{
label: "Completion Document Templates",
keys: [
"createCompletionDocTemplates",
"editCompletionDocTemplates",
"deleteCompletionDocTemplates",
],
},
{
label: "Work Orders",
keys: ["createWorkOrders", "editOthersWorkOrders", "cancelWorkOrders", "deleteWorkOrders"],
},
{
label: "Uplifts",
keys: ["requestUplifts", "autoApproveUplifts", "reviewUplifts"],
},
{
label: "Dashboard",
keys: ["viewAllDispatchersOnDashboard"],
},
] as const;
const PERMISSION_LABELS: Record<string, string> = {
manageTeamMembers: "Manage team members",
changeTeamMemberRole: "Change team member role",
createVendors: "Create vendors",
editVendors: "Edit vendors",
deactivateVendors: "Deactivate vendors",
createSites: "Create sites",
editSites: "Edit sites",
deleteSites: "Delete sites",
createServices: "Create services",
editServices: "Edit services",
deactivateServices: "Deactivate services",
createCompletionDocTemplates: "Create completion document templates",
editCompletionDocTemplates: "Edit completion document templates",
deleteCompletionDocTemplates: "Delete completion document templates",
createWorkOrders: "Create work orders",
editOthersWorkOrders: "Edit other users' work orders",
cancelWorkOrders: "Cancel work orders",
deleteWorkOrders: "Delete work orders",
requestUplifts: "Request uplifts",
autoApproveUplifts: "Automatically approve uplifts",
reviewUplifts: "Review uplifts",
viewAllDispatchersOnDashboard: "View all Dispatchers on dashboard",
};
const ALL_PERMISSION_KEYS = PERMISSION_GROUPS.flatMap((group) => group.keys);
const DISPATCHER_DEFAULTS = new Set([
"createVendors",
"editVendors",
"deactivateVendors",
"createSites",
"editSites",
"createWorkOrders",
"editOthersWorkOrders",
"cancelWorkOrders",
"requestUplifts",
"autoApproveUplifts",
]);
const SCHEDULER_DEFAULTS = new Set([
...Array.from(DISPATCHER_DEFAULTS).filter(
(key) => key !== "requestUplifts" && key !== "autoApproveUplifts",
),
"deleteSites",
"createServices",
"editServices",
"createCompletionDocTemplates",
"editCompletionDocTemplates",
"viewAllDispatchersOnDashboard",
]);
function defaultsForRole(role: TeamMemberRole): Set<string> {
if (role === "Admin") return new Set(ALL_PERMISSION_KEYS);
return role === "Scheduler" ? new Set(SCHEDULER_DEFAULTS) : new Set(DISPATCHER_DEFAULTS);
}
function emptyForm() {
return {
name: "",
role: "Dispatcher" as TeamMemberRole,
color: "",
email: "",
phone: "",
serviceAreas: [] as string[],
permissions: defaultsForRole("Dispatcher"),
};
}
function permissionOverrides(role: TeamMemberRole, selected: Set<string>) {
const defaults = defaultsForRole(role);
return Object.fromEntries(
ALL_PERMISSION_KEYS.filter((key) => defaults.has(key) !== selected.has(key)).map((key) => [
key,
selected.has(key) ? 1 : 2,
]),
) as Record<string, 1 | 2>;
}
type TeamMemberForm = ReturnType<typeof emptyForm>;
type FormErrors = ReturnType<typeof getFormErrors>;
function getFormErrors(form: TeamMemberForm, submitted: boolean, emailIsValid: boolean) {
return {
name: submitted && !form.name.trim() ? "Name is required." : "",
role: submitted && !form.role ? "Role is required." : "",
color: submitted && !form.color ? "Color is required." : "",
email:
submitted && !form.email.trim()
? "Email is required."
: submitted && !emailIsValid
? "Enter a valid email address."
: "",
serviceAreas:
submitted && form.role === "Dispatcher" && form.serviceAreas.length === 0
? "Select at least one service area."
: "",
};
}
function PermissionsSection({
form,
togglePermission,
}: {
form: TeamMemberForm;
togglePermission: (key: string) => void;
}) {
return (
<Box>
<Typography variant="h6" sx={{ mb: 1 }}>
Permissions
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
Permissions start with the selected role's defaults. Customize them before saving.
</Typography>
{PERMISSION_GROUPS.map((group) => (
<Accordion key={group.label} disableGutters>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography>{group.label}</Typography>
</AccordionSummary>
<AccordionDetails>
<Stack>
{group.keys.map((key) => (
<FormControlLabel
key={key}
control={
<Checkbox
checked={form.permissions.has(key)}
onChange={() => togglePermission(key)}
/>
}
label={PERMISSION_LABELS[key]}
/>
))}
</Stack>
</AccordionDetails>
</Accordion>
))}
</Box>
);
}
function TeamMemberFormFields({
form,
setForm,
errors,
updateRole,
toggleArea,
togglePermission,
}: {
form: TeamMemberForm;
setForm: Dispatch<SetStateAction<TeamMemberForm>>;
errors: FormErrors;
updateRole: (role: TeamMemberRole) => void;
toggleArea: (area: string) => void;
togglePermission: (key: string) => void;
}) {
return (
<Stack spacing={2.5}>
<TextField
label="Name"
placeholder="Team member name"
value={form.name}
onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
error={Boolean(errors.name)}
helperText={errors.name}
required
fullWidth
/>
<FormControl fullWidth required error={Boolean(errors.role)}>
<InputLabel id="team-member-role-label">Role</InputLabel>
<Select
labelId="team-member-role-label"
label="Role"
value={form.role}
onChange={(event) => updateRole(event.target.value as TeamMemberRole)}
>
{ROLES.map((role) => (
<MenuItem key={role} value={role}>
{role}
</MenuItem>
))}
</Select>
{Boolean(errors.role) && <FormHelperText>{errors.role}</FormHelperText>}
</FormControl>
<Box>
<Typography component="p" variant="body2" sx={{ mb: 1, fontWeight: 600 }}>
Color <span aria-hidden="true">*</span>
</Typography>
<Stack direction="row" spacing={1} useFlexGap sx={{ flexWrap: "wrap" }}>
{COLORS.map((color) => (
<Button
key={color}
type="button"
aria-label={`Select color ${color}`}
aria-pressed={form.color === color}
onClick={() => setForm((current) => ({ ...current, color }))}
sx={{
minWidth: 32,
width: 32,
height: 32,
borderRadius: "50%",
backgroundColor: color,
border: form.color === color ? "3px solid" : "2px solid transparent",
borderColor: form.color === color ? "text.primary" : "transparent",
boxShadow: form.color === color ? "0 0 0 2px white" : "none",
p: 0,
"&:hover": { backgroundColor: color, opacity: 0.85 },
}}
/>
))}
</Stack>
{Boolean(errors.color) && <FormHelperText error>{errors.color}</FormHelperText>}
</Box>
{form.role === "Dispatcher" && (
<Box>
<Typography component="p" variant="body2" sx={{ mb: 1, fontWeight: 600 }}>
Service Area <span aria-hidden="true">*</span>
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
{form.serviceAreas.length ? form.serviceAreas.join(", ") : "Select service areas…"}
</Typography>
<Stack direction="row" useFlexGap sx={{ flexWrap: "wrap", columnGap: 1 }}>
{AREA_ZONES.map((area) => (
<FormControlLabel
key={area}
control={
<Checkbox
checked={form.serviceAreas.includes(area)}
onChange={() => toggleArea(area)}
/>
}
label={area}
/>
))}
</Stack>
{Boolean(errors.serviceAreas) && (
<FormHelperText error>{errors.serviceAreas}</FormHelperText>
)}
</Box>
)}
{form.role !== "Dispatcher" && (
<Typography variant="body2" color="text.secondary">
Not applicable for this role
</Typography>
)}
<TextField
label="Phone"
placeholder="(555) 555-0100"
value={form.phone}
onChange={(event) => setForm((current) => ({ ...current, phone: event.target.value }))}
fullWidth
/>
<TextField
label="Email"
placeholder="name@seahavenind.com"
value={form.email}
onChange={(event) => setForm((current) => ({ ...current, email: event.target.value }))}
error={Boolean(errors.email)}
helperText={errors.email || "A valid email is required to send the invite"}
required
type="email"
fullWidth
/>
<PermissionsSection form={form} togglePermission={togglePermission} />
</Stack>
);
}
export function AddTeamMemberDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const [form, setForm] = useState(emptyForm);
const [submitted, setSubmitted] = useState(false);
const submissionId = useRef(0);
const { error: mutationError, isPending, mutate, reset } = useCreateTeamMember();
useEffect(() => {
submissionId.current += 1;
reset();
if (open) {
setForm(emptyForm());
setSubmitted(false);
}
}, [open, reset]);
const handleClose = () => {
if (isPending) return;
submissionId.current += 1;
reset();
onClose();
};
const emailIsValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email.trim());
const errors = useMemo(
() => getFormErrors(form, submitted, emailIsValid),
[emailIsValid, form, submitted],
);
const isValid =
Boolean(form.name.trim()) &&
Boolean(form.role) &&
Boolean(form.color) &&
emailIsValid &&
(form.role !== "Dispatcher" || form.serviceAreas.length > 0);
const updateRole = (role: TeamMemberRole) => {
setForm((current) => ({
...current,
role,
serviceAreas: [],
permissions: defaultsForRole(role),
}));
};
const togglePermission = (key: string) => {
setForm((current) => {
const permissions = new Set(current.permissions);
if (permissions.has(key)) permissions.delete(key);
else permissions.add(key);
return { ...current, permissions };
});
};
const toggleArea = (area: string) => {
setForm((current) => ({
...current,
serviceAreas: current.serviceAreas.includes(area)
? current.serviceAreas.filter((value) => value !== area)
: [...current.serviceAreas, area],
}));
};
const submit = () => {
setSubmitted(true);
if (!isValid) return;
const input: CreateTeamMemberInput = {
name: form.name.trim(),
role: form.role,
color: form.color,
email: form.email.trim(),
phone: form.phone.trim() || undefined,
serviceAreas: form.serviceAreas,
permissionOverrides: permissionOverrides(form.role, form.permissions),
};
const currentSubmissionId = submissionId.current;
mutate(input, {
onSuccess: () => {
if (submissionId.current !== currentSubmissionId) return;
reset();
onClose();
},
});
};
return (
<Dialog open={open} onClose={handleClose} fullWidth maxWidth="md" scroll="paper">
<DialogTitle>Add Member</DialogTitle>
<DialogContent dividers>
<Typography color="text.secondary" sx={{ mb: 3 }}>
Register a new team member.
</Typography>
{Boolean(mutationError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{mutationError?.message}
</Alert>
)}
<TeamMemberFormFields
form={form}
setForm={setForm}
errors={errors}
updateRole={updateRole}
toggleArea={toggleArea}
togglePermission={togglePermission}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} disabled={isPending}>
Cancel
</Button>
<Button variant="contained" onClick={submit} disabled={isPending}>
{isPending ? <CircularProgress size={20} color="inherit" /> : "Add Member"}
</Button>
</DialogActions>
</Dialog>
);
}

View file

@ -0,0 +1,110 @@
import {
Avatar,
Button,
CircularProgress,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
} from "@mui/material";
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
const HEADINGS = ["Team Member", "Role", "Service Area", "Phone", "Email", "Color", "Status"];
function memberStatusLabel(member: TeamMemberListItem) {
return member.pendingRegistration ? "Pending registration" : member.status;
}
export function TeamMembersTable({
rows,
isLoading,
hasError,
tab,
onOpen,
}: {
rows: TeamMemberListItem[];
isLoading: boolean;
hasError: boolean;
tab: "active" | "inactive";
onOpen: (member: TeamMemberListItem) => void;
}) {
return (
<TableContainer component={Paper} variant="outlined">
<Table stickyHeader size="small" sx={{ minWidth: 900 }}>
<TableHead>
<TableRow>
{HEADINGS.map((heading) => (
<TableCell key={heading} className="font-semibold">
{heading}
</TableCell>
))}
<TableCell align="right" className="font-semibold">
Actions
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{isLoading ? (
<TableRow>
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
<CircularProgress size={28} />
</TableCell>
</TableRow>
) : hasError ? (
<TableRow>
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
<Typography sx={{ fontWeight: 600 }}>Unable to load team members</Typography>
<Typography variant="body2" color="text.secondary">
Check your connection and try again.
</Typography>
</TableCell>
</TableRow>
) : rows.length === 0 ? (
<TableRow>
<TableCell colSpan={8} align="center" sx={{ py: 8 }}>
<Typography sx={{ fontWeight: 600 }}>No {tab} team members found</Typography>
<Typography variant="body2" color="text.secondary">
Try a different search, or add a new team member.
</Typography>
</TableCell>
</TableRow>
) : (
rows.map((member) => (
<TableRow
key={String(member.id)}
hover
onClick={() => onOpen(member)}
sx={{ cursor: "pointer" }}
>
<TableCell>{member.name || "—"}</TableCell>
<TableCell>{member.role || "—"}</TableCell>
<TableCell>{member.serviceArea || "—"}</TableCell>
<TableCell>{member.phone || "—"}</TableCell>
<TableCell>{member.email || "—"}</TableCell>
<TableCell>
<Avatar sx={{ width: 22, height: 22, bgcolor: member.color || "primary.main" }} />
</TableCell>
<TableCell>{memberStatusLabel(member)}</TableCell>
<TableCell align="right">
<Button
size="small"
onClick={(event) => {
event.stopPropagation();
onOpen(member);
}}
>
View
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableContainer>
);
}

View file

@ -0,0 +1,184 @@
import { useState } from "react";
import { useDebounce } from "@/hooks/use-debounce";
import { useTeamMembersList } from "@/domain/team-members/use-cases/use-team-members-list";
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
import {
Alert,
Avatar,
Box,
Button,
Chip,
Drawer,
IconButton,
Stack,
Tab,
Tabs,
TextField,
Typography,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { TeamMembersTable } from "./_components/team-members-table";
import { AddTeamMemberDialog } from "./_components/add-team-member-dialog";
type StatusTab = "active" | "inactive";
const STATUS_LABELS: Record<StatusTab, "Active" | "Inactive"> = {
active: "Active",
inactive: "Inactive",
};
function MemberStatus({ status }: { status: TeamMemberListItem["status"] }) {
return <Chip size="small" label={status} color={status === "Active" ? "success" : "default"} />;
}
function TeamMemberDrawer({
member,
onClose,
}: {
member: TeamMemberListItem | null;
onClose: () => void;
}) {
return (
<Drawer anchor="right" open={Boolean(member)} onClose={onClose}>
<Box sx={{ width: { xs: "100vw", sm: 380 }, p: 3 }}>
<Stack
direction="row"
sx={{ alignItems: "center", justifyContent: "space-between", mb: 3 }}
>
<Typography variant="h6">Team Member</Typography>
<IconButton aria-label="Close team member details" onClick={onClose}>
<CloseIcon />
</IconButton>
</Stack>
{member !== null && (
<Stack spacing={2}>
<Stack direction="row" spacing={2} sx={{ alignItems: "center" }}>
<Avatar sx={{ bgcolor: member.color || "primary.main" }}>
{member.name.slice(0, 1).toUpperCase() || "?"}
</Avatar>
<Box>
<Typography variant="h6">{member.name || "—"}</Typography>
<Typography color="text.secondary">{member.role || "—"}</Typography>
</Box>
</Stack>
<MemberStatus status={member.status} />
<Typography>
<strong>Service Area:</strong> {member.serviceArea || "—"}
</Typography>
<Typography>
<strong>Phone:</strong> {member.phone || "—"}
</Typography>
<Typography>
<strong>Email:</strong> {member.email || "—"}
</Typography>
</Stack>
)}
</Box>
</Drawer>
);
}
export default function TeamMembersListPage() {
const [search, setSearch] = useState("");
const [tab, setTab] = useState<StatusTab>("active");
const [selectedMember, setSelectedMember] = useState<TeamMemberListItem | null>(null);
const [addMemberOpen, setAddMemberOpen] = useState(false);
const debouncedSearch = useDebounce(search, 300).trim().toLowerCase();
const { data, isLoading, error } = useTeamMembersList();
const allMembers = data?.items ?? [];
const activeCount = allMembers.filter((member) => member.status === "Active").length;
const inactiveCount = allMembers.length - activeCount;
const rows = allMembers
.filter((member) => member.status === STATUS_LABELS[tab])
.filter((member) => !debouncedSearch || member.name.toLowerCase().includes(debouncedSearch));
return (
<Box
className="flex h-full flex-col overflow-hidden"
sx={{ backgroundColor: "var(--color-bg-page)" }}
>
<Stack
direction={{ xs: "column", sm: "row" }}
spacing={2}
sx={{
alignItems: { xs: "stretch", sm: "center" },
justifyContent: "space-between",
p: 2.5,
backgroundColor: "var(--color-bg-surface)",
borderBottom: "1px solid var(--color-border)",
}}
>
<Box>
<Typography variant="h4" component="h1">
Team Members
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mt: 0.75 }}>
{allMembers.length} team member{allMembers.length === 1 ? "" : "s"} · {activeCount}{" "}
active
</Typography>
</Box>
<Stack direction="row" spacing={1} sx={{ alignItems: "center" }}>
<TextField
size="small"
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Search team member…"
aria-label="Search team member"
sx={{ width: 224 }}
/>
<Button variant="contained" size="small" onClick={() => setAddMemberOpen(true)}>
Add Member
</Button>
</Stack>
</Stack>
<Tabs
value={tab}
onChange={(_event, value: StatusTab) => setTab(value)}
aria-label="Team member status"
>
<Tab value="active" label={`Active ${activeCount}`} />
<Tab value="inactive" label={`Inactive ${inactiveCount}`} />
</Tabs>
{Boolean(error) && (
<Alert severity="error">
{error instanceof Error ? error.message : "Failed to load team members"}
</Alert>
)}
<Box sx={{ flex: 1, overflow: "auto", p: 2 }}>
<TeamMembersTable
rows={rows}
isLoading={isLoading}
hasError={Boolean(error)}
tab={tab}
onOpen={setSelectedMember}
/>
</Box>
<Stack
direction="row"
sx={{
justifyContent: "space-between",
px: 2,
py: 1,
borderTop: "1px solid var(--color-border)",
backgroundColor: "var(--color-bg-surface)",
}}
>
<Typography variant="caption" color="text.secondary">
{rows.length} {tab} team member{rows.length === 1 ? "" : "s"}
{debouncedSearch ? " · filtered" : ""}
</Typography>
<Typography variant="caption" color="text.secondary">
{activeCount} active · {inactiveCount} inactive
</Typography>
</Stack>
<TeamMemberDrawer member={selectedMember} onClose={() => setSelectedMember(null)} />
<AddTeamMemberDialog open={addMemberOpen} onClose={() => setAddMemberOpen(false)} />
</Box>
);
}

View file

@ -16,6 +16,7 @@ export interface VendorListState {
isActive: boolean;
companies: string[];
trades: string[];
areas: string[];
locations: string[];
jobBuckets: string[];
};
@ -45,6 +46,7 @@ export function useVendorListState(): VendorListState {
isActive,
companies: appliedFilters.companies,
trades: appliedFilters.trades,
areas: appliedFilters.areas,
locations: appliedFilters.locations,
jobBuckets: appliedFilters.jobBuckets,
}),

View file

@ -1,4 +1,4 @@
import { useCallback, useMemo, useState } from "react";
import { useCallback, useContext, useMemo, useState } from "react";
import { toast } from "react-toastify";
import { useForm, useWatch, type FieldErrors } from "react-hook-form";
import {
@ -15,6 +15,8 @@ import {
type EditedCompanyFields,
} from "@/domain/vendors/use-cases/use-save-vendor-company-roster";
import { useVendorRosterResolver } from "./use-vendor-roster-resolver";
import { AuthContext } from "@/providers/auth-context";
import { isAdminUser } from "@/lib/auth/user-utils";
const VENDOR_ROSTER_NO_CHANGES_MESSAGE =
"No changes to save. Enter technician details or update a company field.";
@ -28,6 +30,7 @@ const EDITABLE_COMPANY_FIELDS = [
"state",
"zip",
"notes",
"areaId",
] as const;
/**
@ -48,10 +51,21 @@ import { useVendorFacets } from "@/domain/vendors/use-cases/use-vendor-facets";
import { isVendorRosterConflictError } from "@/domain/vendors/lib/vendor-roster-conflict";
import type {
VendorCompanyRoster,
VendorFacetArea,
VendorFacetCompany,
VendorRosterConflict,
} from "@/domain/vendors/types/vendor";
export interface VendorRosterAreaFieldProps {
areaOptions: VendorFacetArea[];
currentArea: VendorFacetArea | null;
canAssignArea: boolean;
}
function toCurrentArea(roster: VendorCompanyRoster | null | undefined): VendorFacetArea | null {
return roster && roster.areaId !== "" ? { id: roster.areaId, name: roster.areaName } : null;
}
function withoutBlankNewTechnicians(
values: VendorCompanyRosterFormValues,
): VendorCompanyRosterFormValues {
@ -96,6 +110,7 @@ export interface VendorRosterForm {
companies: VendorFacetCompany[];
trades: string[];
tradesLoading: boolean;
areaField: VendorRosterAreaFieldProps;
selectedCompanyId: string | number | null;
selectCompany: (company: VendorFacetCompany | null) => Promise<void>;
clearSelectedCompany: (nextName?: string) => void;
@ -116,6 +131,8 @@ export function useVendorRosterForm({
);
const { data: facets, isLoading: facetsLoading } = useVendorFacets();
const save = useSaveVendorCompanyRoster();
// Area assignment is Admin-only; the API enforces it and the field mirrors it.
const canAssignArea = isAdminUser(useContext(AuthContext)?.user?.userRoles);
const [conflict, setConflict] = useState<VendorRosterConflict | null>(null);
const routeRoster = mode === "update" ? query.data : undefined;
@ -151,6 +168,14 @@ export function useVendorRosterForm({
clearConflict,
});
const { resetSelection } = selection;
const areaField = useMemo<VendorRosterAreaFieldProps>(
() => ({
areaOptions: facets?.areas ?? [],
currentArea: toCurrentArea(routeRoster ?? selection.selectedRoster),
canAssignArea,
}),
[canAssignArea, facets, routeRoster, selection.selectedRoster],
);
const isValid = useMemo(() => {
if (vendorCompanyRosterSchema.safeParse(watched).success) return true;
@ -238,6 +263,7 @@ export function useVendorRosterForm({
companies,
trades,
tradesLoading: facetsLoading,
areaField,
selectedCompanyId: selection.selectedCompanyId,
selectCompany: selection.selectCompany,
clearSelectedCompany: selection.clearSelectedCompany,

View file

@ -43,6 +43,7 @@ export function toFormValues(roster: VendorCompanyRoster): VendorCompanyRosterFo
// The deprecated stored Maps URL is intentionally not seeded: the form has
// no input for it, and carrying it would re-emit a legacy value on write.
notes: roster.notes,
areaId: roster.areaId,
technicians: roster.technicians.map((technician) => ({
id: technician.id,
contactName: technician.contactName,

View file

@ -77,6 +77,7 @@ export function VendorCreateModal({ open, onClose }: VendorCreateModalProps) {
selectedCompanyId={form.selectedCompanyId}
onSelectCompany={form.selectCompany}
onClearSelectedCompany={form.clearSelectedCompany}
{...form.areaField}
/>
</Box>
</Stack>

View file

@ -155,6 +155,7 @@ function CompanySection({ roster }: { roster: VendorCompanyRoster }) {
<Field label="State" value={roster.state} />
</Box>
</Stack>
<Field label="Service Area" value={roster.areaName || "Unassigned"} />
<AddressMapPreview address={address} />
</Stack>
);
@ -336,6 +337,7 @@ function DrawerEditor({
tradeOptions={form.trades}
tradeOptionsLoading={form.tradesLoading}
showTechnicianStatus={false}
{...form.areaField}
/>
{selectedIndex >= 0 && (
<>

View file

@ -3,6 +3,7 @@ import BusinessOutlinedIcon from "@mui/icons-material/BusinessOutlined";
import BuildOutlinedIcon from "@mui/icons-material/BuildOutlined";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import LocationOnOutlinedIcon from "@mui/icons-material/LocationOnOutlined";
import MapOutlinedIcon from "@mui/icons-material/MapOutlined";
import TagOutlinedIcon from "@mui/icons-material/TagOutlined";
import {
Accordion,
@ -17,13 +18,14 @@ import {
TextField,
Typography,
} from "@mui/material";
import type {
VendorFacets,
VendorFacetCompany,
VendorFacetJobBucket,
VendorFacetLocation,
import {
type VendorFacetArea,
type VendorFacets,
type VendorFacetCompany,
type VendorFacetJobBucket,
type VendorFacetLocation,
} from "@/domain/vendors/types/vendor";
import type { VendorFilters } from "./vendor-filters";
import { serviceAreaFilterOptions, type VendorFilters } from "./vendor-filters";
type DraftSetter = Dispatch<SetStateAction<VendorFilters>>;
@ -156,6 +158,33 @@ interface FilterProps<T> {
setDraft: DraftSetter;
}
function ServiceAreaFilter({ options, draft, setDraft }: FilterProps<VendorFacetArea>) {
return (
<FilterSection title="Service Area" icon={<MapOutlinedIcon />}>
<Autocomplete
multiple
size="small"
options={options}
getOptionLabel={(option) => option.name}
isOptionEqualToValue={(option, value) => option.id === value.id}
value={options.filter((option) => draft.areas.includes(option.id))}
onChange={(_event, value) =>
setDraft((current) => ({ ...current, areas: value.map((entry) => entry.id) }))
}
renderValue={(value, getItemProps) =>
value.map((option, index) => {
const { key, ...chipProps } = getItemProps({ index });
return <Chip key={key} size="small" label={option.name} {...chipProps} />;
})
}
renderInput={(params) => (
<TextField {...params} placeholder={draft.areas.length === 0 ? "All areas" : ""} />
)}
/>
</FilterSection>
);
}
function LocationFilter({ options, draft, setDraft }: FilterProps<VendorFacetLocation>) {
return (
<FilterSection title="Location" icon={<LocationOnOutlinedIcon />}>
@ -245,6 +274,11 @@ export function VendorFilterOptions({
<>
<CompanyFilter options={facets?.companies ?? []} draft={draft} setDraft={setDraft} />
<TradeFilter options={facets?.trades ?? []} draft={draft} setDraft={setDraft} />
<ServiceAreaFilter
options={serviceAreaFilterOptions(facets?.areas ?? [])}
draft={draft}
setDraft={setDraft}
/>
<LocationFilter options={facets?.locations ?? []} draft={draft} setDraft={setDraft} />
<JobCountFilter options={facets?.jobBuckets ?? []} draft={draft} setDraft={setDraft} />
</>

View file

@ -31,7 +31,11 @@ export function VendorFiltersDrawer({
}, [open, appliedFilters]);
const activeCount =
draft.companies.length + draft.trades.length + draft.locations.length + draft.jobBuckets.length;
draft.companies.length +
draft.trades.length +
draft.areas.length +
draft.locations.length +
draft.jobBuckets.length;
const handleClear = () => {
setDraft(emptyVendorFilters);

View file

@ -1,6 +1,10 @@
import { VENDOR_AREA_UNASSIGNED, type VendorFacetArea } from "@/domain/vendors/types/vendor";
export interface VendorFilters {
companies: string[];
trades: string[];
/** Stable Area ids or VENDOR_AREA_UNASSIGNED; OR within the facet. */
areas: string[];
locations: string[];
jobBuckets: string[];
}
@ -8,6 +12,17 @@ export interface VendorFilters {
export const emptyVendorFilters: VendorFilters = {
companies: [],
trades: [],
areas: [],
locations: [],
jobBuckets: [],
};
const UNASSIGNED_AREA_OPTION: VendorFacetArea = { id: VENDOR_AREA_UNASSIGNED, name: "Unassigned" };
/** Unassigned first, then the active Area catalogue A–Z (case-insensitive). */
export function serviceAreaFilterOptions(areas: VendorFacetArea[]): VendorFacetArea[] {
const sorted = [...areas].sort((a, b) =>
a.name.localeCompare(b.name, undefined, { sensitivity: "base" }),
);
return [UNASSIGNED_AREA_OPTION, ...sorted];
}

View file

@ -30,8 +30,11 @@ import {
type RosterTechnicianValues,
type VendorCompanyRosterFormValues,
} from "@/domain/vendors/schemas/vendor-roster-schema";
import type { VendorFacetCompany } from "@/domain/vendors/types/vendor";
import type { VendorFacetArea, VendorFacetCompany } from "@/domain/vendors/types/vendor";
import { normalizeStateCode } from "@/data/areas";
import { VendorCompanyContactFields } from "./vendor-company-contact-fields";
import { VendorServiceAreaField } from "./vendor-service-area-field";
import { VendorStateSelectField } from "./vendor-state-select-field";
interface VendorRosterFormFieldsProps {
control: Control<VendorCompanyRosterFormValues>;
@ -43,6 +46,9 @@ interface VendorRosterFormFieldsProps {
onSelectCompany?: (company: VendorFacetCompany | null) => Promise<void>;
onClearSelectedCompany?: (nextName?: string) => void;
showTechnicianStatus?: boolean;
areaOptions?: VendorFacetArea[];
currentArea?: VendorFacetArea | null;
canAssignArea?: boolean;
}
function CompanyNameField({
@ -136,6 +142,9 @@ function CompanyFields({
selectedCompanyId,
onSelectCompany,
onClearSelectedCompany,
areaOptions = [],
currentArea = null,
canAssignArea = false,
}: VendorRosterFormFieldsProps) {
const notes = useWatch({ control, name: "notes" }) ?? "";
const { field: streetField } = useController({ control, name: "address" });
@ -163,7 +172,7 @@ function CompanyFields({
// revalidates — a plain assignment would be discarded on save.
streetField.onChange(parts.street);
cityField.onChange(parts.city);
stateField.onChange(parts.state);
stateField.onChange(normalizeStateCode(parts.state) ?? parts.state);
}}
label="Street Address (required)"
required
@ -183,15 +192,13 @@ function CompanyFields({
fullWidth
slotProps={{ htmlInput: { required: true } }}
/>
<TextField
{...stateField}
<VendorStateSelectField
value={stateField.value ?? ""}
label="State (required)"
placeholder="e.g., MO"
onChange={stateField.onChange}
onBlur={stateField.onBlur}
inputRef={stateField.ref}
error={Boolean(errors.state)}
helperText={errors.state?.message}
fullWidth
slotProps={{ htmlInput: { required: true } }}
/>
</Stack>
<Controller
@ -234,6 +241,12 @@ function CompanyFields({
/>
)}
/>
<VendorServiceAreaField
control={control}
areaOptions={areaOptions}
currentArea={currentArea}
canAssign={canAssignArea}
/>
</Stack>
</Box>
);

View file

@ -0,0 +1,58 @@
import { Controller, type Control } from "react-hook-form";
import { Autocomplete, TextField } from "@mui/material";
import type { VendorCompanyRosterFormValues } from "@/domain/vendors/schemas/vendor-roster-schema";
import type { VendorFacetArea } from "@/domain/vendors/types/vendor";
interface VendorServiceAreaFieldProps {
control: Control<VendorCompanyRosterFormValues>;
areaOptions: VendorFacetArea[];
currentArea?: VendorFacetArea | null;
canAssign: boolean;
}
export const SERVICE_AREA_ADMIN_ONLY_MESSAGE = "Only administrators can assign a Service Area.";
/**
* Zero or one Service Area per vendor company, chosen from the Area
* catalogue by stable id. Clearing the selection leaves the company Unassigned.
* The saved Area stays visible when it is no longer in the active catalogue.
*/
export function VendorServiceAreaField({
control,
areaOptions,
currentArea,
canAssign,
}: VendorServiceAreaFieldProps) {
const options =
currentArea && !areaOptions.some((area) => area.id === currentArea.id)
? [...areaOptions, currentArea]
: areaOptions;
return (
<Controller
control={control}
name="areaId"
render={({ field }) => (
<Autocomplete<VendorFacetArea>
options={options}
value={options.find((area) => area.id === field.value) ?? null}
onChange={(_event, option) => field.onChange(option?.id ?? "")}
onBlur={field.onBlur}
getOptionLabel={(option) => option.name}
isOptionEqualToValue={(option, value) => option.id === value.id}
disabled={!canAssign}
fullWidth
renderInput={(params) => (
<TextField
{...params}
label="Service Area (optional)"
placeholder="Unassigned"
inputRef={field.ref}
helperText={canAssign ? undefined : SERVICE_AREA_ADMIN_ONLY_MESSAGE}
/>
)}
/>
)}
/>
);
}

View file

@ -0,0 +1,57 @@
import type { Ref } from "react";
import { Autocomplete, TextField } from "@mui/material";
import {
US_STATE_CODES,
formatStateOptionLabel,
normalizeStateCode,
type StateCode,
} from "@/data/areas";
interface VendorStateSelectFieldProps {
value: string;
onChange: (value: string) => void;
onBlur?: () => void;
inputRef?: Ref<HTMLInputElement>;
error?: boolean;
helperText?: string;
}
/**
* Closed, searchable list of the 50 US states for the vendor company.
* Legacy full names are shown as their canonical code. Service Area is chosen
* independently, so no Area is derived from the selected State here.
*/
export function VendorStateSelectField({
value,
onChange,
onBlur,
inputRef,
error,
helperText,
}: VendorStateSelectFieldProps) {
const selected: StateCode | null = normalizeStateCode(value);
return (
<Autocomplete<StateCode>
options={US_STATE_CODES}
value={selected}
onChange={(_event, option) => onChange(option ?? "")}
onBlur={onBlur}
getOptionLabel={formatStateOptionLabel}
fullWidth
renderInput={(params) => (
<TextField
{...params}
label="State (required)"
placeholder="Select a state"
inputRef={inputRef}
error={error}
helperText={helperText}
slotProps={{
...params.slotProps,
htmlInput: { ...params.slotProps?.htmlInput, required: true },
}}
/>
)}
/>
);
}

View file

@ -155,6 +155,7 @@ function CompanyCells({ row }: { row: VendorListItem }) {
<CellText value={row.address} testId="vendor-text-street-address" focusable />
<CellText value={row.city} testId="vendor-text-city" focusable />
<CellText value={row.state} testId="vendor-text-state" focusable />
<CellText value={row.areaName || "Unassigned"} testId="vendor-text-service-area" focusable />
</>
);
}

View file

@ -21,6 +21,7 @@ const TABLE_COLUMNS = [
"Street Address",
"City",
"State",
"Service Area",
"Trade",
"Technician",
"Technician Phone",
@ -66,7 +67,7 @@ export function VendorsTable({
size="small"
stickyHeader
sx={{
minWidth: 2050,
minWidth: 2200,
tableLayout: "fixed",
"& .MuiTableCell-head": {
backgroundColor: "var(--color-bg-muted)",
@ -94,7 +95,7 @@ export function VendorsTable({
}}
>
<colgroup>
{[190, 160, 220, 220, 140, 100, 190, 220, 170, 110, 120, 130].map((width, index) => (
{[190, 160, 220, 220, 140, 100, 150, 190, 220, 170, 110, 120, 130].map((width, index) => (
<col key={`${width}-${index}`} style={{ width }} />
))}
</colgroup>

View file

@ -13,7 +13,7 @@ import { VendorsTable } from "./_components/vendors-table";
import { useVendorDeactivation } from "./_components/use-vendor-deactivation";
import { useVendorListState } from "./_components/use-vendor-list-state";
import type { VendorFilters } from "./_components/vendor-filters";
import type { VendorListItem } from "@/domain/vendors/types/vendor";
import { VENDOR_AREA_UNASSIGNED, type VendorListItem } from "@/domain/vendors/types/vendor";
import { useVendorFacets } from "@/domain/vendors/use-cases/use-vendor-facets";
import { useVendorDirectoryList } from "@/domain/vendors/use-cases/use-vendor-directory-list";
@ -91,6 +91,7 @@ function VendorStatusTabs({
function describeChips(
filters: VendorFilters,
jobBucketLabels: Map<string, string>,
areaLabels: Map<string, string>,
): AppliedChip[] {
const chips: AppliedChip[] = [];
filters.companies.forEach((value) =>
@ -99,6 +100,13 @@ function describeChips(
filters.trades.forEach((value) =>
chips.push({ category: "trades", value, label: `Trade: ${value}` }),
);
filters.areas.forEach((value) =>
chips.push({
category: "areas",
value,
label: `Service Area: ${areaLabels.get(value) ?? value}`,
}),
);
filters.locations.forEach((value) =>
chips.push({ category: "locations", value, label: `Location: ${value}` }),
);
@ -146,7 +154,15 @@ export default function VendorsListPage() {
() => new Map((facets?.jobBuckets ?? []).map((bucket) => [bucket.id, bucket.label])),
[facets],
);
const appliedChips = describeChips(filters.appliedFilters, jobBucketLabels);
const areaLabels = useMemo(
() =>
new Map([
[VENDOR_AREA_UNASSIGNED, "Unassigned"],
...(facets?.areas ?? []).map((area): [string, string] => [area.id, area.name]),
]),
[facets],
);
const appliedChips = describeChips(filters.appliedFilters, jobBucketLabels, areaLabels);
return (
<Box className="flex h-full flex-col overflow-hidden px-4 pt-4 pb-0">

View file

@ -6,6 +6,7 @@ import {
getDispatcherAvatarColor,
getInitialsFromName,
} from "@/domain/work-orders/utils/dispatcher-avatar-color";
import { formatAuditTimestamp } from "@/domain/work-orders/utils/format-audit-timestamp";
import { formatBoardAuditAction } from "@/domain/work-orders/utils/format-board-audit-action";
function isSystemEntry(entry: WorkOrderAuditEntry): boolean {
@ -15,36 +16,6 @@ function isSystemEntry(entry: WorkOrderAuditEntry): boolean {
return !name || name.toLowerCase() === "system";
}
function formatClock(date: Date): string {
return date.toLocaleTimeString("en-US", {
hour: "numeric",
minute: "2-digit",
});
}
/**
* Manual (image): `· 9:48 AM`
* System (image): `05/13 · 8:00 AM`
* Prefer API display strings that already include · / AM|PM.
*/
function formatAuditTime(value: string, isSystem: boolean): string {
if (!value) return "";
if (/[·•]/.test(value) || /\b(AM|PM)\b/i.test(value)) return value;
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
const timePart = formatClock(date);
if (isSystem) {
const datePart = date.toLocaleDateString("en-US", {
month: "2-digit",
day: "2-digit",
});
return `${datePart} · ${timePart}`;
}
return `· ${timePart}`;
}
type SlideOverAuditListProps = {
entries: WorkOrderAuditEntry[];
users?: WorkOrderUser[];
@ -151,7 +122,7 @@ export function SlideOverAuditList({ entries, users = [] }: SlideOverAuditListPr
color: "#9CA3AF",
}}
>
{formatAuditTime(entry.createdAt, isSys)}
{formatAuditTimestamp(entry.createdAt)}
</Text>
</div>
</div>

View file

@ -8,13 +8,29 @@ type SlideOverCompletionActionsProps = {
docStatus: CompletionDocStatus;
rowVersion?: string | number | null;
completionPending: boolean;
/** Completion documents require a selected primary service. */
hasService: boolean;
hasUploadHandler: boolean;
pdfInputRef: RefObject<HTMLInputElement | null>;
onPdfSelected: (files: FileList | null) => void;
onOpenCompletionDoc: () => void;
};
function DocStatusButtonContent({ docStatus }: { docStatus: CompletionDocStatus }) {
function DocStatusButtonContent({
docStatus,
hasService,
}: {
docStatus: CompletionDocStatus;
hasService: boolean;
}) {
if (!hasService) {
return (
<>
<FileText size={13} />
Select service
</>
);
}
if (docStatus === "Yes") {
return (
<>
@ -43,6 +59,7 @@ export function SlideOverCompletionActions({
docStatus,
rowVersion,
completionPending,
hasService,
hasUploadHandler,
pdfInputRef,
onPdfSelected,
@ -83,10 +100,17 @@ export function SlideOverCompletionActions({
<Button
variant="outline"
className="w-full gap-1.5 text-[12px]"
disabled={!hasService}
title={hasService ? undefined : "Select a service before opening the completion document"}
onClick={onOpenCompletionDoc}
>
<DocStatusButtonContent docStatus={docStatus} />
<DocStatusButtonContent docStatus={docStatus} hasService={hasService} />
</Button>
{!hasService && (
<Text as="p" style={{ fontSize: 11, color: "var(--color-text-muted)" }}>
Select a service before opening the completion document.
</Text>
)}
</div>
);
}

View file

@ -6,7 +6,8 @@ import type { UploadableMediaCategory } from "@/domain/work-orders/mappers/work-
import type { WorkOrderBoardCompletion } from "@/domain/work-orders/types/work-order-board-detail";
import type { MediaFile } from "@/domain/work-orders/types/work-order-media";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
import { hasCompletionDocService } from "@/domain/work-orders/utils/completion-doc-service-gate";
import { hasCompletionMediaGallery } from "@/domain/work-orders/utils/partition-slide-over-media";
import {
formatMediaSizeLimit,
isWorkOrderFileTooLarge,
@ -16,10 +17,6 @@ import { SlideOverCompletionMedia } from "./slide-over-completion-media";
import { SlideOverCompletionReadonlyStatus } from "./slide-over-completion-readonly-status";
import { SlideOverCompletionSignoffs } from "./slide-over-completion-signoffs";
function isMediaWO(type: WOType | ""): boolean {
return type === "Emergency" || type === "Reactive";
}
type SlideOverCompletionTabProps = {
row: WorkOrderTableRow;
isReadOnly: boolean;
@ -56,7 +53,7 @@ export function SlideOverCompletionTab({
const templateUrl = completion?.template?.templateUrl;
const signOffAttachment = completion?.signOffAttachment;
if (isMediaWO(row.type)) {
if (hasCompletionMediaGallery(row.type)) {
return (
<SlideOverCompletionMedia
isReadOnly={isReadOnly}
@ -130,6 +127,7 @@ export function SlideOverCompletionTab({
docStatus={docStatus}
rowVersion={row.rowVersion}
completionPending={completionPending}
hasService={hasCompletionDocService(row.pm)}
hasUploadHandler={Boolean(onUploadCompletionPdf)}
pdfInputRef={pdfInputRef}
onPdfSelected={handlePdfSelected}

View file

@ -34,6 +34,14 @@ const FILETYPE_ICON: Record<FileCategory, typeof ImageIcon> = {
other: Paperclip,
};
const FILETYPE_LABEL: Record<FileCategory, string> = {
image: "Photo",
video: "Video",
pdf: "PDF",
doc: "Document",
other: "File",
};
const EXTRA_DOC_PURPOSES: Array<Extract<UploadableMediaCategory, "Extra" | "Aveta">> = [
"Extra",
"Aveta",
@ -92,8 +100,13 @@ function ExtraDocRow({
const purpose = file.purpose === "Aveta" || isAveta ? "Aveta" : "Extra";
return (
<div className="flex items-center gap-2 py-1">
<div
role="group"
aria-label={`${FILETYPE_LABEL[file.fileType]}, ${purpose}: ${file.name}`}
className="flex items-center gap-2 py-1"
>
<ItemIcon
aria-hidden
size={12}
className="shrink-0"
style={{ color: isAveta ? "var(--warning)" : "var(--color-text-muted)" }}

View file

@ -19,6 +19,10 @@ import type { WizardWOStatus } from "@/domain/work-orders/types/work-order-wizar
import { deriveDayFields } from "@/domain/work-orders/utils/table-day-utils";
import { toVendorTablePatch } from "@/domain/work-orders/utils/vendor-assignment-patch";
import { DocBadge } from "./slide-over-doc-badge";
import {
clearDueDateBeforeSchedule,
resolveDueDateFloor,
} from "@/domain/work-orders/utils/due-date-floor";
type SlideOverInfoTabEditViewProps = {
draft: WorkOrderTableRow;
@ -52,6 +56,7 @@ function SlideOverScheduleOnField({
schedMode={draft.schedMode}
onSave={(scheduledOn) =>
onDraftChange({
...clearDueDateBeforeSchedule(draft.dueDate, scheduledOn),
scheduledOn,
scheduleWeekOnly: false,
targetWeek: scheduledOn ? "" : draft.targetWeek,
@ -63,6 +68,7 @@ function SlideOverScheduleOnField({
}
onSaveWeek={(weekStart) =>
onDraftChange({
...clearDueDateBeforeSchedule(draft.dueDate, weekStart),
scheduledOn: "",
targetWeek: weekStart,
scheduleWeekOnly: true,
@ -74,6 +80,7 @@ function SlideOverScheduleOnField({
}
onSaveRange={(start, end) =>
onDraftChange({
...clearDueDateBeforeSchedule(draft.dueDate, start),
scheduledOn: start,
scheduleEnd: end,
schedMode: "range",
@ -175,6 +182,7 @@ export function SlideOverInfoTabEditView({
<DueDateCell
type={draft.type}
value={draft.dueDate}
minDate={resolveDueDateFloor(draft)}
onSave={(dueDate) => onDraftChange({ dueDate })}
/>
</SlideOverInfoRow>

View file

@ -12,6 +12,7 @@ import type {
UploadWorkOrderMediaInput,
} from "@/domain/work-orders/use-cases/use-work-order-mutations";
import {
hasCompletionMediaGallery,
isCompletionSurfaceMedia,
isExtrasSurfaceMedia,
type MediaSurfaceOwnership,
@ -80,6 +81,7 @@ export function useSlideOverMediaState({
categorizeMediaMutation,
}: UseSlideOverMediaStateArgs) {
const workOrderId = detailForRow?.info.id;
const completionHasGallery = hasCompletionMediaGallery(detailForRow?.info.type);
const [mediaBatchPending, setMediaBatchPending] = useState(false);
const [ownership, setOwnershipState] = useState<MediaSurfaceOwnership>(() =>
loadOwnership(workOrderId),
@ -116,16 +118,16 @@ export function useSlideOverMediaState({
useMediaUploadSession(detailForRow, persistCompletionUpload);
const completionMedia = useMemo(
() => uploads.filter((item) => isCompletionSurfaceMedia(item, ownership)),
[uploads, ownership],
() => uploads.filter((item) => isCompletionSurfaceMedia(item, ownership, completionHasGallery)),
[uploads, ownership, completionHasGallery],
);
const extrasUploads = useMemo(
() =>
boardMediaItemsToMediaFiles(detailForRow?.media ?? []).filter((item) =>
isExtrasSurfaceMedia(item, ownership),
isExtrasSurfaceMedia(item, ownership, completionHasGallery),
),
[detailForRow?.media, ownership],
[detailForRow?.media, ownership, completionHasGallery],
);
const hasLocalUploading = uploads.some((item) => item.uploadStatus === "uploading");

View file

@ -28,6 +28,7 @@ export function buildInlineDraftCreateInput(
scheduledOn: draft.scheduledOn,
dueDate: draft.dueDate,
pm: draft.pm,
serviceId: null,
extraServices: draft.extraServices ?? [],
avetaRequired: Boolean(draft.avetaRequired),
pmNote: draft.serviceNotes ?? "",

View file

@ -25,6 +25,8 @@ type DateCellProps = {
onClear?: () => void;
/** Screen-reader-only status appended inside the button so the accessible name keeps the visible date and adds durable state. */
srStatusSuffix?: string;
/** Earliest selectable day in the date calendar (SH-356). */
minDate?: string;
};
export function DateCell({
@ -41,6 +43,7 @@ export function DateCell({
onSaveRange,
onClear,
srStatusSuffix,
minDate,
}: DateCellProps) {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const open = Boolean(anchorEl);
@ -154,6 +157,7 @@ export function DateCell({
) : (
<MiniCalendar
value={value}
minDate={minDate}
onChange={(d) => {
onSave(d);
setAnchorEl(null);

View file

@ -8,6 +8,7 @@ type DueDateCalendarDialogProps = {
onOpenChange: (open: boolean) => void;
value: string;
onSave: (iso: string) => void;
minDate?: string;
};
/**
@ -19,6 +20,7 @@ export function DueDateCalendarDialog({
onOpenChange,
value,
onSave,
minDate,
}: DueDateCalendarDialogProps) {
return (
<Dialog
@ -44,6 +46,7 @@ export function DueDateCalendarDialog({
<div className="flex justify-center">
<MiniCalendar
value={value}
minDate={minDate}
onChange={(iso) => {
onSave(iso);
onOpenChange(false);

View file

@ -16,6 +16,8 @@ type DueDateCellProps = {
* read by colour alone.
*/
pastDue?: boolean;
/** Schedule On floor: earlier days are not selectable (SH-356). */
minDate?: string;
onSave: (date: string) => void;
};
@ -29,6 +31,7 @@ export function DueDateCell({
q,
highlight,
pastDue = false,
minDate,
onSave,
}: DueDateCellProps) {
const [open, setOpen] = useState(false);
@ -40,6 +43,7 @@ export function DueDateCell({
q={q}
highlight={highlight}
onSave={onSave}
minDate={minDate}
srStatusSuffix={pastDue ? "Past due" : undefined}
/>
);
@ -87,7 +91,13 @@ export function DueDateCell({
style={{ color: "var(--muted-foreground)" }}
/>
</button>
<DueDateCalendarDialog open={open} onOpenChange={setOpen} value={value} onSave={onSave} />
<DueDateCalendarDialog
minDate={minDate}
open={open}
onOpenChange={setOpen}
value={value}
onSave={onSave}
/>
</>
);
}

View file

@ -3,6 +3,12 @@ import { toast } from "react-toastify";
import { workOrdersApi } from "@/domain/work-orders/api/work-orders-api";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
import { findDuplicateWoNumberRow } from "@/domain/work-orders/utils/find-duplicate-wo-number-row";
import {
WO_NUMBER_DOWNGRADE_MESSAGE,
WO_NUMBER_FORMAT_MESSAGE,
isValidBoardWoNumber,
isWoNumberDowngrade,
} from "@/domain/work-orders/utils/wo-number-input";
import { EditableWONumberInput } from "./editable-wo-number-input";
import { HighlightText } from "./highlight-text";
import { AddOnPill, CarriedOverCounterPill, RescheduleCounterPill } from "./wo-counter-pills";
@ -22,8 +28,13 @@ type EditableWONumberCellProps = {
onSave: (v: string) => void;
onDuplicateFound?: (existing: WorkOrderTableRow) => void;
locked?: boolean;
/** Empty-state label for create flows; renders with a persistent required asterisk. */
requiredPlaceholder?: string;
};
/** Inline-create rows pass this id; their number is draft state, never a saved WO number. */
const UNSAVED_DRAFT_ID = "draft";
async function resolveDuplicateWoNumber(
draft: string,
allOrders: WorkOrderTableRow[],
@ -34,6 +45,28 @@ async function resolveDuplicateWoNumber(
return remote && String(remote.id) !== String(currentId) ? remote : undefined;
}
function EmptyWoNumberLabel({
value,
q,
requiredPlaceholder,
}: {
value: string;
q?: string;
requiredPlaceholder?: string;
}) {
if (value) {
return <HighlightText text={value} q={q} />;
}
if (!requiredPlaceholder) {
return "-";
}
return (
<span className="font-sans text-[13px] font-normal">
{requiredPlaceholder} <span style={{ color: "var(--destructive)" }}>*</span>
</span>
);
}
export function EditableWONumberCell({
value,
rescheduleCount,
@ -49,6 +82,7 @@ export function EditableWONumberCell({
onSave,
onDuplicateFound,
locked = false,
requiredPlaceholder,
}: EditableWONumberCellProps) {
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(value);
@ -63,8 +97,14 @@ export function EditableWONumberCell({
setEditing(false);
return;
}
if (draft.length !== 11) {
toast("Work order number must be exactly 11 digits");
if (!isValidBoardWoNumber(draft)) {
toast(WO_NUMBER_FORMAT_MESSAGE);
return;
}
if (String(currentId) !== UNSAVED_DRAFT_ID && isWoNumberDowngrade(value, draft)) {
toast.error(WO_NUMBER_DOWNGRADE_MESSAGE);
setDraft(value);
setEditing(false);
return;
}
setIsChecking(true);
@ -97,14 +137,14 @@ export function EditableWONumberCell({
const handleBlur = () => {
if (isChecking) return;
if (draft !== value && draft.length === 11) {
if (draft !== value && isValidBoardWoNumber(draft)) {
commit();
return;
}
setEditing(false);
};
const invalid = editing && draft.length > 0 && draft.length !== 11;
const invalid = editing && draft.length > 0 && !isValidBoardWoNumber(draft);
if (locked) {
return (
@ -162,7 +202,7 @@ export function EditableWONumberCell({
padding: "2px 4px",
}}
>
{value ? <HighlightText text={value} q={q} /> : "-"}
<EmptyWoNumberLabel value={value} q={q} requiredPlaceholder={requiredPlaceholder} />
</span>
)}
<AddOnPill when={isAddOn} />

View file

@ -1,3 +1,5 @@
import { sanitizeBoardWoNumberInput } from "@/domain/work-orders/utils/wo-number-input";
type EditableWONumberInputProps = {
draft: string;
invalid: boolean;
@ -21,9 +23,8 @@ export function EditableWONumberInput({
<input
autoFocus
disabled={isChecking}
inputMode="numeric"
value={draft}
onChange={(event) => onChange(event.target.value.replace(/\D/g, "").slice(0, 11))}
onChange={(event) => onChange(sanitizeBoardWoNumberInput(event.target.value))}
onFocus={(event) => event.target.select()}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
@ -36,7 +37,7 @@ export function EditableWONumberInput({
}
}}
onBlur={onBlur ?? onCommit}
placeholder="12345678901"
placeholder="e.g. 12345678901 or SH00001"
aria-label="Work order number"
aria-invalid={invalid}
className="font-mono focus:outline-none"

View file

@ -39,7 +39,7 @@ export function PmTypePickerPopover({
autoFocus
value={search}
onChange={(e) => onSearchChange(e.target.value)}
placeholder="Search PM type…"
placeholder="Search service…"
className="w-full rounded border border-border bg-[var(--color-bg-surface)] px-2 py-1 text-xs text-[var(--color-text-primary)] focus:outline-none"
/>
</div>

View file

@ -7,6 +7,7 @@ type SiteDialogPocSectionProps = {
pocNotes: string;
additionalContacts: WorkOrderAdditionalContact[];
showPrimaryErrors?: boolean;
primaryRequired?: boolean;
onPocNameChange: (value: string) => void;
onPocPhoneChange: (value: string) => void;
onPocNotesChange: (value: string) => void;
@ -19,6 +20,7 @@ export function SiteDialogPocSection({
pocNotes,
additionalContacts,
showPrimaryErrors = false,
primaryRequired = false,
onPocNameChange,
onPocPhoneChange,
onPocNotesChange,
@ -31,6 +33,7 @@ export function SiteDialogPocSection({
pocNotes={pocNotes}
additionalContacts={additionalContacts}
showPrimaryErrors={showPrimaryErrors}
primaryRequired={primaryRequired}
onPocNameChange={onPocNameChange}
onPocPhoneChange={onPocPhoneChange}
onPocNotesChange={onPocNotesChange}

View file

@ -86,7 +86,7 @@ export function SiteDialog({
<fieldset disabled={viewOnly} className="mt-3 space-y-3 border-0 p-0">
<div>
<FieldLabel>Site</FieldLabel>
<FieldLabel required={createMode}>Site</FieldLabel>
<WizardFieldSelect
value={s.locId}
placeholder="Select site …"
@ -130,6 +130,7 @@ export function SiteDialog({
pocNotes={s.notes}
additionalContacts={s.extraContacts}
showPrimaryErrors={createMode && s.showErrors}
primaryRequired={createMode}
onPocNameChange={s.setPn}
onPocPhoneChange={s.setPp}
onPocNotesChange={s.setNotes}

View file

@ -9,10 +9,10 @@ import {
tableRowToClosabilityInput,
} from "@/domain/work-orders/utils/wo-closability";
import {
BOARD_INLINE_STATUSES,
PAST_DUE_BADGE_TOOLTIP,
PAST_DUE_POPOVER_BODY,
PAST_DUE_RESCHEDULE_CTA,
getInlineStatusTransitions,
getStatusOptionState,
} from "@/domain/work-orders/utils/wo-lifecycle-transitions";
import { HoverChevron } from "./hover-chevron";
@ -27,6 +27,7 @@ type StatusCellProps = {
onPastDueAttempt?: () => void;
onRequestComplete?: () => void;
readOnly?: boolean;
/** Explicit list for inline create; existing WOs derive valid transitions from `wo.status`. */
statusOptions?: readonly WizardWOStatus[];
};
@ -128,10 +129,11 @@ export function StatusCell({
onPastDueAttempt,
onRequestComplete,
readOnly = false,
statusOptions = BOARD_INLINE_STATUSES,
statusOptions,
}: StatusCellProps) {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const closabilityGaps = rowClosabilityGaps(wo);
const options = statusOptions ?? getInlineStatusTransitions(wo.status);
if (readOnly) {
return <ReadOnlyStatusLabel status={wo.status} />;
@ -169,7 +171,7 @@ export function StatusCell({
onClick={(e) => e.stopPropagation()}
slotProps={{ paper: { className: "min-w-[190px] rounded-lg border border-border p-1" } }}
>
{statusOptions.map((status) => {
{options.map((status) => {
const option = getStatusOptionState(wo, status, closabilityGaps);
return (

View file

@ -9,6 +9,7 @@ import { shouldNotifyCrossWeek } from "@/domain/work-orders/utils/should-notify-
import type { ReturnTypeOfUseWorkOrdersTableData } from "./wo-table-types";
import { rescheduleNotify, weekMoveNotify } from "./reschedule-notify";
import type { WoTableRowHandlers } from "./wo-table-row";
import { clearDueDateBeforeSchedule } from "@/domain/work-orders/utils/due-date-floor";
function revealOrNotifyScheduledDay(args: {
id: string | number;
@ -31,6 +32,35 @@ function revealOrNotifyScheduledDay(args: {
revealScheduledRow(id);
}
type DragHandlersArgs = Pick<
ReturnTypeOfUseWorkOrdersTableData,
"dragState" | "setDragViz" | "reorderRows" | "endDrag"
>;
function createDragHandlers({ dragState, setDragViz, reorderRows, endDrag }: DragHandlersArgs) {
return {
onDragStart: (id: string | number) => {
dragState.current = { dragId: id, overId: null };
setDragViz({ dragId: id, overId: null });
},
onDragOver: (id: string | number) => {
const did = dragState.current.dragId;
if (did && did !== id && dragState.current.overId !== id) {
dragState.current.overId = id;
setDragViz((v) => ({ ...v, overId: id }));
}
},
onDrop: () => {
const { dragId, overId } = dragState.current;
if (dragId && overId) {
reorderRows(dragId, overId);
}
endDrag();
},
onDragEnd: endDrag,
};
}
type UseWoTableRowHandlersOptions = {
tableData: ReturnTypeOfUseWorkOrdersTableData;
weekMonday: string;
@ -101,8 +131,11 @@ export function useWoTableRowHandlers({
onPatch: (id, patch, options) => {
onPatch(id, patch, options);
},
onScheduleDate: (id: string | number, date: string) => {
onPatch(id, applySchedulePatch(date, false));
onScheduleDate: (id: string | number, date: string, dueDate?: string) => {
onPatch(id, {
...applySchedulePatch(date, false),
...clearDueDateBeforeSchedule(dueDate, date),
});
revealOrNotifyScheduledDay({
id,
date,
@ -111,8 +144,11 @@ export function useWoTableRowHandlers({
revealScheduledRow,
});
},
onScheduleRange: (id: string | number, start: string, end: string) => {
onPatch(id, applyScheduleRangePatch(start, end));
onScheduleRange: (id: string | number, start: string, end: string, dueDate?: string) => {
onPatch(id, {
...applyScheduleRangePatch(start, end),
...clearDueDateBeforeSchedule(dueDate, start),
});
revealOrNotifyScheduledDay({
id,
date: start,
@ -121,7 +157,7 @@ export function useWoTableRowHandlers({
revealScheduledRow,
});
},
onScheduleWeek: (id: string | number, week: string) => {
onScheduleWeek: (id: string | number, week: string, dueDate?: string) => {
const isClear = week === "";
onPatch(
id,
@ -135,6 +171,7 @@ export function useWoTableRowHandlers({
schedMode: "week",
dayGroup: "",
dayLabel: "",
...clearDueDateBeforeSchedule(dueDate, week),
},
);
weekMoveNotify(week, {
@ -153,25 +190,12 @@ export function useWoTableRowHandlers({
onRequestComplete,
onPastDueAttempt: (id: string | number) => onScheduleHighlight(id),
onReorder: reorderRows,
onDragStart: (id: string | number) => {
dragStateRef.current = { dragId: id, overId: null };
setDragViz({ dragId: id, overId: null });
},
onDragOver: (id: string | number) => {
const did = dragStateRef.current.dragId;
if (did && did !== id && dragStateRef.current.overId !== id) {
dragStateRef.current.overId = id;
setDragViz((v) => ({ ...v, overId: id }));
}
},
onDrop: () => {
const { dragId, overId } = dragStateRef.current;
if (dragId && overId) {
reorderRows(dragId, overId);
}
endDrag();
},
onDragEnd: endDrag,
...createDragHandlers({
dragState: dragStateRef,
setDragViz,
reorderRows,
endDrag,
}),
}),
[
tableData,

View file

@ -11,9 +11,10 @@ export const WO_TABLE_COLS = [
{ key: "vendor", label: "VENDOR", w: 184 },
{ key: "appt", label: "APPT TIME", w: 128 },
{ key: "status", label: "STATUS", w: 148 },
// Completed Date gates the Completion Document, so it sits between Status and Comp Doc.
{ key: "completed", label: "COMPLETED DATE", w: 130 },
{ key: "doc", label: "COMP DOC", w: 84 },
{ key: "uplift", label: "UPLIFT", w: 108 },
{ key: "completed", label: "COMPLETED DATE", w: 130 },
{ key: "actions", label: "", w: 100 },
] as const;

View file

@ -1,4 +1,5 @@
import { WO_TABLE_COLS } from "./wo-table-cols";
import { WoTableHeaderLabel } from "./wo-table-header-label";
export function WoTableHead() {
return (
@ -25,7 +26,7 @@ export function WoTableHead() {
borderBottom: "1px solid var(--border)",
}}
>
{col.label}
<WoTableHeaderLabel colKey={col.key} label={col.label} />
{Boolean(srLabel) && <span className="sr-only">{srLabel}</span>}
</th>
);

View file

@ -0,0 +1,39 @@
import { Tooltip } from "@mui/material";
import { CircleQuestionMark } from "lucide-react";
import { getWoTableHeaderTooltip } from "@/domain/work-orders/constants/wo-table-header-tooltips";
type WoTableHeaderLabelProps = {
colKey: string;
label: string;
};
export function WoTableHeaderLabel({ colKey, label }: WoTableHeaderLabelProps) {
const tooltip = getWoTableHeaderTooltip(colKey);
if (!tooltip) {
return <>{label}</>;
}
return (
<span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
{label}
<Tooltip title={tooltip} arrow placement="top">
<button
type="button"
aria-label={`${label} column help`}
style={{
display: "inline-flex",
cursor: "help",
color: "var(--color-text-muted)",
padding: 0,
border: 0,
background: "transparent",
}}
>
<CircleQuestionMark size={13} aria-hidden="true" />
</button>
</Tooltip>
</span>
);
}

View file

@ -89,6 +89,7 @@ export function WoTableInlineIdentityCells({
allOrders={allRows as never[]}
onSave={(v) => onPatch({ woNumber: v })}
onDuplicateFound={onDuplicateFound}
requiredPlaceholder="Insert WO #"
/>
<AddOnOverrideToggle
checked={draft.isAddOnOverride}

View file

@ -17,7 +17,7 @@ export function WoTableInlineRowActions({
onCancel,
}: WoTableInlineRowActionsProps) {
return (
<div className="flex items-center gap-0.5">
<div className="flex items-center gap-0.5" style={{ minHeight: 34 }}>
<button
type="button"
onClick={onSave}

View file

@ -1,4 +1,4 @@
import type { RefObject } from "react";
import type { ReactNode, RefObject } from "react";
import type {
LocationOption,
VendorDropdownItem,
@ -21,8 +21,13 @@ import { StatusCell } from "./cells/status-cell";
import { TypeCell } from "./cells/type-cell";
import { VendorCell } from "./cells/vendor-cell";
import { toVendorTablePatch } from "@/domain/work-orders/utils/vendor-assignment-patch";
import { InlineCreateField } from "./inline-create-field";
import { toInlineDraftRow } from "./to-inline-draft-row";
import { WoTableInlineIdentityCells } from "./wo-table-inline-identity-cells";
import {
clearDueDateBeforeSchedule,
resolveDueDateFloor,
} from "@/domain/work-orders/utils/due-date-floor";
type WoTableInlineRowCellsProps = {
draft: WorkOrderTableDraft;
@ -43,6 +48,17 @@ type WoTableInlineRowCellsProps = {
onRequestComplete?: () => void;
};
/** Matches the identity cells: top-aligned so field boxes and error helpers line up. */
const INLINE_FIELD_TD_STYLE = { padding: "8px 6px 0", verticalAlign: "top" } as const;
function InlineFieldCell({ children }: { children: ReactNode }) {
return (
<td className="group/cell" style={INLINE_FIELD_TD_STYLE}>
<InlineCreateField>{children}</InlineCreateField>
</td>
);
}
function InlineTypeSeverityCell({
draft,
onPatch,
@ -51,20 +67,22 @@ function InlineTypeSeverityCell({
onPatch: (patch: Partial<WorkOrderTableDraft>) => void;
}) {
return (
<td className="group/cell" style={{ padding: "0 14px" }}>
<InlineFieldCell>
<TypeCell
value={draft.type}
severity={draft.severity}
onSave={(t, sev) => onPatch({ type: t, severity: sev })}
/>
</td>
</InlineFieldCell>
);
}
function InlineMutedDashCell() {
return (
<td style={{ padding: "0 14px" }}>
<span style={{ fontSize: 11, color: "var(--color-text-muted)" }}>—</span>
<td style={INLINE_FIELD_TD_STYLE}>
<div className="flex items-center" style={{ minHeight: 34 }}>
<span style={{ fontSize: 11, color: "var(--color-text-muted)" }}>—</span>
</div>
</td>
);
}
@ -81,18 +99,18 @@ function InlineScheduleOnCell({
const hasSchedule =
Boolean(draft.scheduledOn) || Boolean(draft.targetWeek) || Boolean(draft.scheduleEnd);
return (
<td className="group/cell" style={{ padding: "0 14px" }}>
<InlineFieldCell>
<DateCell
value={draft.scheduledOn}
allowWeekMode
targetWeek={draft.targetWeek}
defaultMode={weekDefault ? "week" : "date"}
highlight={!draft.scheduledOn && !draft.targetWeek}
scheduleEnd={draft.scheduleEnd}
schedMode={draft.schedMode}
onSave={(date) =>
onPatch(
withAutoScheduleStatus(draft, {
...clearDueDateBeforeSchedule(draft.dueDate, date),
scheduledOn: date,
scheduleWeekOnly: false,
targetWeek: "",
@ -105,6 +123,7 @@ function InlineScheduleOnCell({
onSaveWeek={(week) =>
onPatch(
withAutoScheduleStatus(draft, {
...clearDueDateBeforeSchedule(draft.dueDate, week),
scheduledOn: "",
targetWeek: week,
scheduleWeekOnly: true,
@ -117,6 +136,7 @@ function InlineScheduleOnCell({
onSaveRange={(start, end) =>
onPatch(
withAutoScheduleStatus(draft, {
...clearDueDateBeforeSchedule(draft.dueDate, start),
scheduledOn: start,
scheduleEnd: end,
schedMode: "range",
@ -142,7 +162,7 @@ function InlineScheduleOnCell({
: undefined
}
/>
</td>
</InlineFieldCell>
);
}
@ -184,26 +204,26 @@ export function WoTableInlineRowCells({
<InlineTypeSeverityCell draft={draft} onPatch={onPatch} />
<td className="group/cell" style={{ padding: "0 14px" }}>
<InlineFieldCell>
<AssignedToCell
dispatcherId={draft.dispatcherId}
users={users}
highlight={!draft.dispatcherId}
onSave={(id) => {
onPatch({ dispatcherId: id, status: draft.status || "Incomplete" });
}}
/>
</td>
</InlineFieldCell>
<InlineScheduleOnCell draft={draft} weekDefault={weekDefault} onPatch={onPatch} />
<td className="group/cell" style={{ padding: "0 14px" }}>
<InlineFieldCell>
<DueDateCell
type={draft.type}
value={draft.dueDate}
minDate={resolveDueDateFloor(draft)}
onSave={(date) => onPatch({ dueDate: date })}
/>
</td>
<td className="group/cell" style={{ padding: "0 14px" }}>
</InlineFieldCell>
<InlineFieldCell>
<PMTypeCell
value={draft.pm}
pmTypes={pmTypes}
@ -221,8 +241,8 @@ export function WoTableInlineRowCells({
})
}
/>
</td>
<td className="group/cell" style={{ padding: "0 14px" }}>
</InlineFieldCell>
<InlineFieldCell>
<VendorCell
vendorId={draft.vendorId}
company={draft.company}
@ -231,8 +251,8 @@ export function WoTableInlineRowCells({
vendors={vendors}
onSave={(p) => onPatch(toVendorTablePatch(p))}
/>
</td>
<td className="group/cell" style={{ padding: "0 14px" }}>
</InlineFieldCell>
<InlineFieldCell>
<ApptTimeCell
apptTime={
draft.apptStart ? `${draft.apptStart}${draft.apptEnd ? ` – ${draft.apptEnd}` : ""}` : ""
@ -242,8 +262,8 @@ export function WoTableInlineRowCells({
onPatch({ apptStart: start ?? "", apptEnd: end ?? "" });
}}
/>
</td>
<td className="group/cell" style={{ padding: "0 14px" }}>
</InlineFieldCell>
<InlineFieldCell>
<StatusCell
wo={draftRow as never}
statusOptions={CREATION_INLINE_STATUSES}
@ -251,7 +271,7 @@ export function WoTableInlineRowCells({
onOpenSlideOver={() => {}}
onRequestComplete={onRequestComplete}
/>
</td>
</InlineFieldCell>
<InlineMutedDashCell />
<InlineMutedDashCell />

View file

@ -115,15 +115,17 @@ export function WoTableInlineRow({
pointerEvents: saving ? "none" : undefined,
}}
>
<td style={{ padding: "0 0 0 6px" }} />
<td style={{ padding: "8px 0 0 6px", verticalAlign: "top" }} />
<td style={{ padding: "0 2px 0 8px" }}>
<Flag
size={14}
strokeWidth={1.75}
aria-hidden="true"
style={{ color: "var(--color-border)" }}
/>
<td style={{ padding: "8px 2px 0 8px", verticalAlign: "top" }}>
<div className="flex items-center" style={{ minHeight: 34 }}>
<Flag
size={14}
strokeWidth={1.75}
aria-hidden="true"
style={{ color: "var(--color-border)" }}
/>
</div>
</td>
<WoTableInlineRowCells
@ -145,7 +147,7 @@ export function WoTableInlineRow({
onRequestComplete={() => setConfirmComplete(true)}
/>
<td style={{ padding: "0 4px" }}>
<td style={{ padding: "8px 4px 0", verticalAlign: "top" }}>
<WoTableInlineRowActions
canSave={canSave}
saving={saving}

View file

@ -16,6 +16,7 @@ import { EditableWONumberCell } from "./cells/editable-wo-number-cell";
import { SiteCell } from "./cells/site-cell";
import { TypeCell } from "./cells/type-cell";
import type { WoTableRowHandlers } from "./wo-table-row";
import { resolveDueDateFloor } from "@/domain/work-orders/utils/due-date-floor";
type WoTableRowCellsProps = {
row: WorkOrderTableRow;
@ -146,9 +147,9 @@ export function WoTableRowCells({
targetWeek={row.targetWeek}
scheduleEnd={row.scheduleEnd}
schedMode={row.schedMode}
onSave={(date) => handlers.onScheduleDate(row.id, date)}
onSaveWeek={(week) => handlers.onScheduleWeek(row.id, week)}
onSaveRange={(start, end) => handlers.onScheduleRange(row.id, start, end)}
onSave={(date) => handlers.onScheduleDate(row.id, date, row.dueDate)}
onSaveWeek={(week) => handlers.onScheduleWeek(row.id, week, row.dueDate)}
onSaveRange={(start, end) => handlers.onScheduleRange(row.id, start, end, row.dueDate)}
onClear={hasSchedule && !viewOnly ? () => handlers.onScheduleWeek(row.id, "") : undefined}
/>
</td>
@ -163,6 +164,7 @@ export function WoTableRowCells({
q={search}
highlight={forceDueDateHighlight || row.isPastDue}
pastDue={row.isPastDue}
minDate={resolveDueDateFloor(row)}
onSave={(date) => onPatchRow({ dueDate: date })}
/>
</td>

View file

@ -105,6 +105,17 @@ export function WoTableRowServiceCells({
onRequestComplete={() => handlers.onRequestComplete?.(row)}
/>
</td>
<td
className="group/cell"
style={{ padding: "0 14px", ...mutationCellStyle }}
onClick={(e) => e.stopPropagation()}
>
<DateCell
value={row.completedDate}
q={search}
onSave={(date) => onPatchRow({ completedDate: date })}
/>
</td>
<td style={{ padding: "0 14px" }} onClick={(e) => e.stopPropagation()}>
<CompDocCell
status={row.docStatus}
@ -126,17 +137,6 @@ export function WoTableRowServiceCells({
}
/>
</td>
<td
className="group/cell"
style={{ padding: "0 14px", ...mutationCellStyle }}
onClick={(e) => e.stopPropagation()}
>
<DateCell
value={row.completedDate}
q={search}
onSave={(date) => onPatchRow({ completedDate: date })}
/>
</td>
</>
);
}

View file

@ -36,9 +36,10 @@ export type WoTableRowHandlers = {
patch: Partial<WorkOrderTableRow>,
options?: WorkOrderTablePatchOptions,
) => void;
onScheduleDate: (id: string | number, date: string) => void;
onScheduleWeek: (id: string | number, week: string) => void;
onScheduleRange: (id: string | number, start: string, end: string) => void;
/** `dueDate` is the row's current Due Date, cleared when the new schedule passes it (SH-356). */
onScheduleDate: (id: string | number, date: string, dueDate?: string) => void;
onScheduleWeek: (id: string | number, week: string, dueDate?: string) => void;
onScheduleRange: (id: string | number, start: string, end: string, dueDate?: string) => void;
onDuplicateFound?: (existing: WorkOrderTableRow) => void;
onOpenSlideOver: (row: WorkOrderTableRow) => void;
onRequestComplete?: (row: WorkOrderTableRow) => void;
@ -77,17 +78,17 @@ function guardScheduleHandlers(
if (!canApplyWorkOrderTablePatch(row.status, patch)) return;
handlers.onPatch(id, patch, options);
},
onScheduleDate: (id, date) => {
onScheduleDate: (id, date, dueDate) => {
if (!canApplyWorkOrderTablePatch(row.status, { scheduledOn: date })) return;
handlers.onScheduleDate(id, date);
handlers.onScheduleDate(id, date, dueDate);
},
onScheduleWeek: (id, week) => {
onScheduleWeek: (id, week, dueDate) => {
if (!canApplyWorkOrderTablePatch(row.status, { targetWeek: week })) return;
handlers.onScheduleWeek(id, week);
handlers.onScheduleWeek(id, week, dueDate);
},
onScheduleRange: (id, start, end) => {
onScheduleRange: (id, start, end, dueDate) => {
if (!canApplyWorkOrderTablePatch(row.status, { scheduledOn: start })) return;
handlers.onScheduleRange(id, start, end);
handlers.onScheduleRange(id, start, end, dueDate);
},
};
}

View file

@ -5,31 +5,49 @@ import { ToolbarButton } from "@/components/ui/toolbar-button";
type WorkOrdersListHeaderProps = {
search: string;
/** Compact label of the active board week (e.g. "5/4–5/8"). */
weekLabel: string;
onSearchChange: (value: string) => void;
/** Omit until Advanced Search slice mounts the sheet. */
onOpenAdvancedFilters?: () => void;
/** Omit until wizard shell slice mounts New WO. */
onNewWorkOrder?: () => void;
activeFilterCount: number;
/** True while Advanced Filters are applied; results are global and the keyword box is inert. */
advancedFiltersActive?: boolean;
isFetching?: boolean;
};
export function WorkOrdersListHeader({
search,
weekLabel,
onSearchChange,
onOpenAdvancedFilters,
onNewWorkOrder,
activeFilterCount,
advancedFiltersActive = false,
isFetching = false,
}: WorkOrdersListHeaderProps) {
return (
<>
<SearchInput
value={search}
onChange={onSearchChange}
placeholder="Search this week…"
aria-label="Search work orders"
/>
<div className="relative">
<SearchInput
value={search}
onChange={onSearchChange}
placeholder="Search this week…"
aria-label="Search work orders"
/>
{/* Keyword search is scoped to the active week; make that scope visible. */}
{!advancedFiltersActive && search.trim() !== "" && Boolean(weekLabel) && (
<span
role="status"
className="absolute left-0 whitespace-nowrap text-(length:--text-xs) text-muted-foreground"
style={{ top: "calc(100% + 4px)" }}
>
Searching within {weekLabel}
</span>
)}
</div>
{Boolean(onOpenAdvancedFilters) && (
<ToolbarButton

View file

@ -1,3 +1,4 @@
import { useId } from "react";
import { Plus, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Text } from "@/components/ui/text";
@ -23,6 +24,8 @@ type PocContactFieldsProps = {
onAdditionalContactsChange: (contacts: WorkOrderAdditionalContact[]) => void;
helperText?: string;
showPrimaryErrors?: boolean;
/** Labels the primary name/phone inputs with a persistent required asterisk. */
primaryRequired?: boolean;
};
function extraNameMissing(contact: WorkOrderAdditionalContact): boolean {
@ -135,7 +138,9 @@ export function PocContactFields({
onAdditionalContactsChange,
helperText,
showPrimaryErrors = false,
primaryRequired = false,
}: PocContactFieldsProps) {
const fieldId = useId();
const nameMissing = showPrimaryErrors && !pocName.trim();
const phoneMissing = showPrimaryErrors && !pocPhone.trim();
@ -153,7 +158,13 @@ export function PocContactFields({
)}
<div className="space-y-2">
<div>
{primaryRequired && (
<FieldLabel required htmlFor={`${fieldId}-name`}>
POC name
</FieldLabel>
)}
<input
id={`${fieldId}-name`}
value={pocName}
onChange={(event) => onPocNameChange(event.target.value)}
placeholder="POC name"
@ -168,7 +179,13 @@ export function PocContactFields({
</Text>
</div>
<div>
{primaryRequired && (
<FieldLabel required htmlFor={`${fieldId}-phone`}>
POC phone
</FieldLabel>
)}
<input
id={`${fieldId}-phone`}
value={pocPhone}
onChange={(event) => onPocPhoneChange(event.target.value)}
placeholder="POC phone"

View file

@ -12,6 +12,8 @@ type MiniCalendarProps = {
range?: boolean;
rangeStart?: string;
rangeEnd?: string;
/** Days before this ISO date are disabled (SH-356 Due Date floor). */
minDate?: string;
};
export function MiniCalendar({
@ -20,9 +22,11 @@ export function MiniCalendar({
range,
rangeStart = "",
rangeEnd = "",
minDate = "",
}: MiniCalendarProps) {
const initRaw = range ? rangeStart || value : value;
const init = /^\d{4}-\d{2}-\d{2}$/.test(initRaw) ? initRaw : todayIso();
const fallback = minDate > todayIso() ? minDate : todayIso();
const init = /^\d{4}-\d{2}-\d{2}$/.test(initRaw) ? initRaw : fallback;
const [iy, im] = init.split("-").map(Number);
const [viewY, setViewY] = useState(iy);
const [viewM, setViewM] = useState(im);
@ -94,6 +98,7 @@ export function MiniCalendar({
}
const iso = `${viewY}-${pad2(viewM)}-${pad2(day)}`;
const isToday = iso === today;
const beforeMin = Boolean(minDate) && iso < minDate;
const { bg, fg, radius, filled } = getMiniCalendarCellStyle({
iso,
value,
@ -107,8 +112,9 @@ export function MiniCalendar({
<button
key={i}
type="button"
disabled={beforeMin}
onClick={() => onChange(iso)}
className="text-center text-[12px] transition-colors hover:bg-[var(--color-primary-tint)]"
className="text-center text-[12px] transition-colors hover:bg-[var(--color-primary-tint)] disabled:cursor-not-allowed disabled:bg-transparent disabled:opacity-40"
style={{
height: 26,
borderRadius: radius,

View file

@ -82,7 +82,10 @@ export function NewWoWizard({
locationDetail={wizard.locationDetail}
locationDetailLoading={wizard.locationDetailLoading}
locationDetailError={wizard.locationDetailError}
services={wizard.problems.map((p) => ({ id: p.id, value: p.value }))}
services={wizard.services.map((service) => ({
id: service.id,
value: service.name,
}))}
showErrors={wizard.showErrors}
svcOpen={wizard.svcOpen}
onSvcOpenChange={wizard.setSvcOpen}

View file

@ -2,8 +2,6 @@ import { useEffect } from "react";
import { guardDialogClose } from "@/lib/dialog-guard";
import { useDropdownOptionsByCategory } from "@/domain/settings/dropdown-options/use-cases/use-dropdown-options-by-category";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
import type { WorkOrderWizardDraft } from "@/domain/work-orders/types/work-order-wizard";
@ -16,6 +14,7 @@ import { useCreateWorkOrderFromWizard } from "@/domain/work-orders/use-cases/use
import { useNewWoWizardDraft } from "@/app/(protected)/workorders/_components/wizard/use-new-wo-wizard-draft";
import { useWizardDuplicateActions } from "@/app/(protected)/workorders/_components/wizard/use-wizard-duplicate-actions";
import { useWizardPocAutofill } from "@/app/(protected)/workorders/_components/wizard/use-wizard-poc-autofill";
import { useServicesForWorkOrderType } from "@/domain/services/use-cases/use-services-for-work-order-type";
type UseNewWoWizardControllerArgs = {
open: boolean;
@ -32,7 +31,7 @@ export function useNewWoWizardController({
const draftState = useNewWoWizardDraft(open);
const { data: locations = [] } = useLocationSites();
const { data: problems = [] } = useDropdownOptionsByCategory("Problem");
const { data: registryServices = [] } = useServicesForWorkOrderType(draftState.draft.type);
const {
data: locationDetail,
isLoading: locationDetailLoading,
@ -78,7 +77,7 @@ export function useNewWoWizardController({
...draftState,
patchDraft,
locations,
problems,
services: registryServices,
locationDetail,
locationDetailLoading,
locationDetailError,

View file

@ -19,6 +19,8 @@ type WizardDateFieldProps = {
scheduleEnd?: string;
schedMode?: WizardSchedMode;
onChangeRange?: (start: string, end: string) => void;
/** Earliest selectable day in the date calendar (SH-356). */
minDate?: string;
};
function fieldLabel(args: {
@ -49,6 +51,7 @@ export function WizardDateField({
scheduleEnd = "",
schedMode,
onChangeRange,
minDate,
}: WizardDateFieldProps) {
const { anchorEl, open, setAnchor, close } = useMenuAnchor();
const allowRange = Boolean(allowWeekMode && onChangeRange);
@ -127,6 +130,7 @@ export function WizardDateField({
) : (
<MiniCalendar
value={value}
minDate={minDate}
onChange={(iso) => {
onChange(iso);
close();

View file

@ -10,6 +10,8 @@ type WizardDueDateFieldProps = {
value: string;
placeholder: string;
onChange: (iso: string) => void;
/** Schedule On floor: earlier days are not selectable (SH-356). */
minDate?: string;
};
/**
@ -21,11 +23,19 @@ export function WizardDueDateField({
value,
placeholder,
onChange,
minDate,
}: WizardDueDateFieldProps) {
const [open, setOpen] = useState(false);
if (type !== "Emergency") {
return <WizardDateField value={value} placeholder={placeholder} onChange={onChange} />;
return (
<WizardDateField
value={value}
placeholder={placeholder}
onChange={onChange}
minDate={minDate}
/>
);
}
return (
@ -63,7 +73,13 @@ export function WizardDueDateField({
</span>
<ChevronDown size={13} className="shrink-0" style={{ color: "var(--muted-foreground)" }} />
</button>
<DueDateCalendarDialog open={open} onOpenChange={setOpen} value={value} onSave={onChange} />
<DueDateCalendarDialog
open={open}
onOpenChange={setOpen}
value={value}
onSave={onChange}
minDate={minDate}
/>
</>
);
}

View file

@ -26,6 +26,7 @@ export function WizardStepLocationPocFields({
onAdditionalContactsChange={(contacts) => onUpdate("additionalContacts", contacts)}
helperText="Auto-filled from records — edit if outdated"
showPrimaryErrors={showErrors && pocIncomplete}
primaryRequired
/>
);
}

View file

@ -32,8 +32,10 @@ export function WizardStepLocationServiceSelect({
nextPm !== draft.pm ? { vendorId: "", vendorName: "", techPhone: "" } : {};
const selectSvc = (p: string) => {
const selected = services.find((service) => service.value === p);
onPatch({
pm: p,
serviceId: selected?.id ?? null,
extraServices: [],
...clearVendorIfPrimaryChanged(p),
});
@ -48,7 +50,7 @@ export function WizardStepLocationServiceSelect({
icon={
<Droplets size={16} className="shrink-0" style={{ color: "var(--muted-foreground)" }} />
}
searchPlaceholder="Search PM type…"
searchPlaceholder="Search services…"
options={services.map((s) => {
const Icon = getPmTypeIcon(s.value);
return {

View file

@ -29,6 +29,10 @@ import {
import { WizardSeverityPicker } from "@/app/(protected)/workorders/_components/wizard/wizard-severity-picker";
import { CheckCircle2, Clock, Flame, Users, Wrench, Zap } from "lucide-react";
import type { ElementType } from "react";
import {
clearDueDateBeforeSchedule,
resolveDueDateFloor,
} from "@/domain/work-orders/utils/due-date-floor";
const WO_TYPE_ICONS: Record<WOType, ElementType> = {
PM: Wrench,
@ -165,6 +169,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
onChange={(iso) =>
onPatch(
withAutoScheduleStatus(draft, {
...clearDueDateBeforeSchedule(draft.dueDate, iso),
scheduledOn: iso,
scheduleWeekOnly: false,
scheduleEnd: "",
@ -177,6 +182,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
onChangeWeek={(w) =>
onPatch(
withAutoScheduleStatus(draft, {
...clearDueDateBeforeSchedule(draft.dueDate, w),
scheduledOn: w,
scheduleWeekOnly: Boolean(w),
scheduleEnd: "",
@ -189,6 +195,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
onChangeRange={(s, e) =>
onPatch(
withAutoScheduleStatus(draft, {
...clearDueDateBeforeSchedule(draft.dueDate, s),
scheduledOn: s,
scheduleEnd: e,
schedMode: "range",
@ -211,6 +218,7 @@ function WizardTypeScheduleDates({ draft, onUpdate, onPatch }: WizardTypeSchedul
<WizardDueDateField
type={draft.type}
value={draft.dueDate}
minDate={resolveDueDateFloor(draft)}
placeholder="No due date"
onChange={(iso) => onUpdate("dueDate", iso)}
/>
@ -262,9 +270,23 @@ export function WizardStepTypeSchedule({
<WoTypePicker
selected={draft.type}
onSelect={(t) => {
const typeChanged = t !== draft.type;
onPatch({
type: t,
severity: nextSeverityForType(draft.type, t, draft.severity),
// A registry service is scoped to its work-order type, so a service picked
// under the previous type fails backend ResolveServiceAsync (SH-187/#131).
// Clear the service (and its vendor, filtered by the service) on a type change.
...(typeChanged
? {
pm: "",
serviceId: null,
extraServices: [],
vendorId: "",
vendorName: "",
techPhone: "",
}
: {}),
});
}}
/>

View file

@ -33,7 +33,8 @@ export function useWorkOrdersBoardSource(filters: FiltersReturn): WorkOrdersBoar
() =>
buildResolvedBoardSearchParams({
advApplied: filters.advApplied,
search: filters.search,
// Advanced Filters are global by design; the week-scoped keyword box has no effect.
search: "",
page: filters.page,
pageSize: filters.pageSize,
sortBy: filters.sortBy,
@ -43,7 +44,6 @@ export function useWorkOrdersBoardSource(filters: FiltersReturn): WorkOrdersBoar
}),
[
filters.advApplied,
filters.search,
filters.page,
filters.pageSize,
filters.sortBy,

View file

@ -8,6 +8,7 @@ import {
} from "@/domain/work-orders/use-cases/use-work-order-detail";
import { useWorkOrderUsers } from "@/domain/work-orders/use-cases/use-work-orders-list";
import { useWorkOrderTableMutations } from "@/domain/work-orders/use-cases/use-work-order-table-mutations";
import { shouldCompleteAfterCompletionDoc } from "@/domain/work-orders/utils/completion-doc-auto-complete";
import {
patchWorkOrderAsCanceled,
patchWorkOrderAsCompleted,
@ -112,7 +113,17 @@ export function useWorkOrdersListPage() {
generatedAt: data.generatedAt,
};
setCompletionDocs((prev) => ({ ...prev, [String(row.id)]: nextData }));
await patchFieldAsync(row.id, { docStatus: status });
const saved = await patchFieldAsync(row.id, { docStatus: status });
if (saved.kind !== "board" || !shouldCompleteAfterCompletionDoc(status, saved.row)) {
return;
}
try {
// Generation is the one automatic completion — no confirmation dialog.
await patchFieldAsync(row.id, { status: "Completed" }, saved.row);
} catch {
// The document is saved; the table mutation already surfaced the status error and
// refetched, so the WO stays in its prior status for a manual retry.
}
};
return {

View file

@ -43,10 +43,12 @@ export default function WorkOrdersListPage() {
actions={
<WorkOrdersListHeader
search={filters.search}
weekLabel={filters.weekLabel}
onSearchChange={filters.handleSearchChange}
onOpenAdvancedFilters={() => filters.setAdvOpen(true)}
onNewWorkOrder={() => page.setWizardOpen(true)}
activeFilterCount={filters.activeFilterCount}
advancedFiltersActive={filters.advApplied != null}
isFetching={tableData.isFetching && !tableData.isLoading}
/>
}

View file

@ -10,6 +10,7 @@ import {
Bell,
BarChart3,
Star,
Users,
} from "lucide-react";
export type NavItemDef = {
@ -58,6 +59,10 @@ export const navGroups: NavGroup[] = [
{ label: "Sites", icon: MapPin, path: "/locations" },
],
},
{
title: "TEAM",
items: [{ label: "Team Members", icon: Users, path: "/team-members" }],
},
// {
// title: "INTERNAL",
// items: [{ label: "Documents", icon: FileText, path: "/documents" }],

View file

@ -0,0 +1,30 @@
import { apiGet } from "@/api/api";
import { API_PATHS } from "@/api/api-paths";
import { handleApiResponse } from "@/api/handle-api-response";
import { mapServices } from "@/domain/services/mappers/service-mapper";
import type { Service } from "@/domain/services/types/service";
import { WORK_ORDER_TYPE_API } from "@/domain/work-orders/types/work-order-board";
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
const TYPE_TO_API: Record<Exclude<WOType, "Overdue">, number> = {
PM: WORK_ORDER_TYPE_API.PM,
Reactive: WORK_ORDER_TYPE_API.Reactive,
Emergency: WORK_ORDER_TYPE_API.Emergency,
};
export const servicesApi = {
getActive: async (): Promise<Service[]> => {
const data = await apiGet<unknown>(API_PATHS.services.list, {
searchParams: { isActive: true },
});
return mapServices(handleApiResponse(data));
},
getActiveForWorkOrderType: async (workOrderType: WOType): Promise<Service[]> => {
if (workOrderType === "Overdue") return [];
const data = await apiGet<unknown>(API_PATHS.services.list, {
searchParams: { isActive: true, workOrderType: TYPE_TO_API[workOrderType] },
});
return mapServices(handleApiResponse(data));
},
};

View file

@ -0,0 +1,71 @@
import type { Service } from "@/domain/services/types/service";
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
function asRecord(raw: unknown): Record<string, unknown> {
return typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>) : {};
}
function readId(item: Record<string, unknown>): string | number {
const value = item.id ?? item.Id;
return typeof value === "string" || typeof value === "number" ? value : "";
}
function readString(item: Record<string, unknown>, ...keys: string[]): string {
for (const key of keys) {
const value = item[key];
if (typeof value === "string") return value.trim();
}
return "";
}
function readBool(item: Record<string, unknown>, ...keys: string[]): boolean {
for (const key of keys) {
const value = item[key];
if (typeof value === "boolean") return value;
}
return false;
}
function mapWorkOrderType(value: unknown): WOType | null {
if (typeof value === "number") {
return value === 2 ? "PM" : value === 3 ? "Emergency" : value === 6 ? "Reactive" : null;
}
if (typeof value === "string") {
const normalized = value.trim().toLowerCase();
return normalized === "pm" || normalized === "preventivemaintenance"
? "PM"
: normalized === "emergency"
? "Emergency"
: normalized === "reactive"
? "Reactive"
: null;
}
return null;
}
export function mapService(raw: unknown): Service {
const item = asRecord(raw);
const types = item.supportedWorkOrderTypes ?? item.SupportedWorkOrderTypes;
return {
id: readId(item),
name: readString(item, "name", "Name"),
trade: readString(item, "trade", "Trade"),
iconKey: readString(item, "iconKey", "IconKey"),
requiresCompletionDocument: readBool(
item,
"requiresCompletionDocument",
"RequiresCompletionDocument",
),
isActive: readBool(item, "isActive", "IsActive"),
supportedWorkOrderTypes: Array.isArray(types)
? types.flatMap((value) => {
const mapped = mapWorkOrderType(value);
return mapped ? [mapped] : [];
})
: [],
};
}
export function mapServices(raw: unknown): Service[] {
return Array.isArray(raw) ? raw.map(mapService).filter((service) => service.id !== "") : [];
}

View file

@ -0,0 +1,11 @@
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
export interface Service {
id: string | number;
name: string;
trade: string;
iconKey: string;
requiresCompletionDocument: boolean;
isActive: boolean;
supportedWorkOrderTypes: WOType[];
}

View file

@ -0,0 +1,25 @@
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
import { servicesApi } from "@/domain/services/api/services-api";
import type { Service } from "@/domain/services/types/service";
import type { WOType } from "@/domain/work-orders/types/work-order-wizard";
import { queryKeys } from "@/infra/query-key/query-key";
export function useServicesForWorkOrderType(
workOrderType: WOType | "",
): UseQueryResult<Service[], Error> {
const effectiveType = workOrderType || "PM";
return useQuery({
queryKey: queryKeys.services.byWorkOrderType(effectiveType),
queryFn: () => servicesApi.getActiveForWorkOrderType(effectiveType),
enabled: effectiveType !== "Overdue",
staleTime: 60 * 1000,
});
}
export function useActiveServices(): UseQueryResult<Service[], Error> {
return useQuery({
queryKey: queryKeys.services.active(),
queryFn: () => servicesApi.getActive(),
staleTime: 60 * 1000,
});
}

View file

@ -0,0 +1,22 @@
import { apiGet, apiPost } from "@/api/api";
import { API_PATHS } from "@/api/api-paths";
import { handleApiResponse } from "@/api/handle-api-response";
import { mapTeamMemberListItems } from "@/domain/team-members/mappers/team-member-mapper";
import type {
CreateTeamMemberInput,
TeamMemberCreated,
TeamMemberListResult,
} from "@/domain/team-members/types/team-member";
export const teamMembersApi = {
getList: async (): Promise<TeamMemberListResult> => {
const data = await apiGet<unknown>(API_PATHS.teamMember.getList);
const items = handleApiResponse<unknown[]>(data);
return { items: mapTeamMemberListItems(Array.isArray(items) ? items : []) };
},
create: async (input: CreateTeamMemberInput): Promise<TeamMemberCreated> => {
const data = await apiPost<unknown>(API_PATHS.teamMember.create, input);
return handleApiResponse<TeamMemberCreated>(data);
},
};

View file

@ -0,0 +1,46 @@
import type { TeamMemberListItem } from "@/domain/team-members/types/team-member";
function readString(record: Record<string, unknown>, ...keys: string[]): string {
for (const key of keys) {
const value = record[key];
if (typeof value === "string") return value;
if (typeof value === "number") return String(value);
}
return "";
}
function readBoolean(record: Record<string, unknown>, ...keys: string[]): boolean {
for (const key of keys) {
const value = record[key];
if (typeof value === "boolean") return value;
if (typeof value === "string") return value.toLowerCase() === "true";
}
return false;
}
export function mapTeamMemberListItem(raw: unknown): TeamMemberListItem {
const record = (typeof raw === "object" && raw !== null ? raw : {}) as Record<string, unknown>;
const id = record.id ?? record.Id;
const status =
readString(record, "status", "Status").toLowerCase() === "inactive" ||
readBoolean(record, "isDeleted", "IsDeleted")
? "Inactive"
: "Active";
return {
id: typeof id === "string" || typeof id === "number" ? id : "",
name: readString(record, "name", "Name"),
role: readString(record, "role", "Role", "roleName", "RoleName"),
serviceArea: readString(record, "serviceArea", "ServiceArea", "locations", "Locations"),
phone: readString(record, "phone", "Phone"),
email: readString(record, "email", "Email"),
color: readString(record, "color", "Color"),
status,
isAccountOwner: readBoolean(record, "isAccountOwner", "IsAccountOwner"),
pendingRegistration: readBoolean(record, "pendingRegistration", "PendingRegistration"),
};
}
export function mapTeamMemberListItems(rawItems: unknown[]): TeamMemberListItem[] {
return rawItems.map(mapTeamMemberListItem);
}

View file

@ -0,0 +1,39 @@
export interface TeamMemberListItem {
id: string | number;
name: string;
role: string;
serviceArea: string;
phone: string;
email: string;
color: string;
status: "Active" | "Inactive";
isAccountOwner: boolean;
pendingRegistration: boolean;
}
export type TeamMemberRole = "Dispatcher" | "Scheduler" | "Admin";
export interface CreateTeamMemberInput {
name: string;
role: TeamMemberRole;
color: string;
email: string;
phone?: string;
serviceAreas: string[];
permissionOverrides: Record<string, 1 | 2>;
}
export interface TeamMemberCreated {
id: string;
name: string;
role: TeamMemberRole;
color: string;
email: string;
phone: string;
serviceAreas: string[];
pendingRegistration: boolean;
}
export interface TeamMemberListResult {
items: TeamMemberListItem[];
}

View file

@ -0,0 +1,27 @@
import { useMutation, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
import { toast } from "react-toastify";
import { teamMembersApi } from "@/domain/team-members/api/team-members-api";
import type {
CreateTeamMemberInput,
TeamMemberCreated,
} from "@/domain/team-members/types/team-member";
import { queryKeys } from "@/infra/query-key/query-key";
export function useCreateTeamMember(): UseMutationResult<
TeamMemberCreated,
Error,
CreateTeamMemberInput
> {
const queryClient = useQueryClient();
return useMutation({
mutationFn: teamMembersApi.create,
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: queryKeys.teamMembers.all });
toast.success("Team member created with pending registration.");
},
onError: (error: Error) => {
toast.error(error.message || "Failed to create team member");
},
});
}

View file

@ -0,0 +1,11 @@
import { useQuery, type UseQueryResult } from "@tanstack/react-query";
import { teamMembersApi } from "@/domain/team-members/api/team-members-api";
import type { TeamMemberListResult } from "@/domain/team-members/types/team-member";
import { queryKeys } from "@/infra/query-key/query-key";
export function useTeamMembersList(): UseQueryResult<TeamMemberListResult, Error> {
return useQuery({
queryKey: queryKeys.teamMembers.list(),
queryFn: teamMembersApi.getList,
});
}

View file

@ -56,6 +56,7 @@ function buildListParams(params: VendorsListParams): Record<string, string | num
pushRepeated(searchParams, "trades", params.trades);
pushRepeated(searchParams, "locations", params.locations);
pushRepeated(searchParams, "jobBuckets", params.jobBuckets);
pushRepeated(searchParams, "areas", params.areas);
return searchParams;
}

View file

@ -2,6 +2,7 @@ import type {
Vendor,
VendorDeactivationImpact,
VendorDirectoryTechnician,
VendorFacetArea,
VendorFacetCompany,
VendorFacetJobBucket,
VendorFacetLocation,
@ -126,6 +127,8 @@ export function mapVendorListItem(raw: unknown): VendorListItem {
tradeSpecialties: readString(item, "tradeSpecialties", "TradeSpecialties"),
isActive: readBool(item, "isActive", "IsActive"),
preferredContact: readPreferredContact(item, "preferredContact", "PreferredContact"),
areaId: readString(item, "areaId", "AreaId"),
areaName: readString(item, "areaName", "AreaName"),
};
const rawTechnicians = item.technicians ?? item.Technicians;
const technicians = Array.isArray(rawTechnicians)
@ -290,6 +293,14 @@ function mapFacetLocation(raw: unknown): VendorFacetLocation {
};
}
function mapFacetArea(raw: unknown): VendorFacetArea {
const item = asRecord(raw);
return {
id: readString(item, "id", "Id"),
name: readString(item, "name", "Name"),
};
}
function mapFacetJobBucket(raw: unknown): VendorFacetJobBucket {
const item = asRecord(raw);
return {
@ -304,6 +315,7 @@ export function mapVendorFacets(raw: unknown): VendorFacets {
const tradesRaw = item.trades ?? item.Trades;
const locationsRaw = item.locations ?? item.Locations;
const jobBucketsRaw = item.jobBuckets ?? item.JobBuckets;
const areasRaw = item.areas ?? item.Areas;
return {
companies: Array.isArray(companiesRaw) ? companiesRaw.map(mapFacetCompany) : [],
@ -315,6 +327,9 @@ export function mapVendorFacets(raw: unknown): VendorFacets {
})
.filter(Boolean)
: [],
areas: Array.isArray(areasRaw)
? areasRaw.map(mapFacetArea).filter((area) => area.id !== "" && area.name !== "")
: [],
locations: Array.isArray(locationsRaw) ? locationsRaw.map(mapFacetLocation) : [],
jobBuckets: Array.isArray(jobBucketsRaw) ? jobBucketsRaw.map(mapFacetJobBucket) : [],
};

View file

@ -92,10 +92,18 @@ export function mapVendorCompanyRoster(raw: unknown): VendorCompanyRoster {
zip: readString(item, "zip", "Zip", "zipCode", "ZipCode"),
googleMapsUrl: readString(item, "googleMapsUrl", "GoogleMapsUrl"),
notes: readString(item, "notes", "Notes"),
areaId: readString(item, "areaId", "AreaId"),
areaName: readString(item, "areaName", "AreaName"),
technicians: mapRosterTechnicians(item.technicians ?? item.Technicians),
};
}
/** Form Area ids are strings; the API takes a positive integer id or null (Unassigned). */
export function toBackendAreaId(value: unknown): number | null {
const parsed = Number(typeof value === "string" ? value.trim() : value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
export function mapRosterTechnicianToBackend(technician: unknown): Record<string, unknown> {
const item = asRecord(technician);
const payload: Record<string, unknown> = {
@ -130,6 +138,11 @@ export function mapVendorRosterToBackend(values: unknown): Record<string, unknow
? techniciansRaw.map(mapRosterTechnicianToBackend)
: [],
};
// The form always round-trips its Area (id or null = Unassigned). Callers
// without an Area value omit it, which the API treats as "leave unchanged".
if ("areaId" in item || "AreaId" in item) {
payload.areaId = toBackendAreaId(item.areaId ?? item.AreaId);
}
const rowVersion = readString(item, "rowVersion", "RowVersion");
if (rowVersion) payload.rowVersion = rowVersion;
return payload;
@ -157,9 +170,12 @@ export function mapVendorRosterAdditivePatchToBackend(
// SH-250: match the reconcile write path, which canonicalizes companyPhone.
// Copying companyFields verbatim let additive patches send a different phone
// shape than PUT for the same user input.
const companyFields = { ...patch.companyFields };
const companyFields: Record<string, unknown> = { ...patch.companyFields };
if (companyFields.companyPhone !== undefined)
companyFields.companyPhone = toCanonicalPhone(companyFields.companyPhone);
// An edited Area is sent as an id or an explicit null (Unassigned).
if (companyFields.areaId !== undefined)
companyFields.areaId = toBackendAreaId(companyFields.areaId);
payload.companyFields = companyFields;
}
return payload;

View file

@ -54,6 +54,8 @@ const baseCompanyFields = {
notes: z
.string()
.max(VENDOR_NOTES_MAX_LENGTH, `Notes must be ${VENDOR_NOTES_MAX_LENGTH} characters or fewer`),
// Optional stable Area id; "" means Unassigned. Admin-only to change.
areaId: z.string(),
technicians: z.array(rosterTechnicianSchema),
};
@ -107,5 +109,6 @@ export const emptyVendorCompanyRosterForm: VendorCompanyRosterFormValues = {
state: "",
zip: "",
notes: "",
areaId: "",
technicians: [],
};

View file

@ -30,6 +30,10 @@ export interface VendorListItem {
tradeSpecialties: string;
isActive: boolean;
preferredContact: VendorPreferredContact;
/** Stable Area id as a string; "" when the company is Unassigned. */
areaId: string;
/** Area display name; "" when the company is Unassigned. */
areaName: string;
/** Present on company-grouped directory responses; optional for legacy clients/fixtures. */
technicians?: VendorDirectoryTechnician[];
}
@ -63,6 +67,8 @@ export interface VendorsListParams {
trades?: string[];
locations?: string[];
jobBuckets?: string[];
/** Stable Area ids or the "__unassigned__" sentinel. */
areas?: string[];
}
export interface VendorsListResult {
@ -95,9 +101,19 @@ export interface VendorFacetJobBucket {
label: string;
}
/** Active Area catalogue option. `id` is the stable areas[n] filter value. */
export interface VendorFacetArea {
id: string;
name: string;
}
/** Wire value that selects companies without an Area. */
export const VENDOR_AREA_UNASSIGNED = "__unassigned__";
export interface VendorFacets {
companies: VendorFacetCompany[];
trades: string[];
areas: VendorFacetArea[];
locations: VendorFacetLocation[];
jobBuckets: VendorFacetJobBucket[];
}
@ -147,6 +163,9 @@ export interface VendorCompanyRoster {
zip: string;
googleMapsUrl: string;
notes: string;
/** Stable Area id as a string; "" when the company is Unassigned. */
areaId: string;
areaName: string;
technicians: VendorRosterTechnician[];
}

View file

@ -38,6 +38,7 @@ const COMPANY_FIELDS = [
"state",
"zip",
"notes",
"areaId",
] as const;
const TECHNICIAN_FIELDS = [

View file

@ -0,0 +1,17 @@
/**
* Help copy for date-column headers on the work orders board table.
* Keyed by the `WO_TABLE_COLS` column key; only columns with copy here show a
* header help icon. `appt` (Appt Time) is an intentional open point — do not
* add it without a business-rule decision.
*/
export const WO_TABLE_HEADER_TOOLTIPS = {
sched: "The date the work is planned to happen. Setting it moves the work order to Scheduled.",
due: "The deadline for the work — when it must be completed by.",
completed: "The date the vendor actually finished the work. Required to complete the work order.",
} as const;
export function getWoTableHeaderTooltip(colKey: string): string | undefined {
return colKey in WO_TABLE_HEADER_TOOLTIPS
? WO_TABLE_HEADER_TOOLTIPS[colKey as keyof typeof WO_TABLE_HEADER_TOOLTIPS]
: undefined;
}

View file

@ -0,0 +1,45 @@
import { isHTTPError, isNetworkError, isTimeoutError } from "ky";
import { mapHttpStatusToMessage } from "@/api/api-error";
import {
DISPATCH_REQUIRED_MESSAGE,
DUPLICATE_WO_NUMBER_MESSAGE,
} from "@/domain/work-orders/errors/board-patch-errors";
export const BOARD_CREATE_FAILED_MESSAGE = "Unable to create the work order. Please try again.";
/** Statuses whose mapped copy is fixed product text, never the response body. */
const FIXED_COPY_STATUSES = new Set([401, 403, 404, 500]);
function readErrorCode(data: unknown): string | undefined {
if (typeof data !== "object" || data === null) {
return undefined;
}
const record = data as Record<string, unknown>;
const code = record.code ?? record.Code;
return typeof code === "string" ? code : undefined;
}
/**
* why: board create returns backend validation text ("siteCode is required.",
* "vendorId is required when setting appointment fields.") that must never reach the
* screen. Unknown failures fall back to generic copy, not to `error.message`.
*/
export function boardCreateErrorMessage(error: unknown): string {
if (isHTTPError(error)) {
const code = readErrorCode(error.data);
if (code === "DispatchRequired") {
return DISPATCH_REQUIRED_MESSAGE;
}
if (code === "DuplicateWoNumber") {
return DUPLICATE_WO_NUMBER_MESSAGE;
}
const status = error.response.status;
return FIXED_COPY_STATUSES.has(status)
? mapHttpStatusToMessage(status)
: BOARD_CREATE_FAILED_MESSAGE;
}
if (isNetworkError(error) || isTimeoutError(error)) {
return error.message;
}
return BOARD_CREATE_FAILED_MESSAGE;
}

View file

@ -1,3 +1,5 @@
import { isNetworkError, isTimeoutError } from "ky";
import { ApiError, mapHttpStatusToMessage } from "@/api/api-error";
import type { WorkOrderTableRow } from "@/domain/work-orders/types/work-order-table-row";
export class BoardPatchConflictError extends Error {
@ -22,10 +24,66 @@ export class BoardPatchValidationError extends Error {
}
}
/** why: backend field names must never be exposed through user-facing board toasts. */
export const DISPATCH_REQUIRED_MESSAGE = "Select a vendor company before saving.";
export const BOARD_PATCH_FAILED_MESSAGE = "Unable to save the work order. Please try again.";
export const NO_PERSISTABLE_FIELDS_MESSAGE =
"These changes cannot be saved on the board. Refresh and edit a supported field.";
export const DUPLICATE_WO_NUMBER_MESSAGE =
"This work order number is already assigned to another work order.";
const KNOWN_VALIDATION_COPY: ReadonlyMap<string, string> = new Map([
["DispatchRequired", DISPATCH_REQUIRED_MESSAGE],
["NoPersistableFields", NO_PERSISTABLE_FIELDS_MESSAGE],
// why: editing a WO number to one that already exists returns 422 DuplicateWoNumber;
// show the same product copy as create, not the generic save-failed fallback.
["DuplicateWoNumber", DUPLICATE_WO_NUMBER_MESSAGE],
]);
/**
* why: board PATCH validation text ("vendorId is required…", object ids, backend codes)
* must never reach the screen. Unknown codes fall back to generic copy, not `error.message`.
*/
export function boardPatchValidationMessage(error: BoardPatchValidationError): string {
if (error.code === "DispatchRequired") {
return "Select a vendor company before saving.";
}
return error.message;
return KNOWN_VALIDATION_COPY.get(error.code) ?? BOARD_PATCH_FAILED_MESSAGE;
}
export const BOARD_PATCH_CONFLICT_MESSAGE =
"This work order was changed by someone else. Refresh to see the latest before saving again.";
export const PARTIAL_SAVE_PREFIX = "Some changes were saved, but the rest were not.";
/** Statuses whose mapped copy is fixed product text, never the response body. */
const FIXED_COPY_STATUSES = new Set([401, 403, 404, 500]);
/** why: any board edit failure toast must use product copy, never backend text or field keys. */
export function boardPatchErrorMessage(error: unknown): string {
if (error instanceof BoardPatchConflictError) {
return BOARD_PATCH_CONFLICT_MESSAGE;
}
if (error instanceof BoardPatchValidationError) {
return boardPatchValidationMessage(error);
}
if (error instanceof ApiError && FIXED_COPY_STATUSES.has(error.status)) {
return mapHttpStatusToMessage(error.status);
}
if (isNetworkError(error) || isTimeoutError(error)) {
return error.message;
}
return BOARD_PATCH_FAILED_MESSAGE;
}
/** Thrown when a multi-field board edit fails after some fields already persisted. */
export class BoardPatchPartialSaveError extends Error {
readonly partialRow: WorkOrderTableRow;
readonly failure: unknown;
constructor(partialRow: WorkOrderTableRow, failure: unknown) {
super(`${PARTIAL_SAVE_PREFIX} ${boardPatchErrorMessage(failure)}`);
this.name = "BoardPatchPartialSaveError";
this.partialRow = partialRow;
this.failure = failure;
}
}

View file

@ -19,6 +19,10 @@ export function assignWizardServicePocFields(
payload.primaryService = primaryService;
}
if (draft.serviceId != null) {
payload.serviceId = draft.serviceId;
}
const serviceNotes = trimOrUndefined(draft.pmNote);
if (serviceNotes) {

View file

@ -400,6 +400,7 @@ export function mapWorkOrderTableRow(raw: unknown): WorkOrderTableRow {
locationId:
typeof locationIdRaw === "string" || typeof locationIdRaw === "number" ? locationIdRaw : "",
pm: readString(item, "pm", "PM", "problem", "Problem", "service", "Service", "trade", "Trade"),
serviceId: readNumber(item, "serviceId", "ServiceId"),
serviceNotes: readString(item, "serviceNotes", "ServiceNotes", "pmNote", "PmNote"),
extraServices: readStringArray(item, "extraServices", "ExtraServices"),
vendorId: vendorIdNum != null ? String(vendorIdNum) : "",

Some files were not shown because too many files have changed in this diff Show more