Skip to main content

Reports API

Version: 1.0 — Draft

Table of contents​

Overview​

The Reports API provides current inventory balances, low-stock estimates, and sales measures for Haravan shops. It supports grouped results, metric selection, sorting, and pagination within the caller's permitted location scope.

ReportOperationPurpose
Inventory balancesGET /inventory/location_balancesCurrent physical, committed, available, incoming quantities and inventory value.
Low stockGET /inventory/low_stocksCurrent availability, daily sales, and estimated days until stockout.
SalesGET /sale_analyticsSales measures for an inclusive order-creation-date interval.

Inventory balances do not support historical snapshots. Low-stock estimates are forecasts based on recent sales, not guaranteed stockout dates. Sales data follows order creation time rather than payment or fulfillment time. Data synchronization latency is unspecified for all three operations.

The separate /v2/sale_analytics and /v2/sale_analytics/summary contracts are outside this specification. Their columns and bracketed filter parameters must not be used with the operations described here.

Concepts and terminology​

Dimensions, metrics, and identifiers​

  • A dimension is an attribute used to group records. Each result row represents a combination of selected dimension values.
  • A metric is a measure calculated for that group.
  • Grouping is not filtering: selecting LocId does not restrict results to one location ID.
  • Product, variant, and location IDs identify different entities. Display names, SKU, barcode, and order numbers are not interchangeable with API IDs.
  • Request enum names and response fields differ in casing and sometimes wording. Use the exact names documented for each operation.

Inventory quantities​

MetricVietnamese label in developer documentationMeaning
QtyOnHandTồn khoPhysical quantity currently held in inventory, before subtracting committed quantity.
QtyCommittedĐặtQuantity reserved for orders that is still included in physical inventory.
QtyAvailableKhả dụngOn-hand quantity minus committed quantity.
QtyIncomingChờ nhậpQuantity expected to arrive that has not yet been added to physical inventory.

The supplied Help summary uses “Không khả dụng” for an incoming-related quantity and identifies contradictions in its definitions. This specification uses the developer definition “Chờ nhập” for QtyIncoming. Exact equivalence with the Help label and detailed transfer-state accounting have not been confirmed. These quantities do not by themselves define checkout eligibility or overselling behavior.

Low stock uses request metric QtyAvailability and response field qtyAvailability, while inventory balances use QtyAvailable and qtyAvailable. Low stock uses committed stock internally but does not expose a separate committed-quantity metric.

Units and inventory value​

Unit represents a unit of measure, such as an item, box, or carton. Selecting it groups by conversion unit. Quantities are converted using the source's UnitRatio; SKU and barcode may then identify the conversion unit rather than the variant's usual SKU and barcode.

TotalCostAmount means the current cost value of inventory (“Giá trị hàng trong kho”). It is not the cost of goods sold. The source formulas use UnitMACost and UnitRatio, but those are calculation inputs, not documented response fields. Their detailed unit basis and the currency of the result remain unspecified.

Stockout estimates​

The developer documents define EstimatedDaysUntilStockout as follows:

Value or conditionMeaning
0 when available quantity is zero or negativeNo available stock remains. This does not necessarily mean physical on-hand quantity is zero.
-1 when there is no sales rateInsufficient sales-rate data for an estimate; it does not mean stock ran out yesterday.
OtherwiseAvailable quantity divided by daily sales, with rounding. The exact rounding rule is not specified.

The source lists the nonpositive-availability condition before the no-sales-rate condition; behavior when both conditions apply should be verified with a live example. A numeric ascending sort is not a business interpretation of urgency: treat the -1 sentinel separately from valid stockout estimates.

Stock-status groups​

The report owner confirms that the UI selects report items based on days remaining until stockout. Supplied screenshots show four stock-status cards, with counts labeled as variants:

UI labelDisplayed classification
Đã hết hàngOut of stock. The API defines estimate 0 for nonpositive availability; the screenshot does not expose this card's exact filter expression.
Sắp hết hàng 1–30 ngày tớiEstimated stockout in 1–30 days.
Sắp hết hàng 31–90 ngày tớiEstimated stockout in 31–90 days.
Sắp hết hàng trên 90 ngàyEstimated stockout in more than 90 days.

The tooltip states that selecting a card filters the detail table. The screenshot for the over-90-day group explicitly shows both filters: days until stockout greater than 90 and daily sales greater than 0. It also confirms the displayed formula: available quantity divided by daily sales.

These groups show that the report includes a category beyond 90 days; the report name does not imply that all report items will run out within 30 or 90 days. Exact treatment of fractional estimates at group boundaries and of the -1 sentinel is not shown. UI variant counts must not be equated with API row counts when grouping differs, such as when a variant appears at multiple locations.

This confirms UI classification and filtering, not public query parameters for /inventory/low_stocks. The endpoint's internal eligibility rules and how the UI applies these filters remain to be confirmed.

Sales measures​

  • Gross sales are sales before discounts; net sales deduct product and loyalty discounts according to the developer definition.
  • Paid amount, returns amount, and actually received are distinct from revenue.
  • MACostAmount is cost of goods sold, not current inventory value (TotalCostAmount).
  • ProfitMargin is a ratio, not an already formatted percentage.
  • OrderCountSpecial counts distinct orders within a group, not necessarily across the whole report.

Capabilities​

The documented API can:

  • Retrieve current inventory quantities and value, estimate stock coverage, and report sales for a date interval.
  • Group data by supported dimensions and calculate selected metrics.
  • Filter sales by order-date interval, cancellation status, and channel.
  • Sort by a selected dimension or metric and paginate grouped results.
CapabilityInventory balancesLow stockSales
Date-range filterNot supportedNo public parameterRequired, inclusive OrderDate interval
Location groupingLocIdLocIdLocation
Unit conversion groupingUnitNot in dimension enumNot in dimension enum
Cancellation/channel filtersNot documentedNot documentedorderStatusId, sourceName
Public product/variant/location value filtersNoneNoneNone
Stockout-threshold filterNot applicableNo public parameterNot applicable

Search, inventory writes, saved-report duplication, and export are not documented for these operations. UI features do not establish API support. Sales customer, traffic-source, and hourly dimensions are not in this endpoint's dimension enum; payment status is a grouping dimension, not a query filter.

Business and API rules​

  • Unselected fields remain in JSON as null, 0, or source-defined defaults. Their presence does not establish that they were calculated.

  • The sort field must be selected as a dimension or metric. Set a compatible order when custom selections omit the default sort metric.

  • Omitting LocId from either inventory report aggregates across permitted locations, not necessarily all shop locations.

  • Inventory reports return zero inventory value without a cost-permission error when cost access is missing. Sales protected metrics instead return an error; see permissions.

  • Empty inventory data can reflect a restricted user with no assigned locations and must not be interpreted as proof of zero stock across the shop.

  • Inventory metric QtyIncoming is incoming stock, not a checkout or overselling rule.

  • Low-stock calculations have an unresolved 30-day query versus 28-day denominator discrepancy; preserve returned values rather than silently recalculating them.

  • Only source records with IsDeleted = 0 are included, according to developer documentation.

  • orderDateStart and orderDateEnd filter OrderDate inclusively. End must not precede start.

  • The report owner confirms that sales, payment, return/refund, and cancellation changes are attributed to the order's creation date. Later activity on an older order therefore affects the creation-date reporting period once reflected in report data, rather than moving that order's contribution to the activity date. Historical report totals can change; they are not a frozen period-end snapshot. Synchronization timing remains unspecified.

  • For example, an order created in October, paid later, and refunded in November remains attributed to October for this report. Its November refund is not attributed to November solely because the refund occurred then. A later cancellation is evaluated within the original creation-date period; a NotCancelled query excludes that cancelled order once its updated state is reflected.

  • Day/month grouping converts data to Asia/Ho_Chi_Minh. This does not establish how offset-free request timestamps are interpreted or guarantee the timezone of every response timestamp.

  • Omitting orderStatusId includes all statuses. Use NotCancelled explicitly when cancelled orders must be excluded.

  • OrderCountSpecial counts distinct orders within each group. An order can contribute to multiple groups, so summing group counts does not necessarily yield distinct orders for the whole interval.

  • Profit margins must not be summed or averaged without the appropriate sales/cost basis.

  • When grouping by product, order-level discounts and loyalty discounts are allocated in proportion to value, as confirmed by the report owner. The precise value basis (for example, before or after existing item discounts) and rounding/remainder handling are not yet specified.

  • The report owner confirms that shipping charges/discounts, VAT, collected payments, and channel fees follow a similar value-proportional allocation principle. This does not imply every charge appears on merchandise rows: the supplied UI example has a separate shipping-charge row. Exact allocation bases, rounding, and API representation of non-merchandise rows remain to be confirmed.

  • Refund amounts are allocated according to the report's first dimension. The report owner confirms that changing dimension order changes allocation. Do not assume refunds are always assigned directly to the returned product or reorder dimensions as an equivalent request. The exact allocation algorithm and its mapping to query-array order require request/response examples.

Help describes positive daily sales and inventory tracking as UI eligibility conditions for low stock. Enforcement by /inventory/low_stocks, and its cancellation/return handling, remain unconfirmed. The confirmed UI day-range groups do not establish public threshold filters.

API operations​

Retrieve current inventory balances​

Purpose​

Use this operation to inspect current stock quantities or inventory value at a supported grouping level. Use LocId when location-level results are needed and include product/variant dimensions when those distinctions must be preserved.

Endpoint​

GET /inventory/location_balances
Authorization: Bearer <JWT>

The base URL is not supplied by the available sources. Do not assume that this endpoint uses the Orders API host or its /com path prefix.

Input​

All documented inputs are query parameters. Defaults below describe omitted parameters; explicit empty values and empty arrays are not separately specified.

ParameterTypeRequiredDefaultDescription
dimensionsarray of stringsNoProductId, VariantIdGrouping fields; see dimension values.
metricsarray of stringsNoQtyOnHand, QtyCommitted, QtyAvailable, QtyIncomingMeasures to calculate; see metric values.
orderstringNoQtyOnHandOne supported dimension or metric that is also selected in this request.
directionstringNoDESCASC for ascending or DESC for descending.
limitinteger, int32No100Rows per page; documented maximum is 2001.
pageinteger, int32No1Page number, starting at 1.

Serialize arrays by repeating the query key:

dimensions=ProductId&dimensions=LocId&metrics=QtyOnHand

Do not substitute comma-separated lists for this documented encoding.

Output​

The operation returns JSON, normally with Content-Type: application/json; charset=utf-8, according to the developer documentation. The supplied Swagger screenshot displays text/plain; actual environment behavior has not been tested for this specification.

Successful results contain errors: [], warnings: [], and a data array. Each data entry represents a group of inventory balances. No matching data returns data: []. The Swagger example also includes hasError and hasWarning; their complete contract is not supplied.

See data definitions for the fields. HTTP 200 can also carry business validation errors; inspect the response envelope before treating the result as successful.

Constraints​

  • Requires Bearer JWT authentication and CanReadReport permission.
  • Only the documented dimensions, metrics, and sort directions are supported.
  • The selected sort field must be present in the requested dimensions or metrics.
  • No public filter parameter or historical date parameter is documented for this operation.
  • Pagination does not include a total count or hasNext; callers must examine returned rows.

Examples​

These requests illustrate the documented contract; they are not captured API executions. Paths are relative because the base URL remains unspecified.

Default grouping and metrics:

GET /inventory/location_balances

On-hand and available quantities by product, variant, and location:

GET /inventory/location_balances?dimensions=ProductId&dimensions=VariantId&dimensions=LocId&metrics=QtyOnHand&metrics=QtyAvailable&order=QtyAvailable&direction=ASC&limit=100&page=1

On-hand quantity and inventory value by product, variant, location, and conversion unit:

GET /inventory/location_balances?dimensions=ProductId&dimensions=VariantId&dimensions=LocId&dimensions=Unit&metrics=QtyOnHand&metrics=TotalCostAmount&order=TotalCostAmount&direction=DESC&limit=100&page=1

The latter example requires cost-view permission for meaningful cost values; see permissions.

Minimal empty-result illustration from the developer envelope description; not a complete live response or a guarantee that other envelope fields are absent:

{
"errors": [],
"warnings": [],
"data": []
}

Retrieve low-stock report data​

Purpose​

Use this operation when current availability and recent sales rate are needed to estimate stock coverage or identify items for replenishment review. Include LocId when separate location-level results are required.

Endpoint​

GET /inventory/low_stocks
Authorization: Bearer <JWT>

The schema is published at Reports Swagger. Its documentation host alone does not confirm the intended production API base URL; deployment configuration remains to be supplied.

Input​

All parameters are optional query parameters. Defaults are from the developer documentation; enum values and numeric bounds are confirmed by OpenAPI. Explicit empty-array behavior is not specified.

ParameterTypeRequiredDefaultValues and constraints
dimensionsarray of stringsNoProductId, VariantIdProductId, VariantId, Barcode, SKU, ProductTypeName, ProductVendorName, LocId.
metricsarray of stringsNoQtySoldPerDay, QtyAvailability, EstimatedDaysUntilStockoutQtySoldPerDay, QtyOnHand, QtyAvailability, EstimatedDaysUntilStockout, TotalCostAmount.
orderstringNoEstimatedDaysUntilStockoutAny of the dimension or metric enum values above, provided it is selected.
directionstringNoASCASC or DESC.
limitinteger, int32No100Minimum 1, maximum 2001. OpenAPI says invalid values use 100.
pageinteger, int32No1Minimum 1, maximum 2147483647. OpenAPI says invalid values use 1.

Repeat query keys to supply multiple dimensions or metrics:

dimensions=ProductId&dimensions=LocId&metrics=QtyAvailability

Do not use comma-separated arrays in place of this documented encoding. LocId is a grouping option, not an input for selecting one location ID.

Output​

Successful responses contain an inventory-report data array, with empty errors and warnings arrays in developer examples. No data returns data: [].

OpenAPI declares text/plain, application/json, and text/json response media types against the same object schema. Developer documentation describes JSON, normally application/json; charset=utf-8. No live report request has been executed for this draft.

HTTP 200 can also contain business validation errors. See response envelope before interpreting data as a successful report.

Constraints​

  • Requires Bearer JWT authentication and CanReadReport permission.
  • order must be included in the selected dimensions or metrics.
  • No public inventory, location, product, or forecast-threshold filters are supplied by this contract.
  • The sales period is not configurable through a documented request parameter.
  • No total count, cursor, or hasNext is available.

Examples​

These relative requests illustrate the contract; they are not captured executions.

Default grouping, metrics, and ordering:

GET /inventory/low_stocks

Sales rate, availability, and stockout estimates by product, variant, and location:

GET /inventory/low_stocks?dimensions=ProductId&dimensions=VariantId&dimensions=LocId&metrics=QtySoldPerDay&metrics=QtyAvailability&metrics=EstimatedDaysUntilStockout&order=EstimatedDaysUntilStockout&direction=ASC&limit=100&page=1

On-hand quantity and inventory value, using an explicitly selected sort metric:

GET /inventory/low_stocks?dimensions=ProductId&dimensions=VariantId&metrics=QtyOnHand&metrics=TotalCostAmount&order=TotalCostAmount&direction=DESC&limit=100&page=1

Cost values in the latter request depend on cost-view permission.

Minimal empty-result illustration from developer documentation, not a full captured response or an assurance that other envelope fields are absent:

{
"errors": [],
"warnings": [],
"data": []
}

Retrieve grouped sales​

Purpose​

Use this operation to report sales quantities, revenue, payments, returns, or profitability for a known order-date interval at a supported grouping level.

Endpoint​

GET /sale_analytics
Authorization: Bearer <JWT>

Schema documentation is available on Reports Swagger. The intended runtime base URL must be supplied by deployment configuration; the Swagger host alone does not confirm the production API host.

Input​

All inputs are query parameters. Defaults are from developer documentation; types, enums, required dates, and bounds are from live OpenAPI.

ParameterTypeRequiredDefault / constraints
orderDateStartstring, date-timeYesInclusive start of order dates. Swagger illustrates ISO 8601 with Z.
orderDateEndstring, date-timeYesInclusive end; must not precede start.
orderStatusIdstring enumNoNotCancelled or Cancelled. Omit to include all statuses.
sourceNamearray of stringsNoSupported technical channel codes listed below. Omission behavior is not explicitly defined in the supplied sources.
dimensionsarray of stringsNoDefault: ProductId, VariantId, SKU, Barcode. See dimension table.
metricsarray of stringsNoDefault: Quantity, ReturnQuantity, GrossSaleAmount, NetSaleAmount. See metric table.
orderstring enumNoDefault GrossSaleAmount; one supported dimension or metric that is selected. Matching is case-insensitive according to Swagger.
directionstring enumNoDefault DESC; ASC or DESC, case-insensitive matching.
limitinteger, int32NoDefault 100; minimum 1, maximum 2001. Invalid values use 100.
pageinteger, int32NoDefault 1; minimum 1, maximum 2147483647. Invalid values use 1.

Repeat query keys for arrays, such as sourceName=web&sourceName=pos or metrics=Quantity&metrics=NetSaleAmount. Empty-array semantics are unspecified. Use canonical enum spelling; case-insensitive behavior is documented only for order and direction.

Output​

Returns a response envelope with grouped rows in data. Developer success examples contain errors: [], warnings: [], and data: [...]; an empty result uses data: [].

OpenAPI declares text/plain, application/json, and text/json against SaleAnalyticLineIEnumerableResult. Developer documentation describes JSON, normally application/json; charset=utf-8.

HTTP 200 can also contain business errors. Inspect the envelope before interpreting rows as valid results. Schema retrieval is not a live report execution.

Constraints​

  • Requires Bearer JWT and CanReadReport, plus cost-view permission for protected metrics.
  • Dates are mandatory and end must be at or after start.
  • Sort must reference a selected dimension or metric.
  • Date-span limits, historical retention, rate limits, and snapshot consistency across pages are unspecified.
  • No total count, cursor, or hasNext is documented.

Examples​

Illustrative relative requests, not captured executions. Timestamps below explicitly use UTC and demonstrate inclusive instants, not a shop-local calendar-month preset.

Default grouping and metrics for an interval, explicitly excluding cancelled orders:

GET /sale_analytics?orderDateStart=2026-10-01T00:00:00.000Z&orderDateEnd=2026-10-31T23:59:59.000Z&orderStatusId=NotCancelled

Daily sales for Web and POS, with a compatible sort field:

GET /sale_analytics?orderDateStart=2026-10-01T00:00:00.000Z&orderDateEnd=2026-10-07T23:59:59.000Z&orderStatusId=NotCancelled&sourceName=web&sourceName=pos&dimensions=Day&dimensions=SourceName&metrics=Quantity&metrics=NetSaleAmount&order=Day&direction=ASC&limit=100&page=1

Product-level profitability, requiring cost-view permission:

GET /sale_analytics?orderDateStart=2026-10-01T00:00:00.000Z&orderDateEnd=2026-10-31T23:59:59.000Z&orderStatusId=NotCancelled&dimensions=ProductId&metrics=NetSaleAmount&metrics=MACostAmount&metrics=Profit&metrics=ProfitMargin&order=NetSaleAmount&direction=DESC&limit=100&page=1

Minimal empty-result illustration from the developer envelope description, not a complete live response:

{
"errors": [],
"warnings": [],
"data": []
}

Data definitions​

Inventory dimensions and fields​

The request dimension enum consists of exactly the nine entries below. The response field names follow the supplied Swagger example. Numeric identifiers and strings are shown in that example; exact integer widths and field-specific nullability require the full response schema.

Request dimensionResponse fieldsMeaning
ProductIdproductId, productNameProduct identifier and display name.
VariantIdvariantId, variantNameVariant identifier and display name, such as a color or size.
LocIdlocId, locNameIdentifier and display name of the location holding inventory balances.
ProductTypeNameproductTypeNameMerchant-defined product type.
ProductVendorNameproductVendorNameProduct brand; the developer document identifies the current UI label as “Thương hiệu” despite the technical vendor name.
SKUskuVariant SKU, or conversion-unit SKU when Unit is selected.
BarcodebarcodeVariant or conversion-unit barcode.
CategoryIdproductCategoryIdProduct category/industry classification (“Ngành hàng”). The request and response names differ.
UnitunitUnit of measure used for grouping and conversion.

Product, variant, and location IDs identify different entities. Display names, SKU, and barcode are not interchangeable with those IDs. The source does not establish their use as parameters in other APIs.

Inventory metrics and formulas​

Formulas below preserve the developer source's internal field spelling, including Qty_Commited. SUM aggregates over the selected group. Internal formula inputs are not additional public query parameters or response fields.

Request metricJSON response fieldFormula from developer source
QtyOnHandqtyOnHandSUM(Qty_OnHand / UnitRatio)
QtyCommittedqtyCommittedSUM(Qty_Commited / UnitRatio)
QtyAvailableqtyAvailableSUM((Qty_OnHand − Qty_Commited) / UnitRatio)
QtyIncomingqtyIncomingSUM(Qty_Incoming / UnitRatio)
TotalCostAmounttotalCostAmountSUM(Qty_OnHand × UnitMACost / UnitRatio)

The Swagger example represents these fields as numbers. It does not establish integer-only quantities, precision, rounding, or field-specific nullability. The source does not specify a default UnitRatio when Unit is omitted. Do not import rounding rules from the separate low-stock API.

Low-stock dimensions and fields​

Request dimensionResponse fieldsSchema typeMeaning
ProductIdproductId, productNameint64 ID; nullable string nameProduct identifier and display name.
VariantIdvariantId, variantNameint64 ID; nullable string nameVariant identifier and display name, such as color or size.
Barcodebarcodenullable stringVariant barcode.
SKUskunullable stringVariant stock-keeping code.
ProductTypeNameproductTypeNamenullable stringMerchant-defined product type.
ProductVendorNameproductVendorNamenullable stringProduct brand; developer documentation uses the UI label “Thương hiệu”.
LocIdlocId, locNameint64 ID; nullable string nameSelling location used for sales rate and inventory availability.

Product, variant, and location IDs identify different entities; names, SKU, and barcode are not interchangeable with those IDs. Unlike the Inventory Report API, this dimension enum does not include CategoryId or Unit.

OpenAPI does not mark numeric IDs nullable and does not declare a required-property list. Developer documentation separately states that unselected fields remain as null or 0; field-specific placeholder behavior should be verified using actual responses.

Low-stock metrics and formulas​

All five response metrics have OpenAPI type number, format double. Formulas retain developer source names for calculation inputs; these inputs are not additional public request parameters.

Request metricResponse fieldDeveloper definition
QtySoldPerDayqtySoldPerDaySUM(Quantity / 28). Average daily sales. The developer source notes a 30-day query window, which conflicts with the Help definition of 28-day sales divided by 28.
QtyOnHandqtyOnHandSum of physical on-hand inventory.
QtyAvailabilityqtyAvailabilitySUM(QtyOnHand − QtyCommitted). Stock remaining after reservations.
EstimatedDaysUntilStockoutestimatedDaysUntilStockoutAvailability divided by daily sales, rounded, with special values 0 and -1 described above. Rounding mode is unspecified.
TotalCostAmounttotalCostAmountSUM(ROUND(QtyOnHand × UnitMACost, 0)). Current inventory cost value.

The placement of ROUND inside SUM is part of the documented inventory-value formula. Its tie-breaking mode and currency are unspecified. Do not replace this with the separate inventory-balance API's unit-conversion formula.

The Help definition supports a 28-day business window but does not resolve the implementation discrepancy reported by the developer source. Preserve the API's returned daily-sales value; do not silently recalculate it using a different period. The exact treatment of returns, qualifying sales, time boundaries, and timezone requires backend confirmation.

Sales dimensions and fields​

The following table is the complete SaleAnalyticDimension enum and its response mapping. Nullable display strings may be absent in meaning even when the field is present.

Request dimensionResponse fieldsMeaning / schema details
Dayday, dayFormatedNullable date-time and nullable display string (dd/MM/yyyy per dev). Preserve the spelling Formated.
Monthmonth, monthFormatedNullable date-time and nullable display string (MM/yyyy per dev).
YearyearNullable int32 year.
DayOfWeekdayOfWeekNullable weekday string; complete value set is unspecified.
ShippingProvinceshippingProvinceId, shippingProvinceNameint32 shipping-province ID and nullable name; not billing province.
ProductIdproductId, productNameint64 product ID and nullable name.
VariantIdvariantId, variantNameint64 variant ID and nullable name.
SKUskuNullable variant SKU.
BarcodebarcodeNullable barcode.
ProductVendorNameproductVendorNameNullable product brand; developer UI label is “Thương hiệu”.
ProductTypeNameproductTypeNameNullable merchant-defined product type.
GatewaygatewayNullable payment-method string.
PaymentStatuspaymentStatusId, paymentStatusNameint32 payment-status ID and nullable name; full mapping unspecified.
OrderNumberorderNumberNullable display order number.
OrderStatusorderStatusId, orderStatusNameint32 status ID and nullable name.
SourceNamesourceNameNullable channel display value; may differ from technical filter code.
PaidUserpaidUserId, paidUserNameint64 ID and nullable name of the employee recording/performing payment.
OrderCreatedUserorderCreatedUser, orderCreatedUserNameint64 order-creator ID and nullable name.
LocationlocationId, locationNameint64 sales-location ID and nullable name. Do not use inventory dimension LocId.

Numeric IDs other than year are not marked nullable. The schema does not declare required-property lists; placeholder behavior for unselected fields is described separately by the developer source.

Sales metrics and formulas​

All metrics are OpenAPI number/double except orderCountSpecial, which is integer/int64. This table is the complete SaleAnalyticMetric enum. Developer documentation says remaining monetary metrics aggregate their corresponding source fields; business descriptions below do not establish undocumented allocation logic.

Request metricResponse fieldMeaning / calculation
QuantityquantitySold quantity; SUM(Quantity).
ReturnQuantityreturnQuantityReturned quantity; SUM(ReturnQuantity).
GrossSaleAmountgrossSaleAmountSales before discounts, described as sold quantity × price; SUM(GrossSaleAmount).
DiscountProductValuediscountProductValueMerchandise discounts, excluding shipping discounts; loyalty discounts are represented separately.
RedeemValueredeemValueLoyalty redemption/discount value (“Giảm giá KHTT”).
NetSaleAmountnetSaleAmountSales after product and loyalty discounts; SUM(NetSaleAmount).
ShippingAmountshippingAmountShipping charges to customers.
DiscountShippingValuediscountShippingValueShipping discounts.
TotalSaleAmounttotalSaleAmountMerchandise and shipping amounts after discounts + ProductTaxNotIncludedAmount + ShippingTaxNotIncludedAmount, as confirmed by the report owner. These tax component fields are not exposed in this endpoint's row schema.
PaidAmountpaidAmountCollected payments across payment methods.
ReturnsAmountreturnsAmountRefunded amount for returns/exchanges. Developer documentation notes that source values may be negative; do not silently change the sign.
ActuallyReceivedactuallyReceivedDeveloper definition: collected payments after refunds and marketplace/channel fees. Exact fee components and signed arithmetic remain unspecified.
MACostAmountmaCostAmountCost of goods sold; SUM(MACostAmount × Quantity) using source calculation inputs.
ProfitprofitNetSaleAmount − MACostAmount.
ProfitMarginprofitMarginProfit / NetSaleAmount; zero when net sales are not positive. Returned as a ratio; multiply by 100 for percentage display.
OrderCountSpecialorderCountSpecialCOUNT DISTINCT OrderId within each group. The source OrderId is not an additional row field.

The report owner confirms the invoice-total formula:

TotalSaleAmount
= Merchandise and shipping amounts after discounts
+ ProductTaxNotIncludedAmount
+ ShippingTaxNotIncludedAmount

ProductTaxNotIncludedAmount is product VAT not included in the selling price and collected additionally from the customer. ShippingTaxNotIncludedAmount is confirmed as the other additive tax component; its detailed definition and calculation remain to be supplied. These names describe calculation components, not additional selectable metrics or fields in the /sale_analytics row schema. Do not add product VAT already included in the selling price again as this additional product-tax component.

Help gives simpler invoice-total and actually-received formulas than the developer document and the report-owner clarification: it does not include the same shipping-discount/VAT and channel-fee details. This draft uses the confirmed invoice-total formula and the developer definition for actual receipts rather than equating them with the simplified Help formulas. See Help terminology.

Currency, monetary rounding, API refund/discount sign conventions, and exact allocation bases require confirmation. Refund/payment/cancellation changes are confirmed as attributed to the order's creation date; synchronization latency is still unspecified. Value-proportional allocation and dimension-order-sensitive refund allocation are confirmed at the business-rule level; detailed API examples remain necessary.

The supplied UI screenshot shows order #101941 on three rows: one “Phí vận chuyển” row and two merchandise rows. The shipping row displays shipping of 30,000, invoice total of 33,000, and paid amount of 33,000. The merchandise rows display invoice totals of 150,000 and 1,000,000, and paid amounts of 21,783 and 145,217. Thus the displayed rows sum to invoice total 1,183,000 and paid amount 200,000. Summing only merchandise rows would omit the shipping row's contributions. These sums describe the screenshot; an independent order total was not supplied to establish reconciliation.

The same screenshot shows an order count of 1 on each of those three rows. Their sum of 3 is not three distinct orders. It also shows negative displayed discounts (for example, gross sales 351,000 with discount -50,000 and net sales 301,000). UI display signs do not establish the raw API sign convention.

This UI evidence does not define how /sale_analytics represents a shipping row's product/variant identifiers or whether its data includes the same row types. Do not invent a synthetic product ID, assign the 3,000 difference to a specific tax without confirmation, or assert universal reconciliation from this example.

Sales statuses and channels​

orderStatusId accepts NotCancelled (Không hủy, code 2) and Cancelled (Hủy, code 3), as described by Swagger. Send the string enum, not the numeric display mapping. Omission includes all statuses. Do not import Orders API lifecycle or payment enum values into this filter.

sourceName accepts these technical codes:

web, pos, fb, draft, zalo, phone, staff, lazada, tiki, fbshop,
harafunnel, app_android, app_ios, harapos, shopee, googleshop,
harasocial, sendo, tiktokshop, livestream, instagram

Swagger explicitly maps fbshop to Facebook Shop. A response grouped by channel may use friendly names; do not assume that display strings are valid filter codes. The complete display mapping is not supplied.

Response envelope​

All three reports use an envelope containing data, errors, warnings, hasError, and hasWarning. Inventory balances are currently documented from screenshots and examples; the nullable/read-only details below are confirmed by live OpenAPI for low stock and sales, not yet verified against the full inventory schema.

FieldLow-stock and sales schemaMeaning
dataNullable array of report rowsGrouped results. Developer success examples use [] for no data. Null is not a successful empty result.
errorsNullable, read-only arrayBusiness error details; success examples use [].
warningsNullable, read-only arrayWarning details; conditions and effect on completeness are unspecified.
hasErrorRead-only booleanError indicator; exact relationship to errors is unspecified.
hasWarningRead-only booleanWarning indicator; exact relationship to warnings is unspecified.

The live shared Error and Warning schemas define nullable string field and message, plus nullable refData without a declared type. The inventory screenshot shows strings but does not establish a complete type contract. Do not restrict refData to a string based on placeholder examples.

The inspected low-stock and sales row/envelope schemas disallow additional properties and do not declare required-property lists. Exact inventory-field nullability remains unconfirmed. Developer documentation says sales validation errors usually have data: null; error-path data behavior is not fully specified for every report.

Swagger placeholder values such as true, 0, and "string" are not defaults or captured business results.

Search, filter, sort, and pagination​

  • Use server-side grouping and selected metrics to obtain the required level of detail. Unselected fields can still appear as placeholders.
  • Public value filters are limited to sales dates, cancellation status, and channels. Location restrictions are implicit in user permissions.
  • Send arrays using repeated query keys. Do not substitute comma-separated lists or undocumented V2 filters.
  • Sort by a selected dimension or metric. Tie-breaking is unspecified.
  • Pages start at 1. Default limit is 100; maximum is 2001. Low-stock and sales OpenAPI specify minimum 1 and invalid-value fallback to limit 100 or page 1; the inventory developer document refers to shared pagination rules without enumerating all invalid cases.
  • Keep dimensions, their order, metrics, filters, sort, and limit fixed across page requests.
  • Stop at data: [] or fewer rows than the effective limit, as documented by dev. Use valid limits so fallback behavior does not invalidate the completion check.
  • No total, cursor, or hasNext is documented. A full page is not proof that all results have been retrieved.
  • Snapshot consistency across page requests is unspecified; do not assume data remains frozen while paging.
ReportDefault dimensionsDefault metricsDefault sort
Inventory balancesProductId, VariantIdQtyOnHand, QtyCommitted, QtyAvailable, QtyIncomingQtyOnHand DESC
Low stockProductId, VariantIdQtySoldPerDay, QtyAvailability, EstimatedDaysUntilStockoutEstimatedDaysUntilStockout ASC
SalesProductId, VariantId, SKU, BarcodeQuantity, ReturnQuantity, GrossSaleAmount, NetSaleAmountGrossSaleAmount DESC

For sales, both date boundaries are inclusive. Avoid overlapping instants in adjacent intervals. Timestamp precision and interpretation without an offset remain unspecified. Day/month grouping uses Asia/Ho_Chi_Minh; year/weekday timezone handling still needs confirmation.

Permissions and limitations​

  • All operations require Bearer JWT authentication and application permission CanReadReport. No equivalent OAuth scope is supplied; do not substitute Orders scopes.
  • Location-restricted users receive data only for assigned locations. Inventory and low-stock reports return data: [] when such a user has no assigned locations; sales behavior for that case is not explicitly documented.
  • Cost-view permission has report-specific effects:
ReportProtected metricsMissing cost-view permission
Inventory balances / low stockTotalCostAmountReturns zero without a cost-permission error.
SalesMACostAmount, Profit, ProfitMarginReturns an error; exact metric-specific status/body is unspecified.
  • The exact technical cost-view permission name is not supplied.
  • Help restricts the inventory report UI in basic inventory mode; API enforcement remains unconfirmed.
  • Production base URL, currency details, rate limits, data freshness, and cross-page consistency are unspecified. Date-span limits and historical retention for sales are also unspecified.
  • UI filters, export, and saved-report features do not establish public endpoint capabilities.

Errors and exceptions​

ConditionDocumented behavior
Business validation failureHTTP 200 with errors; sales usually has null data.
Missing authentication or insufficient report accessHTTP 401/403; exact bodies not supplied.
Sort dimension/metric not selectedBusiness error.
Missing sales date or end before startViolates input contract; exact status/payload unspecified.
Invalid paginationDefault fallback is documented; not every malformed encoding is covered.
Missing cost-view permissionZero for inventory-value metrics; error for protected sales metrics.
No matching datadata: [].
Restricted user with no assigned locationsEmpty array for both inventory reports; sales case unconfirmed.

HTTP 200 alone does not establish business success. Inspect errors and supplied indicators before using data. Warning conditions, retries, and usability/completeness of data accompanying errors or warnings are not fully defined; do not silently present it as a verified complete report.

Usage guidance for AI​

  • Choose the report matching the question: current balances, stock coverage, or sales by order creation date.
  • Use exact dimension and metric names for that report, particularly QtyAvailable versus QtyAvailability and LocId versus Location.
  • Do not invent value filters or import V2 parameters. Keep the sort field among selected dimensions/metrics.
  • Preserve dimension order because sales refund allocation is order-sensitive.
  • Treat unselected-field zeros and permission-suppressed inventory value as placeholders, not confirmed measurements.
  • Distinguish stockout estimate -1 (unknown) from 0 (no availability) and positive estimates. UI group membership is not an API threshold filter.
  • Do not silently recalculate daily sales using an assumed 28-day or 30-day period.
  • Do not sum quantities across different units without a confirmed conversion basis.
  • Explicitly select NotCancelled when excluding cancelled sales orders; omission includes all statuses.
  • Attribute later payments, refunds, and cancellations to the order's creation-date period. Historical totals can change; this is not a cash-movement-date report.
  • Distinguish gross/net sales, invoice totals, collections, refunds, and actual receipts. Do not substitute simplified Help formulas for confirmed API calculations.
  • Do not sum distinct-order counts across overlapping groups or average group profit margins without an appropriate basis. Account for documented non-merchandise rows when reconciling money.
  • Report the permitted location scope and complete all necessary pages before describing results as totals.
  • Do not assume currency, real-time freshness, or usable data after errors/warnings when unspecified.
  • Keep multi-step workflows and tool orchestration in the skill.

Sources​

  • Developer-provided API.docx and Variable Description.docx: inventory, low-stock, and sales columns. Request contracts: InventoryAnalyticService.LocationBalanceFilter, InventoryAnalyticService.LowStockFilter, and SaleAnalyticService.SaleFilter.
  • Reports OpenAPI: low-stock and sales parameters, enums, row schemas, and shared envelopes; inventory currently uses supplied Swagger screenshots/response examples.
  • Sales Help and low-stock Help, plus the supplied inventory Help summary: UI/business context, not a substitute for endpoint contracts.
  • Report-owner clarifications and screenshots: invoice tax formula, value-proportional allocation, dimension-sensitive refunds, order-creation-date attribution, UI shipping rows and stock-status groups. Screenshots are UI evidence, not captured API responses.

Developer documentation says Swagger is generated in non-production environments. No authenticated report request has been executed for this draft. Known discrepancies and missing information remain in the checklist below.

Thông tin cần bổ sung​

Các mục dưới đây là thông tin chưa được xác nhận, không phải điều kiện bắt buộc để tiếp tục review bản nháp. Cần chốt các mục ảnh hưởng đến kết nối và tính đúng của số liệu trước khi nghiệm thu tools.

Thông tin chung​

  • Base URL dùng cho test/production và tên kỹ thuật của quyền xem giá vốn.
  • Tiền tệ, độ chính xác, cách làm tròn và cơ sở giá vốn áp dụng cho từng báo cáo.
  • Điều kiện phát sinh warnings, quan hệ giữa hasError/hasWarning và các mảng lỗi/cảnh báo; có được sử dụng data khi có lỗi/cảnh báo không.
  • Response thực tế cho thành công, không có dữ liệu, thiếu quyền và lỗi/cảnh báo; xác nhận Content-Type ở môi trường sử dụng.
  • Độ trễ đồng bộ, rate limit và khả năng giữ dữ liệu nhất quán khi lấy nhiều trang.

Báo cáo tồn kho​

  • Định nghĩa chi tiết UnitRatio, UnitMACost; cách quy đổi khi chọn hoặc bỏ Unit.
  • Schema đầy đủ và nullability của response; hiện phần này dựa trên ảnh Swagger và response mẫu.
  • API có chặn shop dùng chế độ tồn kho cơ bản như UI không?
  • QtyIncoming (“Chờ nhập”) có tương ứng chính xác với “Không khả dụng” trong Help không? Các bước điều chuyển ảnh hưởng từng loại số lượng thế nào?

Báo cáo sắp hết hàng​

  • Chốt query lấy 30 ngày hay 28 ngày và lý do công thức chia 28; cách tính đơn hủy/hoàn trả, biên thời gian và timezone.
  • Quy tắc làm tròn số ngày còn lại; kết quả khi đồng thời không còn khả dụng và không có tốc độ bán.
  • API có tự loại sản phẩm không quản lý tồn kho hoặc có tốc độ bán không dương không? Bộ lọc nhóm ngày trên UI được áp dụng tại endpoint này hay nơi khác?
  • Cách xếp số ngày lẻ tại biên 30/31, 90 ngày và cách xử lý giá trị -1 trong các nhóm UI.

Các nhóm UI “Đã hết hàng”, “1–30 ngày”, “31–90 ngày”, “trên 90 ngày” và bộ lọc UI trên 90 ngày kết hợp tốc độ bán lớn hơn 0 đã được xác nhận; không cần hỏi lại.

Báo cáo bán hàng​

  • Định nghĩa đầy đủ ShippingTaxNotIncludedAmount, cách tính các khoản VAT và danh sách phí kênh/sàn trong ActuallyReceived.
  • Dấu tiền hoàn/giảm giá trong JSON thực tế; không suy ra trực tiếp từ dấu hiển thị UI.
  • Cơ sở giá trị dùng để phân bổ (trước/sau giảm giá nào), làm tròn và xử lý phần dư.
  • Ví dụ request/response khi đổi thứ tự dimensions để xác định cách thứ tự query điều khiển phân bổ tiền hoàn.
  • API biểu diễn dòng “Phí vận chuyển” riêng thế nào, gồm ID sản phẩm/biến thể; đối chiếu response với tổng của đơn gốc để kiểm tra cộng tiền.
  • Timezone và độ chính xác timestamp đầu vào; giới hạn khoảng truy vấn/lịch sử; timezone của nhóm năm và ngày trong tuần.
  • Khi bỏ sourceName thì lấy những kênh nào? Danh sách mapping đầy đủ của trạng thái thanh toán và tên hiển thị kênh.
  • Kết quả với user bị giới hạn kho nhưng không được gán kho; lỗi cụ thể khi thiếu quyền giá vốn.
  • Plugin có cần hỗ trợ thêm các endpoint V2 không? V2 hiện ngoài phạm vi tài liệu này.
  • Ví dụ số liệu cho đơn tạo một kỳ nhưng thanh toán/hoàn/hủy ở kỳ sau để nghiệm thu. Quy tắc ghi nhận theo ngày tạo đơn đã chốt; chỉ cần ví dụ kiểm chứng, không hỏi lại quy tắc.

Các nội dung bán hàng đã xác nhận​

  • Công thức TotalSaleAmount = tiền hàng/phí vận chuyển sau giảm giá + ProductTaxNotIncludedAmount + ShippingTaxNotIncludedAmount.
  • ProductTaxNotIncludedAmount là VAT sản phẩm chưa nằm trong giá bán, thu thêm từ khách.
  • Phân bổ theo tỷ lệ giá trị; các khoản vận chuyển, thuế, tiền thu và phí kênh được xác nhận áp dụng nguyên tắc tương tự. Chi tiết cơ sở tính vẫn cần ví dụ.
  • Tiền hoàn phân bổ theo dimension đầu tiên; đổi thứ tự dimension làm thay đổi phân bổ.
  • Tất cả thay đổi đi theo ngày tạo đơn; số liệu kỳ cũ có thể thay đổi sau thanh toán/hoàn/hủy.
  • Ảnh UI có dòng phí vận chuyển riêng và số đơn lặp theo nhóm; không cộng số đơn theo dòng để suy ra tổng đơn không trùng.