-- Hub 2.0: billing per customer. The schedule (cycle, start, next invoice, review) moves from the -- licence to the customer, so one invoice covers all of a customer's products; each licence keeps -- when it's charged from (billedFrom) and up to which day it has been invoiced (billedUntil). -- Existing billing carries on unchanged: each billed licence's schedule becomes its customer's. -- AlterTable: the customer's schedule, and the invoice's basis. ALTER TABLE "Customer" ADD COLUMN "billingCycle" "BillingCycle" NOT NULL DEFAULT 'none', ADD COLUMN "billingStart" DATE, ADD COLUMN "nextInvoiceDate" DATE, ADD COLUMN "reviewDate" DATE; ALTER TABLE "Invoice" ADD COLUMN "basis" JSONB; ALTER TABLE "Licence" ADD COLUMN "billedFrom" DATE, ADD COLUMN "billedUntil" DATE; -- Copy: a customer takes the schedule of its billed licence (Hub 1.7 billed one Events licence per -- customer; if there were several, the one invoiced next). UPDATE "Customer" c SET "billingCycle" = l."billingCycle", "billingStart" = l."billingStart", "nextInvoiceDate" = l."nextInvoiceDate", "reviewDate" = l."reviewDate" FROM ( SELECT DISTINCT ON ("customerId") "customerId", "billingCycle", "billingStart", "nextInvoiceDate", "reviewDate" FROM "Licence" WHERE "billingCycle" <> 'none' AND status <> 'revoked' ORDER BY "customerId", "nextInvoiceDate" ASC NULLS LAST, "createdAt" ASC ) l WHERE c.id = l."customerId"; -- A billed licence is charged from when its billing started, and has been invoiced up to the day -- before its next invoice. UPDATE "Licence" SET "billedFrom" = COALESCE("billingStart", "nextInvoiceDate"), "billedUntil" = CASE WHEN "nextInvoiceDate" IS NOT NULL THEN "nextInvoiceDate" - 1 END WHERE "billingCycle" <> 'none'; -- The licence's own schedule is gone. ALTER TABLE "Licence" DROP COLUMN "billingCycle", DROP COLUMN "billingStart", DROP COLUMN "nextInvoiceDate", DROP COLUMN "reviewDate"; -- Invoices: one per licence and period before 2.0 (kept as history); one per customer and period -- from 2.0 (licenceId null), not counting void ones. DROP INDEX "Invoice_licenceId_periodStart_key"; CREATE INDEX "Invoice_licenceId_periodStart_idx" ON "Invoice"("licenceId", "periodStart"); CREATE UNIQUE INDEX "Invoice_customerId_periodStart_open_key" ON "Invoice"("customerId", "periodStart") WHERE "licenceId" IS NULL AND "periodStart" IS NOT NULL AND status <> 'void';