Lista de pedidosOrder listLista de pedidos
A lista de pedidos do representante de vendas: todos os pedidos dos varejos sob a sua hierarquia, com status, busca, filtros e acesso ao detalhe. Somente leitura — a criação de pedido vive em outro fluxo. The sales rep's order list: every order from the retails under their hierarchy, with status, search, filters and drill-down to detail. Read-only — order creation lives in another flow. La lista de pedidos del representante de ventas: todos los pedidos de los puntos de venta bajo su jerarquía, con estado, búsqueda, filtros y acceso al detalle. Solo lectura — la creación vive en otro flujo.
O que é e para que serveWhat it is and what it's forQué es y para qué sirve
A Lista de pedidos reúne, num só lugar, todos os pedidos dos varejos que estão sob a hierarquia de localização do representante de vendas — não é por varejo, é a lista inteira. Responde três perguntas do dia a dia: The Order list gathers, in one place, every order from the retails under the sales rep's location hierarchy — it's not per-retail, it's the whole list. It answers three everyday questions: La Lista de pedidos reúne, en un solo lugar, todos los pedidos de los puntos de venta bajo la jerarquía de ubicación del representante de ventas — no es por punto de venta, es la lista entera. Responde tres preguntas del día a día:
Quais pedidos existem?Which orders exist?¿Qué pedidos hay?
Um card por pedido, com varejo, valor, nota fiscal e data de entrega.One card per order, with retail, value, invoice and delivery date.Una tarjeta por pedido, con punto de venta, valor, factura y fecha de entrega.
Em que status estão?What status are they in?¿En qué estado están?
Cada pedido tem uma tag colorida: enviado, pendente ou rejeitado.Each order has a colored tag: ordered, pending or rejected.Cada pedido tiene una etiqueta de color: enviado, pendiente o rechazado.
O que fazer com um?What to do with one?¿Qué hacer con uno?
Tocar num card abre o detalhe, onde ficam itens, pagamentos e ações.Tapping a card opens the detail, where items, payments and actions live.Tocar una tarjeta abre el detalle, donde están ítems, pagos y acciones.
Somente leituraRead-onlySolo lectura Esta tela apenas consulta pedidos. Criar, editar, liberar ou cancelar acontece no detalhe do pedido ou no fluxo de carrinho — não aqui. This screen only views orders. Creating, editing, releasing or cancelling happens in the order detail or the cart flow — not here. Esta pantalla solo consulta pedidos. Crear, editar, liberar o cancelar ocurre en el detalle del pedido o en el flujo del carrito — no aquí.
Como acessarHow to openCómo acceder
- Pela barra inferiorFrom the bottom barDesde la barra inferiorToque na aba Pedidos na navegação inferior. É uma das telas base do app.Tap the Orders tab in the bottom navigation. It's one of the app's base screens.Toque la pestaña Pedidos en la navegación inferior. Es una de las pantallas base de la app.
- Pelo atalho da HomeFrom the Home shortcutDesde el atajo del HomeO módulo Pedidos pendentes na Home abre a lista já filtrada na aba Pendentes.The Pending orders module on Home opens the list already filtered on the Pending tab.El módulo Pedidos pendientes del Home abre la lista ya filtrada en la pestaña Pendientes.
- A lista abreThe list opensLa lista abreMostra os pedidos mais recentes primeiro. Puxe para baixo para atualizar.It shows the most recent orders first. Pull down to refresh.Muestra los pedidos más recientes primero. Deslice hacia abajo para actualizar.
Estrutura da telaScreen structureEstructura de la pantalla
- CabeçalhoHeaderEncabezado
- Título "Pedidos" e a data da última sincronização dos dados."Orders" title and the last sync date of the data.Título "Pedidos" y la fecha de última sincronización.
- AbasTabsPestañas
- Pendentes e Rejeitados, cada uma com um contador. Filtram a lista por grupo de status.Pending and Rejected, each with a counter. They filter the list by status group.Pendientes y Rechazados, cada una con un contador. Filtran la lista por grupo de estado.
- AçõesActionsAcciones
- Botões Ordenar e Filtrar (Filtrar aparece só onde habilitado).Sort and Filter buttons (Filter shows only where enabled).Botones Ordenar y Filtrar (Filtrar solo donde está habilitado).
- CardsCardsTarjetas
- Um por pedido: varejo e SAP, número/PO, nota fiscal, valor + volume, data e status de entrega, e as tags de status e origem.One per order: retail and SAP, number/PO, invoice, value + volume, delivery date and status, plus the status and source tags.Una por pedido: punto de venta y SAP, número/PO, factura, valor + volumen, fecha y estado de entrega, más las etiquetas de estado y origen.
- Contador "X de Y""X of Y" counterContador "X de Y"
- Mostra quantos pedidos estão visíveis do total filtrado; a lista carrega mais ao rolar.Shows how many orders are visible out of the filtered total; the list loads more as you scroll.Muestra cuántos pedidos están visibles del total filtrado; la lista carga más al desplazar.
Status dos pedidosOrder statusesEstados del pedido
Cada pedido tem um status, e cada status pertence a um grupo que define a cor da tag (a lista completa dos ~31 status está na seção técnica Enums):Each order has a status, and each status belongs to a group that sets the tag color (the full list of ~31 statuses is in the technical Enums section):Cada pedido tiene un estado, y cada estado pertenece a un grupo que define el color de la etiqueta (la lista completa de ~31 estados está en la sección técnica Enums):
Idioma dos statusStatus languageIdioma de los estados O texto do status vem em inglês, direto do backend, e é exibido como está (não é traduzido). É uma decisão de produto — o status é um código de negócio compartilhado entre times. The status text comes in English, straight from the backend, and is shown as-is (not translated). This is a product decision — the status is a shared business code across teams. El texto del estado viene en inglés, directo del backend, y se muestra tal cual (no se traduce). Es una decisión de producto — el estado es un código de negocio compartido entre equipos.
Buscar, ordenar e filtrarSearch, sort and filterBuscar, ordenar y filtrar
BuscaSearchBúsqueda
O campo de busca filtra por número do pedido, PO, nome do varejo ou SAP enquanto você digita.The search field filters by order number, PO, retail name or SAP as you type.El campo de búsqueda filtra por número de pedido, PO, nombre del punto de venta o SAP mientras escribe.
OrdenaçãoSortOrdenación
Cinco opções: mais recente (padrão), mais antigo, maior valor, menor valor e nome do varejo.Five options: most recent (default), oldest, highest value, lowest value and retail name.Cinco opciones: más reciente (por defecto), más antiguo, mayor valor, menor valor y nombre del punto de venta.
FiltrosFiltersFiltros
O modal de filtros combina: bloqueios (lock), status, tipo de cliente (vendedor / televendas) e intervalo de datas de entrega. Os filtros só valem depois de tocar em Aplicar.The filter modal combines: locks, status, customer type (seller / telesales) and delivery date range. Filters apply only after you tap Apply.El modal de filtros combina: bloqueos, estado, tipo de cliente (vendedor / televentas) e rango de fechas de entrega. Los filtros valen solo tras tocar Aplicar.
Arquitetura e fluxo de dadosArchitecture & data flowArquitectura y flujo de datos
Clean Architecture + Riverpod + Freezed + gRPC + ObjectBox. A lista é somente leitura: um único RPC (getOrderList) traz o pedido completo. O dado atravessa quatro representações, ligadas por mappers, com cache write-through (todo fetch grava no ObjectBox):Clean Architecture + Riverpod + Freezed + gRPC + ObjectBox. The list is read-only: a single RPC (getOrderList) returns the full order. Data crosses four representations, linked by mappers, with cache write-through (every fetch writes to ObjectBox):Clean Architecture + Riverpod + Freezed + gRPC + ObjectBox. La lista es solo lectura: un único RPC (getOrderList) trae el pedido completo. El dato atraviesa cuatro representaciones, unidas por mappers, con cache write-through (todo fetch graba en ObjectBox):
- OrderReplygRPC proto
- toOrdersDTOOrderDTODTO · Freezed
- toDomainOrderEntitydomain
- toModelOrderModelObjectBox
- toDomainOrderEntitydomain · cache
- watchOrdersNotifier + State
- → UIOrdersPage
- watchOrdersNotifier + State
- toDomainOrderEntitydomain · cache
- toModelOrderModelObjectBox
- toDomainOrderEntitydomain
- toOrdersDTOOrderDTODTO · Freezed
Modelo de dadosData modelModelo de datos
O mesmo pedido existe em quatro representações quase idênticas ao longo das camadas — Proto (wire gRPC) → DTO (Freezed) → Model (ObjectBox) → Entity (domínio) — e cada fronteira é atravessada por um mapper. Os nomes dos campos se mantêm em todas as camadas; muda muito pouco (enums tipados, datas parseadas, relações). O fetch é write-through: todo retorno é gravado no ObjectBox e a UI passa a ler do cache.The same order exists in four near-identical representations across the layers — Proto (gRPC wire) → DTO (Freezed) → Model (ObjectBox) → Entity (domain) — and each boundary is crossed by a mapper. Field names stay the same across layers; very little changes (typed enums, parsed dates, relations). Fetch is write-through: every response is written to ObjectBox and the UI then reads from cache.El mismo pedido existe en cuatro representaciones casi idénticas a lo largo de las capas — Proto (wire gRPC) → DTO (Freezed) → Model (ObjectBox) → Entity (dominio) — y cada frontera se cruza con un mapper. Los nombres se mantienen en todas las capas; cambia muy poco (enums tipados, fechas parseadas, relaciones). El fetch es write-through: toda respuesta se graba en ObjectBox y la UI lee del caché.
A lista chega num container OrdersEntity (lastSyncAt gerado no mapper + orders[]); cada item é um Order de 52 campos, com sub-estruturas aninhadas — pagamentos, itens, bloqueios e nota fiscal. Os enums só existem tipados na Entity; em Proto/DTO/Model trafegam como String. A seguir, na ordem: o proto que transporta tudo, as estruturas de dados campo-a-campo por camada, e os mappers que ligam as camadas.The list arrives in an OrdersEntity container (lastSyncAt generated in the mapper + orders[]); each item is a 52-field Order with nested sub-structures — payments, items, locks and invoice. Enums are only typed in the Entity; in Proto/DTO/Model they travel as String. Next, in order: the proto that carries everything, the field-by-field data structures per layer, and the mappers that link the layers.La lista llega en un container OrdersEntity (lastSyncAt generado en el mapper + orders[]); cada ítem es un Order de 52 campos, con sub-estructuras anidadas — pagos, ítems, bloqueos y factura. Los enums solo están tipados en la Entity; en Proto/DTO/Model viajan como String. A continuación, en orden: el proto que transporta todo, las estructuras de datos campo a campo por capa, y los mappers que unen las capas.
Proto
OrderConectaRep.proto · proto3 · package mn.bat.conectarep.streambridge. Um serviço (OrderConectaRepService), um método unário:One service (OrderConectaRepService), a single unary method:Un servicio (OrderConectaRepService), un método unario:
getOrderListunaryrpc getOrderList(OrderRequest) returns (OrderReply)
path /mn.bat.conectarep.streambridge.OrderConectaRepService/getOrderList
OrderRequestlocationHierarchySfidstring· #1 · hierarquia do representante de vendas (resolvida no repository)sales rep hierarchy (resolved in the repository)jerarquía del representante de ventas (resuelta en el repository)dateReferencestring· #2 · optionallastModifiedDatestring· #3 · optional (não usado hoje)optional (not used today)optional (no usado hoy)
OrderReplyrepeated Order orderList — a lista de pedidos. Os 52 campos de Order estão detalhados nas Estruturas de dados abaixo.the list of orders. Order's 52 fields are detailed in Data structures below.la lista de pedidos. Los 52 campos de Order están detallados en Estructuras de datos abajo.
Estruturas de dadosData structuresEstructuras de datos
Um dropdown por estrutura, aninhados pela hierarquia (as linhas ligam pai e filhos). Cada tabela tem uma coluna por camada — Proto · DTO · Model · Entity; as células com borda marcam onde o tipo primeiro muda (relação ToMany/ToOne no Model, enum na Entity, rename no Proto). ¹ = optional no proto.One dropdown per structure, nested by hierarchy (lines link parent and children). Each table has one column per layer — Proto · DTO · Model · Entity; bordered cells mark where the type first changes (ToMany/ToOne relation in the Model, enum in the Entity, rename in the Proto). ¹ = optional in the proto.Un dropdown por estructura, anidados por jerarquía (las líneas unen padre e hijos). Cada tabla tiene una columna por capa — Proto · DTO · Model · Entity; las celdas con borde marcan dónde primero cambia el tipo (relación ToMany/ToOne en el Model, enum en la Entity, rename en el Proto). ¹ = optional en el proto.
Order raiz 52 campos
Campo Proto DTO Model Entity sfidstring String String String namestring String String String purchaseOrderNumberstring String String String retailerPoNumberstring String String String visitIdstring String String String filtersrepeated OrderFilterInfo List<…DTO> ToMany<…Model>List<…Entity> orderStatusstring String String OrderStatusdeliveryStatusstring String String String orderDatestring String String String deliveryDatestring String String String createdAtstring String String String lastModifiedAtstring String String String orderTypestring String String String orderSourcestring String String OrderSourceorderResourceTypestring String String ResourceTyperesourceNamestring String String String accountNamestring String String String accountSapIdstring String String String accountSfidstring String String String isTelesalesbool bool bool bool subtotaldouble double double double discountdouble double double double creditNotedouble double double double cashFeedouble¹ double? double? double? vatdouble¹ double? double? double? totaldouble double double double volumestring String String String volumeUnitstring String String String paymentMethodstring String String PaymentMode?creditDaysstring String String String paymentsrepeated OrderPayment List<…DTO> ToMany<…Model>List<…Entity> pixStatusstring String String String pixKeystring String String String pixQrCodestring String String String hasLocksbool bool bool bool locksrepeated OrderLock List<…DTO> ToMany<…Model>List<…Entity> isErrorbool bool bool bool errorMessagestring String? String? String? rejectionReasonstring String? String? String? lineItemsrepeated OrderLineItem List<…DTO> ToMany<…Model>List<…Entity> isPromptOrderbool¹ bool? bool? bool? isPromptFulfillmentbool¹ bool? bool? bool? canCancelbool bool bool bool canEditbool bool bool bool canReleasebool bool bool bool canCheckStatusbool bool bool bool canPrintInvoicebool¹ bool? bool? bool? canPrintBankSlipcanPrintBoleto¹bool? bool? bool? canGenerateInvoicePdfbool¹ bool? bool? bool? canTerminateVisitbool¹ bool? bool? bool? canSendToExternalApprovalbool¹ bool? bool? bool? invoiceoptional¹ OrderInvoice …DTO? ToOne<…Model>…Entity? OrderPayment Order.payments[] 6 campos
Campo Proto DTO Model Entity sfidstring String String String sequencestring String String String statusstring String String String valuedouble double double double dueDatestring String DateTime?DateTime? paymentMethodstring String String PaymentMode?OrderLineItem Order.lineItems[] · = InvoiceLineItem 9 campos
Campo Proto DTO Model Entity sfidstring String String String categorystring String String String skustring String String String unitstring String String String productTradeSKUstring String String String productManufacturingSKUstring String String String valuedouble double? double? double? qtyint32 int int int isFreeOfChargebool bool bool bool OrderLock Order.locks[] 4 campos
Campo Proto DTO Model Entity typestring String String OrderLockTypemessagestring String? String? String? productsrepeated LockProduct List<…DTO> ToMany<…Model>List<…Entity> categoriesrepeated LockCategory List<…DTO> ToMany<…Model>List<…Entity> LockProduct OrderLock.products[] 5 campos
Campo Proto DTO Model Entity skustring String String String targetdouble double double double requesteddouble double double double minimumGoaldouble double double double missingdouble double double double LockCategory OrderLock.categories[] 3 campos
Campo Proto DTO Model Entity categorystring String String String valuedouble double double double minimumdouble double double double
OrderInvoice Order.invoice 13 campos
Campo Proto DTO Model Entity sfidstring String String String invoiceNumberstring String String String invoiceStatusstring String String String invoiceDatestring String String String legalNumberstring String? String? String? subtotaldouble double double double discountdouble double double double creditNoteValuedouble double double double totaldouble double double double isVisitDeliverybool bool? bool? bool? isPickListedbool bool? bool? bool? lineItemsrepeated InvoiceLineItem List<…DTO> ToMany<…Model>List<…Entity> printingDataPrintingData¹— — — InvoiceLineItem OrderInvoice.lineItems[] 9 campos
Campo Proto DTO Model Entity sfidstring String String String categorystring String String String skustring String String String unitstring String String String productTradeSKUstring String String String productManufacturingSKUstring String String String valuedouble double? double? double? qtyint32 int int int isFreeOfChargebool bool bool bool
OrderFilterInfo Order.filters[] 2 campos
Campo Proto DTO Model Entity filterNamestring String String String valuestring String String String
Mappers
As conversões entre as camadas, todas como extension (5 direções por tipo):The conversions between layers, all as extensions (5 directions per type):Las conversiones entre capas, todas como extension (5 direcciones por tipo):
| DireçãoDirectionDirección | MétodoMethodMétodo |
|---|---|
| JSON → DTO | static fromMap(Map) |
| Proto → DTO | toDTO() |
| DTO → Entity | toDomain() (resolve enums: fromString/fromCode)(resolves enums: fromString/fromCode)(resuelve enums: fromString/fromCode) |
| Entity → Model | toModel() (enums → .value/.code; popula ToMany/ToOne)(enums → .value/.code; fills relations)(enums → .value/.code; llena relaciones) |
| Model → Entity | toDomain() |
Os únicos deltasThe only deltasLos únicos deltas
- enums tipados só na Entity (
Stringnas outras)enums typed only in the Entity (Stringelsewhere)enums tipados solo en la Entity (Stringen las demás) dueDateString→DateTime?(no Model, viaDateTimeUtils.tryParse)(in the Model, viaDateTimeUtils.tryParse)(en el Model, víaDateTimeUtils.tryParse)- renamerenamerename
canPrintBoleto→canPrintBankSlip(no Proto)(in the Proto)(en el Proto) OrderInvoice.printingDatadescartado do DTO em diantedropped from the DTO onwarddescartado del DTO en adelante- relações viram
ToMany/ToOneno Modelrelations becomeToMany/ToOnein the Modelrelaciones pasan aToMany/ToOneen el Model lastSyncAtgerado no mapper comDateTimeUtils.now()generated in the mapper withDateTimeUtils.now()generado en el mapper conDateTimeUtils.now()
Repository
OrderRepositoryImpl implementaimplementsimplementa OrderRepositoryInterface e injeta os 3 datasources (mock/local/remote) + ConnectivityService + a flag useMockData + Ref. Método a método:and injects the 3 datasources (mock/local/remote) + ConnectivityService + the useMockData flag + Ref. Method by method:e inyecta los 3 datasources (mock/local/remote) + ConnectivityService + la flag useMockData + Ref. Método a método:
Um dropdown por método — assinatura, retorno e comportamento. O getOrders() traz a árvore de decisão de fonte dentro do próprio detalhe.One dropdown per method — signature, return and behavior. getOrders() carries the source decision tree inside its own detail.Un dropdown por método — firma, retorno y comportamiento. getOrders() trae el árbol de decisión de fuente dentro de su propio detalle.
getOrders({source}) mock / local / remote
RetornaReturnsDevuelve Result<OrdersEntity?, Failure>
Ponto de entrada da lista: decide a fonte pela source + flags, mapeia e grava no cache (write-through). Chamado pelo OrdersNotifier.List entry point: picks the source from source + flags, maps and writes to cache (write-through). Called by OrdersNotifier.Punto de entrada de la lista: elige la fuente por source + flags, mapea y graba en caché (write-through). Llamado por OrdersNotifier.
Árvore de decisão de fonteSource decision treeÁrbol de decisión de fuente
useMockData== true ouorosource == mock→_fetchFromMock(): lê o mock, mapeia, grava no cache. A flag global tem precedência máxima.→_fetchFromMock(): reads the mock, maps, writes to cache. The global flag has top precedence.→_fetchFromMock(): lee el mock, mapea, graba en caché. La flag global tiene máxima precedencia.source == localou offlineor offlineu offline→getCachedOrders()(sem rede).→getCachedOrders()(no network).→getCachedOrders()(sin red).- senão (remoto + conectado)otherwise (remote + connected)si no (remoto + conectado)→
_fetchFromRemoteWithFallback(): lêcurrentResourceProvider; senullcai pro cache; senão chama o remoto comlocationHierarchyId, mapeia, grava no cache; em erro, fallback pro cache.→_fetchFromRemoteWithFallback(): readscurrentResourceProvider; ifnullfalls back to cache; else calls remote withlocationHierarchyId, maps, writes to cache; on error, falls back to cache.→_fetchFromRemoteWithFallback(): leecurrentResourceProvider; sinullcae al caché; si no llama al remoto conlocationHierarchyId, mapea, graba en caché; en error, fallback al caché.
getCachedOrders() local
RetornaReturnsDevuelve Result<OrdersEntity?, Failure>
Só cache. null vira Success(null), não erro — quem chama trata "sem dados" sem falha.Cache only. null becomes Success(null), not an error — callers handle "no data" without a failure.Solo caché. null es Success(null), no error — quien llama trata "sin datos" sin fallo.
getCachedOrdersLastSyncAt() local
RetornaReturnsDevuelve DateTime? (sem Result)(no Result)(sin Result)
Timestamp da última sincronização do container, para o DataLoadInfo.The container's last-sync timestamp, for DataLoadInfo.Timestamp de última sincronización del container, para DataLoadInfo.
getCachedOrderBySfid({orderSfid}) local
RetornaReturnsDevuelve Result<OrderEntity, Failure>
Busca 1 pedido no cache pelo sfid; ausente → Error(CacheFailure). Alimenta o Order Detail (§28 cat. A) — nunca dispara remoto.Fetches 1 order from cache by sfid; missing → Error(CacheFailure). Feeds Order Detail (§28 cat. A) — never triggers remote.Busca 1 pedido en caché por sfid; ausente → Error(CacheFailure). Alimenta el Order Detail (§28 cat. A) — nunca dispara remoto.
saveOrders({entity}) local
RetornaReturnsDevuelve Result<void, Failure>
Destrutivo: clearOrders() + regrava tudo (cascata das boxes filhas). É o cache-writer chamado após cada fetch bem-sucedido.Destructive: clearOrders() + rewrites everything (child boxes cascade). It's the cache-writer called after each successful fetch.Destructivo: clearOrders() + regraba todo (cascada de boxes hijas). Es el cache-writer llamado tras cada fetch exitoso.
getOrdersForAccount({accountSfid}) → getOrders()
RetornaReturnsDevuelve Result<List<OrderEntity>, Failure>
Chama getOrders() e filtra pelos pedidos do varejo (ordena por data desc). Vazio se o sfid vier vazio. Alimenta a tela "últimos pedidos".Calls getOrders() and filters the retail's orders (sorts by date desc). Empty if the sfid is empty. Feeds the "last orders" screen.Llama getOrders() y filtra los pedidos del punto de venta (ordena por fecha desc). Vacío si el sfid viene vacío. Alimenta la pantalla "últimos pedidos".
loadOlderOrdersForAccount({accountSfid, beforeDate}) stub
RetornaReturnsDevuelve Result<List<OrderEntity>, Failure>
Stub — sempre Success([]). Paginação por data ainda não implementada no repositório.Stub — always Success([]). Date pagination not implemented in the repository yet.Stub — siempre Success([]). Paginación por fecha aún no implementada en el repositorio.
Datasources
Um card por datasource (dropdown). No corpo: método, envio, retorno, fluxo de uso e tratamento de erro.One card per datasource (dropdown). In the body: method, what it sends, return, usage flow and error handling.Un card por datasource (dropdown). En el cuerpo: método, envío, retorno, flujo de uso y manejo de errores.
Remote OrderRemoteDataSource gRPC
getOrders({locationHierarchySfid, dateReference?})
- EnvioSendsEnvío
- monta
OrderRequeste chama_client.getOrderList(request)no clientOrderConectaRepServiceClient(viaorderServiceClientProvider).buildsOrderRequestand calls_client.getOrderList(request)onOrderConectaRepServiceClient(viaorderServiceClientProvider).armaOrderRequesty llama_client.getOrderList(request)enOrderConectaRepServiceClient(víaorderServiceClientProvider). - RetornoReturnRetorno
OrdersDTO(viaresponse.toOrdersDTO())(viaresponse.toOrdersDTO())(víaresponse.toOrdersDTO())- Fluxo de usoUsage flowFlujo de uso
- chamado pelo caminho remoto do repository (
_fetchFromRemoteWithFallback), quando online e sem mock; o resultado é gravado no cache.called by the repository's remote path (_fetchFromRemoteWithFallback), when online and not mocking; the result is written to cache.llamado por el camino remoto del repository (_fetchFromRemoteWithFallback), online y sin mock; el resultado se graba en caché. - Tratamento de erroError handlingManejo de errores
GrpcError→GrpcExceptionHandler; outros →ServerException. Em erro, o repository faz fallback pro cache.GrpcError→GrpcExceptionHandler; others →ServerException. On error, the repository falls back to cache.GrpcError→GrpcExceptionHandler; otros →ServerException. En error, el repository hace fallback al caché.
Local OrderLocalDataSource ObjectBox
Envio / fluxo: persistência local via ObjectBox (ObjectBoxDatabase), boxes OrdersModel e OrderModel — sem rede. Alimenta os caminhos cache do repository. Erro: falhas de persistência propagam como exceção (não engolidas).Sends / flow: local persistence via ObjectBox (ObjectBoxDatabase), OrdersModel and OrderModel boxes — no network. Feeds the repository's cache paths. Error: persistence failures propagate as exceptions (not swallowed).Envío / flujo: persistencia local vía ObjectBox (ObjectBoxDatabase), boxes OrdersModel y OrderModel — sin red. Alimenta los caminos caché del repository. Error: fallos de persistencia propagan como excepción (no tragados).
getOrders()
- RetornoReturnRetorno
OrdersEntity?- ComportamentoBehaviorComportamiento
models.first.toDomain()— o agregado único, ounullse o cache está vazio.models.first.toDomain()— the single aggregate, ornullif the cache is empty.models.first.toDomain()— el agregado único, onullsi el caché está vacío.
getOrdersLastSyncAt()
- RetornoReturnRetorno
DateTime?- ComportamentoBehaviorComportamiento
models.first.lastSyncAt— timestamp da última sync do container.— the container's last-sync timestamp.— timestamp de última sincronización del container.
getOrderBySfid({orderSfid})
- RetornoReturnRetorno
OrderEntity?- ComportamentoBehaviorComportamiento
- busca linear em
_orderBox.getAll()pelosfid. É o método que alimenta o Order Detail.linear search over_orderBox.getAll()bysfid. This is the method feeding Order Detail.búsqueda lineal en_orderBox.getAll()porsfid. Es el método que alimenta el Order Detail.
saveOrders({entity})
- RetornoReturnRetorno
void- ComportamentoBehaviorComportamiento
- destrutivo:
clearOrders()+_box.put(entity.toModel())(grava boxes filhas em cascata). Cache-writer após cada fetch.destructive:clearOrders()+_box.put(entity.toModel())(writes child boxes in cascade). Cache-writer after each fetch.destructivo:clearOrders()+_box.put(entity.toModel())(graba boxes hijas en cascada). Cache-writer tras cada fetch.
mergeAdhocOrders({incoming, accountSfid})
- RetornoReturnRetorno
void- ComportamentoBehaviorComportamiento
- substitui os pedidos daquele varejo pelos
incoming(viaAdhocOrdersMerge). Não exposto na interface — usado pelo fluxo Ad Hoc.replaces that retail's orders withincoming(viaAdhocOrdersMerge). Not on the interface — used by the Ad Hoc flow.reemplaza los pedidos de ese punto de venta porincoming(víaAdhocOrdersMerge). No expuesto en la interfaz — usado por el flujo Ad Hoc.
clearOrders()
- RetornoReturnRetorno
void- ComportamentoBehaviorComportamiento
- limpa todas as boxes na ordem filhas→raízes.clears all boxes children→roots.limpia todas las boxes hijas→raíces.
Mock OrderMockDataSource JSON
getOrders()
- EnvioSendsEnvío
- carrega o asset JSON
orders_list_and_detail/orders(por mercado, real vs sintético viauseRealMockData) — sem rede.loads the JSON assetorders_list_and_detail/orders(per market, real vs synthetic viauseRealMockData) — no network.carga el asset JSONorders_list_and_detail/orders(por mercado, real vs sintético víauseRealMockData) — sin red. - RetornoReturnRetorno
OrdersDTO(viaOrdersDTOJsonMapper.fromMap)(viaOrdersDTOJsonMapper.fromMap)(víaOrdersDTOJsonMapper.fromMap)- Fluxo de usoUsage flowFlujo de uso
- usado quando
useMockDataestá ligado ousource == mock; grava no cache como um fetch normal.used whenuseMockDatais on orsource == mock; writes to cache like a normal fetch.usado cuandouseMockDataestá activo osource == mock; graba en caché como un fetch normal. - Tratamento de erroError handlingManejo de errores
- asset ausente ou JSON inválido propaga como exceção (sem rede envolvida).missing asset or invalid JSON propagates as an exception (no network involved).asset ausente o JSON inválido propaga como excepción (sin red involucrada).
Enums e labelsEnums & labelsEnums y labels
Os enums só existem tipados na camada Entity; em DTO/Model/Proto trafegam como String. Lista completa de valores:Enums are only typed in the Entity layer; in DTO/Model/Proto they travel as String. Full value list:Los enums solo están tipados en la Entity; en DTO/Model/Proto viajan como String. Lista completa de valores:
OrderStatus 31 valores + grupo31 values + group31 valores + grupo
| case | value | group |
|---|---|---|
rejected | "Rejected" | rejected |
cancelled | "Cancelled" | rejected |
invalid | "Invalid" | rejected |
terminated | "Terminated" | rejected |
customerBlockedForOrder | "Customer is Blocked for Order" | rejected |
creditOverdueFailed | "Credit/ Overdue Failed" | rejected |
externalApprovalFailed | "External Approval Failed" | rejected |
rejectedBy3pl | "Rejected by 3PL" | rejected |
rejectedBySap | "Rejected by SAP" | rejected |
cancelledNotSync | "Cancelled Not Sync" | rejected |
partiallyFulfilled | "Partially Fulfilled" | rejected |
pendingApproval | "Pending Approval" | pending |
pendingExternalApproval | "Pending External Approval" | pending |
draft | "Draft" | pending |
replenishment | "Replenishment" | pending |
pendingRepApproval | "Pending Rep Approval" | pending |
approved | "Approved" | pending |
approvedNotSync | "Approved Not Sync" | pending |
awaitingPixPayment | "Awaiting Pix Payment" | pending |
ordered | "Ordered" | ordered |
invoiced | "Invoiced" | ordered |
onHold | "On-Hold" | ordered |
confirmedBySap | "Confirmed by SAP" | ordered |
released | "Released" | ordered |
promptFulfillment | "Prompt Fulfillment" | ordered |
onHoldForLpConversion | "On-Hold for LP Conversion" | ordered |
confirmedBy3pl | "Confirmed by 3PL" | ordered |
deliveredBy3pl | "Delivered by 3PL" | ordered |
paymentConfirmedBy3pl | "Payment Confirmed by 3PL" | ordered |
invoicedNotSync | "Invoiced Not Sync" | ordered |
unknown | "Unknown" | unknown |
OrderStatusGroup → cor 5
| group | cor |
|---|---|
pending | warning |
rejected | error |
ordered | success |
notSent | onSurfaceTertiary |
unknown | onSurfaceTertiary |
OrderLockType 12 · traduzido (i18n)12 · translated (i18n)12 · traducido (i18n)
| case | value | i18n key |
|---|---|---|
overdueLock | "overdue_lock" | ordersLockOverdue |
categoryTarget | "category_target" | ordersLockBelowTarget |
missingLock | "missing_lock" | ordersLockPendingSku |
creditRequestLock | "credit_request_lock" | ordersLockCreditDays |
creditLimit | "credit_limit" | ordersLockCreditLimit |
belowVolume | "below_volume" | ordersLockBelowVolume |
mandatorySku | "mandatory_sku" | ordersLockMandatorySku |
mandatoryCategories | "mandatory_categories" | ordersLockMandatoryCategories |
orderLimit | "order_limit" | ordersLockOrderLimit |
highRiskOfDefault | "high_risk_of_default" | ordersLockHighRisk |
orderLock | "order_lock" | ordersLockOffRoute |
unknown | "unknown" | "-" |
PaymentMode 13 · code
| case | code |
|---|---|
bankSlip | ZG |
electronicFundsTransfer | ZE |
bankDeposit | ZB |
cash | ZH |
cheque | ZC |
promissoryNote | ZI |
creditNote | Z9 |
pix | ZX |
creditCard | Z1 |
debitCard | Z2 |
paymentOrder | ZP |
directDebit | ZJ |
mobilePayment | ZM |
OrderSource 6
| case | value |
|---|---|
b2b | "B2B" |
mobile | "Mobile" |
external | "External" |
telesales | "Telesales" |
clone | "Clone" |
unknown | "Unknown" |
OrderSort 5
| case | notanotenota |
|---|---|
mostRecent | padrãodefaultpor defecto |
oldest | — |
highestValue | — |
lowestValue | — |
customerName | — |
OrderTabFilter 2
| case |
|---|
pending |
rejected |
OrderCustomerType 3
| case | value |
|---|---|
seller | "seller" |
telesales | "telesales" |
unknown | — |
OrderTransactionStatus 7
| case | value |
|---|---|
cancelled | "Cancelled" |
awaitingPixPayment | "Awaiting Pix Payment" |
pendingApproval | "PA" |
pendingExternalApproval | "Pending External Approval" |
invoiced | "Invoiced" |
invoicedNotSync | "Invoiced Not Sync" |
onHold | "On-Hold" |
DeliveryStatus 6
| case | value |
|---|---|
pending | — |
notDelivered | "not delivered" |
delivered | — |
rescheduled | — |
rejected | — |
unknown | "" |
OrderType 3
| case | value |
|---|---|
salesRep | "slRep" |
b2b | "B2B" |
unknown | "" |
OrderSubmitIntent 4
| case |
|---|
create |
edit |
release |
cancel |
UseCases
Um dropdown por UseCase; dentro, cada método com assinatura, o que retorna e uso. Os UseCases da lista delegam ao repository (sem lógica extra) e seus providers são keepAlive. Os da pasta order/ marcados como domínio não tocam a camada de dados.One dropdown per UseCase; inside, each method with its signature, what it returns and use. The list UseCases delegate to the repository (no extra logic) and their providers are keepAlive. Those in order/ tagged domain don't touch the data layer.Un dropdown por UseCase; dentro, cada método con su firma, qué devuelve y uso. Los UseCases de la lista delegan al repository (sin lógica extra) y sus providers son keepAlive. Los de la carpeta order/ marcados como dominio no tocan la capa de datos.
GetOrdersUseCase 4 · a listathe listla lista
| MétodoMethodMétodo | RetornaReturnsDevuelve | UsoUseUso |
|---|---|---|
execute({source}) | Result<OrdersEntity?, Failure> | Ponto de entrada da lista. Roteia por source (mock/local/remoto) → repository.getOrders. Chamado pelo OrdersNotifier.List entry point. Routes by source (mock/local/remote) → repository.getOrders. Called by OrdersNotifier.Punto de entrada de la lista. Rutea por source (mock/local/remoto) → repository.getOrders. Llamado por OrdersNotifier. |
getCached() | Result<OrdersEntity?, Failure> | Só cache; null vira Success(null). Usado no refresh(local) e por quem só quer o que já está gravado.Cache only; null becomes Success(null). Used on refresh(local) and by callers wanting only what's stored.Solo caché; null es Success(null). Usado en refresh(local) y por quien solo quiere lo ya grabado. |
getCachedLastSyncAt() | DateTime? | Timestamp da última sincronização (sem Result). Alimenta o DataLoadInfo.Last-sync timestamp (no Result). Feeds DataLoadInfo.Timestamp de última sincronización (sin Result). Alimenta DataLoadInfo. |
getCachedBySfid({orderSfid}) | Result<OrderEntity, Failure> | 1 pedido do cache (ausente → Error(CacheFailure)). Alimenta o Order Detail (§28 cat. A).1 order from cache (missing → Error(CacheFailure)). Feeds Order Detail (§28 cat. A).1 pedido del caché (ausente → Error(CacheFailure)). Alimenta el Order Detail (§28 cat. A). |
GetOrdersForAccountUseCase 1
| MétodoMethodMétodo | RetornaReturnsDevuelve | UsoUseUso |
|---|---|---|
execute({accountSfid}) | Result<List<OrderEntity>, Failure> | Pedidos de um varejo (ordenados por data desc), para a tela "últimos pedidos" — não a lista principal. Vazio se sfid vazio.One retail's orders (sorted by date desc), for the "last orders" screen — not the main list. Empty if sfid empty.Pedidos de un punto de venta (ordenados por fecha desc), para la pantalla "últimos pedidos" — no la lista principal. Vacío si sfid vacío. |
LoadOlderOrdersForAccountUseCase 1 · stub
| MétodoMethodMétodo | RetornaReturnsDevuelve | UsoUseUso |
|---|---|---|
execute({accountSfid, beforeDate}) | Result<List<OrderEntity>, Failure> | Stub — sempre Success([]) (paginação por data não implementada no repo).Stub — always Success([]) (date pagination not implemented in the repo).Stub — siempre Success([]) (paginación por fecha no implementada en el repo). |
DetectOrderActionStockIssuesUseCase 1 · domíniodomaindominio
| MétodoMethodMétodo | RetornaReturnsDevuelve | UsoUseUso |
|---|---|---|
execute({order, products, availableStockByProductSfid, checkVanStock}) | List<OrderActionStockIssueEntity> | Detecta itens pagos faltantes ou com estoque ajustado antes de liberar/editar um pedido. Puro domínio — usado pelo Order Detail.Detects missing or adjusted paid items before releasing/editing an order. Pure domain — used by Order Detail.Detecta ítems pagos faltantes o con stock ajustado antes de liberar/editar un pedido. Puro dominio — usado por Order Detail. |
EvaluateOrderCreationAvailabilityUseCase 1 · domíniodomaindominio
| MétodoMethodMétodo | RetornaReturnsDevuelve | UsoUseUso |
|---|---|---|
execute({stage, ctx}) | OrderCreationAvailabilityEntity | Avalia os blockers de criação de pedido por etapa (OrderCreationStage) — ex.: produtos, limite de crédito. Puro domínio, usado no fluxo de criação.Evaluates order-creation blockers per stage (OrderCreationStage) — e.g. products, credit limit. Pure domain, used in the creation flow.Evalúa los blockers de creación de pedido por etapa (OrderCreationStage) — ej.: productos, límite de crédito. Puro dominio, usado en el flujo de creación. |
Notifier & State
O OrdersNotifier (@riverpod, with AsyncGuard<OrdersState>) é o cérebro da tela. O build() observa os UseCases, escuta DataSyncType.orders (→ refresh(local) quando a sync em background grava) e o ordersEntryFilterProvider (deep-link de tab), e retorna _load(). O State (OrdersState, Freezed) é a fonte única de verdade da page: guarda os pedidos e todo o estado de cliente (tab, busca, filtros, sort, paginação). Toda filtragem/ordenação/paginação é client-side, calculada em getters do State — os métodos abaixo só mutam campos e resetam a paginação quando o recorte muda.The OrdersNotifier (@riverpod, with AsyncGuard<OrdersState>) is the screen's brain. build() watches the UseCases, listens to DataSyncType.orders (→ refresh(local) when background sync writes) and ordersEntryFilterProvider (tab deep-link), and returns _load(). The State (OrdersState, Freezed) is the page's single source of truth: it holds the orders and all client state (tab, search, filters, sort, pagination). All filtering/sorting/pagination is client-side, computed in State getters — the methods below only mutate fields and reset pagination when the slice changes.El OrdersNotifier (@riverpod, with AsyncGuard<OrdersState>) es el cerebro de la pantalla. build() observa los UseCases, escucha DataSyncType.orders (→ refresh(local) cuando la sync en background graba) y ordersEntryFilterProvider (deep-link de pestaña), y retorna _load(). El State (OrdersState, Freezed) es la fuente única de verdad de la page: guarda los pedidos y todo el estado de cliente (pestaña, búsqueda, filtros, sort, paginación). Todo filtrado/orden/paginación es client-side, calculado en getters del State — los métodos abajo solo mutan campos y resetean la paginación cuando cambia el recorte.
MétodosMethodsMétodos
_load({source}) private
RetornoReturnRetorno Future<OrdersState>
Dono único da montagem do State: busca config + orders em paralelo (via ref.read) e monta orders, lastSyncAt e visibleModules. Chamado pelo build() e pelo refresh().Sole owner of building the State: fetches config + orders in parallel (via ref.read) and assembles orders, lastSyncAt and visibleModules. Called by build() and refresh().Dueño único del armado del State: busca config + orders en paralelo (vía ref.read) y arma orders, lastSyncAt y visibleModules. Llamado por build() y refresh().
refresh({source = remote}) pull-to-refresh
RetornoReturnRetorno Future<void>
Recarrega via _load() e preserva o estado de cliente: tab, busca, locks, status, customerType, datas e sort. Só o visibleCount volta a 20. Não seta AsyncValue.loading (o pull-to-refresh tem indicador próprio).Reloads via _load() and preserves client state: tab, search, locks, status, customerType, dates and sort. Only visibleCount resets to 20. Doesn't set AsyncValue.loading (pull-to-refresh has its own indicator).Recarga vía _load() y preserva el estado de cliente: pestaña, búsqueda, locks, status, customerType, fechas y sort. Solo visibleCount vuelve a 20. No setea AsyncValue.loading (pull-to-refresh tiene su propio indicador).
toggleTab(tab)
RetornoReturnRetorno void
Liga/desliga a tab (Pendentes/Rejeitados) — tocar na tab ativa a desativa. Reseta visibleCount.Toggles the tab (Pending/Rejected) — tapping the active tab clears it. Resets visibleCount.Alterna la pestaña (Pendientes/Rechazados) — tocar la activa la desactiva. Resetea visibleCount.
selectTab(tab)
RetornoReturnRetorno void
Fixa a tab (usado pelo deep-link da Home). Reseta visibleCount.Sets the tab (used by the Home deep-link). Resets visibleCount.Fija la pestaña (usado por el deep-link del Home). Resetea visibleCount.
setSearchQuery(query)
RetornoReturnRetorno void
Atualiza o termo de busca (número/PO/varejo/SAP). Reseta visibleCount; a filtragem acontece nos getters.Updates the search term (number/PO/retail/SAP). Resets visibleCount; filtering happens in the getters.Actualiza el término de búsqueda (número/PO/punto de venta/SAP). Resetea visibleCount; el filtrado ocurre en los getters.
setSort(sort)
RetornoReturnRetorno void
Define a ordenação (OrderSort). Reseta visibleCount.Sets the sort (OrderSort). Resets visibleCount.Define la ordenación (OrderSort). Resetea visibleCount.
applyModalFilters(...)
RetornoReturnRetorno void
Aplica os filtros do modal (locks, status, customerType, intervalo de datas) de uma vez. Reseta visibleCount.Applies the modal filters (locks, status, customerType, date range) at once. Resets visibleCount.Aplica los filtros del modal (locks, status, customerType, rango de fechas) de una vez. Resetea visibleCount.
clearModalFilters()
RetornoReturnRetorno void
Limpa todos os filtros do modal. Reseta visibleCount.Clears all modal filters. Resets visibleCount.Limpia todos los filtros del modal. Resetea visibleCount.
loadMore()
RetornoReturnRetorno void
Incrementa visibleCount em 20 (paginação apenas visual — os dados já estão em memória).Increments visibleCount by 20 (visual-only pagination — data is already in memory).Incrementa visibleCount en 20 (paginación solo visual — los datos ya están en memoria).
State disponível para a PageState available to the PageState disponible para la Page
OrdersState campos + gettersfields + getterscampos + getters
| campo | tipo | default |
|---|---|---|
orders | List<OrderEntity> | [] |
lastSyncAt | DateTime? | null |
visibleModules | List<ModuleConfig> | [] |
selectedTab | OrderTabFilter? | null |
searchQuery | String | "" |
selectedLocks | List<OrderLockType> | [] |
selectedStatus | OrderStatus? | null |
selectedCustomerType | OrderCustomerType? | null |
initialDeliveryDate / finalDeliveryDate | DateTime? | null |
sort | OrderSort | mostRecent |
visibleCount | int | 20 |
Getters: filteredOrders (filtro + sort), visibleOrders (recorte), totalFilteredOrders, hasMoreToLoad, pendingCount, rejectedCount, visibleTabs, showsFilter, showsListActions, hasActiveSort, hasActiveModalFilters, hasAnyActiveFilter. Toda filtragem/ordenação/paginação é client-side nos getters.Getters: filteredOrders (filter + sort), visibleOrders (slice), totalFilteredOrders, hasMoreToLoad, pendingCount, rejectedCount, visibleTabs, showsFilter, showsListActions, hasActiveSort, hasActiveModalFilters, hasAnyActiveFilter. All filtering/sorting/pagination is client-side in getters.Getters: filteredOrders, visibleOrders, totalFilteredOrders, hasMoreToLoad, pendingCount, rejectedCount, visibleTabs, showsFilter, showsListActions, hasActiveSort, hasActiveModalFilters, hasAnyActiveFilter. Todo filtrado/orden/paginación es client-side en getters.
Page e widgetsPage & widgetsPage y widgets
A OrdersPage (ConsumerWidget) observa o ordersProvider e monta os widgets filhos. Loading e erro são globais (ordersAsync.when); o conteúdo existe só no ramo data. Árvore de composição:OrdersPage (ConsumerWidget) watches ordersProvider and composes the child widgets. Loading and error are global (ordersAsync.when); content exists only in the data branch. Composition tree:OrdersPage (ConsumerWidget) observa ordersProvider y compone los widgets hijos. Loading y error son globales (ordersAsync.when); el contenido existe solo en la rama data. Árbol de composición:
- OrdersPage
- AppPageShell drawer · connectivity · search · notifications
- CustomLoadingIndicator loading
- FailureStateView error → invalidate
- CustomPullToRefresh data → refresh()
- OrdersHeaderWidget DataLoadInfo + título
- OrdersSectorizerWidget tabs Pending/Rejected + contadores
- CustomInput busca → setSearchQuery
- OrdersActionsWidget ConectaSortButton · ConectaFilterButton
- OrdersSortModalContent modal · ConectaSortModalContent<OrderSort> (OrderSort.selectable) → setSort
- OrdersFiltersModalContent modal · locks · status · customerType · datas (cada seção via hasFilterDetail) → applyModalFilters / clearModalFilters
- OrdersListSectionWidget
- OrdersEmptyWidget CustomEmptyState (vazio)
- InfiniteScrollListView → loadMore()
- OrderCardWidget → goToOrderDetail
- OrderAvatarWidget
- OrderStatusTagWidget
- CustomTag origem
- OrderCardWidget → goToOrderDetail
- PaginationCountIndicator X de Y
- AppPageShell drawer · connectivity · search · notifications
Notas por mercadoMarket notesNotas por mercado
Pedidos é dirigido por configuração de mercado (End Market Configuration), não por código fixo. Está habilitado em três mercados:Orders is driven by market configuration (End Market Configuration), not hardcoded. It's enabled in three markets:Pedidos se rige por configuración de mercado (End Market Configuration), no por código fijo. Está habilitado en tres mercados:
Só no BrasilBrazil onlySolo Brasil
Pix (pixStatus/pixKey/pixQrCode) e boleto/NF-e (canPrintBankSlip, PrintingData) são específicos do Brasil, controlados por pixPaymentAvailable.
Pix (pixStatus/pixKey/pixQrCode) and bank slip/e-invoice (canPrintBankSlip, PrintingData) are Brazil-specific, gated by pixPaymentAvailable.
Pix (pixStatus/pixKey/pixQrCode) y boleto/factura electrónica (canPrintBankSlip, PrintingData) son específicos de Brasil, controlados por pixPaymentAvailable.
África do SulSouth AfricaSudáfrica
Usa unidade secundária para todas as categorias (usesSecondaryUomForAllCategories) e não checa estoque de van em pedidos prompt. VAT é relevante aqui.
Uses secondary UoM for all categories (usesSecondaryUomForAllCategories) and doesn't check van stock for prompt orders. VAT is relevant here.
Usa unidad secundaria para todas las categorías (usesSecondaryUomForAllCategories) y no verifica stock de van en pedidos prompt. El VAT es relevante aquí.
AR · PY · PE
Existem como mercados do app, mas não têm ordersConfig — a tela de Pedidos fica vazia (sem abas, sem lista). A moeda é formatada por mercado (BR/CL/AR/PY estilo 1.234,56; ZA/PE estilo 1,234.56; CLP/PYG sem decimais).
They exist as app markets, but have no ordersConfig — the Orders screen is empty (no tabs, no list). Currency is formatted per market (BR/CL/AR/PY as 1.234,56; ZA/PE as 1,234.56; CLP/PYG without decimals).
Existen como mercados de la app, pero no tienen ordersConfig — la pantalla de Pedidos queda vacía (sin pestañas, sin lista). La moneda se formatea por mercado (BR/CL/AR/PY como 1.234,56; ZA/PE como 1,234.56; CLP/PYG sin decimales).