CREATE OR REPLACE FUNCTION dbo.spcreateinvoice("Id" uuid, "UserId" text, "Date" timestamp with time zone)
  RETURNS void AS
$BODY$INSERT INTO dbo."Invoices"("Id", "UserId", "MaxDateUtc", "DateCreatedUtc")
VALUES ($1, $2, $3, CURRENT_TIMESTAMP at time zone 'UTC');

UPDATE dbo."ApiTransactions"
SET "InvoiceId" = $1
WHERE "InvoiceId" IS NULL AND "UserId" = $2 AND "DateUtc" < $3

$BODY$
  LANGUAGE sql VOLATILE
  COST 100;
  
CREATE OR REPLACE FUNCTION dbo.spdeleteinvoice("Id" uuid)
  RETURNS void AS
$BODY$

UPDATE dbo."ApiTransactions"
SET "InvoiceId" = NULL
WHERE "InvoiceId" = $1;

DELETE FROM dbo."Invoices" WHERE "Id" = $1;

$BODY$
  LANGUAGE sql VOLATILE
  COST 100;
