f24b26a139
* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
839 lines
31 KiB
TypeScript
839 lines
31 KiB
TypeScript
/**
|
|
* Deadline generator - creates tax deadlines based on company settings
|
|
*/
|
|
|
|
import { SupabaseClient } from '@supabase/supabase-js'
|
|
import { createLogger } from '@/lib/logger'
|
|
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
|
import type { TaxDeadlineType, DeadlineStatus } from '@/types'
|
|
|
|
const log = createLogger('deadline-generator')
|
|
import {
|
|
getApplicableDeadlineConfigs,
|
|
type CompanySettingsForDeadlines,
|
|
type DeadlineInstance,
|
|
type TaxAssessmentNoticeForDeadline,
|
|
} from './deadline-config'
|
|
import { adjustDeadlineToNextBankingDay } from './swedish-holidays'
|
|
|
|
/**
|
|
* Rolling generation horizons. Recurring skattekonto obligations (monthly
|
|
* and quarterly filings) only generate ~6 months ahead: nobody acts on a
|
|
* moms deadline 14 months out, and the rows just bury the near-term list.
|
|
* Annual obligations keep 12 months so year-end planning still gets
|
|
* warning. The daily backfill cron rolls the window forward: a row is
|
|
* created once its due date enters the horizon.
|
|
*
|
|
* The same cutoff MUST apply in generateTaxDeadlinesForUser and
|
|
* getExpectedUpcomingDeadlineKeys: if detection expected a row the
|
|
* generator refuses to create, the nightly cron would regenerate (and
|
|
* status-reset) the company every day forever.
|
|
*/
|
|
export const RECURRING_HORIZON_DAYS = 183
|
|
export const ANNUAL_HORIZON_DAYS = 365
|
|
|
|
/** Types on the recurring horizon; anything not listed defaults to annual. */
|
|
const RECURRING_HORIZON_TYPES = new Set<TaxDeadlineType>([
|
|
'moms_monthly',
|
|
'moms_quarterly',
|
|
'f_skatt',
|
|
'arbetsgivardeklaration',
|
|
'skatteinbetalning',
|
|
'periodisk_sammanstallning',
|
|
'oss_quarterly',
|
|
'ioss_monthly',
|
|
'intrastat_monthly',
|
|
'punktskatt_monthly',
|
|
])
|
|
|
|
function horizonEndFor(type: TaxDeadlineType, today: Date): Date {
|
|
const days = RECURRING_HORIZON_TYPES.has(type)
|
|
? RECURRING_HORIZON_DAYS
|
|
: ANNUAL_HORIZON_DAYS
|
|
const end = new Date(today)
|
|
end.setDate(end.getDate() + days)
|
|
return end
|
|
}
|
|
|
|
/**
|
|
* Fields in company_settings that affect tax deadline generation
|
|
*/
|
|
export const TAX_RELEVANT_FIELDS = [
|
|
'entity_type',
|
|
'moms_period',
|
|
'f_skatt',
|
|
'preliminary_tax_monthly',
|
|
'vat_registered',
|
|
'pays_salaries',
|
|
'employer_registered',
|
|
'employer_seasonal',
|
|
'fiscal_year_start_month',
|
|
'vat_taxable_base_over_40m',
|
|
'vat_has_eu_trade',
|
|
'vat_filing_method',
|
|
'periodisk_sammanstallning_enabled',
|
|
'periodisk_sammanstallning_period',
|
|
'periodisk_sammanstallning_filing_method',
|
|
'kontrolluppgifter_enabled',
|
|
'rot_rut_enabled',
|
|
'oss_enabled',
|
|
'ioss_enabled',
|
|
'intrastat_enabled',
|
|
'punktskatt_enabled',
|
|
'fyllnadsinbetalning_enabled',
|
|
] as const
|
|
|
|
export const DEADLINE_SETTINGS_SELECT =
|
|
'company_id, entity_type, moms_period, f_skatt, preliminary_tax_monthly, vat_registered, pays_salaries, employer_registered, employer_seasonal, fiscal_year_start_month, vat_taxable_base_over_40m, vat_has_eu_trade, vat_filing_method, periodisk_sammanstallning_enabled, periodisk_sammanstallning_period, periodisk_sammanstallning_filing_method, kontrolluppgifter_enabled, rot_rut_enabled, oss_enabled, ioss_enabled, intrastat_enabled, punktskatt_enabled, fyllnadsinbetalning_enabled' as const
|
|
|
|
/**
|
|
* Check if any tax-relevant fields changed
|
|
*/
|
|
export function didTaxFieldsChange(
|
|
oldSettings: Partial<CompanySettingsForDeadlines>,
|
|
newSettings: Partial<CompanySettingsForDeadlines>
|
|
): boolean {
|
|
for (const field of TAX_RELEVANT_FIELDS) {
|
|
if (oldSettings[field] !== newSettings[field]) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
export function hasTaxRelevantFields(body: Record<string, unknown>): boolean {
|
|
return TAX_RELEVANT_FIELDS.some((field) => Object.prototype.hasOwnProperty.call(body, field))
|
|
}
|
|
|
|
export function toDeadlineSettings(
|
|
settings: Partial<CompanySettingsForDeadlines>,
|
|
): CompanySettingsForDeadlines {
|
|
if (settings.entity_type !== 'aktiebolag' && settings.entity_type !== 'enskild_firma') {
|
|
throw new Error('Company entity type is required to generate tax deadlines')
|
|
}
|
|
|
|
return {
|
|
entity_type: settings.entity_type,
|
|
moms_period: settings.moms_period ?? null,
|
|
f_skatt: settings.f_skatt ?? true,
|
|
preliminary_tax_monthly: settings.preliminary_tax_monthly ?? null,
|
|
vat_registered: settings.vat_registered ?? false,
|
|
pays_salaries: settings.pays_salaries ?? false,
|
|
employer_registered: settings.employer_registered ?? null,
|
|
employer_seasonal: settings.employer_seasonal ?? false,
|
|
fiscal_year_start_month: settings.fiscal_year_start_month ?? 1,
|
|
vat_taxable_base_over_40m: settings.vat_taxable_base_over_40m ?? false,
|
|
vat_has_eu_trade: settings.vat_has_eu_trade ?? false,
|
|
vat_filing_method: settings.vat_filing_method ?? 'electronic',
|
|
periodisk_sammanstallning_enabled: settings.periodisk_sammanstallning_enabled ?? false,
|
|
periodisk_sammanstallning_period: settings.periodisk_sammanstallning_period ?? 'monthly',
|
|
periodisk_sammanstallning_filing_method:
|
|
settings.periodisk_sammanstallning_filing_method ?? 'electronic',
|
|
kontrolluppgifter_enabled: settings.kontrolluppgifter_enabled ?? false,
|
|
rot_rut_enabled: settings.rot_rut_enabled ?? false,
|
|
rot_rut_payment_years: settings.rot_rut_payment_years,
|
|
oss_enabled: settings.oss_enabled ?? false,
|
|
ioss_enabled: settings.ioss_enabled ?? false,
|
|
intrastat_enabled: settings.intrastat_enabled ?? false,
|
|
punktskatt_enabled: settings.punktskatt_enabled ?? false,
|
|
fyllnadsinbetalning_enabled: settings.fyllnadsinbetalning_enabled ?? false,
|
|
tax_assessment_notices: settings.tax_assessment_notices,
|
|
}
|
|
}
|
|
|
|
interface TaxAssessmentNoticeRow {
|
|
id: string
|
|
company_id: string
|
|
decision_type: 'final' | 'reassessment'
|
|
payment_due_date: string
|
|
fiscal_periods: { name: string } | Array<{ name: string }> | null
|
|
}
|
|
|
|
async function fetchActiveTaxAssessmentNotices(
|
|
supabase: SupabaseClient,
|
|
companyId?: string,
|
|
): Promise<TaxAssessmentNoticeRow[]> {
|
|
return fetchAllRows<TaxAssessmentNoticeRow>(({ from, to }) => {
|
|
let query = supabase
|
|
.from('tax_assessment_notices')
|
|
.select('id, company_id, decision_type, payment_due_date, fiscal_periods(name)')
|
|
.is('archived_at', null)
|
|
.order('id', { ascending: true })
|
|
.range(from, to)
|
|
|
|
if (companyId) query = query.eq('company_id', companyId)
|
|
return query
|
|
})
|
|
}
|
|
|
|
function toDeadlineNotice(row: TaxAssessmentNoticeRow): TaxAssessmentNoticeForDeadline {
|
|
const fiscalPeriod = Array.isArray(row.fiscal_periods)
|
|
? row.fiscal_periods[0]
|
|
: row.fiscal_periods
|
|
return {
|
|
id: row.id,
|
|
fiscalPeriodName: fiscalPeriod?.name ?? '',
|
|
decisionType: row.decision_type,
|
|
paymentDueDate: row.payment_due_date,
|
|
}
|
|
}
|
|
|
|
async function hydrateTaxAssessmentNotices(
|
|
supabase: SupabaseClient,
|
|
settingsRows: DeadlineSettingsRow[],
|
|
): Promise<DeadlineSettingsRow[]> {
|
|
const notices = await fetchActiveTaxAssessmentNotices(supabase)
|
|
const byCompany = new Map<string, TaxAssessmentNoticeForDeadline[]>()
|
|
for (const notice of notices) {
|
|
const current = byCompany.get(notice.company_id) ?? []
|
|
current.push(toDeadlineNotice(notice))
|
|
byCompany.set(notice.company_id, current)
|
|
}
|
|
return settingsRows.map((settings) => ({
|
|
...settings,
|
|
tax_assessment_notices: byCompany.get(settings.company_id) ?? [],
|
|
}))
|
|
}
|
|
|
|
/**
|
|
* Decide whether a settings save should (re)generate tax deadlines.
|
|
*
|
|
* Regenerate when a tax-relevant field changed OR when the company has no
|
|
* system-generated deadlines yet. The second case is the common one: tax
|
|
* settings are filled at onboarding, so a later save with no tax-field change
|
|
* used to skip generation entirely and the deadlines page stayed empty even
|
|
* though the settings were "filled in". Backfilling an empty set is safe: there
|
|
* is no existing status/progress to clobber.
|
|
*/
|
|
export function shouldRegenerateTaxDeadlines(
|
|
taxFieldsChanged: boolean,
|
|
existingSystemDeadlineCount: number
|
|
): boolean {
|
|
return taxFieldsChanged || existingSystemDeadlineCount === 0
|
|
}
|
|
|
|
/**
|
|
* What a regenerated system deadline inherits from the row it replaces.
|
|
*
|
|
* Regeneration deletes and reinserts, so anything not carried across here is
|
|
* silently discarded. ONE rule decides the split, not a list of special
|
|
* cases: **the generator owns what the statute decides, the row owns every
|
|
* mark a person put on it.** The template decides which obligation this is,
|
|
* what it is called, when it falls due and which report it opens; the notes,
|
|
* the clock time, the priority flag and the manually advanced status are the
|
|
* user's, and they survive.
|
|
*
|
|
* Inherited (user-owned or system state):
|
|
* - `notes`, `due_time`, `customer_id`: the generator never writes these, so
|
|
* a non-null value can only have come from the deadline editor.
|
|
* - `priority`: the editor's only other non-statutory field.
|
|
* - `status` + `status_changed_at`: only when the stored status is one a
|
|
* human set (see MANUAL_STATUSES); the date-derived ones are recomputed.
|
|
*
|
|
* Deliberately NOT inherited, so a corrected template still reaches rows
|
|
* nobody touched:
|
|
* - `title`, `due_date`: statutory. A law change, a schedule fix or a
|
|
* banking-day correction must propagate. `due_date` additionally forms the
|
|
* backfill identity (`type:period:due_date`), so a preserved divergent date
|
|
* would make findSettingsMissingUpcomingDeadlines flag the company on every
|
|
* cron run without ever converging.
|
|
* - `deadline_type`: the backfill query filters on `deadline_type = 'tax'`.
|
|
* - `linked_report_type`, `linked_report_period`, `tax_assessment_notice_id`:
|
|
* derived from the obligation, no user surface writes them.
|
|
* - `reminder_offsets`: template data today, because no surface lets a user
|
|
* change it. Move it into the inherited set the day one does.
|
|
* - `user_id`: system deadlines are company-owned; migration
|
|
* 20260704100000 made the column nullable precisely so the generator can
|
|
* leave it unset.
|
|
*
|
|
* The schema cannot distinguish "the user edited this field" from "the
|
|
* template changed under an untouched row" for the statutory columns: nothing
|
|
* records the template's value at creation time, and the `deadlines_updated_at`
|
|
* trigger bumps `updated_at` on every automatic status sweep too. Rather than
|
|
* guess, the statutory columns always take the template value, which is the
|
|
* conservative choice for a compliance surface: a stale filing date is a
|
|
* missed filing, a lost title edit is cosmetic.
|
|
*/
|
|
const SUPERSEDED_ROW_SELECT =
|
|
'tax_deadline_type, tax_period, status, status_changed_at, notes, due_time, priority, customer_id' as const
|
|
|
|
interface SupersededDeadlineRow {
|
|
tax_deadline_type: string | null
|
|
tax_period: string | null
|
|
status: DeadlineStatus | null
|
|
status_changed_at: string | null
|
|
notes: string | null
|
|
due_time: string | null
|
|
priority: 'critical' | 'important' | 'normal' | null
|
|
customer_id: string | null
|
|
}
|
|
|
|
/**
|
|
* Statuses only a human sets. `upcoming`, `action_needed` and `overdue` are
|
|
* derived from the due date by the nightly status engine, so a replacement
|
|
* row recomputes them; these three represent work the user reported and are
|
|
* carried across. (`confirmed` also sets `is_completed`, so such a row is
|
|
* never replaced in the first place; it is listed for completeness.)
|
|
*/
|
|
const MANUAL_STATUSES = new Set<DeadlineStatus>(['in_progress', 'submitted', 'confirmed'])
|
|
|
|
/**
|
|
* Format date to YYYY-MM-DD
|
|
*/
|
|
function formatDateISO(date: Date): string {
|
|
const year = date.getFullYear()
|
|
const month = String(date.getMonth() + 1).padStart(2, '0')
|
|
const day = String(date.getDate()).padStart(2, '0')
|
|
return `${year}-${month}-${day}`
|
|
}
|
|
|
|
/**
|
|
* Generate all tax deadlines for a user based on their company settings
|
|
*/
|
|
export async function generateTaxDeadlinesForUser(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
settings: CompanySettingsForDeadlines,
|
|
years: number[] = []
|
|
): Promise<{ created: number; deleted: number }> {
|
|
if (settings.tax_assessment_notices === undefined) {
|
|
const notices = await fetchActiveTaxAssessmentNotices(supabase, companyId)
|
|
settings = {
|
|
...settings,
|
|
tax_assessment_notices: notices.map(toDeadlineNotice),
|
|
}
|
|
}
|
|
|
|
// Recurring deadlines use the current rolling window. Explicit tax notices
|
|
// also include their own due-date years so a newly entered overdue notice is
|
|
// represented instead of disappearing only because its exact date has passed.
|
|
if (years.length === 0) {
|
|
const currentYear = new Date().getFullYear()
|
|
const noticeYears = (settings.tax_assessment_notices ?? [])
|
|
.map((notice) => Number(notice.paymentDueDate.slice(0, 4)))
|
|
.filter(Number.isInteger)
|
|
years = Array.from(new Set([currentYear, currentYear + 1, ...noticeYears]))
|
|
}
|
|
|
|
// The ROT/RUT begäran deadline is data-dependent: a row for year Y only
|
|
// exists when Y has paid ROT/RUT invoices (Lag 2009:194 8 §, payment
|
|
// dates). Resolve the payment years here, in the one place that inserts
|
|
// and deletes rows, so every generation path agrees. Callers that pass
|
|
// pure settings (backfill detection) leave the field undefined and simply
|
|
// never expect rot_rut_begaran rows.
|
|
if (settings.rot_rut_enabled && settings.rot_rut_payment_years === undefined) {
|
|
const rotRutRows = await fetchAllRows<{ paid_at: string | null }>(({ from, to }) =>
|
|
supabase
|
|
.from('invoices')
|
|
.select('paid_at')
|
|
.eq('company_id', companyId)
|
|
.gt('deduction_total', 0)
|
|
.not('paid_at', 'is', null)
|
|
.order('id', { ascending: true })
|
|
.range(from, to),
|
|
)
|
|
settings = {
|
|
...settings,
|
|
rot_rut_payment_years: Array.from(
|
|
new Set(
|
|
rotRutRows
|
|
.filter((row) => row.paid_at)
|
|
.map((row) => Number(String(row.paid_at).slice(0, 4))),
|
|
),
|
|
),
|
|
}
|
|
}
|
|
|
|
// Get applicable deadline configs based on settings
|
|
const applicableConfigs = getApplicableDeadlineConfigs(settings)
|
|
|
|
const today = new Date()
|
|
today.setHours(0, 0, 0, 0)
|
|
const todayIso = formatDateISO(today)
|
|
const endDate = `${Math.max(...years) + 1}-12-31`
|
|
|
|
// Completed deadlines represent real filing progress and dismissed
|
|
// deadlines represent an explicit opt-out; preserve both and do not create
|
|
// a second pending row for the same obligation. The window starts a year
|
|
// before the earliest generated year, NOT today: a completed row can carry
|
|
// a superseded due date that already passed while the current statutory
|
|
// date is still ahead, and filtering on today would resurrect a pending
|
|
// row for an obligation the user already filed.
|
|
const completedFloor = `${Math.min(...years) - 1}-01-01`
|
|
const { data: preservedRows, error: preservedRowsError } = await supabase
|
|
.from('deadlines')
|
|
.select('tax_deadline_type, tax_period')
|
|
.eq('company_id', companyId)
|
|
.eq('source', 'system')
|
|
.or('is_completed.eq.true,dismissed_at.not.is.null')
|
|
.gte('due_date', completedFloor)
|
|
|
|
if (preservedRowsError) {
|
|
log.error('Error fetching completed/dismissed deadlines:', preservedRowsError)
|
|
throw preservedRowsError
|
|
}
|
|
|
|
const completedKeys = new Set(
|
|
(preservedRows ?? []).map(
|
|
(row: { tax_deadline_type: string | null; tax_period: string | null }) =>
|
|
`${row.tax_deadline_type}:${row.tax_period}`,
|
|
),
|
|
)
|
|
|
|
// Everything the user (or the status flow) put on the rows about to be
|
|
// replaced, keyed by the same tax_deadline_type:tax_period identity the
|
|
// completed/dismissed check uses. See SUPERSEDED_ROW_SELECT for the rule.
|
|
const { data: supersededRows, error: supersededError } = await supabase
|
|
.from('deadlines')
|
|
.select(SUPERSEDED_ROW_SELECT)
|
|
.eq('company_id', companyId)
|
|
.eq('source', 'system')
|
|
.eq('is_completed', false)
|
|
.is('dismissed_at', null)
|
|
|
|
if (supersededError) {
|
|
log.error('Error fetching superseded deadlines:', supersededError)
|
|
throw supersededError
|
|
}
|
|
|
|
const supersededByKey = new Map<string, SupersededDeadlineRow>()
|
|
for (const row of (supersededRows ?? []) as SupersededDeadlineRow[]) {
|
|
supersededByKey.set(`${row.tax_deadline_type}:${row.tax_period}`, row)
|
|
}
|
|
|
|
// Generate new deadlines. Every row carries the identical key set: a
|
|
// PostgREST bulk insert rejects objects whose keys differ (PGRST102), so
|
|
// inherited columns are always present, null when there is nothing to
|
|
// inherit.
|
|
const nowIso = new Date().toISOString()
|
|
const deadlines: Array<{
|
|
company_id: string
|
|
title: string
|
|
due_date: string
|
|
due_time: string | null
|
|
deadline_type: 'tax'
|
|
priority: 'critical' | 'important' | 'normal'
|
|
is_completed: boolean
|
|
source: 'system'
|
|
status: DeadlineStatus
|
|
status_changed_at: string
|
|
notes: string | null
|
|
customer_id: string | null
|
|
tax_deadline_type: TaxDeadlineType
|
|
tax_period: string
|
|
linked_report_type: string | null
|
|
linked_report_period: Record<string, unknown> | null
|
|
reminder_offsets: number[]
|
|
is_auto_generated: boolean
|
|
tax_assessment_notice_id: string | null
|
|
}> = []
|
|
|
|
for (const config of applicableConfigs) {
|
|
const horizonEnd = horizonEndFor(config.type, today)
|
|
for (const year of years) {
|
|
const instances = config.generateDates(year, settings)
|
|
|
|
for (const instance of instances) {
|
|
// Create the raw deadline date
|
|
const rawDate = new Date(instance.year, instance.month, instance.day)
|
|
|
|
// Adjust for banking days (skip weekends and holidays). EU-law
|
|
// deadlines (OSS/IOSS) opt out: their dates stand on weekends.
|
|
const adjustedDate = config.skipBankingDayAdjustment
|
|
? rawDate
|
|
: adjustDeadlineToNextBankingDay(rawDate)
|
|
const dueDate = formatDateISO(adjustedDate)
|
|
|
|
// Skip if the deadline is in the past
|
|
if (adjustedDate < today && !instance.taxAssessmentNoticeId) {
|
|
continue
|
|
}
|
|
|
|
// Skip rows beyond the rolling horizon; the daily backfill creates
|
|
// them once they come into view.
|
|
if (adjustedDate > horizonEnd) {
|
|
continue
|
|
}
|
|
|
|
const deadlineKey = `${config.type}:${instance.period}`
|
|
if (completedKeys.has(deadlineKey)) {
|
|
continue
|
|
}
|
|
|
|
// The row this one replaces, if any: its user-owned columns and its
|
|
// manually reported progress carry across (see SUPERSEDED_ROW_SELECT).
|
|
const superseded = supersededByKey.get(deadlineKey)
|
|
|
|
// Determine initial status based on days until deadline, keeping a
|
|
// manually reported status from the row being replaced.
|
|
const daysUntil = Math.ceil((adjustedDate.getTime() - today.getTime()) / (1000 * 60 * 60 * 24))
|
|
const keepsManualStatus =
|
|
superseded?.status != null && MANUAL_STATUSES.has(superseded.status)
|
|
const status: DeadlineStatus = keepsManualStatus
|
|
? superseded!.status!
|
|
: daysUntil <= 14 ? 'action_needed' : 'upcoming'
|
|
|
|
// Generate title from template
|
|
const title = config.titleTemplate.replace('{periodLabel}', instance.periodLabel)
|
|
|
|
// Create linked report period data
|
|
const linkedReportPeriod = createLinkedReportPeriod(instance, config.type)
|
|
|
|
deadlines.push({
|
|
company_id: companyId,
|
|
title,
|
|
due_date: dueDate,
|
|
due_time: superseded?.due_time ?? null,
|
|
deadline_type: 'tax',
|
|
priority: superseded?.priority ?? config.priority,
|
|
is_completed: false,
|
|
source: 'system',
|
|
status,
|
|
// Only meaningful alongside a carried status; a recomputed status
|
|
// changed just now.
|
|
status_changed_at: (keepsManualStatus ? superseded!.status_changed_at : null) ?? nowIso,
|
|
notes: superseded?.notes ?? null,
|
|
customer_id: superseded?.customer_id ?? null,
|
|
tax_deadline_type: config.type,
|
|
tax_period: instance.period,
|
|
linked_report_type: config.linkedReportType,
|
|
linked_report_period: linkedReportPeriod,
|
|
reminder_offsets: [14, 7, 1, 0],
|
|
is_auto_generated: true,
|
|
tax_assessment_notice_id: instance.taxAssessmentNoticeId ?? null,
|
|
})
|
|
}
|
|
}
|
|
}
|
|
|
|
const uniqueDeadlines = Array.from(
|
|
new Map(
|
|
deadlines.map((deadline) => [
|
|
`${deadline.tax_deadline_type}:${deadline.tax_period}`,
|
|
deadline,
|
|
]),
|
|
).values(),
|
|
)
|
|
|
|
// Insert the replacement rows BEFORE deleting the old set. A failed insert
|
|
// then leaves the previous deadlines intact: the old delete-first order
|
|
// meant any insert failure (like the 23502 user_id regression) wiped the
|
|
// company's tax deadlines without replacing them.
|
|
//
|
|
// Not concurrency-safe: two overlapping regenerations (settings save racing
|
|
// the cron backfill) can each delete the other's freshly inserted rows and
|
|
// leave the company with fewer rows than expected. Accepted: the daily
|
|
// backfill cron detects the missing keys and repairs on its next run.
|
|
let newIds: string[] = []
|
|
if (uniqueDeadlines.length > 0) {
|
|
const { data: insertedData, error: insertError } = await supabase
|
|
.from('deadlines')
|
|
.insert(uniqueDeadlines)
|
|
.select('id')
|
|
|
|
if (insertError) {
|
|
log.error('Error inserting deadlines:', insertError)
|
|
throw insertError
|
|
}
|
|
newIds = (insertedData ?? []).map((d: { id: string }) => d.id)
|
|
}
|
|
|
|
// Delete the superseded system-generated deadlines for these years,
|
|
// excluding the rows just inserted. Dismissed rows survive: deleting one
|
|
// would erase the opt-out and let the next regeneration recreate the
|
|
// obligation as a fresh pending row.
|
|
//
|
|
// An obligation the settings no longer produce is deleted even when the
|
|
// user had edited it. Its notes go with it, and that is the right trade:
|
|
// the settings change is the user's own explicit statement that the
|
|
// obligation does not apply, and a deadlines page that keeps showing a
|
|
// momsdeklaration to a company that deregistered from moms is worse than a
|
|
// lost note. Notes on obligations that still apply survive, which is the
|
|
// case this preservation is about; anything worth keeping past a settings
|
|
// change belongs in a manual (source='user') deadline, which the generator
|
|
// never touches.
|
|
let deleteQuery = supabase
|
|
.from('deadlines')
|
|
.delete()
|
|
.eq('company_id', companyId)
|
|
.eq('source', 'system')
|
|
.eq('is_completed', false)
|
|
.is('dismissed_at', null)
|
|
.gte('due_date', todayIso)
|
|
.lte('due_date', endDate)
|
|
|
|
if (newIds.length > 0) {
|
|
deleteQuery = deleteQuery.not('id', 'in', `(${newIds.join(',')})`)
|
|
}
|
|
|
|
const { data: deletedData, error: deleteError } = await deleteQuery.select('id')
|
|
|
|
if (deleteError) {
|
|
log.error('Error deleting existing deadlines:', deleteError)
|
|
throw deleteError
|
|
}
|
|
|
|
return {
|
|
created: uniqueDeadlines.length,
|
|
deleted: deletedData?.length || 0,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create linked report period object for navigation
|
|
*/
|
|
function createLinkedReportPeriod(
|
|
instance: DeadlineInstance,
|
|
_type: TaxDeadlineType
|
|
): Record<string, unknown> | null {
|
|
const period = instance.period
|
|
|
|
// Parse the period string
|
|
if (period.includes('-Q')) {
|
|
// Quarterly: "2025-Q1"
|
|
const [year, quarter] = period.split('-Q')
|
|
return { year: parseInt(year), quarter: parseInt(quarter) }
|
|
}
|
|
|
|
if (period.includes('-') && period.length === 7) {
|
|
// Monthly: "2025-01"
|
|
const [year, month] = period.split('-')
|
|
return { year: parseInt(year), month: parseInt(month) }
|
|
}
|
|
|
|
if (period.includes('/')) {
|
|
// Fiscal year: "2024/2025"
|
|
const [startYear, endYear] = period.split('/')
|
|
return { startYear: parseInt(startYear), endYear: parseInt(endYear) }
|
|
}
|
|
|
|
// Annual: "2025"
|
|
if (/^\d{4}$/.test(period)) {
|
|
return { year: parseInt(period) }
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
/**
|
|
* Regenerate tax deadlines for a user after settings change
|
|
*/
|
|
export async function regenerateTaxDeadlinesForUser(
|
|
supabase: SupabaseClient,
|
|
companyId: string,
|
|
newSettings: CompanySettingsForDeadlines
|
|
): Promise<{ created: number; deleted: number }> {
|
|
const currentYear = new Date().getFullYear()
|
|
return generateTaxDeadlinesForUser(supabase, companyId, newSettings, [currentYear, currentYear + 1])
|
|
}
|
|
|
|
interface DeadlineSettingsRow extends Partial<CompanySettingsForDeadlines> {
|
|
company_id: string
|
|
}
|
|
|
|
interface UpcomingDeadlineCompanyRow {
|
|
id: string
|
|
company_id: string
|
|
tax_deadline_type: string | null
|
|
tax_period: string | null
|
|
due_date: string | null
|
|
is_completed: boolean | null
|
|
dismissed_at: string | null
|
|
}
|
|
|
|
// The due date is part of the identity: rows created by older schedule logic
|
|
// keep their type and period but carry a superseded statutory date, and the
|
|
// repair loop must treat those as missing so they get regenerated.
|
|
function deadlineIdentity(
|
|
type: string | null,
|
|
period: string | null,
|
|
dueDate: string | null,
|
|
): string {
|
|
return `${type}:${period}:${dueDate}`
|
|
}
|
|
|
|
// Completed and dismissed rows use the looser type:period identity (no due
|
|
// date): a filed or opted-out obligation is satisfied even when its stored
|
|
// date comes from a superseded schedule, and the generator never replaces
|
|
// either kind, so flagging them by date would make the repair loop re-run
|
|
// for the same company every day without ever converging.
|
|
function completedIdentity(type: string | null, period: string | null): string {
|
|
return `${type}:${period}`
|
|
}
|
|
|
|
export function getExpectedUpcomingDeadlineKeys(
|
|
settings: CompanySettingsForDeadlines,
|
|
years: number[] = [],
|
|
fromDate: Date = new Date(),
|
|
): Set<string> {
|
|
if (years.length === 0) {
|
|
const currentYear = fromDate.getFullYear()
|
|
years = [currentYear, currentYear + 1]
|
|
}
|
|
|
|
const today = new Date(fromDate)
|
|
today.setHours(0, 0, 0, 0)
|
|
const keys = new Set<string>()
|
|
|
|
for (const config of getApplicableDeadlineConfigs(settings)) {
|
|
const horizonEnd = horizonEndFor(config.type, today)
|
|
for (const year of years) {
|
|
for (const instance of config.generateDates(year, settings)) {
|
|
const rawDate = new Date(instance.year, instance.month, instance.day)
|
|
const adjustedDate = config.skipBankingDayAdjustment
|
|
? rawDate
|
|
: adjustDeadlineToNextBankingDay(rawDate)
|
|
// Same window as the generator: past rows and rows beyond the
|
|
// rolling horizon are never expected.
|
|
if (adjustedDate >= today && adjustedDate <= horizonEnd) {
|
|
keys.add(deadlineIdentity(config.type, instance.period, formatDateISO(adjustedDate)))
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return keys
|
|
}
|
|
|
|
export function findSettingsMissingUpcomingDeadlines(
|
|
settingsRows: DeadlineSettingsRow[],
|
|
upcomingDeadlineRows: UpcomingDeadlineCompanyRow[],
|
|
years: number[] = [],
|
|
fromDate: Date = new Date(),
|
|
): DeadlineSettingsRow[] {
|
|
const actualKeysByCompany = new Map<string, Set<string>>()
|
|
const completedKeysByCompany = new Map<string, Set<string>>()
|
|
for (const row of upcomingDeadlineRows) {
|
|
const keys = actualKeysByCompany.get(row.company_id) ?? new Set<string>()
|
|
keys.add(deadlineIdentity(row.tax_deadline_type, row.tax_period, row.due_date))
|
|
actualKeysByCompany.set(row.company_id, keys)
|
|
|
|
if (row.is_completed || row.dismissed_at) {
|
|
const completed = completedKeysByCompany.get(row.company_id) ?? new Set<string>()
|
|
completed.add(completedIdentity(row.tax_deadline_type, row.tax_period))
|
|
completedKeysByCompany.set(row.company_id, completed)
|
|
}
|
|
}
|
|
|
|
return settingsRows.filter((settings) => {
|
|
try {
|
|
const expectedKeys = getExpectedUpcomingDeadlineKeys(
|
|
toDeadlineSettings(settings),
|
|
years,
|
|
fromDate,
|
|
)
|
|
const actualKeys = actualKeysByCompany.get(settings.company_id) ?? new Set<string>()
|
|
const completedKeys = completedKeysByCompany.get(settings.company_id) ?? new Set<string>()
|
|
return Array.from(expectedKeys).some((key) => {
|
|
if (actualKeys.has(key)) return false
|
|
// key is `${type}:${period}:${dueDate}`; strip the date to compare
|
|
// against the completed set (periods never contain a colon).
|
|
const typeAndPeriod = key.slice(0, key.lastIndexOf(':'))
|
|
return !completedKeys.has(typeAndPeriod)
|
|
})
|
|
} catch {
|
|
// Include malformed settings so the repair loop logs the company-specific
|
|
// generation error without aborting recovery for every other company.
|
|
return true
|
|
}
|
|
})
|
|
}
|
|
|
|
// Paginate: PostgREST silently caps a plain .select() at 1000 rows, which
|
|
// would leave companies beyond the cap without deadlines.
|
|
async function fetchAllDeadlineSettings(supabase: SupabaseClient): Promise<DeadlineSettingsRow[]> {
|
|
return fetchAllRows<DeadlineSettingsRow>(({ from, to }) =>
|
|
supabase
|
|
.from('company_settings')
|
|
.select(DEADLINE_SETTINGS_SELECT)
|
|
.order('company_id', { ascending: true })
|
|
.range(from, to),
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Generate tax deadlines for the new year for every company.
|
|
*/
|
|
export async function generateNewYearDeadlines(
|
|
supabase: SupabaseClient
|
|
): Promise<{ usersProcessed: number; totalCreated: number }> {
|
|
const newYear = new Date().getFullYear()
|
|
const allSettings = await hydrateTaxAssessmentNotices(
|
|
supabase,
|
|
await fetchAllDeadlineSettings(supabase),
|
|
)
|
|
|
|
let usersProcessed = 0
|
|
let totalCreated = 0
|
|
|
|
for (const settings of allSettings) {
|
|
try {
|
|
const result = await generateTaxDeadlinesForUser(
|
|
supabase,
|
|
settings.company_id,
|
|
toDeadlineSettings(settings),
|
|
[newYear, newYear + 1]
|
|
)
|
|
usersProcessed++
|
|
totalCreated += result.created
|
|
} catch (err) {
|
|
log.error(`Error generating deadlines for company ${settings.company_id}:`, err)
|
|
}
|
|
}
|
|
|
|
return { usersProcessed, totalCreated }
|
|
}
|
|
|
|
/**
|
|
* Repair companies whose upcoming system tax deadlines are missing or carry
|
|
* dates from superseded schedule logic.
|
|
*/
|
|
export async function backfillMissingTaxDeadlines(
|
|
supabase: SupabaseClient,
|
|
): Promise<{ companiesScanned: number; companiesRepaired: number; totalCreated: number }> {
|
|
// Window starts a year back, not today: completed rows with a superseded
|
|
// (already passed) due date must still count as satisfied, otherwise the
|
|
// repair loop flags the company forever while the generator (correctly)
|
|
// refuses to recreate a filed obligation. Matches the generator's own
|
|
// completed-row floor.
|
|
const pastFloor = `${new Date().getFullYear() - 1}-01-01`
|
|
const [rawSettings, upcomingDeadlineRows] = await Promise.all([
|
|
fetchAllDeadlineSettings(supabase),
|
|
fetchAllRows<UpcomingDeadlineCompanyRow>(({ from, to }) =>
|
|
supabase
|
|
.from('deadlines')
|
|
.select('id, company_id, tax_deadline_type, tax_period, due_date, is_completed, dismissed_at')
|
|
.eq('source', 'system')
|
|
.eq('deadline_type', 'tax')
|
|
.gte('due_date', pastFloor)
|
|
.order('id', { ascending: true })
|
|
.range(from, to),
|
|
),
|
|
])
|
|
const allSettings = await hydrateTaxAssessmentNotices(supabase, rawSettings)
|
|
|
|
const missingSettings = findSettingsMissingUpcomingDeadlines(allSettings, upcomingDeadlineRows)
|
|
let companiesRepaired = 0
|
|
let totalCreated = 0
|
|
|
|
for (const settings of missingSettings) {
|
|
try {
|
|
const result = await regenerateTaxDeadlinesForUser(
|
|
supabase,
|
|
settings.company_id,
|
|
toDeadlineSettings(settings),
|
|
)
|
|
companiesRepaired++
|
|
totalCreated += result.created
|
|
} catch (err) {
|
|
log.error(`Error repairing deadlines for company ${settings.company_id}:`, err)
|
|
}
|
|
}
|
|
|
|
return {
|
|
companiesScanned: allSettings.length,
|
|
companiesRepaired,
|
|
totalCreated,
|
|
}
|
|
}
|