DocumentaçãoDocumentationDocumentaciónOne Conecta
ÍndiceIndexÍndice
Baixar .mdDownload .mdBajar .md
Feature · RelatóriosFeature · ReportsFeature · Reportes

RelatóriosReportsReportes

Uma área de relatórios do dia aberta pelo menu lateral. Uma tela-índice lista as opções que o mercado e o tipo de representante permitem; hoje há duas: Status de entrega (lista das notas fiscais emitidas e seu estado de entrega) e Resumo do dia (contagens do dia). Tudo é somente leitura — nada é enviado. A day reports area opened from the side drawer. An index screen lists the options the market and rep type allow; today there are two: Delivery status (list of issued invoices and their delivery state) and Daily summary (the day's counts). Everything is read-only — nothing is submitted. Un área de reportes del día abierta desde el menú lateral. Una pantalla-índice lista las opciones que el mercado y el tipo de representante permiten; hoy hay dos: Estado de entrega (lista de las facturas emitidas y su estado de entrega) y Resumen del día (los conteos del día). Todo es solo lectura — nada se envía.

PúblicoAudiencePúblico
Representante · QA · Suporte · DevRep · QA · Support · DevRepresentante · QA · Soporte · Dev
Onde ficaWhereDónde
Menu lateral → RelatóriosSide drawer → ReportsMenú lateral → Reportes
RelacionadoRelatedRelacionado
AtualizadoUpdatedActualizado
22/07/20262026-07-22
Disponível emAvailable inDisponible en BR CL
01

O que é e para que serveWhat it is and what it's forQué es y para qué sirve

Relatórios é o item do menu lateral que abre uma tela-índice com as opções de relatório disponíveis para o representante de vendas naquele mercado. Cada opção abre uma tela própria. Hoje existem duas opções. Reports is the side-drawer item that opens an index screen with the report options available to the sales rep in that market. Each option opens its own screen. Two options exist today. Reportes es el ítem del menú lateral que abre una pantalla-índice con las opciones de reporte disponibles para el representante de ventas en ese mercado. Cada opción abre su propia pantalla. Hoy hay dos opciones.

Índice de relatóriosReports indexÍndice de reportes

Uma lista de cartões de navegação. Quais aparecem depende do mercado e do tipo do representante.A list of navigation cards. Which appear depends on the market and the rep type.Una lista de tarjetas de navegación. Cuáles aparecen depende del mercado y del tipo de representante.

Status de entregaDelivery statusEstado de entrega

Um cartão por nota fiscal emitida: número, estado de entrega, PDV e número da NF.One card per issued invoice: number, delivery state, store and legal number.Una tarjeta por factura emitida: número, estado de entrega, PDV y número de NF.

Resumo do diaDaily summaryResumen del día

Um cartão de contagens: emitidas, entregues, retornadas, reagendadas, total, valor total e parcelas boleto.A counts card: issued, delivered, returned, rescheduled, total, total value and bank-slip installments.Una tarjeta de conteos: emitidas, entregadas, devueltas, reprogramadas, total, valor total y cuotas boleto.

Como os números aparecemHow the numbers appearCómo aparecen los números As duas telas cruzam as notas fiscais do relatório com os Pedidos já baixados (cache local) para montar cada lista e cada contagem. Por isso os relatórios dependem da Lista de pedidos ter sincronizado antes. Both screens join the report's invoices with the already-downloaded Orders (local cache) to build each list and each count. That's why the reports depend on the Order list having synced first. Ambas pantallas cruzan las facturas del reporte con los Pedidos ya descargados (caché local) para armar cada lista y cada conteo. Por eso los reportes dependen de que la Lista de pedidos haya sincronizado antes.

02

Como acessarHow to openCómo acceder

  1. Abra o menu lateralOpen the side drawerAbra el menú lateralToque no menu e escolha Relatórios. O item só existe onde o mercado o habilita (BR e CL).Tap the menu and pick Reports. The item exists only where the market enables it (BR and CL).Toque el menú y elija Reportes. El ítem solo existe donde el mercado lo habilita (BR y CL).
  2. A tela-índice abreThe index screen opensLa pantalla-índice abreCom seta de voltar e a data da última sincronização. Lista os cartões permitidos para o seu tipo de representante.With a back arrow and the last-sync date. It lists the cards allowed for your rep type.Con flecha de volver y la fecha de última sincronización. Lista las tarjetas permitidas para su tipo de representante.
  3. Toque num relatórioTap a reportToque un reporteAbre a tela do relatório (Status de entrega ou Resumo do dia), com puxar para atualizar.It opens the report screen (Delivery status or Daily summary), with pull to refresh.Abre la pantalla del reporte (Estado de entrega o Resumen del día), con deslizar para actualizar.
03

Estrutura da telaScreen structureEstructura de la pantalla

São três telas. Todas rolam em coluna única e trazem, no topo, a data da última sincronização e o título com ícone.Three screens. All scroll as a single column and show, at the top, the last-sync date and the icon title.Son tres pantallas. Todas se desplazan en una columna única y muestran, arriba, la fecha de última sincronización y el título con ícono.

ÍndiceIndexÍndice
Data de sincronização + título "Relatórios" + um cartão de navegação por opção permitida. Vazio se nenhuma opção é permitida.Sync date + "Reports" title + one navigation card per allowed option. Empty if no option is allowed.Fecha de sincronización + título "Reportes" + una tarjeta de navegación por opción permitida. Vacío si ninguna opción está permitida.
Cabeçalho (nas duas telas de relatório)Header (on both report screens)Encabezado (en ambas pantallas)
Título com ícone, o subtítulo do relatório e um card com Usuário (nome do representante) e Data.Icon title, the report subtitle and a card with User (rep name) and Date.Título con ícono, el subtítulo del reporte y una tarjeta con Usuario (nombre del representante) y Fecha.
Status de entrega — listaDelivery status — listEstado de entrega — lista
Um card por nota fiscal: Nº da Fatura, Status, Nome do PDV e Número da NF. Sem itens, mostra um estado vazio.One card per invoice: Invoice number, Status, Store name and Legal number. With no items, shows an empty state.Una tarjeta por factura: N.º de factura, Estado, Nombre del PDV y Número de NF. Sin ítems, muestra un estado vacío.
Resumo do dia — card de contagensDaily summary — counts cardResumen del día — tarjeta de conteos
Um card com rótulo/valor: Emitida, Entregue, Retornada, Reagendada, Total, Valor total e Parcela - Boleto.A label/value card: Issued, Delivered, Returned, Rescheduled, Total, Total value and Installment - Bank slip.Una tarjeta de etiqueta/valor: Emitida, Entregada, Devuelta, Reprogramada, Total, Valor total y Cuota - Boleto.
04

Status de entregaDelivery statusEstado de entrega

Cada nota fiscal traz um estado de entrega, derivado do estado de entrega do pedido correspondente. O texto exibido agrupa os estados em quatro rótulos:Each invoice carries a delivery state, derived from the matching order's delivery status. The displayed text groups states into four labels:Cada factura trae un estado de entrega, derivado del estado de entrega del pedido correspondiente. El texto mostrado agrupa los estados en cuatro etiquetas:

AbertoOpenAbierto
Estados pending e not delivered — a nota foi emitida mas ainda não foi entregue.pending and not delivered states — the invoice was issued but not yet delivered.Estados pending y not delivered — la factura fue emitida pero aún no entregada.
EntregueDeliveredEntregado
Estado delivered.delivered state.Estado delivered.
RetornadaReturnedDevuelto
Estado rejected.rejected state.Estado rejected.
ReagendadaRescheduledReprogramado
Estado rescheduled.rescheduled state.Estado rescheduled.

Só aparece o que tem pedido em cacheOnly what has a cached order showsSolo aparece lo que tiene pedido en caché Uma nota fiscal do relatório só vira linha/contagem se houver, no cache local, um Pedido com aquela nota. Notas sem pedido correspondente são ignoradas — por isso a Lista de pedidos precisa ter sincronizado. A report invoice becomes a row/count only if the local cache has an Order with that invoice. Invoices with no matching order are skipped — that's why the Order list must have synced. Una factura del reporte se vuelve fila/conteo solo si el caché local tiene un Pedido con esa factura. Las facturas sin pedido correspondiente se ignoran — por eso la Lista de pedidos debe haber sincronizado.

05

AçõesActionsAcciones

Relatórios é somente leitura: não cria, edita nem envia nada. As únicas interações são navegar e atualizar.Reports is read-only: it creates, edits and submits nothing. The only interactions are navigate and refresh.Reportes es solo lectura: no crea, edita ni envía nada. Las únicas interacciones son navegar y actualizar.

Abrir um relatórioOpen a reportAbrir un reporte
O cartão do índice leva à tela do relatório. Não há filtros nem busca.The index card opens the report screen. No filters, no search.La tarjeta del índice lleva a la pantalla del reporte. No hay filtros ni búsqueda.
Puxar para atualizarPull to refreshDeslizar para actualizar
Nas duas telas de relatório, puxar para baixo re-busca do servidor (o índice não tem esse gesto). O relatório é rebaixado e os números recalculados.On both report screens, pull down to re-fetch from the server (the index has no such gesture). The report is re-downloaded and the numbers recomputed.En ambas pantallas de reporte, deslizar hacia abajo vuelve a buscar del servidor (el índice no tiene ese gesto). El reporte se vuelve a descargar y los números se recalculan.
06

Arquitetura e fluxo de dadosArchitecture & data flowArquitectura y flujo de datos

Clean Architecture + Riverpod + Freezed + ObjectBox. Feature somente leitura (nenhuma escrita/Dispatcher). Duas frentes: a tela-índice (dirigida por End Market Configuration) e as duas telas de relatório (cada uma com Notifier próprio que agrega dados cruzando Report + Pedidos).Clean Architecture + Riverpod + Freezed + ObjectBox. Read-only feature (no write/Dispatcher). Two fronts: the index screen (driven by End Market Configuration) and the two report screens (each with its own Notifier aggregating data by joining Report + Orders).Clean Architecture + Riverpod + Freezed + ObjectBox. Feature solo lectura (sin escritura/Dispatcher). Dos frentes: la pantalla-índice (dirigida por End Market Configuration) y las dos pantallas de reporte (cada una con su Notifier que agrega datos cruzando Report + Pedidos).

Índice · dirigido por EMCIndex · EMC-drivenÍndice · dirigido por EMC

A ReportsPage não tem Notifier. Lê o MarketConfiguration (com o reportsConfig) e o currentResourceProvider (tipo do representante), e chama reportsConfig.visibleOptionsFor(repType:) para decidir os cartões:ReportsPage has no Notifier. It reads the MarketConfiguration (with reportsConfig) and currentResourceProvider (rep type), and calls reportsConfig.visibleOptionsFor(repType:) to decide the cards:ReportsPage no tiene Notifier. Lee el MarketConfiguration (con reportsConfig) y el currentResourceProvider (tipo de representante), y llama reportsConfig.visibleOptionsFor(repType:) para decidir las tarjetas:

  • MarketConfigurationreportsConfig · EMC
    • + currentResource.resourceTypevisibleOptionsFor(repType:)→ List<ReportType>
      • optionsReportsOptionsListWidget
        • → UIReportsPage

Relatório · agregação Report + PedidosReport · Report + Orders aggregationReporte · agregación Report + Pedidos

Cada tela de relatório tem seu Notifier. O UseCase busca o Report (referências) no ReportRepository e os Pedidos no OrderRepository, cruza notas fiscais por invoiceSfid e produz uma entity derivada (lista ou contagens). Origem padrão = cache local; o refresh() força source: remote:Each report screen has its Notifier. The UseCase fetches the Report (references) from ReportRepository and Orders from OrderRepository, joins invoices by invoiceSfid and produces a derived entity (list or counts). Default origin = local cache; refresh() forces source: remote:Cada pantalla de reporte tiene su Notifier. El UseCase busca el Report (referencias) en ReportRepository y los Pedidos en OrderRepository, cruza facturas por invoiceSfid y produce una entity derivada (lista o conteos). Origen por defecto = caché local; el refresh() fuerza source: remote:

  • ReportRepositoryReport · cache/remote
    • getReport + OrderRepository.getOrdersGetDeliveryStatusReportUseCase
      · GetDailySummaryReportUseCase
      join por invoiceSfid
      • execute(source)DeliveryStatusReportEntity
        · DailySummaryReportEntity
        derivada
        • _load / guardedBuildReportDeliveryStatusNotifier
          · ReportDailySummaryNotifier
          • → UIReportDeliveryStatusPage
            · ReportDailySummaryPage
07

Modelo de dadosData modelModelo de datos

O dado persistido — o Report — existe em quatro representações ligadas por mappers, com cache write-through: Proto (wire gRPC) → DTO (Freezed) → Model (ObjectBox) → Entity (domínio). Mas o Report guarda apenas listas de referência (sfids de notas fiscais, pedidos e pagamentos), não os números que a tela mostra.The persisted data — the Report — exists in four representations linked by mappers, with write-through cache: Proto (gRPC wire) → DTO (Freezed) → Model (ObjectBox) → Entity (domain). But Report holds only reference lists (invoice, order and payment sfids), not the numbers the screen shows.El dato persistido — el Report — existe en cuatro representaciones unidas por mappers, con caché write-through: Proto (wire gRPC) → DTO (Freezed) → Model (ObjectBox) → Entity (dominio). Pero Report guarda solo listas de referencia (sfids de facturas, pedidos y pagos), no los números que la pantalla muestra.

Os números vêm de duas entities derivadasDeliveryStatusReport e DailySummaryReportcalculadas nos UseCases a partir do Report + Pedidos em cache. Elas não têm proto/DTO/Model e não são persistidas. A seguir, na ordem: o proto de origem, as estruturas persistidas campo-a-campo por camada, as estruturas derivadas, os mappers e os deltas.The numbers come from two derived entitiesDeliveryStatusReport and DailySummaryReportcomputed in the UseCases from the Report + cached Orders. They have no proto/DTO/Model and are not persisted. Next, in order: the origin proto, the persisted structures field-by-field per layer, the derived structures, the mappers and the deltas.Los números vienen de dos entities derivadasDeliveryStatusReport y DailySummaryReportcalculadas en los UseCases a partir del Report + Pedidos en caché. No tienen proto/DTO/Model y no se persisten. A continuación, en orden: el proto de origen, las estructuras persistidas campo a campo por capa, las estructuras derivadas, los mappers y los deltas.

Pendências / roadmapPending / roadmapPendientes / roadmap O ReportReply traz do servidor agregados prontosrealizedDeliveries e daily (13 campos: conclusão de visita, visitas produtivas, real × planejado, ad hoc, linhas, valor líquido, total de pedidos, SKU cumprido, média de produtos, notas, parcelas ticket/nota de crédito/Pix). Hoje o mapper descarta esses dois blocos — o ReportEntity guarda só listas de referência, e o Resumo do dia recalcula um subconjunto no cliente cruzando com Pedidos. Também não há tela consumindo orders, digitalOrders e paymentSfids ainda. Roadmap: consumir os agregados do servidor direto. ReportReply carries ready-made aggregates from the server — realizedDeliveries and daily (13 fields: visit conclusion, productive visits, real vs planned, ad hoc, lines, net value, total orders, fulfilled SKU, average products, invoices, ticket/credit-note/Pix installments). Today the mapper drops both blocksReportEntity keeps only reference lists, and Daily summary recomputes a subset client-side by joining with Orders. No screen consumes orders, digitalOrders or paymentSfids yet either. Roadmap: consume the server aggregates directly. ReportReply trae del servidor agregados listosrealizedDeliveries y daily (13 campos: conclusión de visita, visitas productivas, real vs planificado, ad hoc, líneas, valor neto, total de pedidos, SKU cumplido, promedio de productos, facturas, cuotas ticket/nota de crédito/Pix). Hoy el mapper descarta ambos bloques — el ReportEntity guarda solo listas de referencia, y el Resumen del día recalcula un subconjunto en el cliente cruzando con Pedidos. Tampoco hay pantalla consumiendo orders, digitalOrders ni paymentSfids aún. Roadmap: consumir los agregados del servidor directamente.

Proto

ReportConectaRep.proto · proto3 · package mn.bat.conectarep.streambridge. Um único método unário. O Reply é rico, mas só parte é mapeada (ver Estruturas abaixo e as Pendências acima).ReportConectaRep.proto · proto3 · package mn.bat.conectarep.streambridge. A single unary method. The Reply is rich, but only part is mapped (see Structures below and Pending above).ReportConectaRep.proto · proto3 · package mn.bat.conectarep.streambridge. Un único método unario. El Reply es rico, pero solo parte se mapea (ver Estructuras abajo y Pendientes arriba).

getReportunaryunaryunary
MétodoMethodMétodo

rpc getReport(ReportRequest) returns (ReportReply)

path /mn.bat.conectarep.streambridge.ReportConectaRepService/getReport

Request · ReportRequest
locationHierarchySfid
string · #1 · hierarquia do representante (resolvida no Repository, §25)rep hierarchy (resolved in the Repository, §25)jerarquía del representante (resuelta en el Repository, §25)
dateReference
string · #2 · optional · envia "hoje" (nowDateReference)sends "today" (nowDateReference)envía "hoy" (nowDateReference)
lastModifiedDate
string · #3 · optional (não usado hoje)optional (not used today)optional (no usado hoy)
Reply · ReportReply

Seis campos: realizedDeliveries (ReportRealizedDeliveries), daily (ReportDaily), orders (repeated ReportOrderReference), issuedInvoices (repeated ReportInvoiceReference), digitalOrders (repeated ReportOrderReference) e payments (ReportPayments). O app mapeia apenas issuedInvoices, orders, digitalOrders e payments.paymentSfids — as Estruturas abaixo.Six fields: realizedDeliveries (ReportRealizedDeliveries), daily (ReportDaily), orders (repeated ReportOrderReference), issuedInvoices (repeated ReportInvoiceReference), digitalOrders (repeated ReportOrderReference) and payments (ReportPayments). The app maps only issuedInvoices, orders, digitalOrders and payments.paymentSfids — the Structures below.Seis campos: realizedDeliveries (ReportRealizedDeliveries), daily (ReportDaily), orders (repeated ReportOrderReference), issuedInvoices (repeated ReportInvoiceReference), digitalOrders (repeated ReportOrderReference) y payments (ReportPayments). La app mapea solo issuedInvoices, orders, digitalOrders y payments.paymentSfids — las Estructuras abajo.

Estruturas de dadosData structuresEstructuras de datos

Um dropdown por estrutura persistida. Colunas Proto · DTO · Model · Entity; o delta (texto azul) marca onde o tipo primeiro muda. ¹ = optional/injetado no proto.One dropdown per persisted structure. Columns Proto · DTO · Model · Entity; the delta (blue text) marks where the type first changes. ¹ = optional/injected in the proto.Un dropdown por estructura persistida. Columnas Proto · DTO · Model · Entity; el delta (texto azul) marca dónde primero cambia el tipo. ¹ = optional/inyectado en el proto.

  • Report raiz 5 campos
    CampoProtoDTOModelEntity
    lastSyncAtDateTime¹DateTimeDateTime
    issuedInvoicesrepeated ReportInvoiceReferenceList<…DTO>ToMany<…Model>List<…Entity>
    ordersrepeated ReportOrderReferenceList<…DTO>ToMany<…Model>List<…Entity>
    digitalOrdersrepeated ReportOrderReferenceList<…DTO>ToMany<…Model>List<…Entity>
    paymentSfidspayments.paymentSfidsList<String>List<String>List<String>
    • ReportInvoiceReference Report.issuedInvoices[] 2 campos
      CampoProtoDTOModelEntity
      invoiceSfidstringStringStringString
      invoiceLineSfidsrepeated stringList<String>List<String>List<String>
    • ReportOrderReference Report.orders[] · digitalOrders[] 2 campos
      CampoProtoDTOModelEntity
      orderSfidstringStringStringString
      orderLineSfidsrepeated stringList<String>List<String>List<String>

Estruturas derivadas (só domínio)Derived structures (domain-only)Estructuras derivadas (solo dominio)

Montadas nos UseCases; sem proto/DTO/Model. Uma coluna só (Entity).Built in the UseCases; no proto/DTO/Model. Single column (Entity).Construidas en los UseCases; sin proto/DTO/Model. Una sola columna (Entity).

  • DeliveryStatusReport GetDeliveryStatusReportUseCase 2 campos
    CampoEntityOrigemSourceOrigen
    lastSyncAtDateTimereport.lastSyncAt
    itemsList<DeliveryStatusReportItemEntity>um item por nota fiscal com pedido em cacheone item per invoice with a cached orderun ítem por factura con pedido en caché
    • DeliveryStatusReportItem DeliveryStatusReport.items[] 5 campos
      CampoEntityOrigemSourceOrigen
      invoiceSfidStringreference.invoiceSfid
      invoiceNumberStringorder.invoice.invoiceNumber
      legalNumberStringorder.invoice.legalNumber ?? ""
      deliveryStatusDeliveryStatusorder.deliveryStatusType
      accountNameStringorder.accountName
  • DailySummaryReport GetDailySummaryReportUseCase 8 campos
    CampoEntityComo é calculadoHow it's computedCómo se calcula
    lastSyncAtDateTimereport.lastSyncAt
    issuedCountintnotas com status pending/not deliveredinvoices with pending/not deliveredfacturas con pending/not delivered
    deliveredCountintnotas com deliveredinvoices with deliveredfacturas con delivered
    returnedCountintnotas com rejectedinvoices with rejectedfacturas con rejected
    rescheduledCountintnotas com rescheduledinvoices with rescheduledfacturas con rescheduled
    totalCountinttotal de notas com pedido em cachetotal invoices with a cached ordertotal de facturas con pedido en caché
    totalValuedoublesoma de invoice.total das entreguessum of delivered invoice.totalsuma de invoice.total de las entregadas
    ticketInstallmentsCountintparcelas PaymentMode.bankSlip das entreguesPaymentMode.bankSlip installments of deliveredcuotas PaymentMode.bankSlip de las entregadas

Mappers

DireçãoDirectionDirecciónOnde / métodoWhere / methodDónde / métodoNotaNoteNota
JSON → DTOReportDTOMapper.fromMaplê o mock; lastSyncAt parseado ou now(); achata payments.paymentSfidsreads the mock; lastSyncAt parsed or now(); flattens payments.paymentSfidslee el mock; lastSyncAt parseado o now(); aplana payments.paymentSfids
Proto → DTOReportReplyProtoMapper.toDTOlastSyncAt = now() (§21); descarta realizedDeliveries/dailylastSyncAt = now() (§21); drops realizedDeliveries/dailylastSyncAt = now() (§21); descarta realizedDeliveries/daily
DTO → EntityReportDTO.toDomain1:1
Entity → ModelReportEntity.toModelpreenche as três ToManyfills the three ToManyllena las tres ToMany
Model → EntityReportModel.toDomain1:1

Os únicos deltasThe only deltasLos únicos deltas

  • lastSyncAt não existe no proto → injetado por DateTimeUtils.now() no toDTO (§21).lastSyncAt is absent in the proto → injected via DateTimeUtils.now() in toDTO (§21).lastSyncAt no existe en el proto → inyectado por DateTimeUtils.now() en toDTO (§21).
  • paymentSfids é achatado da mensagem aninhada payments.paymentSfids (ReportPayments).paymentSfids is flattened from the nested payments.paymentSfids (ReportPayments).paymentSfids se aplana desde el mensaje anidado payments.paymentSfids (ReportPayments).
  • issuedInvoices/orders/digitalOrders viram ToMany no Model.issuedInvoices/orders/digitalOrders become ToMany in the Model.issuedInvoices/orders/digitalOrders pasan a ToMany en el Model.
  • As entities de tela (DeliveryStatusReport, DailySummaryReport) são derivadas em UseCase — sem proto/DTO/Model.The screen entities (DeliveryStatusReport, DailySummaryReport) are UseCase-derived — no proto/DTO/Model.Las entities de pantalla (DeliveryStatusReport, DailySummaryReport) son derivadas en UseCase — sin proto/DTO/Model.
08

Repository

ReportRepositoryInterface / ReportRepositoryImpl. Só leitura de dado da feature (o save* é cache-writer após fetch). O getReport escolhe a origem por uma árvore de decisão embutida.ReportRepositoryInterface / ReportRepositoryImpl. Feature-data reads only (the save* is a cache-writer after fetch). getReport picks the origin via an embedded decision tree.ReportRepositoryInterface / ReportRepositoryImpl. Solo lectura de dato de la feature (el save* es cache-writer tras el fetch). getReport elige el origen por un árbol de decisión embebido.

  • getReport({DataSourceType source = local}) Result<ReportEntity, Failure>

    Decide a origem e resolve o locationHierarchySfid via currentResourceProvider (§25):Decides the origin and resolves locationHierarchySfid via currentResourceProvider (§25):Decide el origen y resuelve locationHierarchySfid vía currentResourceProvider (§25):

    • useMock ou source == mock_fetchFromMock (mock → salva cache).useMock or source == mock_fetchFromMock (mock → save cache).useMock o source == mock_fetchFromMock (mock → guarda caché).
    • source == local ou offline → _fetchFromCacheOrFail (cache; NetworkFailure se vazio).source == local or offline → _fetchFromCacheOrFail (cache; NetworkFailure if empty).source == local u offline → _fetchFromCacheOrFail (caché; NetworkFailure si vacío).
    • senão → _fetchFromRemoteWithFallback (remote → salva cache; em erro, cai pro cache).else → _fetchFromRemoteWithFallback (remote → save cache; on error, falls back to cache).si no → _fetchFromRemoteWithFallback (remote → guarda caché; en error, cae al caché).
  • getCachedReport() Result<ReportEntity?, Failure>

    Lê o Report do ObjectBox (pode ser null).Reads the Report from ObjectBox (may be null).Lee el Report de ObjectBox (puede ser null).

  • getCachedReportLastSyncAt() DateTime?

    Só o lastSyncAt em cache (sem falhar — retorna null em erro).Just the cached lastSyncAt (never fails — returns null on error).Solo el lastSyncAt en caché (sin fallar — retorna null en error).

  • saveReport({required ReportEntity entity}) Result<void, Failure>

    Cache-writer: limpa e regrava o Report local após um fetch bem-sucedido.Cache-writer: clears and rewrites the local Report after a successful fetch.Cache-writer: limpia y regraba el Report local tras un fetch exitoso.

09

Datasources

Três datasources. Remote e Mock são de método único; Local é CRUD de cache.Three datasources. Remote and Mock are single-method; Local is cache CRUD.Tres datasources. Remote y Mock son de método único; Local es CRUD de caché.

Remote · ReportRemoteDataSource
getReport({locationHierarchySfid, dateReference?, lastModifiedDate?}) ReportDTO
MétodoMethodMétodo
client.getReport(ReportRequest) · gRPC unary
EnvioSendEnvío
ReportRequest com locationHierarchySfid + dateReference/lastModifiedDate quando não vazios.
RetornoReturnRetorno
response.toDTO()
ErroErrorError
GrpcErrorGrpcExceptionHandler.handle; outro → ServerException.
Mock · ReportMockDataSource
getReport() ReportDTO
MétodoMethodMétodo
carrega o asset de mock por mercado (report/report.json, ou *_real_*)loads the per-market mock asset (report/report.json, or *_real_*)carga el asset de mock por mercado (report/report.json, o *_real_*)
RetornoReturnRetorno
ReportDTOMapper.fromMap(jsonMap)
ErroErrorError
CacheException
Local · ReportLocalDataSource

Box<ReportModel> (single-row). Todo método lança CacheException em erro. clearReport limpa também as boxes de referência antes de regravar.Box<ReportModel> (single-row). Every method throws CacheException on error. clearReport also clears the reference boxes before rewriting.Box<ReportModel> (single-row). Cada método lanza CacheException en error. clearReport también limpia las boxes de referencia antes de regrabar.

getReport() ReportEntity?

Primeiro (único) ReportModeltoDomain(), ou null.First (only) ReportModeltoDomain(), or null.Primer (único) ReportModeltoDomain(), o null.

getReportLastSyncAt() DateTime?

Só o lastSyncAt do único registro.Just the single record's lastSyncAt.Solo el lastSyncAt del único registro.

saveReport({required ReportEntity entity}) void

clearReport()entity.toModel()put.clearReport()entity.toModel()put.clearReport()entity.toModel()put.

clearReport() void

Remove ReportInvoiceReferenceModel, ReportOrderReferenceModel e ReportModel.Removes ReportInvoiceReferenceModel, ReportOrderReferenceModel and ReportModel.Elimina ReportInvoiceReferenceModel, ReportOrderReferenceModel y ReportModel.

10

Enums e labelsEnums & labelsEnums y labels

ReportType 3
casevaluei18n key
deliveryStatusdelivery_statusreport_delivery_status
dailySummarydaily_summaryreport_daily_summary
unknownunknownunknown_error
ResourceTypeItem 8 tipo do representante (gating por relatório)rep type (per-report gating)tipo de representante (gating por reporte)
casevalue (wire)
preSalesRepPre-sales Rep
promptSalesRepPrompt-sales Rep
universalRepUniversal Rep
deliveryRepDelivery Rep
telesalesAnalystTelesales Analyst
webAgentDirectWeb Agent - Direct
tradeMarketingRepTrade Marketing Rep
unknownunknown
DeliveryStatus 6 estado de entrega + rótulo de relatóriodelivery state + report labelestado de entrega + etiqueta de reporte
casevalue (wire)rótulo (report)report labeletiqueta (report)
pendingpendingreport_delivery_status_open
notDeliverednot deliveredreport_delivery_status_open
delivereddeliveredreport_delivery_status_delivered
rescheduledrescheduledreport_delivery_status_rescheduled
rejectedrejectedreport_delivery_status_returned
unknown""
11

UseCases

GetReportUseCase acesso ao Report brutoraw Report accessacceso al Report crudo
MétodoMethodMétodoRetornaReturnsRetornaUsoUseUso
execute({source = local})Result<ReportEntity, Failure>Report + salva cacheReport + save cacheReport + guarda caché
getCached()Result<ReportEntity?, Failure>só cachecache-onlysolo caché
getCachedLastSyncAt()DateTime?lastSyncAt do índiceindex lastSyncAtlastSyncAt del índice
GetDeliveryStatusReportUseCase Report + Orders → items
MétodoMethodMétodoRetornaReturnsRetornaUsoUseUso
execute({source = local})Result<DeliveryStatusReportEntity, Failure>busca Report + getOrders(), monta orderByInvoiceSfid e produz um item por nota fiscal com pedido.fetches Report + getOrders(), builds orderByInvoiceSfid and yields one item per invoice with an order.busca Report + getOrders(), arma orderByInvoiceSfid y produce un ítem por factura con pedido.
GetDailySummaryReportUseCase Report + Orders → counts
MétodoMethodMétodoRetornaReturnsRetornaUsoUseUso
execute({source = local})Result<DailySummaryReportEntity, Failure>agrega contagens por bucket de deliveryStatus, soma invoice.total das entregues e conta parcelas boleto.aggregates counts by deliveryStatus bucket, sums delivered invoice.total and counts bank-slip installments.agrega conteos por bucket de deliveryStatus, suma invoice.total de las entregadas y cuenta cuotas boleto.
12

Notifiers & State

A tela-índice (ReportsPage) não tem Notifier — lê providers direto (marketConfigurationProvider, currentResourceProvider e um FutureProvider privado só para o lastSyncAt). As duas telas de relatório têm um Notifier cada, ambos AsyncNotifier com o mixin AsyncGuard (§37): build chama guardedBuild(_load); refresh() re-roda _load(source: remote) via runGuarded, sem AsyncValue.loading (o pull-to-refresh tem indicador próprio).The index screen (ReportsPage) has no Notifier — it reads providers directly (marketConfigurationProvider, currentResourceProvider and a private FutureProvider just for lastSyncAt). The two report screens have one Notifier each, both AsyncNotifier with the AsyncGuard mixin (§37): build calls guardedBuild(_load); refresh() re-runs _load(source: remote) via runGuarded, without AsyncValue.loading (pull-to-refresh has its own indicator).La pantalla-índice (ReportsPage) no tiene Notifier — lee providers directamente (marketConfigurationProvider, currentResourceProvider y un FutureProvider privado solo para el lastSyncAt). Las dos pantallas de reporte tienen un Notifier cada una, ambos AsyncNotifier con el mixin AsyncGuard (§37): build llama guardedBuild(_load); refresh() re-ejecuta _load(source: remote) vía runGuarded, sin AsyncValue.loading (el pull-to-refresh tiene su propio indicador).

MétodosMethodsMétodos

ReportDeliveryStatusNotifier · ReportDailySummaryNotifier
MétodoMethodMétodoRetornoReturnRetornoO que fazWhat it doesQué hace
build()FutureOr<State>observa o UseCase e retorna guardedBuild(() => _load()) (source local).watches the UseCase and returns guardedBuild(() => _load()) (local source).observa el UseCase y retorna guardedBuild(() => _load()) (source local).
_load({source = local})Future<State>currentResource (nome) + useCase.execute(source); monta o State.reads currentResource (name) + useCase.execute(source); builds the State.lee currentResource (nombre) + useCase.execute(source); arma el State.
refresh()Future<void>null-guard em state.value; runGuarded(() => _load(source: remote)).null-guard on state.value; runGuarded(() => _load(source: remote)).null-guard en state.value; runGuarded(() => _load(source: remote)).

State disponível para a PageState available to the PageState disponible para la Page

ReportDeliveryStatusState
Campo/getterField/getterCampo/getterTipoTypeTipo
userNameString
lastSyncAtDateTime
itemsList<DeliveryStatusReportItemEntity>
ReportDailySummaryState
Campo/getterField/getterCampo/getterTipoTypeTipo
userNameString
summaryDailySummaryReportEntity
lastSyncAt getterDateTime → summary.lastSyncAt
13

Pages e widgetsPages & widgetsPages y widgets

Três pages, todas em AppPageShell com displayBackButton e sem drawer. Não há modais.Three pages, all in AppPageShell with displayBackButton and no drawer. No modals.Tres pages, todas en AppPageShell con displayBackButton y sin drawer. No hay modales.

  • ReportsPage índiceindexíndice
    • DataLoadInfo
    • ReportsHeaderWidget ícone + títuloicon + titleícono + título
    • ReportsOptionsListWidget
      • CustomNavigationCard um por opção; toca → AppRouter.goToReport*one per option; tap → AppRouter.goToReport*uno por opción; toca → AppRouter.goToReport*
  • ReportDeliveryStatusPage
    • CustomPullToRefresh
      • DataLoadInfo
      • ReportsHeaderWidget
      • ReportSectionTitleWidget
      • ReportInfoHeaderCard Usuário + DataUser + DateUsuario + Fecha
      • ReportDeliveryItemCardWidget um por item, ou CustomEmptyStateone per item, or CustomEmptyStateuno por ítem, o CustomEmptyState
  • ReportDailySummaryPage
    • CustomPullToRefresh
      • DataLoadInfo
      • ReportsHeaderWidget
      • ReportSectionTitleWidget
      • ReportInfoHeaderCard
      • ReportDailySummaryCardWidget 7 linhas de contagem7 count rows7 filas de conteo

Notas por mercadoMarket notesNotas por mercado

Relatórios é dirigido por End Market Configuration. O item de menu reports e o bloco reportsConfig só existem em BR e CL; onde o item não está no menuConfig (ZA, e AR/PY/PE), a tela é inalcançável.Reports is driven by End Market Configuration. The reports menu item and the reportsConfig block exist only in BR and CL; where the item is absent from menuConfig (ZA, and AR/PY/PE), the screen is unreachable.Reportes se rige por End Market Configuration. El ítem de menú reports y el bloque reportsConfig solo existen en BR y CL; donde el ítem está ausente del menuConfig (ZA, y AR/PY/PE), la pantalla es inalcanzable.

BRx CLx ZA AR PY PE
disponívelavailabledisponible presente, desligadopresent, offpresente, apagado ausenteabsentausente

Habilitação por mercadoEnablement per marketHabilitación por mercado

Chave EMCEMC keyClave EMCBRCLZAARPYPE
menuConfigreports xx
reportsConfigdelivery_status xx
reportsConfigdaily_summary xx

Gating por tipo de representante (BR/CL)Per rep-type gating (BR/CL)Gating por tipo de representante (BR/CL)

Dentro de BR/CL, cada opção lista allowedResourceTypes; o card só aparece se o tipo do representante logado estiver na lista (isVisible && contém).Within BR/CL, each option lists allowedResourceTypes; the card shows only if the logged-in rep type is in the list (isVisible && contains).Dentro de BR/CL, cada opción lista allowedResourceTypes; la tarjeta aparece solo si el tipo del representante logueado está en la lista (isVisible && contiene).

Tipo (wire)Type (wire)Tipo (wire)delivery_statusdaily_summary
pre_sales_repx
prompt_sales_repxx
universal_repxx
delivery_rep
telesales_analyst
web_agent_direct
trade_marketing_rep
BR

BrasilBrazilBrasil Único mercado com deliveredBankSlips e pixInstallments no proto daily. A contagem de "Parcela - Boleto" do Resumo do dia usa PaymentMode.bankSlip — relevante sobretudo no Brasil. The only market with deliveredBankSlips and pixInstallments in the proto daily. Daily summary's "Bank-slip installment" count uses PaymentMode.bankSlip — relevant chiefly in Brazil. Único mercado con deliveredBankSlips y pixInstallments en el proto daily. El conteo "Cuota - Boleto" del Resumen del día usa PaymentMode.bankSlip — relevante sobre todo en Brasil.

ZA · AR · PY · PE Não têm o item reports no menu nem reportsConfig — a feature é inalcançável. AR/PY/PE existem como mercados do app com config PANGEA mínima; ZA tem app completo, mas Relatórios não foi habilitado. They have neither the reports menu item nor reportsConfig — the feature is unreachable. AR/PY/PE exist as app markets with minimal PANGEA config; ZA has the full app, but Reports was not enabled. No tienen el ítem reports en el menú ni reportsConfig — la feature es inalcanzable. AR/PY/PE existen como mercados de la app con config PANGEA mínima; ZA tiene la app completa, pero Reportes no fue habilitado.