From 2bcdb060fda53940c2f2f7952ff1a6e87386b27b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Fri, 6 Nov 2026 11:11:36 -0300 Subject: [PATCH] feat: the launch reset keeps the order numbering and clears the folders (0.11) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The existing launch_reset now also empties the Kanban flow folders, keeps Estampas/, and no longer restarts orders.number: DTF-1…DTF-15 already exist in Tiny. It still refuses real money, counts first and needs APAGAR. --- app/bootstrap.py | 7 +-- ops/launch_reset.py | 66 ++++++++++++++++++--------- ops/reset_board.py | 92 -------------------------------------- tests/launch_reset_test.py | 27 +++++++++-- tests/test_reset_board.py | 32 ------------- 5 files changed, 71 insertions(+), 153 deletions(-) delete mode 100644 ops/reset_board.py delete mode 100644 tests/test_reset_board.py diff --git a/app/bootstrap.py b/app/bootstrap.py index 7ed1a3d..4150df2 100644 --- a/app/bootstrap.py +++ b/app/bootstrap.py @@ -46,11 +46,8 @@ def main(): c.execute(sql.SQL('GRANT USAGE ON SCHEMA dtf_local TO {}').format(sql.Identifier(role))) c.execute(sql.SQL('GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role))) c.execute(sql.SQL('GRANT USAGE,SELECT ON ALL SEQUENCES IN SCHEMA dtf_local TO {}').format(sql.Identifier(role))) - # ops.launch_reset starts the order numbers again at #1 (setval), once - # the test orders are gone; nothing else may change a sequence. - numbers = c.execute("SELECT pg_get_serial_sequence('dtf_local.orders','number')").fetchone()[0] - c.execute(sql.SQL('GRANT UPDATE ON SEQUENCE {} TO {}').format( - sql.Identifier(*numbers.split('.', 1)), sql.Identifier(role))) + # The order identity sequence is never reset: DTF-1…DTF-15 already + # exist as Tiny order numbers (Dropstar, 2026-11-05). # Turn the configured credential into a real account so an existing # deployment keeps logging in exactly as before. Inserts only when that # email is absent, so a password changed with local.operators is never diff --git a/ops/launch_reset.py b/ops/launch_reset.py index 9110691..8fd8fc3 100644 --- a/ops/launch_reset.py +++ b/ops/launch_reset.py @@ -1,28 +1,38 @@ -"""Clear the test orders before the Site opens to customers, once, by hand. +"""Clear the test board 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 + python -m ops.launch_reset --root /srv/Kanban --confirmar APAGAR + also empties the flow folders -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. +Removes every order with its moves, files, notices and history, 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, machines, prices, 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. A database set up before the worker could -do that prints the one command to run in the database container's console. +The order numbering is **not** reset (Dropstar, 2026-11-05): DTF-1…DTF-15 +already exist as Tiny order numbers. DELETE keeps the identity sequence, so +the next card continues from where it stopped. """ import argparse +import shutil import sys +from pathlib import Path from app.core import db TABLES = [ # in an order the foreign keys allow + ('hot_parts', 'peças nas pastas das máquinas'), + ('print_parts', 'partes dos arquivos de impressão'), + ('reworks', 'retrabalhos'), + ('contact_waits', 'esperas de contato'), ('movements', 'movimentos de etapa'), ('order_files', 'arquivos finais e correções'), ('print_files', 'arquivos de impressão gerados'), @@ -34,20 +44,38 @@ TABLES = [ # in an order the foreign keys allow ('upload_thumbnails', 'miniaturas das artes'), ] ACCOUNTS = [('sessions', 'sessões de clientes'), ('accounts', 'contas de clientes')] +FLOW_FOLDERS = ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo', + '4. Revisão', '5. Finalizado', 'Recibos', 'Revisões') CONFIRM = 'APAGAR' -RESTART = 'ALTER TABLE dtf_local.orders ALTER COLUMN number RESTART WITH 1;' -# What the worker's role may do itself (app/bootstrap.py grants it). -RENUMBER = "SELECT setval(pg_get_serial_sequence('dtf_local.orders','number'), 1, false)" def counts(c, tables): return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] for table, _ in tables} +def clean_folders(root, dry_run=True): + """Empty the flow folders under `root`, recreating them; keep Estampas/.""" + root = Path(root) + if not any((root / name).exists() for name in FLOW_FOLDERS): + raise SystemExit(f'{root} does not look like the Kanban root: no flow folders found.') + if dry_run: + return [str(root / name) for name in FLOW_FOLDERS if (root / name).exists()] + cleaned = [] + for name in FLOW_FOLDERS: + path = root / name + if path.is_dir(): + shutil.rmtree(path) + path.mkdir(parents=True, exist_ok=True) + cleaned.append(str(path)) + return cleaned + + 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') + parser.add_argument('--root', type=Path, help='raiz Kanban, a pasta com "1. Arte recebida"') + parser.add_argument('--keep-files', action='store_true', help='não mexer nas pastas do Kanban') args = parser.parse_args(argv) tables = TABLES + (ACCOUNTS if args.contas else []) with connect() as c: @@ -61,22 +89,20 @@ def main(argv=None, out=print, connect=db.connect): 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.root and not args.keep_files: + out('Pastas que serão esvaziadas:') + for folder in clean_folders(args.root, dry_run=True): + out(f' {folder}') 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(RENUMBER) - 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}"') + if args.root and not args.keep_files: + for folder in clean_folders(args.root, dry_run=False): + out(f'esvaziada {folder}') + out('Apagado. A numeração dos pedidos continua de onde parou.') return 0 diff --git a/ops/reset_board.py b/ops/reset_board.py deleted file mode 100644 index 0f9a464..0000000 --- a/ops/reset_board.py +++ /dev/null @@ -1,92 +0,0 @@ -"""0.11 — wipe the board before the site is announced, keeping the setup. - -Deletes orders, quotes, cards, uploads and their history; keeps operators, -machines, integrations, prices, categories and the Tiny ids. Numbering is not -reset: orders.number is an identity column and DELETE keeps its sequence, as -the PDF requires (DTF-1…DTF-15 already exist in Tiny). - -The Kanban folders are written by the browser, so the server cannot discover -them: pass the same root the Kanban's folder setting points at. Only the flow -folders and Recibos/ are emptied; Estampas/ (the art library) stays. - -Dry run by default. To execute:: - - python -m ops.reset_board --root /srv/Kanban --yes - -Run inside the API container or with DATABASE_URL set. -""" -import argparse -import shutil -import sys -from pathlib import Path - -from app.core.db import connect - -# Children before parents; uploads after every row that references them. -TABLES = ( - 'hot_parts', 'print_parts', 'print_files', 'order_files', 'movements', - 'reworks', 'contact_waits', 'outbox', 'payment_intents', 'orders', 'quotes', - 'upload_thumbnails', 'uploads', -) -# payment_events has no foreign key to orders/quotes, but it is payment history. -HISTORY = ('payment_events',) -FLOW_FOLDERS = ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo', - '4. Revisão', '5. Finalizado', 'Recibos', 'Revisões') - - -def counts(c): - return {table: c.execute(f'SELECT count(*) AS n FROM dtf_local.{table}').fetchone()['n'] - for table in TABLES + HISTORY} - - -def clean_folders(root, dry_run=True): - """Empty the flow folders under `root`, recreating them; keep Estampas/.""" - root = Path(root) - if not any((root / name).exists() for name in FLOW_FOLDERS): - raise SystemExit(f'{root} does not look like the Kanban root: no flow folders found.') - if dry_run: - return [str(root / name) for name in FLOW_FOLDERS if (root / name).exists()] - cleaned = [] - for name in FLOW_FOLDERS: - path = root / name - if path.is_dir(): - shutil.rmtree(path) - path.mkdir(parents=True, exist_ok=True) - cleaned.append(str(path)) - return cleaned - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--root', type=Path, help='Kanban root folder (the one with 1. Arte recebida)') - parser.add_argument('--yes', action='store_true', help='execute; without it, only report') - parser.add_argument('--keep-files', action='store_true', help='leave the Kanban folders untouched') - args = parser.parse_args(argv) - dry = not args.yes - with connect() as c: - before = counts(c) - if dry: - print('DRY RUN — nothing was deleted.') - for table, number in before.items(): - print(f' {table}: {number}') - if args.root and not args.keep_files: - print('Folders that would be emptied:') - for folder in clean_folders(args.root, dry_run=True): - print(f' {folder}') - print('Run again with --yes to execute.') - return - for table in TABLES + HISTORY: - c.execute(f'DELETE FROM dtf_local.{table}') - c.execute('ANALYZE') - after = counts(c) - for table in TABLES + HISTORY: - print(f'{table}: {before[table]} -> {after[table]}') - if args.root and not args.keep_files: - for folder in clean_folders(args.root, dry_run=False): - print(f'emptied {folder}') - print('Board wiped. Orders.number was not reset; the next card continues the sequence.') - return 0 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/tests/launch_reset_test.py b/tests/launch_reset_test.py index 069dc6d..018bb8f 100644 --- a/tests/launch_reset_test.py +++ b/tests/launch_reset_test.py @@ -3,6 +3,8 @@ It empties the order tables, so it runs last. Run inside the API container: python -m tests.launch_reset_test """ +import tempfile +from pathlib import Path from uuid import uuid4 from psycopg.types.json import Jsonb @@ -37,6 +39,8 @@ def run(): with db.connect() as c: assert c.execute('SELECT 1 FROM dtf_local.orders WHERE id=%s', (order,)).fetchone() + with db.connect() as c: + before_number = c.execute('SELECT COALESCE(max(number),0) AS n FROM dtf_local.orders').fetchone()['n'] lines.clear() assert launch_reset.main(['--confirmar', 'APAGAR'], out=lines.append) == 0, lines with db.connect() as c: @@ -45,8 +49,8 @@ def run(): 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 'A numeração dos pedidos recomeça em #1.' in lines, lines - # The worker's own role restarts the numbers: the next order is #1. + assert 'Apagado.' in lines and 'continua de onde parou' in lines[-1], lines + # The numbering is not reset: DTF-1…DTF-15 already exist in Tiny. with db.connect() as c: quote = uuid4() c.execute('''INSERT INTO dtf_local.quotes(id,owner,request_key,request_hash,draft,approved,approved_at) @@ -55,10 +59,25 @@ def run(): first = c.execute('''INSERT INTO dtf_local.orders(id,quote_id,owner,snapshot,payment,origin) VALUES(%s,%s,%s,%s,%s,'site') RETURNING number''', (uuid4(), quote, owner, Jsonb({'items': []}), Jsonb({'provider': 'teste'}))).fetchone()['number'] - assert first == 1, first + assert first > before_number, (first, before_number) c.execute('DELETE FROM dtf_local.orders WHERE quote_id=%s', (quote,)) c.execute('DELETE FROM dtf_local.quotes WHERE id=%s', (quote,)) - print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes') + # The Kanban folders: only the flow folders are emptied; Estampas stays. + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) + for name in ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo', + '4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'): + (root / name).mkdir() + (root / name / 'card.txt').write_text('x') + (root / 'Estampas').mkdir() + (root / 'Estampas' / '1001.png').write_bytes(b'art') + lines.clear() + assert launch_reset.main(['--root', temp, '--confirmar', 'APAGAR'], out=lines.append) == 0, lines + for name in ('1. Arte recebida', '2. Arte conferida', '3. Imprimindo', + '4. Revisão', '5. Finalizado', 'Recibos', 'Revisões'): + assert list((root / name).iterdir()) == [], name + assert (root / 'Estampas' / '1001.png').read_bytes() == b'art' + print('PASS: launch cleanup refuses real payments, counts first, then removes test orders and quotes, keeping the numbering and the art library') if __name__ == '__main__': diff --git a/tests/test_reset_board.py b/tests/test_reset_board.py deleted file mode 100644 index 7d8e535..0000000 --- a/tests/test_reset_board.py +++ /dev/null @@ -1,32 +0,0 @@ -"""0.11 folder cleaning: empty the flow folders, keep the art library.""" -import tempfile -import unittest -from pathlib import Path - -from ops.reset_board import FLOW_FOLDERS, clean_folders - - -class ResetFoldersTests(unittest.TestCase): - def test_empties_flow_folders_and_keeps_estampas(self): - with tempfile.TemporaryDirectory() as folder: - root = Path(folder) - for name in FLOW_FOLDERS: - (root / name).mkdir() - (root / name / 'card.txt').write_text('x') - library = root / 'Estampas' - library.mkdir() - (library / '1001.png').write_bytes(b'art') - clean_folders(root, dry_run=False) - for name in FLOW_FOLDERS: - self.assertTrue((root / name).is_dir(), name) - self.assertEqual(list((root / name).iterdir()), [], name) - self.assertEqual((library / '1001.png').read_bytes(), b'art') - - def test_refuses_a_folder_that_is_not_the_kanban_root(self): - with tempfile.TemporaryDirectory() as folder: - with self.assertRaises(SystemExit): - clean_folders(folder, dry_run=True) - - -if __name__ == '__main__': - unittest.main()