Files
pn-new-crm/src/lib/validators/interests.ts
Matt 04a594963f feat: round 2 — stage prompts, berth header, EOI inline edit, measurement units
Berth surfaces
- New compact mooring-chip header (colored plate + status pill, dock-label
  in tooltip) replaces the redundant "Berth B1 / Sold / B DOCK" stack
- Berth list gains a "Latest deal stage" column showing the most-advanced
  pipeline stage of any active linked interest (server-aggregated, ranks by
  PIPELINE_STAGES index)
- "Linked prospect" Select on the status-change dialog rebuilt as a Command
  combobox: search, recent-first sort, stage-coloured pills

Pipeline UX
- Reverting an interest to Open with linked berths now prompts: keep the
  links, unlink and reset, or cancel. Silent when no berths are linked
- Activity feed + entity-activity feed normalise enum field values via
  STAGE_LABELS / formatSource: "deposit_10pct → contract_sent" reads as
  "10% Deposit → Contract Sent"

EOI generate dialog
- Inline-editable rows for client name, nationality (country combobox), and
  yacht name — pencil affordance saves directly via clients/yachts PATCH
- Replaces the single "Edit on client's page" link with two contextual links
  framed by short copy explaining what's inline vs what needs the canonical
  page
- Backend EoiContext now includes client.id + yacht.id so the dialog can
  PATCH without an extra round-trip

Company form
- New "Connections" section lets the rep attach members (clients) and yachts
  during create. Yacht attach uses the existing transfer endpoint so audit
  log + ownership history capture the change
- Inline "+ New client" / "+ New yacht" buttons open the canonical forms
  stacked over the company sheet
- After save, the form chains to a yacht pull-in prompt (if any attached
  client owns yachts not yet linked) and an optional "Create interest" step
  pre-filled with the first attached client

Admin
- /admin landing gains a searchable index — typed query flattens groups into
  a result list matching label + description + group title
- "Documenso & EOI" card relabelled to "EOI signing service" (consistent
  with the user-facing language rename from round 1)

Measurement units (migration 0053)
- interests gains desired_*_m columns + desired_*_unit discriminators so
  the rep's literal entry (ft OR m) is preserved verbatim instead of being
  reconstructed from a single canonical column on every render
- yachts + berths gain matching *_unit columns alongside their existing
  ft + m pairs; defaults to 'ft' so legacy rows still render normally
- Interest form POST/PATCH now sends both ft + m + unit; computed m is
  derived from the ft canonical to keep the recommender SQL unchanged

Misc
- Active-deals tile + topbar type their Link href as `Route` instead of `any`
- Unused REPORT_TYPE_LABELS const dropped from generate-report-form
- Test fixtures (fill-eoi-form, documenso-payload, public-berths) updated
  to include the new id + unit fields on the EoiContext / Berth shapes

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 15:28:22 +02:00

257 lines
11 KiB
TypeScript

import { z } from 'zod';
import { baseListQuerySchema } from '@/lib/api/list-query';
import { PIPELINE_STAGES, LEAD_CATEGORIES } from '@/lib/constants';
import {
optionalCountryIsoSchema,
optionalPhoneE164Schema,
optionalSubdivisionIsoSchema,
} from '@/lib/validators/i18n';
// ─── Create ──────────────────────────────────────────────────────────────────
/**
* Desired-dimension input. Strings/numbers are coerced to a positive
* decimal (string-typed for postgres `numeric` column compatibility);
* empty strings collapse to `undefined` so a blank form field doesn't
* round-trip "" → numeric error on the API.
*/
const optionalDesiredDimSchema = z
.union([z.string(), z.number()])
.optional()
.transform((v) => {
if (v === undefined || v === null || v === '') return undefined;
const n = typeof v === 'number' ? v : parseFloat(v);
if (!Number.isFinite(n) || n <= 0) return undefined;
return String(Math.round(n * 100) / 100);
});
const desiredUnitSchema = z.enum(['ft', 'm']).optional();
export const createInterestSchema = z.object({
clientId: z.string().min(1),
yachtId: z.string().optional(),
berthId: z.string().optional(),
pipelineStage: z.enum(PIPELINE_STAGES).default('open'),
leadCategory: z.enum(LEAD_CATEGORIES).optional(),
source: z.string().optional(),
tagIds: z.array(z.string()).optional().default([]),
// Omitting reminderEnabled / reminderDays falls back to the per-port
// defaults configured at /admin/reminders (resolved in
// createInterest). To opt out explicitly pass false / null.
reminderEnabled: z.boolean().optional(),
reminderDays: z.number().int().min(1).optional(),
desiredLengthFt: optionalDesiredDimSchema,
desiredWidthFt: optionalDesiredDimSchema,
desiredDraftFt: optionalDesiredDimSchema,
desiredLengthM: optionalDesiredDimSchema,
desiredWidthM: optionalDesiredDimSchema,
desiredDraftM: optionalDesiredDimSchema,
desiredLengthUnit: desiredUnitSchema,
desiredWidthUnit: desiredUnitSchema,
desiredDraftUnit: desiredUnitSchema,
});
// ─── Update ──────────────────────────────────────────────────────────────────
export const updateInterestSchema = createInterestSchema
.omit({ clientId: true, tagIds: true })
.partial();
// ─── Change Stage ─────────────────────────────────────────────────────────────
export const changeStageSchema = z.object({
pipelineStage: z.enum(PIPELINE_STAGES),
reason: z.string().optional(),
/** Bypass the canTransitionStage transition table. Requires the caller
* to hold the `interests.override_stage` permission. Reason becomes
* required when override=true (recorded in the audit log). */
override: z.boolean().optional(),
/** Optional ISO date (YYYY-MM-DD or full ISO timestamp) to stamp on the
* matching milestone column instead of "now". Used when a rep marks a
* milestone manually (e.g. deposit received yesterday) so the recorded
* date reflects the real event instead of the click time. */
milestoneDate: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}(T.*)?$/)
.optional(),
});
// ─── Outcome (Won / Lost) ─────────────────────────────────────────────────────
export const INTEREST_OUTCOMES = [
'won',
'lost_other_marina',
'lost_unqualified',
'lost_no_response',
'lost_other',
'cancelled',
] as const;
export type InterestOutcome = (typeof INTEREST_OUTCOMES)[number];
export const setOutcomeSchema = z.object({
outcome: z.enum(INTEREST_OUTCOMES),
reason: z.string().max(2000).optional(),
});
export const clearOutcomeSchema = z.object({
// Stage to revert to when reopening (defaults to in_communication).
reopenStage: z.enum(PIPELINE_STAGES).optional(),
});
// ─── List ─────────────────────────────────────────────────────────────────────
export const listInterestsSchema = baseListQuerySchema.extend({
clientId: z.string().optional(),
yachtId: z.string().optional(),
berthId: z.string().optional(),
pipelineStage: z
.string()
.transform((v) => v.split(',').filter(Boolean))
.optional(),
leadCategory: z.enum(LEAD_CATEGORIES).optional(),
eoiStatus: z.string().optional(),
tagIds: z
.string()
.transform((v) => v.split(',').filter(Boolean))
.optional(),
});
// ─── Board (kanban) ───────────────────────────────────────────────────────────
/**
* Filters accepted by GET /api/v1/interests/board. Strict subset of
* listInterestsSchema — `pipelineStage` and `includeArchived` are
* intentionally omitted (the columns ARE the stages, archived deals
* never belong on the board). No pagination params either.
*/
export const boardFiltersSchema = z.object({
search: z.string().optional(),
leadCategory: z.enum(LEAD_CATEGORIES).optional(),
source: z.string().optional(),
eoiStatus: z.string().optional(),
tagIds: z
.string()
.transform((v) => v.split(',').filter(Boolean))
.optional(),
});
export type BoardFiltersInput = z.infer<typeof boardFiltersSchema>;
// ─── Waiting List ─────────────────────────────────────────────────────────────
export const waitingListAddSchema = z.object({
clientId: z.string().min(1),
priority: z.enum(['normal', 'high']).default('normal'),
notifyPref: z.enum(['email', 'in_app', 'both']).default('email'),
notes: z.string().optional(),
});
// ─── Generate Recommendations ─────────────────────────────────────────────────
export const generateRecommendationsSchema = z.object({
interestId: z.string().min(1),
});
// ─── Public Interest ──────────────────────────────────────────────────────────
const addressSchema = z.object({
street: z.string().max(500).optional(),
city: z.string().max(200).optional(),
/** ISO 3166-2 subdivision code (e.g. 'PL-MZ'). */
subdivisionIso: optionalSubdivisionIsoSchema.optional(),
postalCode: z.string().max(50).optional(),
/** ISO-3166-1 alpha-2 country code. */
countryIso: optionalCountryIsoSchema.optional(),
});
// Nested yacht block. Public submissions must now include yacht data because the
// route inserts a yacht row as part of the trio (client + yacht + interest).
const publicYachtSchema = z.object({
name: z.string().min(1).max(200),
hullNumber: z.string().max(100).optional(),
registration: z.string().max(100).optional(),
flag: z.string().max(100).optional(),
yearBuilt: z.coerce.number().int().min(1800).max(2100).optional(),
lengthFt: z.coerce.number().positive().optional(),
widthFt: z.coerce.number().positive().optional(),
draftFt: z.coerce.number().positive().optional(),
});
// Optional company block. If provided, the route upserts a company row (match
// case-insensitively by (portId, name)) and adds an active membership linking
// the submitting client to the company with the chosen role.
const publicCompanySchema = z.object({
name: z.string().min(1).max(200),
legalName: z.string().max(200).optional(),
taxId: z.string().max(100).optional(),
/** ISO-3166-1 alpha-2 country of incorporation. */
incorporationCountryIso: optionalCountryIsoSchema.optional(),
/** ISO 3166-2 state/province of incorporation. */
incorporationSubdivisionIso: optionalSubdivisionIsoSchema.optional(),
role: z
.enum([
'director',
'officer',
'broker',
'representative',
'legal_counsel',
'employee',
'shareholder',
'other',
])
.optional()
.default('representative'),
});
export const publicInterestSchema = z
.object({
// New: first/last split
firstName: z.string().min(1).max(100).optional(),
lastName: z.string().min(1).max(100).optional(),
// Backward compat
fullName: z.string().min(1).max(200).optional(),
email: z.string().email(),
phone: z.string().min(1),
/** Pre-normalized E.164 form, optional for backwards compat. */
phoneE164: optionalPhoneE164Schema.optional(),
/** ISO-3166-1 alpha-2 country the phone was parsed against. */
phoneCountry: optionalCountryIsoSchema.optional(),
/** ISO-3166-1 alpha-2 nationality. */
nationalityIso: optionalCountryIsoSchema.optional(),
preferredContactMethod: z.enum(['email', 'phone', 'sms']).optional(),
mooringNumber: z.string().max(50).optional(),
// NEW: required structured yacht block. Public submissions after the
// data-model refactor MUST include yacht data.
yacht: publicYachtSchema,
// NEW: optional company block - creates/upserts a company and adds a
// membership linking the submitting client to it.
company: publicCompanySchema.optional(),
source: z.literal('website').default('website'),
address: addressSchema.optional(),
})
.refine((data) => data.fullName || (data.firstName && data.lastName), {
message: 'Either fullName or both firstName and lastName are required',
path: ['fullName'],
});
// ─── Reorder Waiting List ─────────────────────────────────────────────────────
export const reorderWaitingListSchema = z.object({
entryId: z.string().min(1),
newPosition: z.coerce.number().int().min(1),
});
// ─── Types ────────────────────────────────────────────────────────────────────
export type CreateInterestInput = z.infer<typeof createInterestSchema>;
export type UpdateInterestInput = z.infer<typeof updateInterestSchema>;
export type ChangeStageInput = z.infer<typeof changeStageSchema>;
export type ListInterestsInput = z.infer<typeof listInterestsSchema>;
export type WaitingListAddInput = z.infer<typeof waitingListAddSchema>;
export type PublicInterestInput = z.infer<typeof publicInterestSchema>;
export type ReorderWaitingListInput = z.infer<typeof reorderWaitingListSchema>;
export type SetOutcomeInput = z.infer<typeof setOutcomeSchema>;
export type ClearOutcomeInput = z.infer<typeof clearOutcomeSchema>;