From a69b9f71c23ffb11b46578e1cb30cfacf920a705 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 9 Nov 2026 13:25:52 -0300 Subject: [PATCH 1/3] fix: camera, storage images and videos allowed by the page headers Permissions-Policy forbade the camera, so the review's "Revisar" (front 2) could never open it. img-src left out the storage host, so the customer's review photo did not load. And the production CSP had no media-src at all: the Site videos (front 4), served from storage, would not play. The camera is allowed for the page itself only; microphone and geolocation stay off. Co-Authored-By: Claude Opus 5.5 --- deploy/nginx.conf.template | 4 ++-- infra/nginx.conf.template | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/deploy/nginx.conf.template b/deploy/nginx.conf.template index 1092fdb..a1dbc11 100644 --- a/deploy/nginx.conf.template +++ b/deploy/nginx.conf.template @@ -26,8 +26,8 @@ server { add_header X-Content-Type-Options nosniff always; add_header Referrer-Policy no-referrer always; add_header X-Frame-Options DENY always; - add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; - add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; + add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always; + add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; location = /health { access_log off; return 200 'ok'; } location /api/ { diff --git a/infra/nginx.conf.template b/infra/nginx.conf.template index 190d882..c948ebf 100644 --- a/infra/nginx.conf.template +++ b/infra/nginx.conf.template @@ -8,8 +8,8 @@ server { add_header X-Content-Type-Options nosniff always; add_header Referrer-Policy no-referrer always; add_header X-Frame-Options DENY always; - add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always; - add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; + add_header Permissions-Policy "camera=(self), microphone=(), geolocation=()" always; + add_header Content-Security-Policy "default-src 'self'; script-src 'self' @SCRIPT_HASHES@ ${PAYMENT_CSP_SOURCES}; script-src-attr 'none'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: blob: https://cdn.vnda.com.br ${S3_PUBLIC_ENDPOINT} ${PAYMENT_CSP_SOURCES}; media-src 'self' ${S3_PUBLIC_ENDPOINT}; connect-src 'self' ${S3_PUBLIC_ENDPOINT} https://cdn.vnda.com.br ${PAYMENT_CSP_SOURCES}; frame-src 'self' ${PAYMENT_CSP_SOURCES} ${PAYMENT_CHALLENGE_SOURCES}; worker-src 'self' blob:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self' ${PAYMENT_CHALLENGE_SOURCES}" always; location = /health { access_log off; return 200 'ok'; } location /api/ { limit_req zone=api_limit burst=100 nodelay; From 049f51b56ae299b4c84fdab1500c10eb0f6b4b24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 9 Nov 2026 13:25:52 -0300 Subject: [PATCH 2/3] fix: orders from before the PNG print file are generated again, once An order generated before item 13 had a PDF print file and no strips, so the 100% viewer opened it blank. Those still in Arte recebida, with no approved final and no customer correction, are generated again once as PNG with strips (migration png-regenerate-v1). Co-Authored-By: Claude Opus 5.5 --- app/schema.sql | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/app/schema.sql b/app/schema.sql index 7844c25..b0dbd98 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -581,3 +581,20 @@ CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes ( snoozed_by text NOT NULL, snoozed_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(machine_id, alert, cycle_from) ); + +-- Orders generated before the print file was a PNG with its strips (item 13) +-- open blank in the 100% viewer. Those not approved yet are generated again, +-- once: the same layout, now as PNG with strips. An approved final, a +-- customer's correction or a cancelled order is left as it is. +DO $$ BEGIN + IF NOT EXISTS (SELECT 1 FROM dtf_local.migrations WHERE name='png-regenerate-v1') THEN + UPDATE dtf_local.print_files p SET status='pending', attempts=0, claimed_at=NULL, claim_token=NULL, + finished_at=NULL, upload_id=NULL, detail='{}' + FROM dtf_local.orders o + WHERE o.id=p.order_id AND o.state='rec' AND o.cancelled_at IS NULL + AND p.status='ready' AND NOT (p.detail ? 'format') + AND NOT EXISTS (SELECT 1 FROM dtf_local.order_files f WHERE f.order_id=p.order_id + AND f.item_index=p.item_index AND f.active); + INSERT INTO dtf_local.migrations VALUES('png-regenerate-v1'); + END IF; +END $$; From c88d81588e48bcbfb363a316a35c828545b27df0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Faleiros?= Date: Mon, 9 Nov 2026 13:50:45 -0300 Subject: [PATCH 3/3] feat: products and prices from the database, edited in the Kanban's Site tab (front 8.1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .gitea/workflows/deploy.yml | 2 +- app/api/health.py | 12 +++- app/api/quotes.py | 22 ++++--- app/api/site_admin.py | 101 +++++++++++++++++++++++++++++++ app/app.py | 4 +- app/catalog.py | 63 ++++++++++++++++++++ app/core/models.py | 13 +++- app/core/pricing.py | 8 ++- app/quote_review.py | 14 +++-- app/runtime.py | 8 ++- app/schema.sql | 19 ++++++ app/tiny.py | 7 ++- tests/site_admin_test.py | 110 ++++++++++++++++++++++++++++++++++ tests/test_pricing.py | 14 +++++ web/checkout.js | 22 +++++++ web/kanban-site.js | 116 ++++++++++++++++++++++++++++++++++++ web/kanban.css | 19 ++++++ web/kanban.html | 15 ++++- web/kanban.js | 11 ++-- web/site-modes.js | 5 +- 20 files changed, 550 insertions(+), 35 deletions(-) create mode 100644 app/api/site_admin.py create mode 100644 app/catalog.py create mode 100644 tests/site_admin_test.py create mode 100644 web/kanban-site.js diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 55f68f0..6aa2840 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -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 unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test; do + for suite in smoke_test workflow_test security_test scanning_test payment_test unpaid_test quote_pagination_test kanban_test reconcile_test order_actions_test print_file_test users_test stage_limits_test mail_test thumbnail_backfill_test launch_reset_test finished_order_test machine_pull_test site_video_test treatment_gate_test review_media_test machine_log_test machine_stats_test site_admin_test; do echo "--- $suite" $COMPOSE exec -T \ -e SITE_BASE_URL=http://site \ diff --git a/app/api/health.py b/app/api/health.py index 103f685..7527da0 100644 --- a/app/api/health.py +++ b/app/api/health.py @@ -6,10 +6,10 @@ import httpx from fastapi import APIRouter, HTTPException, Request, Response from ..core import db -from .. import mail +from .. import catalog, mail from ..core.auth import client_ip, owner, new_session, rate_limit from ..core.limits import upload_limit_bytes -from ..core.pricing import manual_extra_cents, treatment_cents +from ..core.pricing import manual_extra_cents from ..core.models import FreightAsk, FreightEstimate from ..runtime import (ENVIRONMENT, GUEST_SESSION_LIMIT, PART_BYTES, delivery_services, freight, payment, require_delivery_available, storage) @@ -38,12 +38,18 @@ def session(request: Request, response: Response): rate_limit('guest-sessions', client_ip(request), GUEST_SESSION_LIMIT, 900) with db.connect() as c: session_id = new_session(c, response) + with db.connect() as c: + products = catalog.current(c) + treatment = products['tratamento'] return {'environment': ENVIRONMENT, 'cart_scope': str(session_id), 'part_bytes': PART_BYTES, 'max_upload_bytes': upload_limit_bytes(), 'payment_provider': payment.name, 'password_recovery': mail.configured(), # Per metre on a finished sheet someone opens by hand (app/core/pricing.py). 'manual_extra_cents': manual_extra_cents(), - 'treatment_cents': treatment_cents(), + # Zero keeps the designer's treatment hidden, as an off product does. + 'treatment_cents': treatment['unit_cents'] if treatment['enabled'] else 0, + # What the Site sells now: a switched-off product is hidden there. + 'products': {mode: products[mode] for mode in catalog.MODES}, # Public by design: Mercado Pago's card form needs it in the browser. 'payment_public_key': os.environ.get('MP_PUBLIC_KEY', '') if payment.name == 'mercadopago' else '', # The delivery options the cart quotes, or none: pickup only. diff --git a/app/api/quotes.py b/app/api/quotes.py index 18c45c4..3e3f4b2 100644 --- a/app/api/quotes.py +++ b/app/api/quotes.py @@ -8,7 +8,7 @@ from uuid import UUID, uuid4 from fastapi import APIRouter, Depends, HTTPException from psycopg.types.json import Jsonb -from .. import payments +from .. import catalog, payments from ..core import db from ..core.auth import owner from ..core.models import QuoteRequest @@ -35,15 +35,19 @@ def create_quote(body: QuoteRequest, session_id=Depends(owner)): if item.get('stroke_choice'): item['stroke_choice_at'] = accepted_at reason = quote_review.review_reason(draft) - if reason is not None: - # Waits for review: check the delivery now, priced at approval. - try: - priced = [price(item.mode, str(item.metres), item.grade) for item in body.items] - freight.quote(body.freight.service, body.freight.postal_code, - sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced)) - except ValueError as exc: - raise HTTPException(422, str(exc)) with db.connect() as c: + if reason is not None: + # Waits for review: check the delivery now, priced at approval. + try: + priced = [] + for item in body.items: + catalog.require_enabled(c, item.mode) + priced.append(price(item.mode, str(item.metres), item.grade, + unit_cents=catalog.unit_cents(c, item.mode))) + freight.quote(body.freight.service, body.freight.postal_code, + sum(Decimal(i['billed_metres']) for i in priced), sum(i['total_cents'] for i in priced)) + except ValueError as exc: + raise HTTPException(422, str(exc)) rows = {} for item in body.items: for uid in item.uploads: diff --git a/app/api/site_admin.py b/app/api/site_admin.py new file mode 100644 index 0000000..880b4b1 --- /dev/null +++ b/app/api/site_admin.py @@ -0,0 +1,101 @@ +"""The Site tab: what the Site sells and at what price, edited by Gestão. + +A product is switched on or off here. Prices carry a start date and become +history: a row that has started is never changed or deleted, so only a +scheduled (future) price may be cancelled. Approved quotes keep the price they +were approved with (app/quote_review.py); a switched-off product refuses new +quotes and approvals with 422. +""" +from datetime import datetime, timedelta, timezone + +from fastapi import APIRouter, Depends, HTTPException + +from .. import catalog +from ..core import db +from ..core.auth import audit, can +from ..core.models import SitePriceNew, SiteProductToggle + +router = APIRouter() + + +def price_row(row): + return {'id': row['id'], 'unit_cents': row['unit_cents'], + 'starts_at': row['starts_at'].isoformat(), 'created_by': row['created_by'], + 'created_at': row['created_at'].isoformat()} + + +@router.get('/api/operator/site/products') +def site_products(user=Depends(can('manage'))): + with db.connect() as c: + state = catalog.current(c) + now = c.execute('SELECT now() AS now').fetchone()['now'] + started = {row['product']: row['unit_cents'] for row in c.execute(''' + SELECT DISTINCT ON (product) product, unit_cents + FROM dtf_local.product_prices + WHERE starts_at <= now() + ORDER BY product, starts_at DESC, id DESC''').fetchall()} + rows = c.execute('''SELECT id, product, unit_cents, starts_at, created_by, created_at + FROM dtf_local.product_prices ORDER BY product, created_at DESC, id DESC''').fetchall() + products = [] + for product in catalog.PRODUCTS: + prices = [row for row in rows if row['product'] == product] + future = sorted((row for row in prices if row['starts_at'] > now), + key=lambda row: (row['starts_at'], row['id'])) + products.append({ + 'id': product, 'title': catalog.TITLES[product], 'unit': catalog.UNITS[product], + 'enabled': state[product]['enabled'], + 'unit_cents': state[product]['unit_cents'], + 'fallback': product not in started, + 'scheduled': [price_row(row) for row in future], + 'history': [price_row(row) for row in prices[:20]], + }) + return {'products': products} + + +@router.post('/api/operator/site/products/{product}') +def toggle_product(product: str, body: SiteProductToggle, user=Depends(can('manage'))): + if product not in catalog.PRODUCTS: + raise HTTPException(404, 'Produto não encontrado.') + with db.connect() as c: + c.execute('''INSERT INTO dtf_local.products(id, enabled, updated_by, updated_at) + VALUES(%s,%s,%s,now()) + ON CONFLICT (id) DO UPDATE SET enabled=EXCLUDED.enabled, + updated_by=EXCLUDED.updated_by, updated_at=now()''', + (product, body.enabled, user)) + audit('site_product_changed', product=product, enabled=body.enabled, operator=user) + return {'ok': True} + + +@router.post('/api/operator/site/products/{product}/prices') +def schedule_price(product: str, body: SitePriceNew, user=Depends(can('manage'))): + if product not in catalog.PRODUCTS: + raise HTTPException(404, 'Produto não encontrado.') + if product != 'tratamento' and body.unit_cents <= 0: + raise HTTPException(422, 'O preço precisa ser maior que zero.') + now = datetime.now(timezone.utc) + starts_at = body.starts_at or now + if starts_at.tzinfo is None: + starts_at = starts_at.replace(tzinfo=timezone.utc) + if starts_at < now - timedelta(minutes=1): + raise HTTPException(422, 'A data de início não pode estar no passado.') + with db.connect() as c: + row = c.execute('''INSERT INTO dtf_local.product_prices(product, unit_cents, starts_at, created_by) + VALUES(%s,%s,%s,%s) RETURNING id''', + (product, body.unit_cents, starts_at, user)).fetchone() + audit('site_price_changed', product=product, unit_cents=body.unit_cents, + starts_at=starts_at.isoformat(), operator=user) + return {'id': row['id']} + + +@router.post('/api/operator/site/prices/{price_id}/cancel') +def cancel_price(price_id: int, user=Depends(can('manage'))): + with db.connect() as c: + row = c.execute('''SELECT id, product, unit_cents, starts_at + FROM dtf_local.product_prices WHERE id=%s FOR UPDATE''', (price_id,)).fetchone() + if not row: + raise HTTPException(404, 'Preço não encontrado.') + if row['starts_at'] <= datetime.now(timezone.utc): + raise HTTPException(409, 'Este preço já começou: o histórico não pode ser apagado.') + c.execute('DELETE FROM dtf_local.product_prices WHERE id=%s', (price_id,)) + audit('site_price_cancelled', price=price_id, product=row['product'], operator=user) + return {'ok': True} diff --git a/app/app.py b/app/app.py index cbdd6cb..fe00542 100644 --- a/app/app.py +++ b/app/app.py @@ -13,7 +13,7 @@ from starlette.middleware.trustedhost import TrustedHostMiddleware from .core import db from .core.auth import audit, client_ip from .runtime import ALLOWED_HOSTS, ALLOWED_ORIGINS, storage -from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_videos, uploads, users +from .api import artwork, customer, health, machine_log, operator, orders, payments, quotes, reviews, site_admin, site_videos, uploads, users @asynccontextmanager @@ -45,5 +45,5 @@ async def safe_headers(request, call_next): # Order is not significant: no two routers declare the same path. -for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, reviews, machine_log): +for module in (health, uploads, quotes, orders, payments, operator, customer, artwork, users, site_videos, site_admin, reviews, machine_log): app.include_router(module.router) diff --git a/app/catalog.py b/app/catalog.py new file mode 100644 index 0000000..eb90dbd --- /dev/null +++ b/app/catalog.py @@ -0,0 +1,63 @@ +"""What the Site sells and at what price, edited in the Kanban's Site tab. + +Dropstar, 2026-11-05 (Fase 2, front 8): the products and their prices leave the +code and live in the database, with a start date and a history. `PRICES` in +app/core/pricing.py stays as the seed and the fallback for the four modes; +`treatment_cents()` stays as the fallback for `tratamento`. A price row is never +changed or deleted once its start date has passed (the table is the history), +and an approved quote keeps the price it was approved with. + +`tratamento` is the designer's treatment (front 5), a fixed amount per order: +it counts as offered only when it is switched on and priced above zero. +""" +from fastapi import HTTPException + +from .core import pricing + +# The four modes sold by the metre, and the treatment sold per order. +MODES = ('file', 'avulsa', 'uvfile', 'uv') +PRODUCTS = (*MODES, 'tratamento') + +TITLES = { + 'file': 'Têxtil folha pronta', + 'avulsa': 'Têxtil artes avulsas', + 'uvfile': 'UV folha pronta', + 'uv': 'UV artes avulsas', + 'tratamento': 'Tratamento pelo designer', +} +UNITS = {'file': 'metro', 'avulsa': 'metro', 'uvfile': 'metro', 'uv': 'metro', + 'tratamento': 'pedido'} + + +def fallback_cents(product: str) -> int: + """The price in the code, used until a row in the database takes over.""" + return pricing.treatment_cents() if product == 'tratamento' else pricing.PRICES[product] + + +def current(c) -> dict: + """{'file': {'enabled': bool, 'unit_cents': int}, ...}: what is sold now.""" + enabled = {row['id']: row['enabled'] for row in + c.execute('SELECT id, enabled FROM dtf_local.products').fetchall()} + prices = {row['product']: row['unit_cents'] for row in c.execute(''' + SELECT DISTINCT ON (product) product, unit_cents + FROM dtf_local.product_prices + WHERE starts_at <= now() + ORDER BY product, starts_at DESC, id DESC''').fetchall()} + return {product: {'enabled': bool(enabled.get(product, True)), + 'unit_cents': prices.get(product, fallback_cents(product))} + for product in PRODUCTS} + + +def unit_cents(c, product: str) -> int: + """The current price of one product, or the fallback.""" + row = c.execute('''SELECT unit_cents FROM dtf_local.product_prices + WHERE product=%s AND starts_at <= now() + ORDER BY starts_at DESC, id DESC LIMIT 1''', (product,)).fetchone() + return row['unit_cents'] if row else fallback_cents(product) + + +def require_enabled(c, product: str) -> None: + """Refuse a product someone switched off in the Kanban's Site tab.""" + row = c.execute('SELECT enabled FROM dtf_local.products WHERE id=%s', (product,)).fetchone() + if row and not row['enabled']: + raise HTTPException(422, 'Este produto não está à venda agora.') diff --git a/app/core/models.py b/app/core/models.py index b213c39..492af7c 100644 --- a/app/core/models.py +++ b/app/core/models.py @@ -1,5 +1,5 @@ import re -from datetime import date +from datetime import date, datetime from decimal import Decimal from typing import Literal from uuid import UUID @@ -352,6 +352,17 @@ class MachineSheet(StrictModel): minimums: dict[str, Decimal | None] = Field(default_factory=dict) +class SiteProductToggle(StrictModel): + """Ligar ou desligar um produto na aba Site (Fase 2, front 8).""" + enabled: bool + + +class SitePriceNew(StrictModel): + """Um novo preço e a data em que começa; sem data, começa agora.""" + unit_cents: int = Field(ge=0, le=10000000, strict=True) + starts_at: datetime | None = None + + class Contraction(StrictModel): item_index: int = Field(ge=0, le=100) # None returns the item to the class the browser measured. diff --git a/app/core/pricing.py b/app/core/pricing.py index 0c31965..ef5083f 100644 --- a/app/core/pricing.py +++ b/app/core/pricing.py @@ -44,10 +44,12 @@ def is_manual(item, names) -> bool: for source in item['production']['sources']) -def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1')) -> dict: +def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Decimal = Decimal('1'), + unit_cents: int | None = None) -> dict: """The item's charge. The grade is validated and kept with the item; the price does not depend on it. A split sheet has no minimum of its own: its - group has one (bill_splits).""" + group has one (bill_splits). `unit_cents` is the current price from the + database (app/catalog.py); without it, the table above.""" length = Decimal(str(metres)) if mode not in PRICES or not length.is_finite() or not 0 < length <= 12000: raise ValueError('Invalid product or length') @@ -56,7 +58,7 @@ def price(mode: str, metres: str, grade: int, extra_cents: int = 0, minimum: Dec billed = max(minimum, (length * 10).to_integral_value(rounding=ROUND_CEILING) / 10) if isinstance(extra_cents, bool) or not isinstance(extra_cents, int) or extra_cents < 0: raise ValueError('Invalid extra charge') - unit = PRICES[mode] + extra_cents + unit = (PRICES[mode] if unit_cents is None else unit_cents) + extra_cents priced = {'mode': mode, 'metres': str(length), 'grade': grade, 'billed_metres': str(billed), 'unit_cents': unit, 'total_cents': int(billed * unit)} diff --git a/app/quote_review.py b/app/quote_review.py index ca8bc24..a971736 100644 --- a/app/quote_review.py +++ b/app/quote_review.py @@ -19,10 +19,10 @@ from decimal import Decimal from fastapi import HTTPException from psycopg.types.json import Jsonb -from . import payments +from . import catalog, payments from .proof import PROOF_ABOVE_METRES from .core.models import PRODUCTION_VERSIONS -from .core.pricing import bill_splits, is_manual, manual_extra_cents, price, treatment_cents +from .core.pricing import bill_splits, is_manual, manual_extra_cents, price from .runtime import freight, upload_row from .scanning import require_clean @@ -71,9 +71,11 @@ def approve(c, row, items, reviewer): upload = upload_row(c, upload_id, row['owner']) require_clean(upload) names[str(upload_id)] = upload['name'] + catalog.require_enabled(c, item.mode) extra = manual_extra_cents() if is_manual(original, names) else 0 priced.append({**price(item.mode, str(item.metres), item.grade, extra, - minimum=Decimal('0') if item.split else Decimal('1')), + minimum=Decimal('0') if item.split else Decimal('1'), + unit_cents=catalog.unit_cents(c, item.mode)), 'uploads': original['uploads'], 'production': original['production'], 'quality_status': original['quality_status'], 'quality_acknowledged': original['quality_acknowledged'], @@ -96,7 +98,11 @@ def approve(c, row, items, reviewer): metres, sum(i['total_cents'] for i in priced)) except ValueError as exc: raise HTTPException(422, str(exc)) - treatment = treatment_cents() if draft.get('treatment') else 0 + treatment = 0 + if draft.get('treatment'): + # The designer's treatment is offered only when switched on and priced. + offer = catalog.current(c)['tratamento'] + treatment = offer['unit_cents'] if offer['enabled'] else 0 approved = {'customer': draft['customer'], 'items': priced, 'freight': quoted_freight, 'destination': draft.get('destination'), # The customer's proof only above 10 m (Dropstar, 2026-10-28). diff --git a/app/runtime.py b/app/runtime.py index d450f1d..1acee11 100644 --- a/app/runtime.py +++ b/app/runtime.py @@ -12,6 +12,7 @@ from uuid import uuid5, NAMESPACE_URL from fastapi import HTTPException from psycopg.types.json import Jsonb +from . import catalog from .adapters import FakeFreight, FakePayment, LocalS3Storage, require_runtime from .freight import FreightOptions from .core.secrets import load as load_secret_files @@ -33,7 +34,6 @@ if os.environ.get('FREIGHT_ADAPTER') == 'jadlog': _carriers.append(JadlogFreight()) from . import correios as _correios from . import prumo -from .core.pricing import treatment_cents if _correios.configured(): _carriers.append(_correios.CorreiosFreight()) freight = FreightOptions(_carriers or [FakeFreight()]) @@ -141,8 +141,10 @@ def quote_view(c, row, order=None, attempt=None, known=False): datetime.now(timezone.utc)-timedelta(hours=QUOTE_VALID_HOURS))) items = (row['approved'] or row['draft']).get('items') or [] treatment = (row['approved'] or {}).get('treatment') - if not treatment and (row['draft'] or {}).get('treatment') and treatment_cents(): - treatment = {'cents': treatment_cents(), 'hours': 24} + if not treatment and (row['draft'] or {}).get('treatment'): + offer = catalog.current(c)['tratamento'] + if offer['enabled'] and offer['unit_cents'] > 0: + treatment = {'cents': offer['unit_cents'], 'hours': 24} return {'id': row['id'], 'created_at': row['created_at'], 'draft': row['draft'], 'approved': row['approved'], 'expires_at': expires_at.isoformat() if expires_at else None, diff --git a/app/schema.sql b/app/schema.sql index 7844c25..cd13534 100644 --- a/app/schema.sql +++ b/app/schema.sql @@ -581,3 +581,22 @@ CREATE TABLE IF NOT EXISTS dtf_local.machine_snoozes ( 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); diff --git a/app/tiny.py b/app/tiny.py index 9c393a6..16ebcca 100644 --- a/app/tiny.py +++ b/app/tiny.py @@ -51,7 +51,8 @@ from urllib.parse import urlencode import httpx -from .core.pricing import treatment_cents +from . import catalog +from .core import db API = 'https://api.tiny.com.br/public-api/v3' AUTH = 'https://accounts.tiny.com.br/realms/tiny/protocol/openid-connect' @@ -172,7 +173,9 @@ def required_settings(): setting for mode, setting in PRODUCT_SETTINGS.items() if not (sku_prefix(mode) or step_sku(mode))] # A paid treatment is a line of its own: missing, every treated order would # fail at the Tiny, so ask for it with the rest of the settings. - if treatment_cents() > 0: + with db.connect() as c: + treatment = catalog.current(c)['tratamento'] + if treatment['enabled'] and treatment['unit_cents'] > 0: required.append('TINY_PRODUCT_TREATMENT') return required diff --git a/tests/site_admin_test.py b/tests/site_admin_test.py new file mode 100644 index 0000000..c74b9dc --- /dev/null +++ b/tests/site_admin_test.py @@ -0,0 +1,110 @@ +"""The Kanban's Site tab: products switched on and off, prices with a history. + +Run against the local stack: SITE_BASE_URL=http://site SITE_HOST_HEADER=localhost +python -m tests.site_admin_test +""" +import secrets +from datetime import datetime, timedelta, timezone +from uuid import uuid4 + +from app.core import db +from tests.print_file_test import artwork +from tests.smoke_test import Client, item_spec, upload_bytes + +PASSWORD = 'senha-de-teste-123' +UV = 'uv' + + +def quote(client, item, mail): + return client.call('/quotes', {'request_key': str(uuid4()), + 'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}, + 'items': [item], 'freight': {'service': 'pickup'}}) + + +def run(): + tag = secrets.token_hex(4) + mail = f'site-admin-{tag}@example.test' + client = Client() + client.call('/session') + # The default operator login is the superadmin, which may manage the Site. + manager = Client() + manager.call('/session') + manager.call('/operator/me', operator=True) + manager = manager.operator_client + prices, user = [], None + try: + products = manager.call('/operator/site/products')['products'] + assert {product['id'] for product in products} == {'file', 'avulsa', 'uvfile', 'uv', 'tratamento'} + assert all(product['unit'] in ('metro', 'pedido') and product['title'] for product in products) + + manager.call(f'/operator/site/products/{UV}', {'enabled': True}) + uid = upload_bytes(client, artwork(), name='LOCAL-SITE-ADMIN.png') + item = {**item_spec('uv', '1', 0, uid), 'quality_status': 'warning', 'quality_acknowledged': True} + before = client.call('/session')['products'][UV]['unit_cents'] + + # Switched off: the Site sees it off and the server refuses a new quote. + manager.call(f'/operator/site/products/{UV}', {'enabled': False}) + assert client.call('/session')['products'][UV]['enabled'] is False + refused = client.call('/quotes', {'request_key': str(uuid4()), + 'customer': {'cnpj': '11222333000181', 'zap': '11999999999', 'mail': mail}, + 'items': [item], 'freight': {'service': 'pickup'}}, expected=422) + assert refused['detail'] == 'Este produto não está à venda agora.', refused + manager.call(f'/operator/site/products/{UV}', {'enabled': True}) + assert client.call('/session')['products'][UV]['enabled'] is True + + # A price in the future does not change today's and can be cancelled. + made = manager.call(f'/operator/site/products/{UV}/prices', { + 'unit_cents': 23456, + 'starts_at': (datetime.now(timezone.utc) + timedelta(minutes=1)).isoformat()}) + prices.append(made['id']) + assert client.call('/session')['products'][UV]['unit_cents'] == before + entry = next(product for product in manager.call('/operator/site/products')['products'] + if product['id'] == UV) + assert any(row['id'] == made['id'] for row in entry['scheduled']), entry + manager.call(f'/operator/site/prices/{made["id"]}/cancel', {}) + entry = next(product for product in manager.call('/operator/site/products')['products'] + if product['id'] == UV) + assert not any(row['id'] == made['id'] for row in entry['scheduled']), entry + + # A start date in the past is refused. + manager.call(f'/operator/site/products/{UV}/prices', { + 'unit_cents': 1000, + 'starts_at': (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()}, expected=422) + + # A price that starts now is what /api/session and a new quote charge. + made = manager.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 12345}) + prices.append(made['id']) + assert client.call('/session')['products'][UV]['unit_cents'] == 12345 + created = quote(client, item, mail) + assert created['status'] == 'approved', created + approved = client.call('/quotes/' + created['id'])['approved'] + assert approved['items'][0]['unit_cents'] == 12345, approved + assert approved['items'][0]['total_cents'] == 12345, approved + + # A profile without "manage" cannot see or change the Site tab. + email = f'site-staff-{tag}@example.test' + user = manager.call('/operator/users', {'name': 'Teste Site', 'email': email, + 'role': 'operador', 'password': PASSWORD}) + staff = Client() + staff.call('/session') + staff.call('/operator/login', {'email': email, 'password': PASSWORD}) + staff.call('/operator/site/products', expected=403) + staff.call(f'/operator/site/products/{UV}', {'enabled': True}, expected=403) + staff.call(f'/operator/site/products/{UV}/prices', {'unit_cents': 1000}, expected=403) + staff.call(f'/operator/site/prices/{made["id"]}/cancel', {}, expected=403) + print('PASS: the Site tab switches a product off and refuses quotes, schedules and cancels prices,' + ' charges the new price, and refuses a non-manage profile') + finally: + with db.connect() as c: + if prices: + c.execute('DELETE FROM dtf_local.product_prices WHERE id=ANY(%s::bigint[])', (prices,)) + c.execute("UPDATE dtf_local.products SET enabled=true WHERE id=%s", (UV,)) + if user: + try: + manager.call('/operator/users/' + str(user['id']) + '/delete', {}, expected=200) + except Exception: + pass + + +if __name__ == '__main__': + run() diff --git a/tests/test_pricing.py b/tests/test_pricing.py index 9ba6c9d..26784e8 100644 --- a/tests/test_pricing.py +++ b/tests/test_pricing.py @@ -55,6 +55,20 @@ class PricingTests(unittest.TestCase): for bad in (-1, True, 1.5): with self.assertRaises(ValueError):price('file', '1', 0, bad) + def test_the_catalog_price_replaces_the_table_price(self): + # The Kanban's Site tab sets the price in the database (front 8); the + # minimum and the ten-centimetre rounding stay the Site's. + priced = price('avulsa', '2.75', 90, unit_cents=1234) + self.assertEqual(price('avulsa', '2.75', 90)['unit_cents'], PRICES['avulsa']) + self.assertEqual(priced['unit_cents'], 1234) + self.assertEqual(priced['billed_metres'], '2.8') + self.assertEqual(priced['total_cents'], 3455) + # A hand-opened sheet still pays the extra on top of the new price. + extra = price('file', '1.01', 0, 500, unit_cents=1234) + self.assertEqual(extra['unit_cents'], 1734) + self.assertEqual(extra['billed_metres'], '1.1') + self.assertEqual(extra['total_cents'], 1907) + def test_which_items_are_opened_by_hand(self): def item(kind, measurement, uid='u1'): return {'production': {'sources': [{'kind': kind, 'measurement': measurement, 'upload_id': uid}]}} diff --git a/web/checkout.js b/web/checkout.js index 4d189a3..0b4ecf0 100644 --- a/web/checkout.js +++ b/web/checkout.js @@ -9,6 +9,8 @@ let shownCart = null; let pixClock = null; let busy = false; + // Every product switched off in the Kanban's Site tab (front 8). + let semPedidos = false; let draftId = localStorage.getItem('dtf-quote'); let requestKey = localStorage.getItem('dtf-request-key'); let requestBody = localStorage.getItem('dtf-request-body'); @@ -84,6 +86,25 @@ if(preco)preco.textContent=TAXA_TRATAMENTO>0?rs(TAXA_TRATAMENTO):''; if(!(TAXA_TRATAMENTO>0)&&document.getElementById('fTratamento'))document.getElementById('fTratamento').checked=false; } + // What the Site sells and at what price, from the database (front 8). An + // older server sends no `products`: the page keeps PRECO. + if(session.products){ + for(const [mode,product] of Object.entries(session.products)){ + PRECO[mode]=product.unit_cents/100; + const card=document.querySelector('button.ec[data-modo="'+mode+'"]'); + if(card&&!product.enabled)card.hidden=true; + } + document.querySelectorAll('[data-preco]').forEach(el=>{ + const product=session.products[el.dataset.preco]; + el.textContent=product&&!product.enabled?'Indisponível':rs(PRECO[el.dataset.preco]); + }); + window.dtfProducts=session.products; + if(typeof folhas!=='undefined'&&folhas.length&&typeof pintaFolha==='function')pintaFolha(); + if(typeof itemAtual!=='undefined'&&itemAtual&&typeof carrinho==='function')carrinho(); + if(typeof pintaTipoEnvio==='function')pintaTipoEnvio(); + semPedidos=!Object.values(session.products).some(product=>product.enabled); + if(semPedidos)message('No momento não estamos recebendo pedidos pelo site.','warn'); + } if(typeof pintaPedido==='function')pintaPedido(); }).catch(()=>{}); window.dtfSessionReady=ready; @@ -719,6 +740,7 @@ window.addEventListener('dtf-page-changed',()=>{ if (naPagina()) refresh(); else if (!busy) { refreshVersion++; clearInterval(pixClock); message(''); actions.replaceChildren(); pintaResumo(null); } + if (!naPagina() && semPedidos) message('No momento não estamos recebendo pedidos pelo site.','warn'); }); refresh(); })(); diff --git a/web/kanban-site.js b/web/kanban-site.js new file mode 100644 index 0000000..b05e044 --- /dev/null +++ b/web/kanban-site.js @@ -0,0 +1,116 @@ +/* Kanban DTF: the Site tab. What the Site sells and at what price, edited by + Gestão and the administrators (Fase 2, front 8). Loaded after kanban.js, + which defines api, may, money, when, say, node and button. + A price is history: one that has started is never changed or deleted, so + only a scheduled (future) price may be cancelled. */ +const SITE_UNIT_LABEL={metro:' /m',pedido:' por pedido'}; + +// Reais with a comma, as the Site shows them: "19,90" is 1990 cents. +function moneyInputCents(value){ + let text=String(value||'').trim().replace(/R\$/g,'').replace(/\s/g,''); + if(!text)return null; + if(text.includes(','))text=text.replace(/\./g,'').replace(',','.'); + const number=Number(text); + if(!Number.isFinite(number)||number<0)return null; + return Math.round(number*100); +} + +// A price that already started is refused by the server (409). +const cancelScheduledPrice=id=>api('/site/prices/'+id+'/cancel',{}); + +function siteProductRow(product){ + const tr=node('tr'); + const name=node('td');name.append(node('b',product.title)); + const price=node('td',money(product.unit_cents)+SITE_UNIT_LABEL[product.unit],'nowrap'); + if(product.fallback)price.append(node('span',' · padrão','muted')); + const state=node('td'); + const label=node('label',undefined,'siteSwitch'); + const input=node('input');input.type='checkbox';input.checked=product.enabled; + const word=node('span',product.enabled?'Ligado':'Desligado'); + input.onchange=async()=>{ + input.disabled=true; + try{ + await api('/site/products/'+product.id,{enabled:input.checked}); + word.textContent=input.checked?'Ligado':'Desligado'; + say(product.title+(input.checked?' ligado.':' desligado.')); + await loadSiteAdmin(); + }catch(error){input.checked=!input.checked;say(error.message,true);} + finally{input.disabled=false;} + }; + label.append(input,word); + state.append(label); + tr.append(name,state,price); + return tr; +} + +function sitePriceBlock(product){ + const block=node('div',undefined,'sitePriceBlock'); + const heading=node('h3',product.title); + heading.append(node('span',' · '+product.unit,'muted')); + + // Novo preço: reais with a comma; empty "A partir de" means now. + const form=node('div',undefined,'sitePriceForm'); + const priceLabel=node('label');priceLabel.append(node('span','Novo preço')); + const price=node('input');price.type='text';price.inputMode='decimal';price.className='siteMoney'; + price.placeholder=(product.unit_cents/100).toFixed(2).replace('.',','); + price.setAttribute('aria-label','Novo preço de '+product.title); + priceLabel.append(price); + const startsLabel=node('label');startsLabel.append(node('span','A partir de')); + const starts=node('input');starts.type='datetime-local'; + starts.setAttribute('aria-label','Quando o novo preço de '+product.title+' começa'); + startsLabel.append(starts); + const save=button('Salvar',async()=>{ + const cents=moneyInputCents(price.value); + if(cents===null)throw new Error('Informe o preço em reais, como 19,90.'); + const whenDate=starts.value?new Date(starts.value):null; + if(whenDate&&Number.isNaN(whenDate.getTime()))throw new Error('Data inválida.'); + await api('/site/products/'+product.id+'/prices', + {unit_cents:cents,starts_at:whenDate?whenDate.toISOString():null}); + say(whenDate?'Preço salvo para '+when(whenDate)+'.':'Preço salvo. Vale a partir de agora.'); + await loadSiteAdmin(); + },'btn pri'); + form.append(priceLabel,startsLabel,save); + + const scheduled=node('div',undefined,'siteScheduled'); + if(product.scheduled.length){ + for(const row of product.scheduled){ + const line=node('div',undefined,'siteScheduledRow'); + line.append(node('span',money(row.unit_cents)+SITE_UNIT_LABEL[product.unit]+' a partir de '+when(row.starts_at))); + line.append(button('Cancelar',async()=>{ + await cancelScheduledPrice(row.id); + say('Preço agendado cancelado.'); + await loadSiteAdmin(); + },'btn ghost')); + scheduled.append(line); + } + }else scheduled.append(node('span','Nenhum preço agendado.','muted')); + + const table=node('table',undefined,'table'); + const head=node('thead');const headRow=node('tr'); + for(const title of ['Valor','A partir de','Quem','Quando'])headRow.append(node('th',title)); + head.append(headRow); + const body=node('tbody'); + for(const row of product.history){ + const tr=node('tr'); + tr.append(node('td',money(row.unit_cents),'nowrap'),node('td',when(row.starts_at),'nowrap'), + node('td',row.created_by),node('td',when(row.created_at),'nowrap')); + body.append(tr); + } + if(!product.history.length){ + const tr=node('tr');const td=node('td','Nenhum preço registrado: vale o preço padrão.','muted'); + td.colSpan=4;tr.append(td);body.append(tr); + } + table.append(head,body); + const history=node('div',undefined,'siteHistory'); + history.append(node('h4','Histórico'),table); + + block.append(heading,form,scheduled,history); + return block; +} + +async function loadSiteAdmin(){ + if(!may('manage'))return; + const data=await api('/site/products'); + $('site-products').replaceChildren(...data.products.map(siteProductRow)); + $('site-prices').replaceChildren(...data.products.map(sitePriceBlock)); +} diff --git a/web/kanban.css b/web/kanban.css index 366f10d..f007668 100644 --- a/web/kanban.css +++ b/web/kanban.css @@ -639,6 +639,25 @@ label.fopt{cursor:pointer;user-select:none} .siteVideoField input,.siteVideoField select{max-width:240px;min-height:38px;color:var(--tx);background:var(--sf);border:1px solid var(--ln2);border-radius:8px;padding:6px} .siteVideoToggle{display:flex;align-items:center;gap:7px;min-height:38px;font-size:13px} .siteVideoError{width:100%;margin:0;color:var(--bad);font-size:12px} +/* Site (front 8): what the Site sells, its prices and their history. */ +#tab-site .siteSwitch{display:flex;align-items:center;gap:8px;font-size:13px;font-weight:550;cursor:pointer} +#tab-site .siteSwitch input{width:16px;height:16px;margin:0;accent-color:var(--acc)} +#tab-site .sitePriceBlock{display:flex;flex-direction:column;gap:12px;padding:16px 18px} +#tab-site .sitePriceBlock+.sitePriceBlock{border-top:1px solid var(--ln)} +#tab-site .sitePriceBlock h3{margin:0;font-size:14px;font-weight:650} +#tab-site .sitePriceBlock h3 .muted{font-size:12.5px;font-weight:500} +#tab-site .sitePriceForm{display:flex;align-items:end;gap:12px;flex-wrap:wrap} +#tab-site .sitePriceForm label{display:flex;flex-direction:column;gap:6px;font-size:12px;color:var(--tx2)} +#tab-site .sitePriceForm input{height:38px;padding:0 10px;border-radius:8px;border:1px solid var(--ln2);background:var(--sf);color:var(--tx);font-size:14px;font-family:inherit} +#tab-site .sitePriceForm input:focus{border-color:var(--acc);box-shadow:0 0 0 3px color-mix(in srgb,var(--acc) 18%,transparent);outline:none} +#tab-site .siteMoney{width:140px} +#tab-site .siteScheduled{display:flex;flex-direction:column;gap:8px;font-size:13.5px} +#tab-site .siteScheduledRow{display:flex;align-items:center;gap:10px;flex-wrap:wrap} +#tab-site .siteScheduledRow .btn{height:30px;padding:0 10px;font-size:12.5px} +#tab-site .siteHistory{display:flex;flex-direction:column;gap:6px} +#tab-site .siteHistory h4{margin:0;font-size:12.5px;font-weight:600;color:var(--tx3)} +#tab-site .siteHistory .table{font-size:13px} +#tab-site .siteHistory .table th,#tab-site .siteHistory .table td{padding:8px 12px} .page>*{flex-shrink:0} .pagetools{display:flex;align-items:center;gap:12px;flex-wrap:wrap} .panel{background:var(--sf);border:1px solid var(--ln);border-radius:12px} diff --git a/web/kanban.html b/web/kanban.html index cd71fc4..85bbb8c 100644 --- a/web/kanban.html +++ b/web/kanban.html @@ -40,6 +40,7 @@ + @@ -151,6 +152,18 @@

Velocidade do site e do Prumo

EtapaMédiap95Amostras
+