Under each art the Prumo warns about, the customer can choose Ajuste Fino or Ajuste Fino Redesenho (vectorize or redraw, per art, +48 h, no batch price). It is a disabled product until Gestão prices it in the Site tab; the server charges it per chosen art, Tiny gets a DTFIMP.AJF.RED line and two more business days, the card shows 'Redesenho · N artes' and the designer gate applies. The preview loop is slice R2. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
265 lines
13 KiB
Python
265 lines
13 KiB
Python
"""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.
|
|
"""
|
|
import re
|
|
from datetime import datetime, timedelta, timezone
|
|
from uuid import UUID, uuid4
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
from psycopg.errors import UniqueViolation
|
|
from psycopg.types.json import Jsonb
|
|
|
|
from .. import catalog, grade_rules
|
|
from ..core import db
|
|
from ..core.auth import audit, can
|
|
from ..core.models import CouponNew, CouponUpdate, GradeRules, SitePriceNew, SiteProductToggle
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
def price_row(row):
|
|
return {'id': row['id'], 'unit_cents': row['unit_cents'], 'bands': row['bands'] or [],
|
|
'starts_at': row['starts_at'].isoformat(), 'created_by': row['created_by'],
|
|
'created_at': row['created_at'].isoformat()}
|
|
|
|
|
|
def checked_bands(product, bands):
|
|
"""The bands the row will store; 422 in Portuguese for anything invalid.
|
|
Ajuste Fino counts its bands in arts; the other products in metres."""
|
|
if len(bands) > 5:
|
|
raise HTTPException(422, 'Um preço pode ter no máximo 5 faixas.')
|
|
checked, last = [], None
|
|
for band in bands:
|
|
if not band.from_metres.is_finite() or band.from_metres <= 0:
|
|
raise HTTPException(422, 'O início de cada faixa precisa ser maior que zero.')
|
|
if band.unit_cents <= 0:
|
|
raise HTTPException(422, 'O preço de cada faixa precisa ser maior que zero.')
|
|
if band.unit_cents > 10000000:
|
|
raise HTTPException(422, 'O preço de cada faixa é alto demais.')
|
|
if last is not None and band.from_metres <= last:
|
|
raise HTTPException(422, 'As faixas precisam estar em ordem crescente.')
|
|
last = band.from_metres
|
|
checked.append({'from_metres': str(band.from_metres), 'unit_cents': band.unit_cents})
|
|
return checked
|
|
|
|
|
|
@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, bands, 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'],
|
|
'bands': state[product]['bands'],
|
|
'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 not in ('tratamento', 'redesenho') and body.unit_cents <= 0:
|
|
raise HTTPException(422, 'O preço precisa ser maior que zero.')
|
|
# Redesenho is one price per art: its batch band belongs to the basic only.
|
|
if product == 'redesenho' and body.bands:
|
|
raise HTTPException(422, 'O Redesenho não tem faixas de preço.')
|
|
bands = checked_bands(product, body.bands)
|
|
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, bands)
|
|
VALUES(%s,%s,%s,%s,%s) RETURNING id''',
|
|
(product, body.unit_cents, starts_at, user, Jsonb(bands))).fetchone()
|
|
audit('site_price_changed', product=product, unit_cents=body.unit_cents, bands=bands,
|
|
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}
|
|
|
|
|
|
def as_utc(value):
|
|
if value is None:
|
|
return None
|
|
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
|
|
|
|
|
def coupon_code(value):
|
|
code = (value or '').strip().upper()
|
|
if not re.fullmatch(r'[A-Z0-9-]{3,30}', code):
|
|
raise HTTPException(422, 'O código precisa ter de 3 a 30 letras, números ou hífens.')
|
|
return code
|
|
|
|
|
|
def check_coupon(kind, value, valid_from, valid_until):
|
|
if kind == 'percent' and not 1 <= value <= 90:
|
|
raise HTTPException(422, 'A porcentagem do cupom precisa ser de 1 a 90.')
|
|
if valid_until is not None and valid_until <= valid_from:
|
|
raise HTTPException(422, 'A validade final precisa ser depois do início.')
|
|
|
|
|
|
@router.get('/api/operator/site/coupons')
|
|
def site_coupons(user=Depends(can('manage'))):
|
|
with db.connect() as c:
|
|
rows = c.execute('''SELECT c.*, (SELECT count(*) FROM dtf_local.orders o
|
|
WHERE o.snapshot->'coupon'->>'id'=c.id::text
|
|
AND o.cancelled_at IS NULL AND COALESCE(o.payment->>'provider','') <> 'teste'
|
|
AND o.parent_id IS NULL) AS uses
|
|
FROM dtf_local.coupons c WHERE c.deleted_at IS NULL
|
|
ORDER BY c.paused, c.created_at DESC''').fetchall()
|
|
return {'coupons': [{'id': str(row['id']), 'code': row['code'], 'kind': row['kind'],
|
|
'value': row['value'], 'valid_from': row['valid_from'].isoformat(),
|
|
'valid_until': row['valid_until'].isoformat() if row['valid_until'] else None,
|
|
'min_metres': float(row['min_metres']) if row['min_metres'] is not None else None,
|
|
'max_uses': row['max_uses'], 'max_uses_per_customer': row['max_uses_per_customer'],
|
|
'product': row['product'], 'note': row['note'], 'paused': row['paused'],
|
|
'created_by': row['created_by'], 'created_at': row['created_at'].isoformat(),
|
|
'uses': row['uses']} for row in rows]}
|
|
|
|
|
|
@router.post('/api/operator/site/coupons')
|
|
def create_coupon(body: CouponNew, user=Depends(can('manage'))):
|
|
code = coupon_code(body.code)
|
|
valid_from = as_utc(body.valid_from) or datetime.now(timezone.utc)
|
|
valid_until = as_utc(body.valid_until)
|
|
check_coupon(body.kind, body.value, valid_from, valid_until)
|
|
coupon_id = uuid4()
|
|
try:
|
|
with db.connect() as c:
|
|
if c.execute('SELECT 1 FROM dtf_local.coupons WHERE code=%s AND deleted_at IS NULL',
|
|
(code,)).fetchone():
|
|
raise HTTPException(409, 'Já existe um cupom com este código.')
|
|
c.execute('''INSERT INTO dtf_local.coupons(id,code,kind,value,valid_from,valid_until,
|
|
min_metres,max_uses,max_uses_per_customer,product,note,created_by)
|
|
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)''',
|
|
(coupon_id, code, body.kind, body.value, valid_from, valid_until, body.min_metres,
|
|
body.max_uses, body.max_uses_per_customer, body.product, body.note.strip(), user))
|
|
except UniqueViolation:
|
|
# Two requests with the same new code at once: the partial index decides.
|
|
raise HTTPException(409, 'Já existe um cupom com este código.')
|
|
audit('site_coupon_created', coupon=str(coupon_id), code=code, operator=user)
|
|
return {'id': str(coupon_id)}
|
|
|
|
|
|
@router.post('/api/operator/site/coupons/{coupon_id}')
|
|
def update_coupon(coupon_id: UUID, body: CouponUpdate, user=Depends(can('manage'))):
|
|
fields = body.model_dump(exclude_unset=True)
|
|
# The form never sends null for these; a null would try to write NULL into
|
|
# a NOT NULL column, so an explicit null means "keep what is there".
|
|
for name in ('kind', 'value', 'paused'):
|
|
if name in fields and fields[name] is None:
|
|
fields.pop(name)
|
|
with db.connect() as c:
|
|
row = c.execute('''SELECT * FROM dtf_local.coupons
|
|
WHERE id=%s AND deleted_at IS NULL FOR UPDATE''', (coupon_id,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Cupom não encontrado.')
|
|
kind = fields.get('kind', row['kind'])
|
|
value = fields.get('value', row['value'])
|
|
valid_from = as_utc(fields['valid_from']) if 'valid_from' in fields else row['valid_from']
|
|
valid_from = valid_from or row['valid_from']
|
|
valid_until = as_utc(fields['valid_until']) if 'valid_until' in fields else row['valid_until']
|
|
check_coupon(kind, value, valid_from, valid_until)
|
|
if 'valid_from' in fields:
|
|
fields['valid_from'] = valid_from
|
|
if 'valid_until' in fields:
|
|
fields['valid_until'] = valid_until
|
|
if 'note' in fields:
|
|
fields['note'] = (fields['note'] or '').strip()
|
|
if fields:
|
|
names = list(fields)
|
|
c.execute(f'''UPDATE dtf_local.coupons SET {', '.join(f'{name}=%s' for name in names)}
|
|
WHERE id=%s''', (*[fields[name] for name in names], coupon_id))
|
|
audit('site_coupon_updated', coupon=str(coupon_id), operator=user)
|
|
return {'ok': True}
|
|
|
|
|
|
@router.post('/api/operator/site/coupons/{coupon_id}/delete')
|
|
def delete_coupon(coupon_id: UUID, user=Depends(can('manage'))):
|
|
with db.connect() as c:
|
|
row = c.execute('''UPDATE dtf_local.coupons SET deleted_at=now()
|
|
WHERE id=%s AND deleted_at IS NULL RETURNING code''', (coupon_id,)).fetchone()
|
|
if not row:
|
|
raise HTTPException(404, 'Cupom não encontrado.')
|
|
audit('site_coupon_deleted', coupon=str(coupon_id), code=row['code'], operator=user)
|
|
return {'ok': True}
|
|
|
|
|
|
@router.get('/api/operator/site/grade-rules')
|
|
def site_grade_rules(user=Depends(can('manage'))):
|
|
with db.connect() as c:
|
|
rules = grade_rules.current_rules(c)
|
|
offered = catalog.treatment_offered(c)
|
|
return {'aviso': rules.get('aviso'), 'tratamento': rules.get('tratamento'),
|
|
'treatment_offered': offered}
|
|
|
|
|
|
@router.post('/api/operator/site/grade-rules')
|
|
def save_grade_rules(body: GradeRules, user=Depends(can('manage'))):
|
|
if body.aviso is not None and body.tratamento is not None and body.tratamento > body.aviso:
|
|
raise HTTPException(422, 'A regra do Ajuste Fino precisa ser menor ou igual à do aviso.')
|
|
with db.connect() as c:
|
|
for action, below in (('aviso', body.aviso), ('tratamento', body.tratamento)):
|
|
if below is None:
|
|
c.execute('DELETE FROM dtf_local.grade_rules WHERE action=%s', (action,))
|
|
else:
|
|
c.execute('''INSERT INTO dtf_local.grade_rules(action,below,updated_by,updated_at)
|
|
VALUES(%s,%s,%s,now())
|
|
ON CONFLICT (action) DO UPDATE SET below=EXCLUDED.below,
|
|
updated_by=EXCLUDED.updated_by, updated_at=now()''',
|
|
(action, below, user))
|
|
audit('site_grade_rules_changed', aviso=body.aviso, tratamento=body.tratamento, operator=user)
|
|
return {'ok': True}
|