feat: the launch reset keeps the order numbering and clears the folders (0.11)

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.
This commit is contained in:
Cauê Faleiros
2026-11-06 11:11:36 -03:00
parent 6351a094f4
commit 2bcdb060fd
5 changed files with 71 additions and 153 deletions

View File

@@ -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

View File

@@ -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())