Просмотр исходного кода

Respect explicitly empty invoice number format (#215)

* Respect explicitly empty invoice number format

Clearing the Invoice Number Format field in Settings saved an empty
string, but every consumer fell back through || '{year}-', so the
empty value was treated as unset and the UI reverted on reload.
Switch all invoice prefix reads to ?? so the default only applies
when the setting has never been saved.

Fixes the format-revert issue reported in discussion #55.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Cancel pending autosave when deleting a service record

Editing a work order arms a 5s debounced autosave. Deleting the record
inside that window let the timer fire updateServiceRecord against the
already-deleted record, logging 'Service record not found'. Clear the
timer and block saves before deleting; unblock if the delete fails.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Return empty list from getStatusReportsForService for missing records

Deleting a work order revalidates the current route, which re-renders
the deleted record's page server-side. The page handles the missing
record gracefully, but its parallel getStatusReportsForService fetch
threw 'Service record not found' and logged an error on every delete.
Return an empty list instead, matching getServiceFindings; the reports
query is org-scoped either way.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Bernt Christian Egeland 3 месяцев назад
Родитель
Сommit
14ddc4d867

+ 29 - 0
src/__tests__/features/workorders/create-workorder.test.ts

@@ -203,6 +203,35 @@ describe("createServiceRecord — invoice number", () => {
       })
     );
   });
+
+  it("respects an explicitly empty prefix instead of falling back to the default", async () => {
+    setupAuth();
+    setupCommonMocks();
+    vi.mocked(db.appSetting.findMany).mockResolvedValue([
+      { key: "workshop.invoicePrefix", value: "" } as any,
+    ]);
+
+    const mockCreate = vi.fn().mockResolvedValue({ id: "sr-4" });
+    vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
+      fn({
+        serviceRecord: { create: mockCreate },
+        servicePart: { createMany: vi.fn() },
+        serviceLabor: { createMany: vi.fn() },
+        serviceAttachment: { createMany: vi.fn() },
+        inventoryPart: { findFirst: vi.fn(), update: vi.fn() },
+      })
+    );
+
+    await createServiceRecord({ vehicleId: VEHICLE_ID, title: "Test" });
+
+    expect(mockCreate).toHaveBeenCalledWith(
+      expect.objectContaining({
+        data: expect.objectContaining({
+          invoiceNumber: "1001",
+        }),
+      })
+    );
+  });
 });
 
 // ---------------------------------------------------------------------------

+ 1 - 1
src/app/(authenticated)/settings/invoice/invoice-settings.tsx

@@ -81,7 +81,7 @@ export function InvoiceSettings({
 
   // General tab state
   const [invoicePrefix, setInvoicePrefix] = useState(
-    settings[SETTING_KEYS.INVOICE_PREFIX] || '{year}-'
+    settings[SETTING_KEYS.INVOICE_PREFIX] ?? '{year}-'
   )
   const [invoiceStartNumber, setInvoiceStartNumber] = useState(
     settings[SETTING_KEYS.INVOICE_START_NUMBER] || ''

+ 1 - 1
src/app/api/protected/backup/import-invoice-ninja/route.ts

@@ -293,7 +293,7 @@ export async function POST(request: NextRequest) {
       where: { organizationId, key: "workshop.invoicePrefix" },
     });
     const invoicePrefix = resolveInvoicePrefix(
-      prefixSetting?.value || "{year}-"
+      prefixSetting?.value ?? "{year}-"
     );
 
     // Get the current highest invoice number

+ 1 - 1
src/app/api/protected/backup/import-lubelog/route.ts

@@ -253,7 +253,7 @@ export async function POST(request: NextRequest) {
       where: { organizationId, key: "workshop.invoicePrefix" },
     });
     const invoicePrefix = resolveInvoicePrefix(
-      prefixSetting?.value || "{year}-"
+      prefixSetting?.value ?? "{year}-"
     );
 
     // Get the current highest invoice number to continue the sequence

+ 1 - 1
src/features/billing/Actions/recurringInvoiceActions.ts

@@ -254,7 +254,7 @@ async function generateInvoiceNumber(organizationId: string): Promise<string> {
   const settingsMap: Record<string, string> = {};
   for (const s of settings) settingsMap[s.key] = s.value;
 
-  const prefix = resolveInvoicePrefix(settingsMap["workshop.invoicePrefix"] || "{year}-");
+  const prefix = resolveInvoicePrefix(settingsMap["workshop.invoicePrefix"] ?? "{year}-");
   const startNumber = parseInt(settingsMap["workshop.invoiceStartNumber"] || "0", 10);
 
   const lastRecord = await db.serviceRecord.findFirst({

+ 1 - 1
src/features/quotes/Actions/quoteActions.ts

@@ -345,7 +345,7 @@ export async function convertQuoteToServiceRecord(quoteId: string, vehicleId: st
     ]);
     const settingsMap: Record<string, string> = {};
     for (const s of settings) settingsMap[s.key] = s.value;
-    const prefix = resolveInvoicePrefix(settingsMap["workshop.invoicePrefix"] || "{year}-");
+    const prefix = resolveInvoicePrefix(settingsMap["workshop.invoicePrefix"] ?? "{year}-");
 
     const lastRecord = await db.serviceRecord.findFirst({
       where: { vehicle: { organizationId } },

+ 5 - 2
src/features/status-reports/Actions/getStatusReportsForService.ts

@@ -7,12 +7,15 @@ import { PermissionAction, PermissionSubject } from "@/lib/permissions";
 export async function getStatusReportsForService(serviceRecordId: string) {
   return withAuth(
     async ({ organizationId }) => {
-      // Validate the service record belongs to this org
+      // A missing or foreign-org record yields an empty list rather than an
+      // error: the reports query below is org-scoped anyway, and this action
+      // runs during page renders of just-deleted records (see deleteServiceRecord
+      // revalidating the current route).
       const serviceRecord = await db.serviceRecord.findFirst({
         where: { id: serviceRecordId, vehicle: { organizationId } },
         select: { id: true },
       });
-      if (!serviceRecord) throw new Error("Service record not found");
+      if (!serviceRecord) return [];
 
       const reports = await db.statusReport.findMany({
         where: { serviceRecordId, organizationId },

+ 1 - 1
src/features/vehicles/Actions/createDraftServiceRecord.ts

@@ -87,7 +87,7 @@ export async function createDraftServiceRecord(
         if (tech) techName = tech.name;
       }
 
-      const rawPrefix = settingsMap["workshop.invoicePrefix"] || "{year}-";
+      const rawPrefix = settingsMap["workshop.invoicePrefix"] ?? "{year}-";
       const now = new Date();
       const prefix = rawPrefix
         .replace("{year}", now.getFullYear().toString())

+ 1 - 1
src/features/vehicles/Actions/serviceActions.ts

@@ -234,7 +234,7 @@ export async function createServiceRecord(input: unknown) {
     for (const s of settings) settingsMap[s.key] = s.value;
 
     const shopName = data.shopName || org?.name || undefined;
-    const prefix = resolveInvoicePrefix(settingsMap["workshop.invoicePrefix"] || "{year}-");
+    const prefix = resolveInvoicePrefix(settingsMap["workshop.invoicePrefix"] ?? "{year}-");
 
     // If the caller didn't pass taxInclusive, inherit the org's current setting.
     // Existing callers (vehicle-detail-client, ServiceForm) don't send the field,

+ 6 - 0
src/features/vehicles/Components/service-page/useServiceActions.ts

@@ -172,11 +172,17 @@ export function useServiceActions({
       destructive: true,
     })
     if (!ok) return
+    // A pending autosave firing after the delete would hit a record that no
+    // longer exists, so cancel it and block further saves before deleting.
+    if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
+    isSavingRef.current = true
     const result = await deleteServiceRecord(record.id)
     if (result.success) {
+      setHasUnsavedChanges(false)
       router.push(`/vehicles/${vehicleId}`)
       router.refresh()
     } else {
+      isSavingRef.current = false
       modal.open('error', tc('errors.error'), result.error || t('page.failedDelete'))
     }
   }

+ 1 - 1
src/lib/cron/recurring-invoices.ts

@@ -34,7 +34,7 @@ async function generateInvoiceNumber(organizationId: string): Promise<string> {
   const settingsMap: Record<string, string> = {}
   for (const s of settings) settingsMap[s.key] = s.value
 
-  const prefix = resolveInvoicePrefix(settingsMap['workshop.invoicePrefix'] || '{year}-')
+  const prefix = resolveInvoicePrefix(settingsMap['workshop.invoicePrefix'] ?? '{year}-')
   const startNumber = parseInt(settingsMap['workshop.invoiceStartNumber'] || '0', 10)
 
   const lastRecord = await db.serviceRecord.findFirst({