feat: customers see an order code, not the sequential number
Some checks failed
Build and deploy / Validate source (push) Successful in 5s
Build and deploy / Integration suite on a real stack (push) Failing after 3m2s
Build and deploy / Secret scan and release gate (push) Successful in 6s
Build and deploy / Publish images (push) Has been skipped

"Minha conta" lists and opens orders as "Pedido 1E867B56" (the first 8
characters of the order's id) and searches by that code, so a customer never
sees how many orders the store has. The Kanban shows the code beside the #
number, with a copy button, and its search finds an order by the code a
customer reads out. Tiny keeps its reference (DTF-<number>): it is how a
resent order is found there instead of duplicated, and the WhatsApp notices
the client sends from Tiny use Tiny's own number.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-10-02 16:50:26 -03:00
parent c19941555e
commit d7b1eaae6d
7 changed files with 41 additions and 15 deletions

View File

@@ -13,7 +13,7 @@ from ..artwork import submit_files
from ..core.auth import (DUMMY_PASSWORD_HASH, audit, client_ip, new_session, owner,
login_failed, password_hash, password_matches, session_row, throttle, transfer_guest)
from ..core.models import ArtworkSubmission, EmailChange, Login, PasswordChange, ProfileUpdate, Register
from ..runtime import STATES, file_rows, owned_order, storage
from ..runtime import STATES, file_rows, order_code, owned_order, storage
from ..scanning import require_clean
router = APIRouter()
@@ -166,14 +166,17 @@ ENTRIES = '''WITH live_quote AS (
@router.get('/api/customer/orders')
def orders(identity=Depends(owner), status: Literal['all','pay','prod','cor','fin'] = 'all',
number: int | None = Query(None, ge=1), days: int = Query(0, ge=0, le=3650),
number: int | None = Query(None, ge=1), code: str | None = Query(None, max_length=12, pattern=r'^[0-9A-Fa-f]+$'),
days: int = Query(0, ge=0, le=3650),
page: int = Query(1, ge=1, le=10000), size: int = Query(10, ge=1, le=50)):
"""The customer's orders and the cart waiting for payment, newest first,
filtered and a page at a time, with how many there are in each group."""
params = {'me': identity, 'grp': None if status == 'all' else status, 'number': number,
'code': code.lower() + '%' if code else None,
'since': datetime.now(timezone.utc) - timedelta(days=days) if days else None,
'size': size, 'offset': (page - 1) * size}
where = '''WHERE (%(grp)s::text IS NULL OR grp=%(grp)s) AND (%(number)s::int IS NULL OR number=%(number)s)
AND (%(code)s::text IS NULL OR (kind='order' AND replace(id::text,'-','') LIKE %(code)s))
AND (%(since)s::timestamptz IS NULL OR created_at>=%(since)s)'''
with db.connect() as c:
counts = {r['grp']: r['n'] for r in c.execute(ENTRIES + ' SELECT grp, count(*) AS n FROM entries GROUP BY grp', params).fetchall()}
@@ -183,6 +186,7 @@ def orders(identity=Depends(owner), status: Literal['all','pay','prod','cor','fi
items = []
for r in rows:
entry = {'kind': r['kind'], 'id': r['id'], 'number': r['number'], 'state': r['state'],
'code': order_code(r['id']) if r['kind'] == 'order' else None,
'group': r['grp'], 'total_cents': r['total_cents'], 'created_at': r['created_at'],
'items': [{'mode': i['mode'], 'billed_metres': i.get('billed_metres')} for i in r['items']]}
if r['kind'] == 'quote':
@@ -203,7 +207,8 @@ def detail(oid: UUID, identity=Depends(owner)):
# only a correction's reason is written for the customer.
history = c.execute('''SELECT from_state,to_state,CASE WHEN to_state='cor' THEN reason ELSE '' END AS reason,
created_at FROM dtf_local.movements WHERE order_id=%s AND NOT back ORDER BY id''', (oid,)).fetchall()
return {'id': row['id'], 'number': row['number'], 'state': row['state'], 'version': row['version'],
return {'id': row['id'], 'number': row['number'], 'code': order_code(row['id']),
'state': row['state'], 'version': row['version'],
'created_at': row['created_at'], 'snapshot': row['snapshot'], 'history': history,
'files': file_rows(c,oid)}

View File

@@ -301,6 +301,11 @@ def search(q: str = Query(min_length=2, max_length=100), user=Depends(operator))
if digits and len(digits) <= 9:
sql += ' OR number=%s'
params.append(int(digits))
# The code a customer reads out (the id's first characters, see order_code).
code = q.strip().lstrip('#').lower()
if 6 <= len(code) <= 12 and re.fullmatch(r'[0-9a-f]+', code):
sql += " OR replace(id::text,'-','') LIKE %s"
params.append(code + '%')
quote_match, quote_params = customer_match('q.draft', q)
with db.connect() as c:
orders = c.execute(f'''SELECT * FROM dtf_local.orders WHERE {sql}

View File

@@ -73,6 +73,13 @@ def upload_row(c, upload_id, session_id, lock=False):
return row
def order_code(order_id):
"""What a customer calls an order: the first 8 characters of its id, in
capitals ("F6B9CDBC"). It is stable and says nothing about how many orders
the store has, unlike the sequential number the operators work with."""
return str(order_id).replace('-', '')[:8].upper()
def quote_view(c, row):
from .quote_review import review_reason # it imports this module
order = c.execute('SELECT id,number,state FROM dtf_local.orders WHERE quote_id=%s', (row['id'],)).fetchone()

View File

@@ -353,3 +353,6 @@ a.zap{display:inline-flex;align-items:center;gap:4px;vertical-align:bottom}
.btn.discard:hover{color:var(--bad);border-color:var(--bad-line)}
.callout.bad{background:rgba(244,150,139,.12)}
.callout.bad b{color:var(--bad)}
/* The order code the customer sees, beside the operators' number. */
.ocode{display:inline-flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}

View File

@@ -149,6 +149,9 @@ function paymentBadge(p){
if(p.status==='pending')return badge(p.status_detail==='pending_challenge'?'Cartão aguardando o banco':'Cartão em análise','info',tried.slice(3));
return badge('Pagamento '+p.status,'',tried.slice(3));
}
// What the customer calls the order (the id's first 8 characters, as the
// server's order_code); the # number is the operators'.
const orderCode=id=>String(id).replace(/-/g,'').slice(0,8).toUpperCase();
const sheetSize=p=>p?cm(p.film_width_cm)+' × '+cm(p.height_cm)+' cm':null;
const hoursSince=v=>Math.floor((Date.now()-new Date(v))/3600000);
// The freight's weight: what the package weighs and, when Jadlog charges the
@@ -391,7 +394,9 @@ function renderPanel(order){
const close=node('button',undefined,'close');close.type='button';close.setAttribute('aria-label','Fechar');close.append(icon(['M6 6l12 12M18 6L6 18']));close.onclick=closePanel;
const test=isTest(order)?node('span','TESTE','tag-teste'):null;
if(test)test.title='Pedido de teste: sem pagamento, não vai ao Tiny nem ao WhatsApp';
row.append(node('span','#'+order.number,'num'),stage,...(test?[test]:[]),close);
const code=node('span',undefined,'ocode');code.append('Pedido '+orderCode(order.id),copyButton(orderCode(order.id),'Copiar código do pedido'));
code.title='O código que o cliente vê';
row.append(node('span','#'+order.number,'num'),stage,...(test?[test]:[]),code,close);
// What was paid and when, and whether it is stuck: the first things asked of an order.
const paid=node('div',undefined,'paidline');
paid.append(node('b',money(order.snapshot.total_cents)),isTest(order)?' sem pagamento · '+when(order.created_at):' pago em '+when(order.created_at));
@@ -1022,7 +1027,7 @@ function hitRow(items,title,sub,meta,badge,color,open){
}
function orderHit(order){
const s=order.snapshot;
return hitRow(s.items,'#'+order.number,buyer(s).title,
return hitRow(s.items,'#'+order.number+' · '+orderCode(order.id),buyer(s).title,
s.items.map(i=>SHORT[i.mode]+' · '+metres(i.billed_metres)).join(' + ')+' · '+(s.destination?'Entrega':'Retirada')+' · pago '+when(order.created_at),
order.cancelled_at?'Cancelado':board.states[order.state],order.cancelled_at?'var(--bad)':STAGE_COLORS[order.state],()=>{
// An older finished order is not on the board yet: it joins, like "Carregar mais".

View File

@@ -84,8 +84,8 @@
<p class="acessoIntro" id="guest"></p>
<div class="filtros" id="filtros" role="group" aria-label="Filtrar pedidos"></div>
<div class="busca2">
<label class="sr" for="fNumero">Número do pedido</label>
<input id="fNumero" inputmode="numeric" placeholder="Nº do pedido">
<label class="sr" for="fNumero">Código do pedido</label>
<input id="fNumero" autocomplete="off" placeholder="Código do pedido">
<label class="sr" for="fPeriodo">Período</label>
<select id="fPeriodo">
<option value="30">Últimos 30 dias</option>

View File

@@ -30,7 +30,7 @@ const PRODUTO={file:'DTF Têxtil · folha montada',avulsa:'DTF Têxtil · artes
const TRILHA=['rec','tra','fil','imp','fin'];
const TAMANHO=10;
let scope,states={},environment='',conta=null;
let filtro={status:'all',number:'',days:0,page:1};
let filtro={status:'all',code:'',days:0,page:1};
async function api(path,body){const r=await fetch('/api'+path,{headers:{'Content-Type':'application/json'},...(body===undefined?{}:{method:'POST',body:JSON.stringify(body)})});const d=await r.json();if(!r.ok){const error=new Error(typeof d.detail==='string'?d.detail:'Confira os campos informados.');error.status=r.status;throw error;}return d;}
const aviso=(text,erro)=>{$('message').textContent=text||'';$('message').classList.toggle('erro',!!erro);};
@@ -99,7 +99,7 @@ function resumoItens(items){
function linha(e){
const row=node('div',null,'linha');
const [rotulo,cls]=estado(e);
const num=node('b',e.kind==='quote'?'Carrinho':'#'+e.number,'num');
const num=node('b',e.kind==='quote'?'Carrinho':'Pedido '+e.code,'num');
const oque=node('div',null,'oque');oque.append(node('span',resumoItens(e.items)),node('span',dia(e.created_at),'data'));
const st=node('span',null,'estadoW');st.append(node('span',rotulo,'estado '+cls));
if(e.kind==='quote'&&e.pay_with==='pix')st.append(node('span','PIX','via'));
@@ -158,12 +158,12 @@ function paginas(total){
async function pedidos(){
$('guest').textContent=conta?'':'Você está vendo os pedidos feitos neste navegador. Entre ou crie uma conta para vê-los em qualquer lugar.';
const q=new URLSearchParams({status:filtro.status,days:String(filtro.days),page:String(filtro.page),size:String(TAMANHO)});
if(filtro.number)q.set('number',filtro.number);
if(filtro.code)q.set('code',filtro.code);
const data=await api('/customer/orders?'+q);states=data.states;
filtros(data.counts,data.groups);
const lista=$('orders');lista.replaceChildren();
if(!data.items.length){
const livre=filtro.status==='all'&&!filtro.number&&!filtro.days;
const livre=filtro.status==='all'&&!filtro.code&&!filtro.days;
const vazio=node('div',null,'vazio');
vazio.append(node('p',livre?'Seus pedidos aparecem aqui.':'Nenhum pedido com esse filtro.'));
if(livre){const a=node('a','Enviar uma arte','bPri');a.href='/#envio';vazio.append(a);}
@@ -177,15 +177,16 @@ async function pedidos(){
if(!alvo){
// Not on this page of the list: shown on its own, above it.
try{const o=await api('/customer/orders/'+aberto);
alvo=linha({kind:'order',id:o.id,number:o.number,state:o.state,total_cents:o.snapshot.total_cents,
alvo=linha({kind:'order',id:o.id,number:o.number,code:o.code,state:o.state,total_cents:o.snapshot.total_cents,
created_at:o.created_at,items:o.snapshot.items});lista.prepend(alvo);}catch(e){alvo=null;}
}
if(alvo){await alvo.abrir();alvo.scrollIntoView({block:'start'});}
}
}
let buscaTimer;
$('fNumero').addEventListener('input',e=>{e.target.value=soDigitos(e.target.value);clearTimeout(buscaTimer);
buscaTimer=setTimeout(()=>{filtro={...filtro,number:e.target.value,page:1};pedidos().catch(x=>aviso(x.message,true));},350);});
// The order code the customer was given: letters A–F and digits only.
$('fNumero').addEventListener('input',e=>{e.target.value=e.target.value.toUpperCase().replace(/[^0-9A-F]/g,'').slice(0,8);clearTimeout(buscaTimer);
buscaTimer=setTimeout(()=>{filtro={...filtro,code:e.target.value,page:1};pedidos().catch(x=>aviso(x.message,true));},350);});
$('fPeriodo').addEventListener('change',e=>{filtro={...filtro,days:Number(e.target.value),page:1};pedidos().catch(x=>aviso(x.message,true));});
function itensPedido(snapshot){
@@ -266,7 +267,7 @@ async function geral(){
for(const [key,label] of [['pay','Aguardando pagamento'],['prod','Em produção'],['cor','Correção'],['fin','Finalizados']]){
if(key==='cor'&&!data.counts.cor)continue;
const a=node('a',null,'metrica'+(key==='cor'?' alerta':''));a.href='/conta/pedidos';a.dataset.view='pedidos';
a.addEventListener('click',()=>{filtro={status:key,number:'',days:0,page:1};});
a.addEventListener('click',()=>{filtro={status:key,code:'',days:0,page:1};});
a.append(node('span',label),node('b',String(data.counts[key])));
box.append(a);
}