2026-05-06 18:33:15 +02:00
/ * *
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
* External EOI upload - for EOIs signed outside Documenso ( paper signing ,
2026-05-06 18:33:15 +02:00
* different e - sign vendor , signed in person , etc ) .
*
* Creates BOTH the document row AND the signed - file record in one shot ,
* then advances the interest stage . Distinct from the existing
* uploadSignedManually flow which augments a document row that was
* already created via the Documenso pathway .
* /
2026-05-21 19:34:19 +02:00
import { and , eq , inArray } from 'drizzle-orm' ;
2026-05-06 18:33:15 +02:00
import { db } from '@/lib/db' ;
import { interests } from '@/lib/db/schema/interests' ;
2026-05-21 17:34:59 +02:00
import { documents , documentEvents , documentSigners , files } from '@/lib/db/schema/documents' ;
2026-05-06 18:33:15 +02:00
import { ports } from '@/lib/db/schema/ports' ;
import { env } from '@/lib/env' ;
import { buildStoragePath } from '@/lib/minio' ;
import { getStorageBackend } from '@/lib/storage' ;
import { createAuditLog , type AuditMeta } from '@/lib/audit' ;
feat(audit-session): legacy-stage canonicalization + multi-berth label sweep + PDF/UI polish
Critical data-correctness fixes
- external-eoi.service: stage-advance list rewritten against canonical
7-stage vocab (enquiry/qualified/nurturing → eoi). Was hardcoded to
legacy 9-stage names (open/details_sent/in_communication/eoi_sent), so
EOI uploads from 'qualified' silently skipped the stage flip. Now also
writes eoiDocStatus='signed' alongside eoiStatus='signed'.
- public-interest.service + api/public/interests/route: pipelineStage
'open' → 'enquiry' for new public interests.
- interests.service: legacy 'open' gate → 'enquiry'; inline-stage-picker
comments updated.
- Display fallbacks canonicalized: dashboard.service, dashboard-report-data,
pdf/templates/{interest,client}-summary, interest-picker, timeline route
all route through canonicalizeStage / stageLabelFor.
Multi-berth interest label sweep
- New helper src/lib/templates/interest-berth-label.ts with 9 unit tests
(deriveInterestBerthLabel reuses formatBerthRange + caps at 5 segments,
falls back to 'first + N more').
- New batched aggregator getAllBerthMooringsForInterests on the
interest-berths service.
- BoardInterestRow + listInterests + getInterest extended with
berthMoorings: string[].
- Swept render sites: interest-detail-header, pipeline-card +
pipeline-column (kanban), interest-columns (list), interest-card,
interest-detail (breadcrumb), client-pipeline-summary +
client-interests-tab, yacht-tabs, shared interest-picker.
- PDF report "New interests (in period)" Source column → Berth column.
Dashboard PDF report fixes
- Hardcoded EUR → reads ports.default_currency once at the top of
resolveDashboardReportData. Falls back to USD.
- 'maintenance' berth-status bucket removed everywhere (wasn't in
canonical BERTH_STATUSES); cleaned from dashboard.service,
dashboard-report-data, occupancy-report, berth-status-chart, fixture.
- Berth demand ranking: dropped placeholder Tier column (resolver
hardcoded 'A' — heat-tier never plumbed through).
- Deal pulse distribution: tier values capitalized (hot → Hot etc.).
- Validator widgetIds.max 20 → 40 (catalog has 25 entries; was throwing
"Validation failed" when all sections checked).
- Export dialog: badges tightened (text-[8px] py-px whitespace-nowrap, no
more 2-line wraps on "needs date range"); accepts initialRange?:
DateRange so the dashboard's active range pre-fills dateFrom/dateTo via
rangeToBounds.
Interest banner overcounts fix
- interest-berth-status-banner: filters out self-caused under-offer
berths (where the only active deal touching the berth IS this same
interest). Waits for all competing-queries before committing the
count. Was showing "3 berths unavailable" when only 1 actually had a
competitor.
Sessions list ordering
- sessions-list: client-side sort by lastAt desc + displays lastAt
instead of firstAt so visible timestamp matches the sort key.
Audit log polish
- Details button: side Sheet → Popover anchored to the button (in-place
inline dropdown). Works with the virtualized table.
- From/To date pickers: width w-44 → w-52, wrapper gap-3 → gap-x-4 gap-y-3.
EntityFolderView (Documents Hub entity view)
- Per-row Download button (hover-reveal icon).
- File-type icon prefix + tighter row layout.
- Per-row interest-berth badge: files.ts attaches interestBerthLabel via
one batched getAllBerthMooringsForInterests call across all groups.
AggregatedFile type + EntityFolderView render the badge linking back
to the parent interest.
External EOI upload dialog
- Title input pre-fills from the derived default via controlled
displayTitle = title || defaultTitle (no setState-in-effect).
EOI Generate dialog
- Success toast on mutation success.
- Primary berth's "Include in EOI" checkbox is now forced-on + disabled
with tooltip: the primary IS the canonical "berth for this deal",
excluding it is semantically nonsense.
Primary berth must always be in EOI bundle (service + backfill)
- interest-berths.service: insert path forces is_in_eoi_bundle=true
whenever is_primary=true; update path coerces back to true when the
caller tries to set false on a primary. Backfilled 7 existing rows.
Documenso redirect URL fallback
- port-config getPortDocumensoConfig: resolution chain extended to
documenso_redirect_url → public_site_url → null. Operators with
public_site_url configured (most ports) now get sensible signer
landing without setting two settings.
World-map click → navigate
- website-analytics-shell: country click navigates to the nationality-
filtered Clients page via router.push instead of copying a URL to
clipboard.
Documents Hub: subfolder grid in main panel
- Subfolder cards rendered above the documents list when the current
folder has children. Lets reps drill into subfolders from the main
content area, not only via the sidebar tree.
Interest list initial sort
- usePaginatedQuery gains initialSort option (used when URL has no sort
param). Interest list passes updatedAt desc so the table header
surfaces the active sort visibly + most-recently-added/edited bubble
to the top.
Interest auto-assign on create
- interests.service createInterest: three-tier owner resolution chain
— explicit input → port's default_new_interest_owner setting →
creator (when not super-admin). Super-admins skipped since they often
create on behalf of other reps.
Backfills
- 12 interests with eoi_status='signed' + missing eoi_doc_status='signed'
aligned.
- 7 interest_berths rows with is_primary=true but is_in_eoi_bundle=false
flipped to true.
Verified
- pnpm tsc --noEmit: clean
- pnpm exec vitest run: 1463 / 1463 passed
Captured 25+ additional UAT findings to docs/superpowers/audits/alpha-uat-master.md
across all 4 buckets, including two OPEN QUESTIONS (Reservations module
re-imagine, Reports dedicated page promotion).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 20:41:27 +02:00
import { canonicalizeStage , type PipelineStage } from '@/lib/constants' ;
2026-05-21 19:34:19 +02:00
import { CodedError , ConflictError , NotFoundError , ValidationError } from '@/lib/errors' ;
2026-05-06 18:33:15 +02:00
import { emitToRoom } from '@/lib/socket/server' ;
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
import type { ExternalSignedDocType } from '@/lib/services/external-signing.service' ;
/ * *
* Per - doc - type config for an externally - signed * upload * ( file present ) .
* Mirrors external - signing . service ' s no - file status / rule maps and adds the
* storage / document - type / stage - advance details the file path needs , so the
* one upload service correctly files an EOI , a reservation agreement , OR a
* contract instead of always filing as an EOI .
* /
const UPLOAD_CONFIG : Record <
ExternalSignedDocType ,
{
documentType : 'eoi' | 'reservation_agreement' | 'contract' ;
fileCategory : 'eoi' | 'contract' ;
storagePrefix : 'eoi-signed' | 'reservation-signed' | 'contract-signed' ;
docStatusCol : 'eoiDocStatus' | 'reservationDocStatus' | 'contractDocStatus' ;
dateCol : 'dateEoiSigned' | 'dateReservationSigned' | 'dateContractSigned' ;
targetStage : PipelineStage ;
advanceFrom : PipelineStage [ ] ;
rule : 'eoi_signed' | 'contract_signed' | null ;
label : string ;
}
> = {
eoi : {
documentType : 'eoi' ,
fileCategory : 'eoi' ,
storagePrefix : 'eoi-signed' ,
docStatusCol : 'eoiDocStatus' ,
dateCol : 'dateEoiSigned' ,
targetStage : 'eoi' ,
advanceFrom : [ 'enquiry' , 'qualified' , 'nurturing' ] ,
rule : 'eoi_signed' ,
label : 'EOI' ,
} ,
reservation : {
documentType : 'reservation_agreement' ,
fileCategory : 'contract' ,
storagePrefix : 'reservation-signed' ,
docStatusCol : 'reservationDocStatus' ,
dateCol : 'dateReservationSigned' ,
targetStage : 'reservation' ,
advanceFrom : [ 'enquiry' , 'qualified' , 'nurturing' , 'eoi' ] ,
rule : null ,
label : 'reservation agreement' ,
} ,
contract : {
documentType : 'contract' ,
fileCategory : 'contract' ,
storagePrefix : 'contract-signed' ,
docStatusCol : 'contractDocStatus' ,
dateCol : 'dateContractSigned' ,
targetStage : 'contract' ,
advanceFrom : [ 'enquiry' , 'qualified' , 'nurturing' , 'eoi' , 'reservation' , 'deposit_paid' ] ,
rule : 'contract_signed' ,
label : 'contract' ,
} ,
} ;
2026-05-06 18:33:15 +02:00
2026-05-21 17:34:59 +02:00
/** A single signatory on an externally-signed document. */
export interface ExternalSignatory {
name : string ;
email : string ;
/ * * D r i v e s a u t o - f i l l o n t h e d i a l o g + d o w n s t r e a m " E m a i l c o p y " r e c i p i e n t
* list . ` cc ` recipients aren ' t signers but show up on send - out lists . * /
role : 'client' | 'developer' | 'rep' | 'witness' | 'cc' ;
}
2026-05-06 18:33:15 +02:00
export interface ExternalEoiInput {
interestId : string ;
portId : string ;
/** PDF bytes. */
fileData : { buffer : Buffer ; originalName : string ; mimeType : string ; size : number } ;
/** Free-text title for the document row. Defaults to "External EOI - <date>". */
title? : string ;
/** When the signing actually happened (the date on the paper / contract). */
signedAt? : Date ;
2026-05-21 17:34:59 +02:00
/ * *
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
* Structured signatory list - preferred over the legacy ` signerNames `
2026-05-21 17:34:59 +02:00
* CSV . When present , the service inserts one ` document_signers ` row
* per non - CC entry pre - stamped ` status='signed' ` so the
* "X / Y signed" badge renders correctly downstream .
* /
signatories? : ExternalSignatory [ ] ;
/** Legacy CSV form kept for backwards compat with older callers. */
2026-05-06 18:33:15 +02:00
signerNames? : string [ ] ;
/** Free-text note (e.g. "signed in person at boat show"). */
notes? : string ;
2026-05-25 13:15:22 +02:00
/ * *
* Optional : id of an active generated EOI to cancel as part of this
* upload . When set , the service voids the Documenso envelope and flips
* the prior local row to ` status='cancelled' ` BEFORE creating the new
* external - EOI doc so a deal carries one canonical EOI at any moment .
* Idempotent — already - cancelled / wrong - port ids are ignored .
* /
cancelActiveDocumentId? : string ;
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
/ * * W h i c h s i g n e d d o c u m e n t t h i s u p l o a d r e p r e s e n t s . D e f a u l t s t o ' e o i ' f o r
* backward compatibility ; reservation / contract tabs pass their own type so
* the file is filed + the interest advanced under the correct kind . * /
docType? : ExternalSignedDocType ;
2026-05-06 18:33:15 +02:00
meta : AuditMeta ;
}
export async function uploadExternallySignedEoi ( input : ExternalEoiInput ) {
const { interestId , portId , fileData , meta } = input ;
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
const docType : ExternalSignedDocType = input . docType ? ? 'eoi' ;
const cfg = UPLOAD_CONFIG [ docType ] ;
2026-05-06 18:33:15 +02:00
if ( fileData . size <= 0 ) throw new ValidationError ( 'Empty file' ) ;
if ( fileData . size > 25 * 1024 * 1024 ) {
throw new ValidationError ( 'File too large (max 25 MB)' ) ;
}
if (
fileData . mimeType !== 'application/pdf' &&
! fileData . originalName . toLowerCase ( ) . endsWith ( '.pdf' )
) {
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
throw new ValidationError ( ` Only PDF uploads are accepted for signed ${ cfg . label } s ` ) ;
2026-05-06 18:33:15 +02:00
}
const interest = await db . query . interests . findFirst ( {
where : eq ( interests . id , interestId ) ,
} ) ;
if ( ! interest || interest . portId !== portId ) throw new NotFoundError ( 'Interest' ) ;
const port = await db . query . ports . findFirst ( { where : eq ( ports . id , portId ) } ) ;
if ( ! port ) throw new NotFoundError ( 'Port' ) ;
2026-05-25 13:15:22 +02:00
// Replace-mode: cancel the prior active EOI before creating the new one.
// Done OUTSIDE the upload transaction so a Documenso void error doesn't
// block the upload the rep has already photographed/scanned. cancelDocument
// is idempotent on status='cancelled' so concurrent calls are safe.
let cancelledDocumentId : string | null = null ;
if ( input . cancelActiveDocumentId ) {
try {
const { cancelDocument } = await import ( '@/lib/services/documents.service' ) ;
await cancelDocument ( input . cancelActiveDocumentId , portId , meta , {
reason : 'Replaced by external upload' ,
cancelMode : 'delete' ,
} ) ;
cancelledDocumentId = input . cancelActiveDocumentId ;
} catch {
// Swallow — the rep meant to replace, but failing to cancel the prior
// doc shouldn't lose the upload. The audit log on the new doc still
// captures the rep's intent via metadata.replacedDocumentId.
}
}
2026-05-06 18:33:15 +02:00
const documentId = crypto . randomUUID ( ) ;
const fileId = crypto . randomUUID ( ) ;
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
const storagePath = buildStoragePath ( port . slug , cfg . storagePrefix , documentId , fileId , 'pdf' ) ;
2026-05-06 18:33:15 +02:00
2026-05-06 22:11:00 +02:00
// Upload to storage FIRST so we have a stable key for the DB rows,
// then commit all four DB writes in one transaction. If the tx fails
// the storage object becomes orphaned (S3 isn't transactional) but
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
// the DB stays clean - orphan reaper handles those.
2026-05-06 18:33:15 +02:00
await (
await getStorageBackend ( )
) . put ( storagePath , fileData . buffer , {
contentType : 'application/pdf' ,
sizeBytes : fileData.size ,
} ) ;
const title =
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
input . title ? ?
` External ${ cfg . label } - ${ ( input . signedAt ? ? new Date ( ) ) . toISOString ( ) . slice ( 0 , 10 ) } ` ;
2026-05-06 18:33:15 +02:00
2026-05-06 22:11:00 +02:00
const result = await db . transaction ( async ( tx ) = > {
const [ fileRecord ] = await tx
. insert ( files )
. values ( {
portId ,
clientId : interest.clientId ,
filename : fileData.originalName ,
originalName : fileData.originalName ,
mimeType : 'application/pdf' ,
sizeBytes : String ( fileData . size ) ,
storagePath ,
storageBucket : env.MINIO_BUCKET ,
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
category : cfg.fileCategory ,
2026-05-06 22:11:00 +02:00
uploadedBy : meta.userId ,
} )
. returning ( ) ;
if ( ! fileRecord ) {
throw new CodedError ( 'INSERT_RETURNING_EMPTY' , {
internalMessage : 'External EOI file insert returned no row' ,
} ) ;
}
const [ doc ] = await tx
. insert ( documents )
. values ( {
id : documentId ,
portId ,
interestId ,
clientId : interest.clientId ,
yachtId : interest.yachtId ,
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
documentType : cfg.documentType ,
2026-05-06 22:11:00 +02:00
title ,
status : 'completed' ,
isManualUpload : true ,
signedFileId : fileRecord.id ,
notes : input.notes ? ? null ,
createdBy : meta.userId ,
} )
. returning ( ) ;
if ( ! doc ) {
throw new CodedError ( 'INSERT_RETURNING_EMPTY' , {
internalMessage : 'External EOI document insert returned no row' ,
} ) ;
}
2026-05-21 17:34:59 +02:00
// Backfill document_signers rows for the structured signatory list
// so the document-detail "X / Y signed" badge counts correctly. CC
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
// recipients aren't signatories - they're recipients of the email
2026-05-21 17:34:59 +02:00
// copy and don't show up in the signed-count denominator.
const signedAtMoment = input . signedAt ? ? new Date ( ) ;
const signerRows = ( input . signatories ? ? [ ] )
. filter ( ( s ) = > s . role !== 'cc' )
. map ( ( s , i ) = > ( {
documentId : doc.id ,
signerName : s.name ,
signerEmail : s.email ,
signerRole : s.role ,
signingOrder : i + 1 ,
status : 'signed' as const ,
signedAt : signedAtMoment ,
} ) ) ;
if ( signerRows . length > 0 ) {
await tx . insert ( documentSigners ) . values ( signerRows ) ;
}
2026-05-06 22:11:00 +02:00
await tx . insert ( documentEvents ) . values ( {
documentId : doc.id ,
eventType : 'completed' ,
eventData : {
isManualUpload : true ,
external : true ,
2026-05-21 17:34:59 +02:00
signerNames : input.signerNames ? ? ( input . signatories ? ? [ ] ) . map ( ( s ) = > s . name ) ,
signatories : input.signatories ? ? null ,
signedAt : signedAtMoment.toISOString ( ) ,
2026-05-06 22:11:00 +02:00
fileId : fileRecord.id ,
} ,
2026-05-06 18:33:15 +02:00
} ) ;
2026-05-21 17:01:35 +02:00
// Two concerns to keep separate:
feat(audit-session): legacy-stage canonicalization + multi-berth label sweep + PDF/UI polish
Critical data-correctness fixes
- external-eoi.service: stage-advance list rewritten against canonical
7-stage vocab (enquiry/qualified/nurturing → eoi). Was hardcoded to
legacy 9-stage names (open/details_sent/in_communication/eoi_sent), so
EOI uploads from 'qualified' silently skipped the stage flip. Now also
writes eoiDocStatus='signed' alongside eoiStatus='signed'.
- public-interest.service + api/public/interests/route: pipelineStage
'open' → 'enquiry' for new public interests.
- interests.service: legacy 'open' gate → 'enquiry'; inline-stage-picker
comments updated.
- Display fallbacks canonicalized: dashboard.service, dashboard-report-data,
pdf/templates/{interest,client}-summary, interest-picker, timeline route
all route through canonicalizeStage / stageLabelFor.
Multi-berth interest label sweep
- New helper src/lib/templates/interest-berth-label.ts with 9 unit tests
(deriveInterestBerthLabel reuses formatBerthRange + caps at 5 segments,
falls back to 'first + N more').
- New batched aggregator getAllBerthMooringsForInterests on the
interest-berths service.
- BoardInterestRow + listInterests + getInterest extended with
berthMoorings: string[].
- Swept render sites: interest-detail-header, pipeline-card +
pipeline-column (kanban), interest-columns (list), interest-card,
interest-detail (breadcrumb), client-pipeline-summary +
client-interests-tab, yacht-tabs, shared interest-picker.
- PDF report "New interests (in period)" Source column → Berth column.
Dashboard PDF report fixes
- Hardcoded EUR → reads ports.default_currency once at the top of
resolveDashboardReportData. Falls back to USD.
- 'maintenance' berth-status bucket removed everywhere (wasn't in
canonical BERTH_STATUSES); cleaned from dashboard.service,
dashboard-report-data, occupancy-report, berth-status-chart, fixture.
- Berth demand ranking: dropped placeholder Tier column (resolver
hardcoded 'A' — heat-tier never plumbed through).
- Deal pulse distribution: tier values capitalized (hot → Hot etc.).
- Validator widgetIds.max 20 → 40 (catalog has 25 entries; was throwing
"Validation failed" when all sections checked).
- Export dialog: badges tightened (text-[8px] py-px whitespace-nowrap, no
more 2-line wraps on "needs date range"); accepts initialRange?:
DateRange so the dashboard's active range pre-fills dateFrom/dateTo via
rangeToBounds.
Interest banner overcounts fix
- interest-berth-status-banner: filters out self-caused under-offer
berths (where the only active deal touching the berth IS this same
interest). Waits for all competing-queries before committing the
count. Was showing "3 berths unavailable" when only 1 actually had a
competitor.
Sessions list ordering
- sessions-list: client-side sort by lastAt desc + displays lastAt
instead of firstAt so visible timestamp matches the sort key.
Audit log polish
- Details button: side Sheet → Popover anchored to the button (in-place
inline dropdown). Works with the virtualized table.
- From/To date pickers: width w-44 → w-52, wrapper gap-3 → gap-x-4 gap-y-3.
EntityFolderView (Documents Hub entity view)
- Per-row Download button (hover-reveal icon).
- File-type icon prefix + tighter row layout.
- Per-row interest-berth badge: files.ts attaches interestBerthLabel via
one batched getAllBerthMooringsForInterests call across all groups.
AggregatedFile type + EntityFolderView render the badge linking back
to the parent interest.
External EOI upload dialog
- Title input pre-fills from the derived default via controlled
displayTitle = title || defaultTitle (no setState-in-effect).
EOI Generate dialog
- Success toast on mutation success.
- Primary berth's "Include in EOI" checkbox is now forced-on + disabled
with tooltip: the primary IS the canonical "berth for this deal",
excluding it is semantically nonsense.
Primary berth must always be in EOI bundle (service + backfill)
- interest-berths.service: insert path forces is_in_eoi_bundle=true
whenever is_primary=true; update path coerces back to true when the
caller tries to set false on a primary. Backfilled 7 existing rows.
Documenso redirect URL fallback
- port-config getPortDocumensoConfig: resolution chain extended to
documenso_redirect_url → public_site_url → null. Operators with
public_site_url configured (most ports) now get sensible signer
landing without setting two settings.
World-map click → navigate
- website-analytics-shell: country click navigates to the nationality-
filtered Clients page via router.push instead of copying a URL to
clipboard.
Documents Hub: subfolder grid in main panel
- Subfolder cards rendered above the documents list when the current
folder has children. Lets reps drill into subfolders from the main
content area, not only via the sidebar tree.
Interest list initial sort
- usePaginatedQuery gains initialSort option (used when URL has no sort
param). Interest list passes updatedAt desc so the table header
surfaces the active sort visibly + most-recently-added/edited bubble
to the top.
Interest auto-assign on create
- interests.service createInterest: three-tier owner resolution chain
— explicit input → port's default_new_interest_owner setting →
creator (when not super-admin). Super-admins skipped since they often
create on behalf of other reps.
Backfills
- 12 interests with eoi_status='signed' + missing eoi_doc_status='signed'
aligned.
- 7 interest_berths rows with is_primary=true but is_in_eoi_bundle=false
flipped to true.
Verified
- pnpm tsc --noEmit: clean
- pnpm exec vitest run: 1463 / 1463 passed
Captured 25+ additional UAT findings to docs/superpowers/audits/alpha-uat-master.md
across all 4 buckets, including two OPEN QUESTIONS (Reservations module
re-imagine, Reports dedicated page promotion).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 20:41:27 +02:00
// 1. Document metadata - always write dateEoiSigned, eoiStatus, and
// eoiDocStatus from the upload. Even if the rep already advanced
// the stage manually, the paper signing event needs a recorded
// date + doc-status badge so downstream surfaces (SkipAheadBanner,
// milestone strip, EOI merge fields, signing-progress chip) reflect
// reality. Honour an existing dateEoiSigned - covers the case where
// the rep is uploading evidence for an event whose date was already
// backfilled.
// 2. Stage advance - in the 7-stage pipeline (PIPELINE_STAGES), every
// pre-EOI stage (enquiry / qualified / nurturing) should flip to
// 'eoi' on signing. The doc-status 'signed' carries the within-stage
// sub-state. Bypasses canTransitionStage because the operator just
// brought concrete proof. Idempotent at the 'eoi' / 'reservation' /
// 'deposit_paid' / 'contract' stages (stays put).
const stageBeforeAdvance = interest . pipelineStage as PipelineStage | null | undefined ;
const canonicalStage = canonicalizeStage ( stageBeforeAdvance ) ;
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
const shouldAdvanceStage = cfg . advanceFrom . includes ( canonicalStage ) ;
2026-05-21 17:01:35 +02:00
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
const existingDate = ( interest [ cfg . dateCol ] as Date | null ) ? ? null ;
const interestPatch = {
[ cfg . dateCol ] : existingDate ? ? input . signedAt ? ? new Date ( ) ,
[ cfg . docStatusCol ] : 'signed' ,
// EOI carries a dedicated `eoi_status` lifecycle column; reservation /
// contract have only the `*_doc_status` sub-state (mirrors markExternallySigned).
. . . ( docType === 'eoi' ? { eoiStatus : 'signed' as const } : { } ) ,
. . . ( shouldAdvanceStage ? { pipelineStage : cfg.targetStage } : { } ) ,
updatedAt : new Date ( ) ,
} as Partial < typeof interests. $ inferInsert > ;
await tx . update ( interests ) . set ( interestPatch ) . where ( eq ( interests . id , interestId ) ) ;
2026-05-06 22:11:00 +02:00
2026-05-21 17:01:35 +02:00
return {
documentId : doc.id ,
fileId : fileRecord.id ,
stageChanged : shouldAdvanceStage ,
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
newStage : shouldAdvanceStage ? cfg.targetStage : canonicalStage ,
2026-05-21 17:01:35 +02:00
} ;
2026-05-06 18:33:15 +02:00
} ) ;
2026-05-21 17:01:35 +02:00
const { documentId : docId , fileId : fId , stageChanged , newStage } = result ;
2026-05-06 18:33:15 +02:00
void createAuditLog ( {
portId ,
userId : meta.userId ,
action : 'create' ,
entityType : 'document' ,
2026-05-06 22:11:00 +02:00
entityId : docId ,
2026-05-06 18:33:15 +02:00
metadata : {
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
kind : ` external_ ${ docType } _upload ` ,
docType ,
2026-05-06 18:33:15 +02:00
interestId ,
title ,
signerNames : input.signerNames ? ? [ ] ,
signedAt : ( input . signedAt ? ? new Date ( ) ) . toISOString ( ) ,
fileSizeBytes : fileData.size ,
2026-05-25 13:15:22 +02:00
. . . ( cancelledDocumentId ? { replacedDocumentId : cancelledDocumentId } : { } ) ,
2026-05-06 18:33:15 +02:00
} ,
ipAddress : meta.ipAddress ,
userAgent : meta.userAgent ,
} ) ;
2026-05-06 22:11:00 +02:00
emitToRoom ( ` port: ${ portId } ` , 'document:completed' , { documentId : docId } ) ;
2026-05-06 18:33:15 +02:00
2026-05-21 17:01:35 +02:00
// Berth rules engine: a manually-uploaded external EOI is still an
// EOI-signed event for the rules that watch this trigger (e.g.
// auto-mark the primary berth Under Offer). Fire via dynamic import
// to dodge the circular dep between berth-rules-engine and the
// interest services.
try {
fix(signing): route paper-signed reservation/contract uploads to the right doc type
The Reservation and Contract tabs reused ExternalEoiUploadDialog, but the
service hard-coded the EOI document type, status columns, stage target, and
berth rule. A signed contract uploaded from the Contract tab filed as an
`eoi`, flipped `eoi_status`, and advanced the stage to `eoi` - wrong doc
kind, wrong sub-state, wrong stage.
- external-eoi.service: UPLOAD_CONFIG keyed off docType (eoi | reservation
| contract) parameterises documentType, file category, storage prefix,
doc-status column, signed-date column, target stage, advance-from set,
and berth rule. eoi_status is written only for docType=eoi.
- route: parse docType from the form (default eoi).
- dialog: docType prop; generalised copy; EOI-only UI (active-EOI replace
banner, public-map flip, cancelActiveDocumentId) gated to docType=eoi.
- reservation/contract tabs: pass docType; drop the coming-soon comments.
- test: docType routing cases (reservation -> reservation_agreement +
reservation cols; contract -> contract + contract cols; eoi_status stays
null on both; contract idempotent at/past contract stage).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 21:28:04 +02:00
if ( cfg . rule ) {
const { evaluateRule } = await import ( '@/lib/services/berth-rules-engine' ) ;
await evaluateRule ( cfg . rule , interestId , portId , meta ) ;
}
2026-05-21 17:01:35 +02:00
} catch {
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
// Swallow - rules engine failures should never block the upload
2026-05-21 17:01:35 +02:00
// that the rep has already completed end-to-end. The orphan-reaper
// path doesn't apply; a missed rule evaluation is a soft failure.
}
2026-05-25 13:15:22 +02:00
return { documentId : docId , fileId : fId , stageChanged , newStage , cancelledDocumentId } ;
2026-05-06 18:33:15 +02:00
}
2026-05-21 19:34:19 +02:00
// ─── Edit metadata on a previously-uploaded external EOI ─────────────────────
/** Signatory row in an edit payload. `id` distinguishes update vs insert. */
export interface ExternalEoiSignatoryEdit {
/** Present on existing rows; omitted to insert a new signer. */
id? : string ;
name : string ;
email : string ;
role : 'client' | 'developer' | 'rep' | 'witness' | 'cc' ;
}
export interface ExternalEoiMetadataPatch {
documentId : string ;
portId : string ;
/** Undefined = leave unchanged; null is not allowed (title is NOT NULL). */
title? : string ;
/** Undefined = leave unchanged; null clears `interests.dateEoiSigned`. */
signedAt? : Date | null ;
/** Undefined = leave unchanged; '' clears the column. */
notes? : string ;
/ * *
* Full replacement set when present . Rows with an id are UPDATEd ; rows
* without are INSERTed ; existing rows whose id isn ' t in the array are
* DELETEd . CC entries are stored but excluded from the X / Y signed
* count ( status stays signed = signedAt to match the upload - time
* pre - stamp ) .
* /
signatories? : ExternalEoiSignatoryEdit [ ] ;
meta : AuditMeta ;
}
/ * *
* Update title / notes / signed - date / signatories on a previously - uploaded
* external EOI . Refuses to touch Documenso - managed documents because their
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
* signer rows are the vendor ' s source of truth - any edit would drift from
2026-05-21 19:34:19 +02:00
* the upstream envelope .
*
* Mirrors the upload service ' s invariants :
* - ` signedAt ` updates BOTH ` documents ` events and ` interests.dateEoiSigned `
* ( and the per - signer ` signedAt ` stamp for the structured signatories ) .
* - Document_signers writes are full - replacement when ` signatories ` is
* present ( insert / update / delete by id - presence ) . Same shape as the
* upload - time insert : CC entries persisted but not counted as signers .
*
chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:
- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
redirects (ocr to ai, reports to dashboard, invitations to users),
docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
let-reassign), set-state-in-effect disables in CountryFlag and
UploadForSigning preview-bytes effect, unused 'confirm' destructures in
interest contract + reservation tabs, unescaped apostrophe in test-template
card copy
2026-05-23 00:52:59 +02:00
* Stage advance is NOT re - evaluated - that fires once at upload and shouldn ' t
2026-05-21 19:34:19 +02:00
* be reversed by a metadata edit . If the rep needs to roll a stage back ,
* they do it through the stage - change UI directly .
* /
export async function updateExternalEoiMetadata ( input : ExternalEoiMetadataPatch ) {
const { documentId , portId , meta } = input ;
const document = await db . query . documents . findFirst ( {
where : and ( eq ( documents . id , documentId ) , eq ( documents . portId , portId ) ) ,
} ) ;
if ( ! document ) throw new NotFoundError ( 'Document' ) ;
if ( ! document . isManualUpload ) {
throw new ConflictError (
'Only manually-uploaded documents can have their metadata edited. Documenso-managed documents inherit their signers and signing date from the upstream envelope.' ,
) ;
}
if ( document . documentType !== 'eoi' ) {
// The form only knows EOI shape today; widen later when other doc
// types grow their own external-upload pathways.
throw new ConflictError (
'Metadata edit is currently supported only for EOI documents. Open a ticket if you need it for contracts or reservations.' ,
) ;
}
// Capture before-state for the audit log.
const beforeSigners = await db . query . documentSigners . findMany ( {
where : eq ( documentSigners . documentId , documentId ) ,
} ) ;
const result = await db . transaction ( async ( tx ) = > {
// 1) Patch the document row itself.
const docPatch : Partial < typeof documents. $ inferInsert > = { updatedAt : new Date ( ) } ;
if ( input . title !== undefined ) docPatch . title = input . title ;
if ( input . notes !== undefined ) docPatch . notes = input . notes === '' ? null : input . notes ;
await tx . update ( documents ) . set ( docPatch ) . where ( eq ( documents . id , documentId ) ) ;
// 2) Sync the interest's `dateEoiSigned` when signedAt is being
// edited. Honour the upload-side rule: a metadata edit IS the
// canonical source for the date, so we overwrite even when the
// column already has a value (the rep is presumably fixing it).
if ( input . signedAt !== undefined && document . interestId ) {
await tx
. update ( interests )
. set ( {
dateEoiSigned : input.signedAt ,
updatedAt : new Date ( ) ,
} )
. where ( eq ( interests . id , document . interestId ) ) ;
}
// 3) Replace the signatories list when provided. Mirror the upload
// invariants: status='signed' on every non-CC row (the doc has
// already been signed externally), signedAt stamped from the
// edit's effective signing date.
if ( input . signatories !== undefined ) {
const signedAtMoment =
input . signedAt !== undefined
? ( input . signedAt ? ? new Date ( ) )
: ( beforeSigners [ 0 ] ? . signedAt ? ? new Date ( ) ) ;
const submittedIds = new Set ( input . signatories . filter ( ( s ) = > s . id ) . map ( ( s ) = > s . id ! ) ) ;
const existingIds = beforeSigners . map ( ( s ) = > s . id ) ;
const toDelete = existingIds . filter ( ( id ) = > ! submittedIds . has ( id ) ) ;
if ( toDelete . length > 0 ) {
await tx . delete ( documentSigners ) . where ( inArray ( documentSigners . id , toDelete ) ) ;
}
for ( let i = 0 ; i < input . signatories . length ; i ++ ) {
const s = input . signatories [ i ] ! ;
const isSigner = s . role !== 'cc' ;
if ( s . id && existingIds . includes ( s . id ) ) {
await tx
. update ( documentSigners )
. set ( {
signerName : s.name ,
signerEmail : s.email ,
signerRole : s.role ,
signingOrder : i + 1 ,
status : isSigner ? 'signed' : 'pending' ,
signedAt : isSigner ? signedAtMoment : null ,
} )
. where ( eq ( documentSigners . id , s . id ) ) ;
} else {
await tx . insert ( documentSigners ) . values ( {
documentId ,
signerName : s.name ,
signerEmail : s.email ,
signerRole : s.role ,
signingOrder : i + 1 ,
status : isSigner ? 'signed' : 'pending' ,
signedAt : isSigner ? signedAtMoment : null ,
} ) ;
}
}
}
// 4) Trail in document_events so the activity timeline reflects the
// edit alongside the original 'completed' row.
await tx . insert ( documentEvents ) . values ( {
documentId ,
eventType : 'metadata_updated' ,
eventData : {
editedBy : meta.userId ,
fields : {
title : input.title !== undefined ,
signedAt : input.signedAt !== undefined ,
notes : input.notes !== undefined ,
signatories : input.signatories !== undefined ,
} ,
} ,
} ) ;
return { documentId } ;
} ) ;
void createAuditLog ( {
portId ,
userId : meta.userId ,
action : 'update' ,
entityType : 'document' ,
entityId : documentId ,
metadata : {
kind : 'external_eoi_metadata_edit' ,
fieldsChanged : {
title : input.title !== undefined ,
signedAt : input.signedAt !== undefined ,
notes : input.notes !== undefined ,
signatories : input.signatories !== undefined ,
} ,
} ,
ipAddress : meta.ipAddress ,
userAgent : meta.userAgent ,
} ) ;
emitToRoom ( ` port: ${ portId } ` , 'document:updated' , { documentId : result.documentId } ) ;
return { documentId : result.documentId } ;
}