feat: a launch cleanup that clears the test orders, run once by hand

ops.launch_reset counts the orders, quotes, payment attempts and
notifications, and with --confirmar APAGAR removes them, with their moves,
files and notices. The artwork files are marked expired so the worker
deletes them from storage. Operators, the Tiny connection and the backups
stay; --contas also removes customer accounts. It refuses if any payment
was made with real money. Order numbers restart at #1 with the database
administrator's rights, so the script prints the psql line for the db
container when the worker's role cannot do it.

The test runs last in CI, since it empties the order tables.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-05 12:07:24 -03:00
parent 1b445f0459
commit b1fbaad2bd
4 changed files with 152 additions and 1 deletions

View File

@@ -73,7 +73,7 @@ jobs:
# one a developer exercises on localhost.
- name: API and workflow regressions
run: |
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test; do
for suite in smoke_test workflow_test security_test scanning_test payment_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test launch_reset_test; do
echo "--- $suite"
$COMPOSE exec -T \
-e SITE_BASE_URL=http://site \

View File

@@ -175,6 +175,21 @@ SHA of the last known-good Gitea commit and redeploy. This rolls back Site, API,
Kanban, and worker code; it does not undo database migrations or restore data.
After recovery and a corrected release, return `IMAGE_TAG` to `latest`.
## 6. Before opening to customers
Once, right before launch, clear the test orders from the worker's console
(Containers > worker > Console):
```bash
python -m ops.launch_reset # only counts
python -m ops.launch_reset --confirmar APAGAR # removes orders, quotes and payments
```
It refuses if any payment was made with real money. Order numbers restart at
#1 only with the database administrator: the script prints the `psql` line to
run in the `db` container's console. Add `--contas` to remove the test
customer accounts too.
## Current blocker
This is the final deployment shape, but it is not authorized for production

83
ops/launch_reset.py Normal file
View File

@@ -0,0 +1,83 @@
"""Clear the test orders before the Site opens to customers, once, by hand.
Run from the worker's console (Portainer > Containers > worker > Console):
python -m ops.launch_reset shows what would be removed
python -m ops.launch_reset --confirmar APAGAR removes it
python -m ops.launch_reset --confirmar APAGAR --contas also customer accounts
Removes every order with its moves, files and notices, every quote, payment
attempt and payment notification, and the artwork pictures. The artwork
files are marked expired, so the worker deletes them from storage within a
minute. Operators, the Tiny connection and the backups are kept.
It refuses if any payment was made with real money (Mercado Pago's
live_mode): those are customers' orders, not tests.
Order numbers start again at #1 only with the database administrator's
rights, which the worker does not have. The script prints the one command
to run in the database container's console for that.
"""
import argparse
import sys
from app.core import db
TABLES = [ # in an order the foreign keys allow
('movements', 'movimentos de etapa'),
('order_files', 'arquivos finais e correções'),
('print_files', 'arquivos de impressão gerados'),
('outbox', 'envios ao Tiny e avisos'),
('orders', 'pedidos'),
('payment_intents', 'tentativas de pagamento'),
('payment_events', 'avisos de pagamento'),
('quotes', 'cotações'),
('upload_thumbnails', 'miniaturas das artes'),
]
ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')]
CONFIRM = 'APAGAR'
RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;'
def counts(c, tables):
return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables}
def main(argv=None, out=print, connect=db.connect):
parser = argparse.ArgumentParser(prog='python -m ops.launch_reset')
parser.add_argument('--confirmar', default='', help=f'escreva {CONFIRM} para apagar')
parser.add_argument('--contas', action='store_true', help='apagar também as contas de clientes')
args = parser.parse_args(argv)
tables = TABLES + (ACCOUNTS if args.contas else [])
with connect() as c:
live = c.execute("""SELECT count(*) AS n FROM dtf_local.payment_intents
WHERE response->>'live_mode'='true'""").fetchone()['n']
if live:
out(f'Recusado: {live} pagamento(s) com dinheiro real (live_mode). Esses pedidos são de clientes.')
return 1
before = counts(c, tables)
files = c.execute('SELECT count(*) AS n FROM dtf_local.uploads WHERE purged_at IS NULL').fetchone()['n']
for table, label in tables:
out(f'{before[table]:>7} {label}')
out(f'{files:>7} arquivos de arte (o worker apaga do armazenamento)')
if args.confirmar != CONFIRM:
out(f'Nada foi apagado. Repita com --confirmar {CONFIRM} para apagar.')
return 0
for table, _ in tables:
c.execute(f'DELETE FROM dtf_local.{table}')
c.execute('UPDATE dtf_local.uploads SET expires_at=now() WHERE purged_at IS NULL')
out('Apagado.')
try:
with connect() as c:
c.execute(RESTART)
out('A numeração dos pedidos recomeça em #1.')
except Exception as exc: # the application's role cannot alter the table
if 'permission' not in str(exc).lower() and 'owner' not in str(exc).lower():
raise
out('Para a numeração recomeçar em #1, rode no console do container do banco (db):')
out(f' psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "{RESTART}"')
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@@ -0,0 +1,53 @@
"""The launch cleanup removes test orders and refuses when real money was paid.
It empties the order tables, so it runs last. Run inside the API container:
python -m tests.launch_reset_test
"""
from uuid import uuid4
from psycopg.types.json import Jsonb
from app.core import db
from ops import launch_reset
def run():
quote, order, owner = uuid4(), uuid4(), uuid4()
with db.connect() as c:
c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at)
VALUES(%s,%s,%s,'reset-fixture',%s,%s,now())''',
(quote, owner, uuid4(), Jsonb({'customer': {}, 'items': []}), Jsonb({'items': [], 'total_cents': 1490})))
c.execute('INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment) VALUES(%s,%s,%s,%s,%s)',
(order, quote, owner, Jsonb({'items': [], 'total_cents': 1490}), Jsonb({'provider': 'teste'})))
live = c.execute('''INSERT INTO dtf_local.payment_intents(id,quote_id,provider,provider_payment_id,method,
status,amount_cents,response) VALUES(%s,%s,'mercadopago',%s,'card','approved',1490,%s) RETURNING id''',
(uuid4(), quote, str(uuid4()), Jsonb({'live_mode': True}))).fetchone()['id']
lines = []
# Real money paid: nothing happens, even when confirmed.
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 1
assert 'dinheiro real' in lines[-1]
with db.connect() as c:
c.execute("UPDATE dtf_local.payment_intents SET response='{\"live_mode\": false}' WHERE id=%s", (live,))
# Without the word, it only counts.
lines.clear()
assert launch_reset.main([], out=lines.append) == 0
assert 'Nada foi apagado' in lines[-1]
with db.connect() as c:
assert c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (order,)).fetchone()
lines.clear()
assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 0, lines
with db.connect() as c:
for table in ('orders', 'quotes', 'payment_intents', 'movements', 'outbox'):
assert c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] == 0, table
assert not c.execute('''SELECT 1 FROM dtf_local.uploads WHERE purged_at IS NULL
AND expires_at>now()''').fetchone()
assert c.execute('SELECT count(*) AS n FROM dtf_local.operators').fetchone()['n'] >= 1
assert 'Apagado.' in lines and any('#1' in line for line in lines), lines
print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes')
if __name__ == '__main__':
run()