Gestão and the administrators switch each product on and off and set its price from a start date; a price that has started is history and cannot change, a scheduled one can be cancelled. The Site and the server read the current price; with no row the code's prices and TREATMENT_CENTS still apply, so nothing changes until someone sets one. A switched-off product disappears from the Site and new quotes with it are refused. Approved quotes and paid orders keep their price. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
603 lines
35 KiB
SQL
603 lines
35 KiB
SQL
-- Separate schema: never imports/migrates the historical schema.sql or SQLite.
|
|
CREATE SCHEMA IF NOT EXISTS dtf_local;
|
|
CREATE TABLE IF NOT EXISTS dtf_local.uploads (
|
|
id uuid PRIMARY KEY, owner uuid NOT NULL, name text NOT NULL,
|
|
size bigint NOT NULL, object_key text UNIQUE NOT NULL, multipart_id text NOT NULL,
|
|
complete boolean NOT NULL DEFAULT false,
|
|
created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.quotes (
|
|
id uuid PRIMARY KEY, owner uuid NOT NULL, request_key uuid NOT NULL,
|
|
request_hash text NOT NULL, draft jsonb NOT NULL, approved jsonb,
|
|
reviewed_by text, approved_at timestamptz,
|
|
created_at timestamptz NOT NULL DEFAULT now(), UNIQUE(owner, request_key)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.orders (
|
|
id uuid PRIMARY KEY, number bigint GENERATED ALWAYS AS IDENTITY UNIQUE,
|
|
quote_id uuid NOT NULL UNIQUE REFERENCES dtf_local.quotes(id), owner uuid NOT NULL,
|
|
snapshot jsonb NOT NULL, payment jsonb NOT NULL, state text NOT NULL DEFAULT 'rec',
|
|
version integer NOT NULL DEFAULT 0, created_at timestamptz NOT NULL DEFAULT now(),
|
|
updated_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.movements (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id),
|
|
from_state text NOT NULL, to_state text NOT NULL, operator text NOT NULL,
|
|
reason text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.outbox (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, event_key text NOT NULL UNIQUE,
|
|
provider text NOT NULL, payload jsonb NOT NULL, attempts integer NOT NULL DEFAULT 0,
|
|
available_at timestamptz NOT NULL DEFAULT now(), delivered_at timestamptz,
|
|
last_error text, receipt jsonb
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.accounts (
|
|
id uuid PRIMARY KEY, email text UNIQUE NOT NULL, password_hash text NOT NULL,
|
|
profile jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
-- Confirmed with an e-mailed code (at signup or on a change): only then does
|
|
-- the account bring guest orders placed with its CPF/CNPJ and e-mail.
|
|
ALTER TABLE dtf_local.accounts ADD COLUMN IF NOT EXISTS email_verified boolean NOT NULL DEFAULT false;
|
|
CREATE TABLE IF NOT EXISTS dtf_local.sessions (
|
|
id uuid PRIMARY KEY, owner uuid NOT NULL,
|
|
expires_at timestamptz NOT NULL DEFAULT now() + interval '7 days'
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.migrations (name text PRIMARY KEY);
|
|
-- Preserve pre-account guest sessions once, without resurrecting logged-out sessions.
|
|
DO $$ BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='customer-sessions-v1') THEN
|
|
INSERT INTO dtf_local.sessions(id,owner)
|
|
SELECT owner,owner FROM (
|
|
SELECT owner FROM dtf_local.orders UNION SELECT owner FROM dtf_local.quotes
|
|
UNION SELECT owner FROM dtf_local.uploads
|
|
) legacy ON CONFLICT DO NOTHING;
|
|
INSERT INTO dtf_local.migrations VALUES('customer-sessions-v1');
|
|
END IF;
|
|
END $$;
|
|
CREATE TABLE IF NOT EXISTS dtf_local.login_attempts (
|
|
key text PRIMARY KEY, attempts integer NOT NULL DEFAULT 0,
|
|
started_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.operator_sessions (
|
|
token_hash text PRIMARY KEY, username text NOT NULL,
|
|
expires_at timestamptz NOT NULL DEFAULT now() + interval '8 hours'
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.operators (
|
|
id uuid PRIMARY KEY, email text UNIQUE NOT NULL, name text NOT NULL DEFAULT '',
|
|
password_hash text NOT NULL, active boolean NOT NULL DEFAULT true,
|
|
created_at timestamptz NOT NULL DEFAULT now(), last_login_at timestamptz
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.payment_events (
|
|
id uuid PRIMARY KEY, provider text NOT NULL, event_id text NOT NULL,
|
|
reference text, status text NOT NULL, amount_cents bigint,
|
|
payload jsonb NOT NULL, received_at timestamptz NOT NULL DEFAULT now(),
|
|
processed_at timestamptz, outcome text,
|
|
UNIQUE(provider, event_id)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.security_events (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
event text NOT NULL, details jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS expires_at timestamptz;
|
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS purged_at timestamptz;
|
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS original_name text;
|
|
UPDATE dtf_local.uploads SET original_name=name WHERE original_name IS NULL;
|
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_state text NOT NULL DEFAULT 'pending';
|
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_reason text;
|
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scanned_at timestamptz;
|
|
ALTER TABLE dtf_local.uploads ADD COLUMN IF NOT EXISTS scan_after timestamptz NOT NULL DEFAULT now();
|
|
UPDATE dtf_local.uploads SET expires_at=created_at + interval '30 days' WHERE expires_at IS NULL;
|
|
ALTER TABLE dtf_local.uploads ALTER COLUMN expires_at SET DEFAULT now() + interval '30 days';
|
|
CREATE TABLE IF NOT EXISTS dtf_local.order_files (
|
|
id uuid PRIMARY KEY, order_id uuid NOT NULL REFERENCES dtf_local.orders(id),
|
|
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id), item_index integer NOT NULL,
|
|
kind text NOT NULL CHECK(kind IN ('final','correction')), active boolean NOT NULL DEFAULT true,
|
|
note text NOT NULL, created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
|
UNIQUE(order_id,upload_id,kind)
|
|
);
|
|
-- A payment started at the provider for an approved quote: which provider
|
|
-- payment belongs to which quote, and its latest known status.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.payment_intents (
|
|
id uuid PRIMARY KEY, quote_id uuid NOT NULL REFERENCES dtf_local.quotes(id),
|
|
provider text NOT NULL, provider_payment_id text NOT NULL, method text NOT NULL,
|
|
status text NOT NULL, amount_cents bigint NOT NULL, response jsonb NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
|
|
UNIQUE(provider, provider_payment_id)
|
|
);
|
|
-- OAuth connections to providers (Tiny). One row per provider; the refresh
|
|
-- token rotates on use, so it lives here, never in configuration.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.provider_tokens (
|
|
provider text PRIMARY KEY, access_token text NOT NULL, refresh_token text NOT NULL,
|
|
access_expires_at timestamptz NOT NULL, refresh_expires_at timestamptz,
|
|
connected_by text NOT NULL, connected_at timestamptz NOT NULL DEFAULT now(),
|
|
updated_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
-- Renewal health, cleared by the next successful renewal or connection.
|
|
-- refused_at: the provider rejected the refresh token, so only a new
|
|
-- connection helps. offline: the grant is not bound to a login session.
|
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refresh_failed_at timestamptz;
|
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refresh_error text;
|
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS refused_at timestamptz;
|
|
ALTER TABLE dtf_local.provider_tokens ADD COLUMN IF NOT EXISTS offline boolean NOT NULL DEFAULT false;
|
|
-- Single-use states for an operator-started OAuth connection. They protect the
|
|
-- callback, which arrives cross-site without the operator's cookie.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.oauth_states (
|
|
state text PRIMARY KEY, provider text NOT NULL, operator text NOT NULL,
|
|
expires_at timestamptz NOT NULL
|
|
);
|
|
-- The print file generated from each paid item's approved layout. One row per
|
|
-- item: the worker claims it, renders, and records either the file or why the
|
|
-- item has to be prepared by hand. Regenerating replaces the row's result.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.print_files (
|
|
id uuid PRIMARY KEY, order_id uuid NOT NULL REFERENCES dtf_local.orders(id),
|
|
item_index integer NOT NULL,
|
|
status text NOT NULL DEFAULT 'pending'
|
|
CHECK(status IN ('pending','rendering','ready','manual','failed')),
|
|
upload_id uuid REFERENCES dtf_local.uploads(id), detail jsonb NOT NULL DEFAULT '{}',
|
|
attempts integer NOT NULL DEFAULT 0, claimed_at timestamptz,
|
|
created_at timestamptz NOT NULL DEFAULT now(), finished_at timestamptz,
|
|
UNIQUE(order_id,item_index)
|
|
);
|
|
ALTER TABLE dtf_local.print_files ADD COLUMN IF NOT EXISTS claim_token uuid;
|
|
|
|
-- Each run of the off-server database backup (ops/db_backup.py), which the
|
|
-- Kanban shows so a backup that stopped working does not go unnoticed.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.backups (
|
|
id uuid PRIMARY KEY, started_at timestamptz NOT NULL, finished_at timestamptz NOT NULL,
|
|
status text NOT NULL CHECK(status IN ('ok','failed')), object_key text, bytes bigint, detail text
|
|
);
|
|
CREATE INDEX IF NOT EXISTS backups_finished ON dtf_local.backups(finished_at DESC);
|
|
-- "Fazer backup agora" in the Kanban; the backup service looks every minute.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.backup_requests (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, requested_at timestamptz NOT NULL DEFAULT now(),
|
|
requested_by text NOT NULL
|
|
);
|
|
|
|
-- Why a quote waits for review, when the reason came from its files (the grade
|
|
-- the server recomputed) and cannot be worked out again from the draft alone.
|
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS review_note text;
|
|
|
|
CREATE INDEX IF NOT EXISTS uploads_owner ON dtf_local.uploads(owner);
|
|
|
|
-- Indexes follow the queries the application actually issues. Only these; every
|
|
-- extra index is paid for on each write.
|
|
|
|
-- The customer portal lists a person's orders and open quotes, newest first.
|
|
CREATE INDEX IF NOT EXISTS orders_owner ON dtf_local.orders(owner, created_at DESC);
|
|
CREATE INDEX IF NOT EXISTS quotes_owner ON dtf_local.quotes(owner, created_at DESC);
|
|
|
|
-- Order detail and the movement history read by order.
|
|
CREATE INDEX IF NOT EXISTS movements_order ON dtf_local.movements(order_id, id);
|
|
CREATE INDEX IF NOT EXISTS order_files_order ON dtf_local.order_files(order_id);
|
|
-- submit_files checks whether an upload is already attached, by upload.
|
|
CREATE INDEX IF NOT EXISTS order_files_upload ON dtf_local.order_files(upload_id);
|
|
|
|
-- The worker polls this once a second, and the table only grows. Partial, so the
|
|
-- index stays the size of the backlog rather than of all history.
|
|
CREATE INDEX IF NOT EXISTS outbox_pending ON dtf_local.outbox(available_at, id)
|
|
WHERE delivered_at IS NULL;
|
|
-- The system sends no WhatsApp messages (the client's own n8n does, from Tiny):
|
|
-- its old log rows would wait for an adapter that no longer exists.
|
|
DELETE FROM dtf_local.outbox WHERE provider='whatsapp';
|
|
|
|
-- The scanner and the retention sweep both walk live uploads in arrival order.
|
|
-- now() cannot appear in a partial index predicate, so the time comparisons stay
|
|
-- in the query and the index narrows to rows still worth looking at.
|
|
CREATE INDEX IF NOT EXISTS uploads_live ON dtf_local.uploads(created_at)
|
|
WHERE purged_at IS NULL;
|
|
|
|
-- Sign-in transfers and logout delete a person's sessions by owner.
|
|
CREATE INDEX IF NOT EXISTS sessions_owner ON dtf_local.sessions(owner);
|
|
|
|
-- Disabling an operator revokes their open sessions by name.
|
|
CREATE INDEX IF NOT EXISTS operator_sessions_username ON dtf_local.operator_sessions(username);
|
|
|
|
-- security_status reads recent events; the worker prunes old ones by age.
|
|
CREATE INDEX IF NOT EXISTS security_events_created ON dtf_local.security_events(created_at);
|
|
|
|
-- The webhook looks an event up by provider and id on every delivery, and the
|
|
-- unique constraint already indexes that pair. Only the unprocessed sweep needs
|
|
-- its own index, and it stays the size of the backlog.
|
|
CREATE INDEX IF NOT EXISTS payment_events_unprocessed ON dtf_local.payment_events(received_at)
|
|
WHERE processed_at IS NULL;
|
|
|
|
-- The render worker polls for unclaimed or abandoned jobs; the order view reads
|
|
-- by order through the unique constraint.
|
|
CREATE INDEX IF NOT EXISTS print_files_open ON dtf_local.print_files(created_at)
|
|
WHERE status IN ('pending','rendering');
|
|
|
|
-- The generated files of each item (item 13, 2026-10-29): one PNG, or the parts
|
|
-- of a film over 15 m, in order. print_files.upload_id stays the first.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.print_parts (
|
|
order_id uuid NOT NULL, item_index integer NOT NULL, part integer NOT NULL CHECK(part >= 1),
|
|
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
|
|
PRIMARY KEY(order_id,item_index,part),
|
|
FOREIGN KEY(order_id,item_index) REFERENCES dtf_local.print_files(order_id,item_index) ON DELETE CASCADE
|
|
);
|
|
CREATE INDEX IF NOT EXISTS print_parts_upload ON dtf_local.print_parts(upload_id);
|
|
|
|
-- What each machine's hot folder gets (item 10, app/hotfolder.py): one row per
|
|
-- file or part, per entry into Imprimindo (round), written by one computer.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.hot_parts (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
|
round integer NOT NULL, seq integer NOT NULL, item_index integer NOT NULL,
|
|
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
|
|
name text NOT NULL, folder text,
|
|
state text NOT NULL DEFAULT 'queued'
|
|
CHECK(state IN ('queued','claimed','written','consumed','withdraw','gone')),
|
|
claimed_at timestamptz, claimed_by text, written_at timestamptz, done_at timestamptz,
|
|
created_at timestamptz NOT NULL DEFAULT now(),
|
|
UNIQUE(order_id, round, seq)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS hot_parts_open ON dtf_local.hot_parts(order_id)
|
|
WHERE state IN ('queued','claimed','written','withdraw');
|
|
INSERT INTO dtf_local.print_parts(order_id,item_index,part,upload_id)
|
|
SELECT order_id,item_index,1,upload_id FROM dtf_local.print_files WHERE upload_id IS NOT NULL
|
|
ON CONFLICT DO NOTHING;
|
|
|
|
-- A movement that undid an earlier one (a mistaken move), shown as such.
|
|
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS back boolean NOT NULL DEFAULT false;
|
|
CREATE INDEX IF NOT EXISTS movements_finished_latest ON dtf_local.movements(order_id, created_at DESC)
|
|
WHERE to_state='fin' AND NOT back;
|
|
|
|
-- The Kanban lists payment events a person must act on (money without an
|
|
-- order, or a reversed payment on an existing order) until resolved.
|
|
ALTER TABLE dtf_local.payment_events ADD COLUMN IF NOT EXISTS resolved_at timestamptz;
|
|
ALTER TABLE dtf_local.payment_events ADD COLUMN IF NOT EXISTS resolved_by text;
|
|
ALTER TABLE dtf_local.payment_events ADD COLUMN IF NOT EXISTS resolution text;
|
|
CREATE INDEX IF NOT EXISTS payment_events_open_issues ON dtf_local.payment_events(received_at)
|
|
WHERE (outcome LIKE 'refused%' OR outcome LIKE 'attention%') AND resolved_at IS NULL;
|
|
|
|
-- Payment intents look up by quote (customer retry) and by provider id (webhook).
|
|
CREATE INDEX IF NOT EXISTS payment_intents_quote ON dtf_local.payment_intents(quote_id, created_at DESC);
|
|
|
|
-- A small picture of each artwork (about 480 px), made by the customer's
|
|
-- browser from the file it already read, so the Kanban shows what an order is
|
|
-- without opening the original. It goes when the file's bytes go.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.upload_thumbnails (
|
|
upload_id uuid PRIMARY KEY REFERENCES dtf_local.uploads(id),
|
|
mime text NOT NULL, data bytea NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
|
|
-- An operator may discard an unpaid quote (it leaves the Kanban and can no
|
|
-- longer be paid) and cancel a paid order (it leaves the board but keeps its
|
|
-- payment and history; a refund is made at the provider).
|
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_at timestamptz;
|
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS discarded_by text;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_at timestamptz;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancelled_by text;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS cancel_reason text;
|
|
|
|
-- An order's place in its column's queue, when an operator dragged it up or
|
|
-- down. Empty means "by payment time"; it is cleared when the order moves on.
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS queue_key double precision;
|
|
|
|
-- The company name behind each customer's CNPJ, from the public registry
|
|
-- (app/cnpj.py). failed_at alone: the lookup failed and is retried later.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.cnpj_names (
|
|
cnpj text PRIMARY KEY, legal_name text, trade_name text,
|
|
fetched_at timestamptz, failed_at timestamptz
|
|
);
|
|
|
|
-- Who may do what on the Kanban. superadmin is the system's own account (set
|
|
-- from the console); administrators manage users and machines; gestão runs
|
|
-- the business; designers approve artwork; operadores print; revisores check
|
|
-- the printed sheet and are the only ones to release it to Finalizado;
|
|
-- vendedores only read.
|
|
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS role text NOT NULL DEFAULT 'admin';
|
|
ALTER TABLE dtf_local.operators DROP CONSTRAINT IF EXISTS operators_role;
|
|
ALTER TABLE dtf_local.operators ADD CONSTRAINT operators_role
|
|
CHECK (role IN ('superadmin','admin','gestao','designer','operador','revisor','vendedor','financeiro'));
|
|
-- Print machines and which products each prints. An order gets its machine
|
|
-- when someone pulls it into Imprimindo; no machine is assigned at payment.
|
|
-- limit_metres remains the load shown for a machine.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.machines (
|
|
id uuid PRIMARY KEY, name text UNIQUE NOT NULL, products text[] NOT NULL DEFAULT '{}',
|
|
active boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS limit_metres numeric(8,1) CHECK (limit_metres > 0);
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS machine_chosen boolean NOT NULL DEFAULT false;
|
|
-- Until now only a person's choice was stored.
|
|
DO $$ BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-chosen-v1') THEN
|
|
UPDATE dtf_local.orders SET machine_chosen=true WHERE machine_id IS NOT NULL;
|
|
INSERT INTO dtf_local.migrations VALUES('machine-chosen-v1');
|
|
END IF;
|
|
END $$;
|
|
-- Remove the old automatic suggestions before printing. Keep real choices
|
|
-- and machines already printing, whose hot-folder files may be in flight.
|
|
DO $$ BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='machine-pull-only-v1') THEN
|
|
UPDATE dtf_local.orders SET machine_id=NULL, machine_chosen=false
|
|
WHERE NOT machine_chosen AND state IN ('rec','tra','cor');
|
|
INSERT INTO dtf_local.migrations VALUES('machine-pull-only-v1');
|
|
END IF;
|
|
END $$;
|
|
-- Acceptable time per stage (front 11): Gestão edits these; a card past the
|
|
-- limit turns yellow, at twice the limit red. `responsible` is who the board
|
|
-- names for that column. The final stage counts days without pickup.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.stage_limits (
|
|
state text PRIMARY KEY CHECK (state IN ('rec','tra','imp','rev','fin')),
|
|
hours numeric NOT NULL CHECK (hours > 0),
|
|
responsible text NOT NULL DEFAULT '',
|
|
updated_by text NOT NULL DEFAULT 'sistema',
|
|
updated_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
-- Videos are uploaded by Gestão; the Site reads only enabled, scanned files.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.site_videos (
|
|
id text PRIMARY KEY CHECK (id IN ('subindo','nota','png','avulsas','retirada','sala')),
|
|
upload_id uuid REFERENCES dtf_local.uploads(id),
|
|
captions_id uuid REFERENCES dtf_local.uploads(id),
|
|
video_key text,
|
|
captions_key text,
|
|
product text CHECK (product IN ('file','avulsa','uvfile','uv')),
|
|
enabled boolean NOT NULL DEFAULT false,
|
|
updated_by text NOT NULL DEFAULT 'sistema',
|
|
updated_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS video_key text;
|
|
ALTER TABLE dtf_local.site_videos ADD COLUMN IF NOT EXISTS captions_key text;
|
|
INSERT INTO dtf_local.stage_limits(state,hours,responsible) VALUES
|
|
('rec',2,'Designer'), ('tra',6,'Operador'), ('imp',4,'Operador'),
|
|
('rev',2,'Revisor'), ('fin',72,'Atendimento')
|
|
ON CONFLICT (state) DO NOTHING;
|
|
|
|
-- The machines an operator works on; none means every machine.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.operator_machines (
|
|
operator_id uuid NOT NULL REFERENCES dtf_local.operators(id) ON DELETE CASCADE,
|
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
|
PRIMARY KEY (operator_id, machine_id)
|
|
);
|
|
|
|
|
|
-- E-mail (app/mail.py): queued in the transaction that caused it, sent by the
|
|
-- worker. A recovery message's text is erased once sent; the subject stays.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.mail_queue (
|
|
id bigserial PRIMARY KEY, kind text NOT NULL,
|
|
to_addr text NOT NULL, subject text NOT NULL, body text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT now(), available_at timestamptz NOT NULL DEFAULT now(),
|
|
attempts int NOT NULL DEFAULT 0, last_error text, sent_at timestamptz, failed_at timestamptz
|
|
);
|
|
-- The HTML version of a customer message (app/mail_html.py); erased with the
|
|
-- text for a code or a recovery link.
|
|
ALTER TABLE dtf_local.mail_queue ADD COLUMN IF NOT EXISTS html text;
|
|
CREATE INDEX IF NOT EXISTS mail_queue_pending ON dtf_local.mail_queue(available_at, id)
|
|
WHERE sent_at IS NULL AND failed_at IS NULL;
|
|
-- A customer's password recovery: only the token's hash is kept, for an hour,
|
|
-- and it works once.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.password_resets (
|
|
token_hash text PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
|
|
created_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL, used_at timestamptz
|
|
);
|
|
CREATE INDEX IF NOT EXISTS password_resets_account ON dtf_local.password_resets(account_id);
|
|
-- Kanban users who get the team's alerts by e-mail.
|
|
ALTER TABLE dtf_local.operators ADD COLUMN IF NOT EXISTS alerts boolean NOT NULL DEFAULT false;
|
|
|
|
-- "Aguardando contato": an order whose file needs a word with the customer
|
|
-- before printing. A mark on the card, not a stage: the order stays where it is.
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_since timestamptz;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_by text;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contact_note text;
|
|
|
|
-- A signup waiting for its e-mail code. The account is created only when the
|
|
-- code is entered; the password is already hashed and the code only hashed.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.account_signups (
|
|
id uuid PRIMARY KEY, email text NOT NULL, profile jsonb NOT NULL, password_hash text NOT NULL,
|
|
code_hash text, created_at timestamptz NOT NULL DEFAULT now(), sent_at timestamptz NOT NULL DEFAULT now(),
|
|
expires_at timestamptz NOT NULL, sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0,
|
|
done_at timestamptz
|
|
);
|
|
CREATE INDEX IF NOT EXISTS account_signups_created ON dtf_local.account_signups(created_at);
|
|
|
|
-- A customer changing the account's e-mail: the change waits for the code sent
|
|
-- to the new address, as a signup does, and the old address is told.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.email_changes (
|
|
id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES dtf_local.accounts(id) ON DELETE CASCADE,
|
|
new_email text NOT NULL, code_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
|
sent_at timestamptz NOT NULL DEFAULT now(), expires_at timestamptz NOT NULL,
|
|
sends int NOT NULL DEFAULT 1, attempts int NOT NULL DEFAULT 0, done_at timestamptz
|
|
);
|
|
-- Accounts confirmed by a code before email_verified existed. The signups
|
|
-- are deleted after a day; the code e-mail sent before the account existed
|
|
-- stays in the queue.
|
|
UPDATE dtf_local.accounts a SET email_verified=true WHERE NOT a.email_verified AND (
|
|
EXISTS (SELECT 1 FROM dtf_local.account_signups s WHERE s.email=a.email AND s.done_at IS NOT NULL)
|
|
OR EXISTS (SELECT 1 FROM dtf_local.email_changes e WHERE e.account_id=a.id AND e.new_email=a.email AND e.done_at IS NOT NULL)
|
|
OR EXISTS (SELECT 1 FROM dtf_local.mail_queue m WHERE m.kind='code' AND lower(m.to_addr)=a.email
|
|
AND m.created_at<=a.created_at));
|
|
-- E-mail kinds: a password-recovery link, a code, the notice that an account
|
|
-- already exists, the notice of a changed e-mail, a customer's paid order,
|
|
-- the team's alerts and a test.
|
|
-- Defined once, here: the schema runs on every start, and an earlier, narrower
|
|
-- copy would refuse the rows of the kinds added after it.
|
|
ALTER TABLE dtf_local.mail_queue DROP CONSTRAINT IF EXISTS mail_queue_kind_check;
|
|
ALTER TABLE dtf_local.mail_queue ADD CONSTRAINT mail_queue_kind_check
|
|
CHECK(kind IN ('reset','code','account','notice','order','alert','test'));
|
|
|
|
-- The print proof (Dropstar, 2026-10-21): an order above 10 m, or one whose
|
|
-- customer asked for a proof at checkout, prints 20 cm first; the room marks
|
|
-- "Prova OK" once it is checked, and without it the order does not reach
|
|
-- Finalizado.
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_at timestamptz;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_ok_by text;
|
|
|
|
-- Fila de impressão left the board (Dropstar, 2026-10-23): Arte conferida is
|
|
-- the queue. An order still in it moves there once, with a line in its history.
|
|
WITH moved AS (UPDATE dtf_local.orders SET state='tra', version=version+1, updated_at=now()
|
|
WHERE state='fil' RETURNING id)
|
|
INSERT INTO dtf_local.movements(order_id,from_state,to_state,operator,reason)
|
|
SELECT id,'fil','tra','sistema','A Fila de impressão saiu do quadro: Arte conferida é a fila.' FROM moved;
|
|
|
|
-- Each time an order waited for a word with the customer ("Aguardando
|
|
-- contato"): that wait has no deadline and does not count in the time figures
|
|
-- of Números (Dropstar's rule D-38, 2026-10-26). An open wait has no end. The
|
|
-- waits already open when this table came are recorded from their start.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.contact_waits (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
|
started_at timestamptz NOT NULL, ended_at timestamptz
|
|
);
|
|
CREATE INDEX IF NOT EXISTS contact_waits_order ON dtf_local.contact_waits(order_id);
|
|
INSERT INTO dtf_local.contact_waits(order_id, started_at)
|
|
SELECT o.id, o.contact_since FROM dtf_local.orders o
|
|
WHERE o.contact_since IS NOT NULL AND NOT EXISTS (SELECT 1 FROM dtf_local.contact_waits w WHERE w.order_id=o.id);
|
|
|
|
-- Every card is born with its origin (Dropstar's rules D-21 and D-35,
|
|
-- 2026-10-26): site, dropflow (the montador's batches) or atendimento (an
|
|
-- order the team enters). No order without one, and no default: a default
|
|
-- would become the origin of almost everything, so each way in names its own.
|
|
-- The orders from before this column all came from the Site.
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS origin text;
|
|
UPDATE dtf_local.orders SET origin='site' WHERE origin IS NULL;
|
|
ALTER TABLE dtf_local.orders ALTER COLUMN origin SET NOT NULL;
|
|
ALTER TABLE dtf_local.orders DROP CONSTRAINT IF EXISTS orders_origin_check;
|
|
ALTER TABLE dtf_local.orders ADD CONSTRAINT orders_origin_check CHECK (origin IN ('site','dropflow','atendimento'));
|
|
|
|
-- Rework (Dropstar's rules D-02 to D-04, 2026-10-26; the user's answers of
|
|
-- 2026-10-27). Gestão opens it with its cause, and the cause never changes
|
|
-- after (D-03); an Administrador authorizes or declines it, never one they
|
|
-- opened, and only an authorized rework counts. Bad art the customer approved
|
|
-- is recorded apart, outside the goal (D-04). printed_by is who sent the
|
|
-- sheet to Revisão, as the rework enters the printer's pay.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.reworks (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
|
cause text NOT NULL CHECK (cause IN ('impressao','perfil_cor','tratamento','pedido','arte_cliente')),
|
|
metres numeric NOT NULL CHECK (metres > 0),
|
|
note text NOT NULL DEFAULT '',
|
|
printed_by text,
|
|
opened_by text NOT NULL, opened_at timestamptz NOT NULL DEFAULT now(),
|
|
authorized boolean, decided_by text, decided_at timestamptz, decline_reason text
|
|
);
|
|
CREATE INDEX IF NOT EXISTS reworks_order ON dtf_local.reworks(order_id);
|
|
|
|
-- The pickup receipt (Dropstar's third round, item 14, 2026-10-29): due when
|
|
-- an order to be picked up reaches Finalizado; one computer's folder claims
|
|
-- it and saves the PDF in Recibos/, where the counter's print queue sends it
|
|
-- to the Bematech. Claimed once, so it is never printed twice.
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_due_at timestamptz;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_at timestamptz;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS receipt_saved_by text;
|
|
-- "Retirado": when, who handed it over and, optionally, a photo of the
|
|
-- signed receipt. Finalizado means ready; this means delivered.
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_at timestamptz;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_by text;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS picked_up_photo uuid REFERENCES dtf_local.uploads(id) ON DELETE SET NULL;
|
|
|
|
-- The machine a session works on (Dropstar's third round, item 12, 2026-10-30):
|
|
-- chosen after signing in, per session, so one person may be on two machines,
|
|
-- one per computer. machine_answered: the question was answered, "Não estou em
|
|
-- máquina" included. The links Usuários showed before (operator_machines)
|
|
-- are no longer read.
|
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_id uuid REFERENCES dtf_local.machines(id) ON DELETE SET NULL;
|
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_at timestamptz;
|
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS machine_answered boolean NOT NULL DEFAULT false;
|
|
-- The contraction class chosen per item (item 9), keyed by item index, with
|
|
-- who chose it and when; the measured class stays in the order's snapshot.
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS contraction jsonb NOT NULL DEFAULT '{}'::jsonb;
|
|
|
|
-- The proof card (Dropstar, 2026-10-30, app/proof.py): an order of its own,
|
|
-- child of the order it proves, with no quote of its own; its answer, Prova OK
|
|
-- or reprovada with its reason, by whom and when.
|
|
ALTER TABLE dtf_local.orders ALTER COLUMN quote_id DROP NOT NULL;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS parent_id uuid REFERENCES dtf_local.orders(id) ON DELETE CASCADE;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_result text CHECK (proof_result IN ('ok','rejected'));
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_at timestamptz;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_decided_by text;
|
|
ALTER TABLE dtf_local.orders ADD COLUMN IF NOT EXISTS proof_reason text;
|
|
CREATE INDEX IF NOT EXISTS orders_parent ON dtf_local.orders(parent_id) WHERE parent_id IS NOT NULL;
|
|
-- An order's own rows go with it, so deleting an order takes its proof cards
|
|
-- and theirs too. Done once: a constraint already cascading is left alone.
|
|
DO $$
|
|
DECLARE r record;
|
|
BEGIN
|
|
FOR r IN SELECT c.conname, c.conrelid::regclass AS tbl FROM pg_constraint c
|
|
WHERE c.contype='f' AND c.confrelid='dtf_local.orders'::regclass AND c.confdeltype<>'c'
|
|
AND c.conrelid IN ('dtf_local.movements'::regclass, 'dtf_local.order_files'::regclass,
|
|
'dtf_local.print_files'::regclass)
|
|
LOOP
|
|
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', r.tbl, r.conname);
|
|
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I FOREIGN KEY (order_id) REFERENCES dtf_local.orders(id) ON DELETE CASCADE',
|
|
r.tbl, r.conname);
|
|
END LOOP;
|
|
END $$;
|
|
-- When the session was last used (Usuários: who is on the system now).
|
|
ALTER TABLE dtf_local.operator_sessions ADD COLUMN IF NOT EXISTS seen_at timestamptz;
|
|
-- The machine of whoever moved a card, as it was named then: "Imprimindo ·
|
|
-- Thales · máquina2".
|
|
ALTER TABLE dtf_local.movements ADD COLUMN IF NOT EXISTS machine text;
|
|
|
|
-- An approved quote nobody paid in 24 h expires (Fase 2, front 9, app/unpaid.py).
|
|
ALTER TABLE dtf_local.quotes ADD COLUMN IF NOT EXISTS expired_at timestamptz;
|
|
|
|
-- The Revisor's photo or short video of the printed sheet (Fase 2, front 2,
|
|
-- app/reviews.py): DTF-<n>-revisao-<seq>, the record of when and by whom it
|
|
-- was checked. A photo is required to finish an order above 1 m.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.order_reviews (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
order_id uuid NOT NULL REFERENCES dtf_local.orders(id) ON DELETE CASCADE,
|
|
seq integer NOT NULL CHECK(seq >= 1),
|
|
upload_id uuid NOT NULL REFERENCES dtf_local.uploads(id) ON DELETE CASCADE,
|
|
kind text NOT NULL CHECK(kind IN ('photo','video')),
|
|
width integer, height integer,
|
|
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
|
|
UNIQUE(order_id, seq)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS order_reviews_order ON dtf_local.order_reviews(order_id);
|
|
|
|
-- Each machine's sheet (Fase 2, front 1, app/machine_log.py): what it cost and
|
|
-- when it started, typed once by Gestão; what goes into it, entered by the
|
|
-- room; and the minimum of each supply that raises the alert.
|
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS price_cents bigint CHECK (price_cents >= 0);
|
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS installed_on date;
|
|
-- When the counters start: a machine with no cleaning on record counts from
|
|
-- here, not from everything it printed before the sheet existed.
|
|
ALTER TABLE dtf_local.machines ADD COLUMN IF NOT EXISTS log_since timestamptz NOT NULL DEFAULT now();
|
|
CREATE TABLE IF NOT EXISTS dtf_local.machine_entries (
|
|
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
|
kind text NOT NULL CHECK(kind IN ('supply','part','event')),
|
|
item text NOT NULL,
|
|
quantity numeric(12,3) CHECK (quantity > 0),
|
|
cost_cents bigint CHECK (cost_cents >= 0),
|
|
serial text, note text,
|
|
stop_minutes integer CHECK (stop_minutes > 0),
|
|
from_alert boolean NOT NULL DEFAULT false,
|
|
created_by text NOT NULL, created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS machine_entries_machine ON dtf_local.machine_entries(machine_id, created_at);
|
|
CREATE TABLE IF NOT EXISTS dtf_local.machine_minimums (
|
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
|
item text NOT NULL, minimum numeric(12,3) NOT NULL CHECK (minimum >= 0),
|
|
PRIMARY KEY(machine_id, item)
|
|
);
|
|
-- "Adiar uma vez": an alert postponed lets one more card be pulled, once per
|
|
-- cycle (the cycle starts at the event that resets its counter).
|
|
CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes (
|
|
machine_id uuid NOT NULL REFERENCES dtf_local.machines(id) ON DELETE CASCADE,
|
|
alert text NOT NULL, cycle_from timestamptz NOT NULL,
|
|
snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(),
|
|
PRIMARY KEY(machine_id, alert, cycle_from)
|
|
);
|
|
|
|
-- Front 8: what the Site sells and at what price, edited in the Kanban's Site tab.
|
|
CREATE TABLE IF NOT EXISTS dtf_local.products (
|
|
id text PRIMARY KEY CHECK (id IN ('file','avulsa','uvfile','uv','tratamento')),
|
|
enabled boolean NOT NULL DEFAULT true,
|
|
updated_by text NOT NULL DEFAULT 'sistema',
|
|
updated_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
INSERT INTO dtf_local.products(id) VALUES ('file'),('avulsa'),('uvfile'),('uv'),('tratamento')
|
|
ON CONFLICT (id) DO NOTHING;
|
|
CREATE TABLE IF NOT EXISTS dtf_local.product_prices (
|
|
id bigserial PRIMARY KEY,
|
|
product text NOT NULL REFERENCES dtf_local.products(id),
|
|
unit_cents integer NOT NULL CHECK (unit_cents >= 0 AND unit_cents <= 10000000),
|
|
starts_at timestamptz NOT NULL,
|
|
created_by text NOT NULL,
|
|
created_at timestamptz NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS product_prices_current ON dtf_local.product_prices(product, starts_at DESC);
|