feat: products and prices from the database, edited in the Kanban's Site tab (front 8.1)

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>
This commit is contained in:
Cauê Faleiros
2026-11-09 13:50:45 -03:00
parent 4219db8215
commit c88d81588e
20 changed files with 550 additions and 35 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 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 \

View File

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

View File

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

101
app/api/site_admin.py Normal file
View File

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

View File

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

63
app/catalog.py Normal file
View File

@@ -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.')

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

110
tests/site_admin_test.py Normal file
View File

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

View File

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

View File

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

116
web/kanban-site.js Normal file
View File

@@ -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));
}

View File

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

View File

@@ -40,6 +40,7 @@
<button class="nav" type="button" data-tab="quotes" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M5 2.75h7l3 3v11.5H5z M12 2.75v3h3 M7.5 9.5h5 M7.5 12.5h5 M7.5 15h3"></path></svg><span>Cotações</span><span class="pip" id="badge-quotes"></span></button>
<button class="nav" type="button" data-tab="payments" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 5h14.5v10H2.75z M2.75 8.25h14.5 M5.5 12.25h3"></path></svg><span>Pagamentos</span><span class="pip" id="badge-payments"></span></button>
<button class="nav" type="button" data-tab="stats" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M3 16.75h14 M4.75 14V9.5 M8.5 14V4.5 M12.25 14V7.5 M16 14v-3.5"></path></svg><span>Números</span></button>
<button class="nav" type="button" data-tab="site" aria-selected="false" hidden><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M2.75 10h14.5 M10 2.75c2 2 3 4.5 3 7.25s-1 5.25-3 7.25 M10 2.75c-2 2-3 4.5-3 7.25s1 5.25 3 7.25"></path></svg><span>Site</span></button>
<button class="nav" type="button" data-tab="integrations" aria-selected="false"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M8.5 6.5H6a3.25 3.25 0 0 0 0 6.5h2.5 M11.5 6.5H14a3.25 3.25 0 0 1 0 6.5h-2.5 M7 9.75h6"></path></svg><span>Integrações</span><span class="pip" id="badge-integrations" title="A pasta da fila precisa de atenção"></span></button>
<button class="nav" type="button" data-tab="users" aria-selected="false" hidden><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M6.75 6.25a3.25 3.25 0 1 0 6.5 0a3.25 3.25 0 1 0 -6.5 0 M3.75 17c.6-3.2 3.1-5 6.25-5s5.65 1.8 6.25 5"></path></svg><span>Usuários</span></button>
<button class="nav phone" id="more-nav" type="button" aria-haspopup="menu"><svg class="i" viewBox="0 0 20 20" aria-hidden="true"><path d="M4.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0 M9.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0 M14.1 10a.9.9 0 1 0 1.8 0a.9.9 0 1 0 -1.8 0"></path></svg><span>Mais</span><span class="pip" id="badge-more"></span></button>
@@ -151,6 +152,18 @@
<section class="panel clip"><div class="phead"><h2>Velocidade do site e do Prumo</h2><span class="hint tip-l" tabindex="0" data-tip="Média e p95 do que o cliente sente, por pedido pago no período: abrir a página, subir o arquivo (segundos por MB), a conferência do Prumo, a montagem das avulsas, a geração do arquivo final por 10 m e o tempo do evento de pagamento até o card. Referências: página < 3 s; conferência < 30 s; geração < 2 min por 10 m; card em até 1 min."><svg class="i s" viewBox="0 0 20 20" aria-hidden="true"><path d="M2.75 10a7.25 7.25 0 1 0 14.5 0a7.25 7.25 0 1 0 -14.5 0 M10 9v4.5 M10 6.25v.75"></path></svg></span></div>
<table class="table"><thead><tr><th scope="col">Etapa</th><th scope="col" class="r">Média</th><th scope="col" class="r">p95</th><th scope="col" class="r">Amostras</th></tr></thead><tbody id="stats-speed"></tbody></table></section>
</section>
<section id="tab-site" class="page" hidden>
<section class="panel clip">
<div class="phead"><h2>Produtos</h2></div>
<p class="phint">O que o Site mostra e vende agora. Um produto desligado some do Site e o servidor recusa novos pedidos com ele.</p>
<div class="scrollx"><table class="table"><thead><tr><th scope="col">Produto</th><th scope="col">Situação</th><th scope="col">Preço atual</th></tr></thead><tbody id="site-products"></tbody></table></div>
</section>
<section class="panel clip">
<div class="phead"><h2>Preços</h2></div>
<p class="phint">Cada preço vale a partir da data escolhida. Um preço que já começou não muda mais: o histórico fica abaixo. Só um preço agendado pode ser cancelado.</p>
<div id="site-prices"></div>
</section>
</section>
<section id="tab-users" class="page" hidden>
<section class="panel clip">
<div class="phead"><h2>Pessoas</h2><span class="n" id="users-count"></span>
@@ -188,4 +201,4 @@
<div class="scrim" id="scrim"></div>
<aside class="drawer" id="panel" aria-label="Pedido"></aside>
</div>
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script></body></html>
<script src="/upload.js"></script><script src="/kanban-viewer.js"></script><script src="/kanban.js"></script><script src="/kanban-site.js"></script></body></html>

View File

@@ -59,7 +59,8 @@ const mayAct=order=>ME?.role!=='operador'||order.state==='tra'||isMine(order);
// Vendedor and Financeiro consult Cotações and Números without acting there.
const consults=()=>['vendedor','financeiro'].includes(ME?.role);
const TAB_NEEDS={quotes:o=>may('manage')||consults(),payments:()=>may('payments'),
stats:()=>may('manage')||consults(),integrations:()=>may('manage')||may('print'),users:()=>may('users')};
stats:()=>may('manage')||consults(),site:()=>may('manage'),
integrations:()=>may('manage')||may('print'),users:()=>may('users')};
function applyRole(){
for(const b of document.querySelectorAll('[data-tab]')){const need=TAB_NEEDS[b.dataset.tab];b.hidden=!!need&&!need();}
if(TAB_NEEDS[tab]&&!TAB_NEEDS[tab]())showTab('board');
@@ -654,14 +655,14 @@ async function load(quiet=false){
}
}
// The page's name in the top bar; Produção also says what is open.
const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',integrations:'Integrações',users:'Usuários'};
const PAGE_TITLES={board:'Produção',quotes:'Cotações',payments:'Pagamentos',stats:'Números',site:'Site',integrations:'Integrações',users:'Usuários'};
function showTab(name){
tab=name;$('tab-quotes').classList.remove('reviewing');
for(const b of document.querySelectorAll('[data-tab]'))b.setAttribute('aria-selected',String(b.dataset.tab===name));
$('page-title').textContent=PAGE_TITLES[name];$('board-summary').hidden=name!=='board';$('filter-open').hidden=name!=='board';
$('more-nav').classList.toggle('on',['integrations','users'].includes(name));
for(const id of ['board','quotes','payments','stats','integrations','users'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
for(const id of ['board','quotes','payments','stats','site','integrations','users'])$('tab-'+id).hidden=name!==id;
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers};
if(board&&lists[name])lists[name]().catch(e=>say(e.message,true));
}
function render(){
@@ -674,7 +675,7 @@ function render(){
tinyHeader();renderBoard();renderIntegrations();
$('badge-more').textContent=$('badge-integrations').textContent;
// Lists live on their own pages of the API; refresh the one being looked at.
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,integrations:eventsIfAllowed,users:loadUsers};
const lists={quotes:loadQuotes,payments:loadIssues,stats:loadStats,site:loadSiteAdmin,integrations:eventsIfAllowed,users:loadUsers};
if(lists[tab])lists[tab]().catch(e=>say(e.message,true));
if(openOrder){const order=board.orders.find(o=>o.id===openOrder);if(order)renderPanel(order);else closePanel();}
}

View File

@@ -54,9 +54,12 @@ function pintaTipoEnvio(){
$('tipoAvulsaPreco').textContent=rs(PRECO[avulsa])+' /m';
$('larguraFolhaPronta').textContent=String(MODOS[folha].larg).replace('.',',');
const atual = ehFolha() ? 'folha' : 'avulsa';
// A product switched off in the Kanban cannot be chosen (front 8).
const ligado=m=>!(window.dtfProducts&&window.dtfProducts[m]&&!window.dtfProducts[m].enabled);
el.querySelectorAll('.cam').forEach(b=>{
const alvo=b.dataset.tipo==='folha'?folha:avulsa;
b.classList.toggle('on', b.dataset.tipo===atual);
b.disabled=folhas.length>0 || artes.length>0; // já tem arquivo: a escolha está feita
b.disabled=!ligado(alvo) || folhas.length>0 || artes.length>0; // já tem arquivo: a escolha está feita
});
}
function avisoTipo(txt){