← Como vender algo que ainda não existe: preview 3D, aprovação e arquitetura no ImpressãoMais3D
Como vender algo que ainda não existe: preview 3D, aprovação e arquitetura no ImpressãoMais3D
Português ↔ English
O produto mais difícil do catálogo era justamente o que não existia
No ImpressãoMais3D, a loja precisava vender dois tipos de item no mesmo fluxo:
- peças prontas;
- peças sob demanda enviadas pelo próprio cliente como arquivo 3D.
O primeiro caso se parece com e-commerce tradicional.
O segundo não.
Se o cliente envia um STL, OBJ ou 3MF, ele não está comprando exatamente um item existente. Está autorizando uma transformação física de um arquivo.
A pergunta crítica deixa de ser "o pagamento passou?" e vira:
o cliente viu o que vamos produzir e aprovou exatamente essa versão?
Essa pergunta orientou a arquitetura inteira.
Renderizar o arquivo não era enfeite; era redução de risco
Preview 3D pode parecer feature visual.
Eu tratei como controle operacional.
arquivo enviado
↓
parse / validação
↓
normalização de cena
↓
render no navegador
↓
cliente revisa
↙ ↘
rejeita aprova
↓
produção liberada
Sem essa etapa, o cliente imagina um resultado e a gráfica imagina outro.
Depois da impressão, a discussão acontece tarde demais.
A prova visual move a validação para antes do custo físico.
React Three Fiber deixou Three.js caber melhor no produto React
Three.js é a base gráfica. React Three Fiber é um renderer React para Three.js, o que me permitiu manter o visualizador dentro do mesmo modelo mental da interface.
Uma cena mínima pode ser algo assim:
<Canvas camera={{ position: [0, 0, 4] }}>
<ambientLight intensity={1.5} />
<Model geometry={geometry} />
<OrbitControls />
</Canvas>
A parte relevante não é desenhar o mesh. É o que acontece antes de exibi-lo.
Arquivos vindos de usuários são heterogêneos:
- escala pode variar;
- origem do modelo pode estar longe do centro;
- orientação pode parecer estranha;
- bounding box pode ser enorme ou minúsculo;
- formato pode falhar no parse.
O preview precisa normalizar a experiência sem fingir que o arquivo é válido quando não é.
Centralizar o objeto melhora a experiência sem alterar o original
Uma técnica comum é calcular bounding box e recentralizar visualmente o objeto.
Conceitualmente:
const box = new THREE.Box3().setFromObject(object)
const center = box.getCenter(new THREE.Vector3())
const size = box.getSize(new THREE.Vector3())
object.position.sub(center)
const maxAxis = Math.max(size.x, size.y, size.z)
const scale = 2 / maxAxis
object.scale.setScalar(scale)
Isso é para visualização.
Eu não quero que o frontend silenciosamente "conserte" o arquivo que será fabricado sem deixar claro o que mudou.
Uma coisa é transformar a câmera e a cena para enxergar melhor. Outra é alterar geometria de produção.
Separar essas responsabilidades evita uma classe perigosa de surpresa.
Preview não é validação geométrica completa
Ver o objeto no navegador não prova que ele é imprimível.
Um mesh pode ter problemas como:
- faces não manifold;
- normais inconsistentes;
- espessura inviável;
- interseções;
- dimensões incompatíveis com a máquina.
Por isso, eu considero importante comunicar o limite da feature.
O preview responde:
"é este objeto que você está enviando e aprovando visualmente?"
Ele não deve prometer:
"este objeto certamente será impresso sem preparação técnica".
Arquitetura boa também é dizer o que um componente não garante.
Aprovação precisava apontar para um artefato imutável
Se o usuário aprova um preview e depois substitui o arquivo, a aprovação anterior não pode continuar valendo.
Então aprovação deve referenciar uma versão.
type Proof = {
id: string
orderItemId: string
sourceFileId: string
version: number
status: 'pending' | 'approved' | 'rejected'
approvedAt?: Date
approvedBy?: string
}
A regra fica clara:
if (proof.sourceFileId !== currentFile.id) {
throw new Error('A prova aprovada não corresponde ao arquivo atual')
}
O nome do arquivo não basta. O vínculo precisa ser estrutural.
Produção é bloqueada por domínio, não por botão escondido
Eu não confio em "o botão de produzir só aparece se estiver aprovado" como proteção suficiente.
UI é conveniência. Invariante vive abaixo dela.
function releaseToProduction(item: OrderItem) {
if (item.paymentStatus !== 'paid') {
throw new DomainError('Pagamento pendente')
}
if (item.proofStatus !== 'approved') {
throw new DomainError('Prova visual pendente')
}
return item.markProductionReleased()
}
Mesmo se alguém chamar a API diretamente, a transição continua protegida.
Esse é um padrão que uso muito: regra importante deve sobreviver à interface.
Vinte módulos não significam vinte microserviços
O projeto acabou organizado em cerca de vinte bounded contexts, incluindo catálogo, preço, carrinho, pedido, pagamento, arte, prova visual, expedição, cupom, campanha, CRM e base de conhecimento da IA.
Minha decisão deliberada foi mantê-los em um monólito modular.
Por quê?
Porque fronteira lógica e distribuição física são decisões diferentes.
Eu queria:
- vocabulário separado;
- regras locais;
- imports controlados;
- testes por módulo;
- deploy simples;
- transações locais quando úteis.
Eu não precisava pagar por:
- descoberta de serviço;
- comunicação distribuída;
- consistência eventual em tudo;
- observabilidade de dezenas de processos;
- versionamento de contratos entre serviços.
Microserviços teriam criado problemas que o negócio ainda não possuía.
A regra de dependência virou código
Cada módulo segue uma separação parecida com:
module/
domain/
application/
infrastructure/
presentation/
A parte mais importante é impedir que domain conheça framework ou banco.
Em vez de confiar só em documentação, usei regras de importação para transformar violação arquitetural em erro de desenvolvimento.
domain
↓ permitido
application
↓ permitido
infrastructure / presentation
Nunca ao contrário.
Isso não faz o sistema automaticamente "clean". Mas reduz erosão silenciosa.
RLS era uma segunda linha de defesa
Com Supabase/PostgreSQL, Row Level Security permite colocar autorização dentro do banco.
Isso é especialmente útil em um sistema em que cliente, equipe interna e possivelmente outros perfis acessam recursos diferentes.
Uma política simplificada poderia ser:
CREATE POLICY "customer reads own orders"
ON orders
FOR SELECT
USING (customer_id = auth.uid());
A aplicação ainda valida acesso.
Mas, se uma rota errar um filtro, o banco não precisa errar junto.
Defesa em profundidade faz sentido quando o custo de vazamento é alto.
Testei os fluxos em que o bug vira prejuízo
A suíte E2E não precisava provar que todo card renderiza.
Precisava provar que dinheiro e produção atravessavam os portões corretos.
Eu priorizei cenários como:
pagamento aprovado
+
prova pendente
=
produção BLOQUEADA
pagamento aprovado
+
prova aprovada
=
produção LIBERADA
nova versão de arquivo
=
aprovação anterior inválida
Playwright é especialmente útil aqui porque atravessa frontend, API, autenticação e persistência como o usuário atravessa.
Testar exatamente onde o domínio dói é mais valioso do que perseguir cobertura abstrata.
E a IA? Só onde havia papel claro
O projeto também usa AI SDK em pontos específicos.
Minha regra é não colocar LLM no centro de uma invariante de produção.
IA pode ajudar a:
- explicar opções;
- responder dúvidas da base de conhecimento;
- auxiliar atendimento;
- organizar informação.
Mas "pode produzir?" continua sendo uma decisão determinística baseada em estados verificáveis.
Esse limite ficou ainda mais importante à medida que comecei a trabalhar com agentes.
LLM é ótimo onde existe ambiguidade. Portão operacional deve preferir regra explícita.
O insight que ficou: software para mundo físico precisa pensar em irreversibilidade
Em software puro, muita coisa é reversível.
Rollback de deploy. Update no registro. Reprocessamento de evento. Estorno de operação.
Quando software controla uma ação física, a conta muda.
Impressão consome material. Expedição desloca um objeto. Corte, fabricação e montagem têm custo.
Então eu passei a perguntar mais cedo:
qual é o último ponto em que ainda consigo voltar atrás barato?
No ImpressãoMais3D, esse ponto é antes da produção.
Por isso o preview, a versão da prova, a aprovação e os testes não são features separadas. São camadas diferentes protegendo o mesmo limite de irreversibilidade.
Essa forma de pensar vale para impressão, logística, manufatura, automação industrial e qualquer sistema que termine em uma ação que não pode ser desfeita com git revert.
Referências
The hardest product in the catalog was the one that did not exist yet
In ImpressãoMais3D, customers can upload a model and order something that only becomes a physical object after the purchase.
That changes the usual e-commerce relationship. A customer is not choosing a photo of a finished SKU; they are sending part of the manufacturing input.
The central product question therefore became: how do I reduce uncertainty before production starts?
A preview, an approval record and a production gate may look like independent features. In practice, they protect the same boundary.
Rendering the uploaded file was risk reduction, not decoration
Supporting STL, OBJ or 3MF-like flows in the browser is useful because it gives the customer visual feedback before money and material move further through the process.
A simplified pipeline is:
upload
↓
parse model
↓
compute bounds
↓
normalize position / camera
↓
render interactive preview
↓
customer confirms
React Three Fiber was useful because it let the 3D scene live inside a React product without forcing the rest of the application to become a Three.js application.
That distinction matters. The scene is a specialized interface, not the architecture of the whole product.
Centering the model improves UX without modifying the source
Raw uploaded geometry can have arbitrary coordinates. A model can open far from the origin, too large for the camera or positioned in a way that makes the preview look broken.
The renderer can compute a bounding box, derive its center and radius, then transform the preview scene rather than mutating the customer's original file.
Conceptually:
const box = new Box3().setFromObject(model)
const center = box.getCenter(new Vector3())
const size = box.getSize(new Vector3())
model.position.sub(center)
const radius = Math.max(size.x, size.y, size.z) / 2
The exact implementation varies by format and renderer, but the principle is useful: presentation normalization should not silently rewrite the manufacturing artifact.
A preview is not full geometric validation
Seeing a model on screen does not prove it is printable.
A mesh can have issues such as wall thickness, non-manifold geometry, unsupported structures or dimensions that exceed equipment limits.
I therefore avoid presenting a browser preview as an engineering certification. It answers a narrower question: "is this the file and orientation the customer expects?"
That keeps the UI honest and leaves manufacturing validation to rules and human review appropriate to the process.
Approval must point to an immutable artifact
If the customer approves version A and later uploads version B, the system cannot simply keep approved = true on the order.
Approval belongs to a specific proof version.
type ProofVersion = {
id: string
orderId: string
filePath: string
checksum: string
version: number
createdAt: Date
approvedAt?: Date
approvedBy?: string
}
A replacement file creates a new version and therefore a new approval question.
This is a small modeling choice with a large operational consequence: when someone asks what was authorized for production, the system can answer with an exact artifact.
Production is blocked by a domain rule, not by a hidden button
Hiding the "Start production" button in one screen is not a business invariant.
The invariant needs to live closer to the domain:
const canStartProduction =
order.paymentStatus === 'paid' &&
order.proofStatus === 'approved'
Every entry point—admin UI, API, background job—must pass through the same rule.
That matters because physical actions are much more expensive to undo than a database update.
Twenty modules do not mean twenty microservices
The project grew into many bounded contexts, but I deliberately kept a modular monolith.
Examples include catalog, configuration, pricing, cart, orders, files, proofs, payments, production, shipping, users and notifications.
The important architecture work was defining dependencies between modules, not deploying each one independently.
Microservices would have added network failure, distributed tracing, deployment coordination and eventual-consistency questions without a team or load profile that justified them.
A modular monolith gave me strong boundaries with a much smaller operational tax.
A boundary that relies only on discipline will eventually break
Saying "domain code must not import Supabase" is useful documentation. Enforcing it with lint rules is better.
Architectural constraints can become automated feedback:
'no-restricted-imports': ['error', {
patterns: ['@/lib/supabase/*', 'next/*']
}]
The exact paths are project-specific. The idea is not.
When an architecture rule protects maintainability, the toolchain should help defend it.
RLS became a second line of defense
Application-level authorization is necessary, but with Supabase/PostgreSQL I also like database-level Row Level Security for tenant-owned data.
That does not replace server-side checks. It adds another boundary.
A bug that forgets a filter should not automatically become a cross-customer data leak.
Defense in depth is especially useful in products where user files, orders and approvals all carry ownership.
I tested the workflows where a bug becomes physical loss
Not every component needs a browser test.
The critical E2E paths are the ones where state crosses boundaries:
- upload model;
- generate or display preview;
- create order;
- approve the correct proof version;
- verify production remains blocked before approval;
- release production after the required states are satisfied.
Pure calculations belong in unit tests. A production gate deserves an end-to-end test because a defect can consume real material.
And AI? Only where it has a clear job
It is easy to put an LLM in every screen because the product is modern.
I prefer using AI where ambiguity exists—helping classify requests, summarize information or assist support—while keeping operational gates deterministic.
An LLM can be useful when the answer is fuzzy. A manufacturing permission should prefer an explicit rule.
The lesson that stayed with me: physical software must model irreversibility
Pure software gives us many cheap reversals: rollback a deploy, update a record, reprocess an event, refund an operation.
Manufacturing consumes material. Shipping moves an object. Cutting and printing create costs that git revert cannot recover.
So I started asking much earlier:
what is the last point where I can still go back cheaply?
In ImpressãoMais3D, that point is before production.
The preview, proof version, approval and tests are not separate conveniences. They are layers protecting the same irreversible boundary.
That way of thinking applies far beyond 3D printing—to logistics, manufacturing, industrial automation and any system whose final side effect happens in the physical world.