document-lock.server.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. import 'server-only'
  2. import { cache } from 'react'
  3. import { db } from './db'
  4. import {
  5. assertEditable,
  6. invoiceLockState,
  7. quoteLockState,
  8. readDocumentLockSettings,
  9. type DocumentLockSettings,
  10. type LockState,
  11. } from './document-lock'
  12. import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
  13. import { isCancelled } from '@/features/work-order-statuses/Lib/stages'
  14. import { CancelledInvoiceError } from '@/features/invoices/Lib/cancelInvoice'
  15. const LOCK_SETTING_KEYS = {
  16. invoiceLockEnabled: SETTING_KEYS.INVOICE_LOCK_ENABLED,
  17. invoiceLockTrigger: SETTING_KEYS.INVOICE_LOCK_TRIGGER,
  18. quoteLockEnabled: SETTING_KEYS.QUOTE_LOCK_ENABLED,
  19. quoteLockTrigger: SETTING_KEYS.QUOTE_LOCK_TRIGGER,
  20. }
  21. /**
  22. * The org's lock configuration, read straight from the settings table.
  23. * Wrapped in React's per-request cache so a render or action that checks the
  24. * lock more than once pays for the settings query once.
  25. */
  26. export const getDocumentLockSettings = cache(
  27. async (organizationId: string): Promise<DocumentLockSettings> => {
  28. const rows = await db.appSetting.findMany({
  29. where: { organizationId, key: { in: Object.values(LOCK_SETTING_KEYS) } },
  30. select: { key: true, value: true },
  31. })
  32. const map: Record<string, string> = {}
  33. for (const row of rows) map[row.key] = row.value
  34. return readDocumentLockSettings(map, LOCK_SETTING_KEYS)
  35. }
  36. )
  37. /**
  38. * The lock state of one invoice, loading only the fields the rules need.
  39. * A record that does not exist is reported as editable, leaving the caller's
  40. * own not-found handling to produce the error.
  41. */
  42. export async function getInvoiceLockState(
  43. recordId: string,
  44. organizationId: string
  45. ): Promise<LockState> {
  46. return (await loadInvoiceLock(recordId, organizationId)).state
  47. }
  48. async function loadInvoiceLock(
  49. recordId: string,
  50. organizationId: string
  51. ): Promise<{ state: LockState; cancelled: boolean }> {
  52. const [record, settings] = await Promise.all([
  53. db.serviceRecord.findFirst({
  54. where: { id: recordId, organizationId },
  55. select: {
  56. status: true,
  57. sentAt: true,
  58. manuallyPaid: true,
  59. totalAmount: true,
  60. cost: true,
  61. editUnlockedAt: true,
  62. payments: { select: { amount: true } },
  63. },
  64. }),
  65. getDocumentLockSettings(organizationId),
  66. ])
  67. if (!record) return { state: { locked: false, reason: null, unlockedAt: null }, cancelled: false }
  68. return { state: invoiceLockState(record, settings), cancelled: isCancelled(record.status) }
  69. }
  70. export async function getQuoteLockState(
  71. quoteId: string,
  72. organizationId: string
  73. ): Promise<LockState> {
  74. const [quote, settings] = await Promise.all([
  75. db.quote.findFirst({
  76. where: { id: quoteId, organizationId },
  77. select: { status: true, sentAt: true, editUnlockedAt: true },
  78. }),
  79. getDocumentLockSettings(organizationId),
  80. ])
  81. if (!quote) return { locked: false, reason: null, unlockedAt: null }
  82. return quoteLockState(quote, settings)
  83. }
  84. /**
  85. * Refuses an edit to a locked invoice. Call this before any change to what the
  86. * document says it is owed; payments, status and sharing do not go through it.
  87. */
  88. export async function assertInvoiceEditable(recordId: string, organizationId: string) {
  89. const { state, cancelled } = await loadInvoiceLock(recordId, organizationId)
  90. // A cancelled invoice is final, whatever the lock setting says: the copy
  91. // the customer holds says cancelled, and its number is spent.
  92. if (cancelled) throw new CancelledInvoiceError()
  93. assertEditable(state)
  94. }
  95. export async function assertQuoteEditable(quoteId: string, organizationId: string) {
  96. assertEditable(await getQuoteLockState(quoteId, organizationId))
  97. }
  98. /**
  99. * Records that the invoice reached the customer, which is what "lock when
  100. * sent" keys off. Every send channel — email, share link, SMS with the link —
  101. * must come through here (or stamp sentAt in the same write, as
  102. * generatePublicLink does): a channel that forgets makes the lock silently
  103. * wrong for everyone who only uses that channel. Every send counts, not just
  104. * the first, so re-issuing after an unlock locks the corrected copy too.
  105. */
  106. export async function markInvoiceSent(
  107. recordId: string,
  108. organizationId: string,
  109. options: {
  110. /**
  111. * The caller already issued the invoice, to render the copy it sent from
  112. * the same snapshot. Skips the second, identical capture.
  113. */
  114. alreadyIssued?: boolean
  115. } = {}
  116. ) {
  117. // Issued before the stamp, so what the customer receives and what is kept
  118. // are the same copy. An invoice already issued is left as it is, unless an
  119. // owner unlocked it since; see shouldIssue.
  120. if (!options.alreadyIssued) {
  121. const { issueInvoice } = await import('@/features/invoices/Lib/issueInvoice')
  122. await issueInvoice(recordId, organizationId, 'sent')
  123. }
  124. await db.serviceRecord.updateMany({
  125. where: { id: recordId, organizationId },
  126. data: { sentAt: new Date() },
  127. })
  128. }
  129. /**
  130. * The quote counterpart of markInvoiceSent. Also moves a draft to "sent",
  131. * matching what emailing a quote has always done, so a shared link and an
  132. * emailed copy agree about whether the quote went to the customer. Accepted
  133. * and converted quotes keep their status; only sentAt moves.
  134. */
  135. export async function markQuoteSent(quoteId: string, organizationId: string) {
  136. await db.quote.updateMany({
  137. where: { id: quoteId, organizationId },
  138. data: { sentAt: new Date() },
  139. })
  140. await db.quote.updateMany({
  141. where: { id: quoteId, organizationId, status: { notIn: ['accepted', 'converted'] } },
  142. data: { status: 'sent' },
  143. })
  144. }