CaiWuXiTong/app/Business/KukaPostingReconciliation/KukaReconciliationPageData.php
chenxi bb0e83da80 feat(顾家对账): 按料号透视灵珊虚拟过账 (#1348)
灵珊虚拟过账按顾家料号透视,ERP商品导入、开票模板和库存模板读取同一批透视行,销售金额按料号汇总计算。
2026-11-21 16:13:37 +08:00

976 lines
36 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Business\KukaPostingReconciliation;
use App\Business\KukaPostingBase\KukaPostingBaseRepository;
use Illuminate\Database\ConnectionInterface;
use Illuminate\Database\DatabaseManager;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
class KukaReconciliationPageData
{
private const PAGE_SIZE = 100;
private const SALES_MARKUP_DIVISOR = '0.9';
private const INVOICE_COMPANY = '宁波顾家望业家居有限公司';
private const INVOICE_TAX_CLASSIFICATION = '1050201010000000000';
private const INVOICE_TITLE = '常州灵珊家居有限公司';
private const INVOICE_TAX_NUMBER = '91320412MA25WFD89G';
private const INVOICE_ADDRESS = '武进国家高新技术产业开发区天安数码城33幢903室';
private const INVOICE_PHONE = '17826132483';
private const INVOICE_BANK = '中国工商银行股份有限公司常州河苑路支行';
private const INVOICE_ACCOUNT = '1105050709000527644';
private const INVOICE_EMAIL = 'yuechenna@dingtalk.com';
private const INVOICE_MOBILE = '15061959991';
private const INVENTORY_ELS_ACCOUNT = '435421';
private const INVENTORY_ELS_NAME = '常州欧伯娜家居有限公司';
private const INVENTORY_SAP_CODE = 'OA01207289';
private const VIRTUAL_SUPPLIER_NAME = '欧伯娜';
private const VIRTUAL_SUPPLIER_CODE = self::INVENTORY_SAP_CODE;
public function __construct(
private readonly DatabaseManager $databases,
private readonly KukaPostingBaseRepository $baseRepository,
) {
}
/**
* @return array<string, mixed>
*/
public function build(Request $request, int $companyId): array
{
return $this->buildData($request, $companyId, false);
}
/**
* @return array{period: string, rows: list<array<int, string>>, quantity_total: string, supplier_amount_total: string}
*/
public function postingExport(Request $request, int $companyId): array
{
$data = $this->buildData($request, $companyId, true);
if (($data['error'] ?? null) !== null) {
throw new \RuntimeException((string) $data['error']);
}
return [
'period' => (string) $data['period'],
'rows' => $data['views']['posting-data']['rows'],
'quantity_total' => (string) $data['summary']['posting_quantity_total'],
'supplier_amount_total' => (string) $data['summary']['posting_supplier_amount_total'],
];
}
/**
* @return array<string, mixed>
*/
private function buildData(Request $request, int $companyId, bool $allPostingRows): array
{
$periods = $this->baseRepository->periods($companyId);
$latestImport = $this->baseRepository->latestImport($companyId);
$period = trim((string) $request->query('period', ''));
if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $period) !== 1) {
$period = (string) ($latestImport->period ?? ($periods[0] ?? now()->format('Y-m')));
}
$page = max(1, (int) $request->integer('reconciliation_page', 1));
$empty = $this->emptyResult($period, $periods, $page);
if (! $this->baseRepository->available()) {
$empty['error'] = '顾家过账基础数据镜像尚未建立。';
return $empty;
}
$connection = $this->connection();
$sourceRows = [];
$skippedMissingMaterial = 0;
$skippedZeroQuantity = 0;
$skippedInvalidCost = 0;
$validMaterialRows = 0;
foreach ($connection->table('kuka_posting_base_rows')
->where('company_id', $companyId)
->where('period', $period)
->orderBy('source_row_number')
->cursor() as $row) {
$values = json_decode((string) $row->source_values, true, 512, JSON_THROW_ON_ERROR);
$materialNumber = trim((string) ($values['物料编号'] ?? ''));
if ($materialNumber === '') {
$skippedMissingMaterial++;
continue;
}
$validMaterialRows++;
$quantity = $this->normalizeDecimal($values['实发数量'] ?? '');
if ($quantity === null || (float) $quantity <= 0) {
$skippedZeroQuantity++;
continue;
}
$unitPrice = $this->normalizeDecimal($values['成本'] ?? '');
if ($unitPrice === null) {
$skippedInvalidCost++;
continue;
}
$sourceRows[] = [
'source_row_number' => (int) $row->source_row_number,
'values' => $values,
'material_number' => $materialNumber,
'quantity' => $quantity,
'unit_price' => $unitPrice,
];
}
$materials = array_values(array_unique(array_column($sourceRows, 'material_number')));
$quotations = $this->loadQuotations($connection, $companyId, $materials);
$shippingLookup = $this->loadShippingLookup($sourceRows);
$lineItems = [];
$posting = [];
$orders = [];
$supplierAmountTotal = '0.00';
$salesAmountTotal = '0.00';
$shippingMatched = 0;
$phoneRows = 0;
$addressRows = 0;
foreach ($sourceRows as $source) {
$values = $source['values'];
$quantity = $source['quantity'];
$unitPrice = $source['unit_price'];
$supplierAmount = $this->multiplyMoney($unitPrice, $quantity);
$salesAmount = $this->divideMoney($supplierAmount, self::SALES_MARKUP_DIVISOR);
$salesUnitPrice = $this->divideMoney($salesAmount, $quantity);
$materialNumber = $source['material_number'];
$description = trim((string) ($values['型号'] ?? ''));
$productName = trim((string) ($values['商品名称'] ?? ''));
if ($productName === '') {
$productName = $description;
}
$supplier = $quotations[$materialNumber] ?? [
'account' => '',
'name' => '',
];
$shipping = $this->resolveShipping($shippingLookup, $source);
if ($shipping !== null) {
$shippingMatched++;
}
$receiverMobile = trim((string) ($shipping?->receiver_mobile ?? ''));
$receiverPhone = trim((string) ($shipping?->receiver_phone ?? ''));
$receiverAddress = trim((string) ($shipping?->receiver_address ?? ''));
if ($receiverMobile !== '' || $receiverPhone !== '') {
$phoneRows++;
}
if ($receiverAddress !== '') {
$addressRows++;
}
$province = trim((string) ($shipping?->receiver_state ?? ''));
if ($province === '') {
$province = trim((string) ($values['省'] ?? ''));
}
$city = trim((string) ($shipping?->receiver_city ?? ''));
if ($city === '') {
$city = trim((string) ($values['市'] ?? ''));
}
$district = trim((string) ($shipping?->receiver_district ?? ''));
if ($district === '') {
$district = trim((string) ($values['区县'] ?? ''));
}
if ($receiverAddress === '') {
$receiverAddress = trim($province.$city.$district);
}
$orderNo = trim((string) ($values['线上订单号'] ?? ''));
$internalOrderNo = trim((string) ($values['内部订单号'] ?? ''));
if ($internalOrderNo !== '') {
$orders[$internalOrderNo] = true;
}
$supplierName = $supplier['name'];
if ($supplierName === '') {
$supplierName = trim((string) ($values['供销商'] ?? ''));
}
$orderDate = trim((string) ($values['订单日期'] ?? ''));
$paymentDate = trim((string) ($values['付款日期'] ?? ''));
$shippingDate = trim((string) ($values['发货日期'] ?? ''));
$item = [
'year' => substr($period, 0, 4),
'month' => (string) (int) substr($period, 5, 2),
'order_no' => $orderNo,
'internal_order_no' => $internalOrderNo,
'material_number' => $materialNumber,
'description' => $description,
'product_name' => $productName,
'product_code' => trim((string) ($values['商品编码'] ?? '')),
'style_code' => trim((string) ($values['款式编码'] ?? '')),
'item_number' => trim((string) ($values['货号'] ?? '')),
'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice),
'supplier_amount' => $supplierAmount,
'sales_unit_price' => $salesUnitPrice,
'sales_amount' => $salesAmount,
'supplier_name' => $supplierName,
'supplier_account' => $supplier['account'],
'store' => trim((string) ($values['店铺'] ?? '')),
'warehouse' => trim((string) ($values['发货仓'] ?? '')),
'order_date' => $orderDate,
'payment_date' => $paymentDate,
'shipping_date' => $shippingDate,
'receiver_name' => $this->firstNonEmpty([
$shipping?->receiver_name,
$values['收货人'] ?? '',
]),
'receiver_state' => $province,
'receiver_city' => $city,
'receiver_district' => $district,
'receiver_address' => $receiverAddress,
'receiver_mobile' => $receiverMobile,
'receiver_phone' => $receiverPhone,
'receiver_zip' => '',
'buyer_nick' => $this->firstNonEmpty([
$shipping?->buyer_nick,
$values['买家账号'] ?? '',
]),
'buyer_memo' => trim((string) ($shipping?->buyer_memo ?? '')),
'seller_memo' => $this->firstNonEmpty([
$shipping?->seller_memo,
$values['卖家备注'] ?? '',
]),
'express_name' => $this->firstNonEmpty([
$shipping?->express_name1,
$values['订单快递公司'] ?? '',
]),
'express_no' => $this->firstNonEmpty([
$shipping?->express_no,
$values['订单快递单号'] ?? '',
]),
'freight' => $this->formatMoney(
$shipping?->freight ?? $values['运费支出'] ?? '',
),
'order_status' => trim((string) ($values['订单状态'] ?? '')),
'product_spec' => $this->firstNonEmpty([
$values['颜色规格'] ?? '',
$values['规格型号'] ?? '',
]),
'model_spec' => trim((string) ($values['规格型号'] ?? '')),
'product_material' => trim((string) ($values['材质'] ?? '')),
'salesperson' => trim((string) ($values['业务员'] ?? '')),
'posting_tag' => trim((string) ($values['过账标签'] ?? '')),
];
$lineItems[] = $item;
if (trim((string) ($values['过账标签'] ?? '')) === '是') {
if (! isset($posting[$materialNumber])) {
$posting[$materialNumber] = [
'year' => $item['year'],
'month' => $item['month'],
'material_number' => $materialNumber,
'description' => $description,
'quantity' => '0',
'unit_price' => $item['unit_price'],
'supplier_amount' => '0.00',
];
}
$posting[$materialNumber]['quantity'] = $this->addDecimal(
$posting[$materialNumber]['quantity'],
$quantity,
);
$posting[$materialNumber]['supplier_amount'] = $this->addMoney(
$posting[$materialNumber]['supplier_amount'],
$supplierAmount,
);
}
$supplierAmountTotal = $this->addMoney($supplierAmountTotal, $supplierAmount);
$salesAmountTotal = $this->addMoney($salesAmountTotal, $salesAmount);
}
ksort($posting, SORT_NATURAL);
$generatedAt = now()->format('Y-m-d H:i:s');
$postingRows = array_map(fn (array $row): array => [
$row['year'],
$row['month'],
$row['material_number'],
$row['description'],
$this->formatQuantity($row['quantity']),
$row['unit_price'],
$row['supplier_amount'],
], array_values($posting));
$virtualRows = $this->virtualRows($lineItems, $generatedAt);
$virtualQuantityTotal = '0';
$virtualSupplierAmountTotal = '0.00';
$virtualSalesAmountTotal = '0.00';
foreach ($virtualRows as $virtualRow) {
$virtualQuantityTotal = $this->addDecimal($virtualQuantityTotal, (string) ($virtualRow[5] ?? '0'));
$virtualSupplierAmountTotal = $this->addMoney($virtualSupplierAmountTotal, (string) ($virtualRow[7] ?? '0'));
$virtualSalesAmountTotal = $this->addMoney($virtualSalesAmountTotal, (string) ($virtualRow[9] ?? '0'));
}
$erpRecipients = $this->loadErpRecipients($companyId);
$erpRows = $this->erpRows($virtualRows, $generatedAt, $erpRecipients);
$inventoryRows = $this->inventoryRows($virtualRows, $generatedAt);
$invoiceRows = $this->invoiceRows($virtualRows);
$invoiceQuantityTotal = '0';
$invoiceAmountTotal = '0.00';
foreach ($invoiceRows as $invoiceRow) {
$invoiceQuantityTotal = $this->addDecimal($invoiceQuantityTotal, (string) ($invoiceRow[9] ?? '0'));
$invoiceAmountTotal = $this->addMoney($invoiceAmountTotal, (string) ($invoiceRow[10] ?? '0'));
}
$views = [
'posting-data' => $this->paginate(
$postingRows,
$page,
$allPostingRows ? max(1, count($postingRows)) : self::PAGE_SIZE,
),
'toc-orders' => $this->paginate(
array_map(fn (array $row): array => [
$row['year'],
$row['month'],
$row['order_no'],
$row['material_number'],
$row['description'],
$this->formatQuantity($row['quantity']),
], array_values(array_filter(
$lineItems,
static fn (array $row): bool => ($row['posting_tag'] ?? '') === '是',
))),
$page,
),
'lingshan-virtual-posting' => $this->paginate(
$virtualRows,
$page,
),
'erp-product-import' => $this->paginate($erpRows, $page),
'invoice-entry-template' => $this->paginate(
$invoiceRows,
$page,
),
'inventory-management-template' => $this->paginate($inventoryRows, $page),
];
$empty['error'] = null;
$empty['periods'] = $periods;
$empty['period'] = $period;
$empty['generated_at'] = $generatedAt;
$empty['views'] = $views;
$empty['summary'] = [
'source_rows' => $validMaterialRows + $skippedMissingMaterial,
'valid_material_rows' => $validMaterialRows,
'generated_rows' => count($lineItems),
'material_count' => count($materials),
'posting_material_count' => count($posting),
'posting_quantity_total' => $this->formatQuantity($virtualQuantityTotal),
'posting_supplier_amount_total' => $virtualSupplierAmountTotal,
'posting_sales_amount_total' => $virtualSalesAmountTotal,
'posting_row_sales_amount_total' => $virtualSalesAmountTotal,
'virtual_sales_rounding_adjustment' => '0.00',
'erp_quantity_total' => $this->formatQuantity($virtualQuantityTotal),
'erp_detail_amount_total' => $virtualSalesAmountTotal,
'erp_amount_rounding_adjustment' => '0.00',
'erp_amount_total' => $virtualSalesAmountTotal,
'erp_paid_amount_total' => $virtualSalesAmountTotal,
'invoice_quantity_total' => $this->formatQuantity($invoiceQuantityTotal),
'invoice_amount_total' => $invoiceAmountTotal,
'toc_quantity_total' => $this->formatQuantity($virtualQuantityTotal),
'order_count' => count($orders),
'skipped_missing_material_rows' => $skippedMissingMaterial,
'skipped_zero_quantity_rows' => $skippedZeroQuantity,
'skipped_invalid_cost_rows' => $skippedInvalidCost,
'supplier_amount_total' => $supplierAmountTotal,
'sales_amount_total' => $salesAmountTotal,
'shipping_matched_rows' => $shippingMatched,
'receiver_phone_rows' => $phoneRows,
'receiver_address_rows' => $addressRows,
];
$empty['notices'] = [
'erp' => $erpRecipients === []
? '工作簿5收货人池尚未导入,ERP导入的收货人字段暂时为空。'
: null,
];
return $empty;
}
/**
* @param list<array<string, mixed>> $lineItems
* @return list<array<int, string>>
*/
private function virtualRows(array $lineItems, string $generatedAt): array
{
$groups = [];
$datePrefix = str_replace('-', '', substr($generatedAt, 0, 10));
foreach ($lineItems as $row) {
if (($row['posting_tag'] ?? '') !== '是') {
continue;
}
$materialNumber = trim((string) ($row['material_number'] ?? ''));
if ($materialNumber === '') {
continue;
}
if (! isset($groups[$materialNumber])) {
$groups[$materialNumber] = [
'year' => (string) ($row['year'] ?? ''),
'month' => (string) ($row['month'] ?? ''),
'description' => trim((string) ($row['description'] ?? '')),
'quantity' => '0',
'supplier_amount' => '0.00',
];
} elseif (($groups[$materialNumber]['description'] ?? '') === '') {
$groups[$materialNumber]['description'] = trim((string) ($row['description'] ?? ''));
}
$groups[$materialNumber]['quantity'] = $this->addDecimal(
$groups[$materialNumber]['quantity'],
(string) $row['quantity'],
);
$groups[$materialNumber]['supplier_amount'] = $this->addMoney(
$groups[$materialNumber]['supplier_amount'],
(string) $row['supplier_amount'],
);
}
ksort($groups, SORT_NATURAL);
$rows = [];
$serial = 0;
foreach ($groups as $materialNumber => $group) {
$serial++;
$quantity = (string) $group['quantity'];
$supplierAmount = (string) $group['supplier_amount'];
// 按料号汇总供应商金额后再计算销售金额,避免逐行四舍五入累积尾差。
$salesAmount = $this->divideMoney($supplierAmount, self::SALES_MARKUP_DIVISOR);
$rows[] = [
$group['year'],
$group['month'],
(string) $serial,
(string) $materialNumber,
$group['description'],
$this->formatQuantity($quantity),
$this->divideMoney($supplierAmount, $quantity),
$supplierAmount,
$this->divideMoney($salesAmount, $quantity),
$salesAmount,
self::VIRTUAL_SUPPLIER_NAME,
self::VIRTUAL_SUPPLIER_CODE,
$datePrefix.str_pad((string) $serial, 6, '0', STR_PAD_LEFT),
'',
'',
'',
];
}
return $rows;
}
/**
* @param list<array<int, string>> $virtualRows
* @return list<array<int, string>>
*/
private function inventoryRows(array $virtualRows, string $generatedAt): array
{
return array_map(fn (array $row): array => [
$row[0],
$row[1],
self::INVENTORY_ELS_ACCOUNT,
self::INVENTORY_SAP_CODE,
self::INVENTORY_ELS_NAME,
$row[3],
$row[4],
$row[5],
$row[5],
'',
'',
'',
'',
'',
'',
'',
$row[4],
'',
'',
'',
'',
'',
'',
'',
'',
$generatedAt,
$row[5],
'',
], array_values($virtualRows));
}
/**
* @param list<array<int, string>> $virtualRows
* @param list<object> $recipients
* @return list<array<int, string>>
*/
private function erpRows(array $virtualRows, string $generatedAt, array $recipients): array
{
$orderedAt = Carbon::parse($generatedAt);
$recipientCount = count($recipients);
$dateFormat = 'Y/n/j H:i:s';
return array_map(function (array $row, int $index) use (
$orderedAt,
$recipientCount,
$recipients,
$dateFormat,
): array {
$recipient = $recipientCount === 0
? null
: $recipients[$index % $recipientCount];
$amount = (string) ($row[9] ?? '0.00');
$quantity = $this->normalizeDecimal($row[5] ?? '') ?? '1';
$unitPrice = $this->divideMoney($amount, $quantity);
$paidAt = $orderedAt->copy()->addMinutes(5);
$deliveryAt = $orderedAt->copy()->addDays(5);
return [
$row[0],
$row[1],
'616',
$row[12],
$row[3],
$row[5],
'',
'0',
$unitPrice,
$amount,
$amount,
$orderedAt->format($dateFormat),
$paidAt->format($dateFormat),
$deliveryAt->format($dateFormat),
'',
'',
$recipient?->receiver_name ?? '',
'',
$recipient?->receiver_mobile ?? '',
'',
'',
$recipient?->receiver_state ?? '',
$recipient?->receiver_city ?? '',
$recipient?->receiver_district ?? '',
'',
$recipient?->receiver_address ?? '',
'',
'0.00',
'',
'',
'',
$recipient?->buyer_nick ?? '',
'',
'',
];
}, array_values($virtualRows), array_keys(array_values($virtualRows)));
}
/**
* @param list<array<int, string>> $virtualRows
* @return list<array<int, string>>
*/
private function invoiceRows(array $virtualRows): array
{
return array_map(fn (array $row): array => [
$row[0],
$row[1],
self::INVOICE_COMPANY,
'',
'',
$row[4],
'',
self::INVOICE_TAX_CLASSIFICATION,
'套',
$row[5],
$row[9],
'0.13',
self::INVOICE_TITLE,
self::INVOICE_TAX_NUMBER,
self::INVOICE_ADDRESS,
self::INVOICE_PHONE,
self::INVOICE_BANK,
self::INVOICE_ACCOUNT,
self::INVOICE_EMAIL,
self::INVOICE_MOBILE,
], $virtualRows);
}
/**
* @param list<array<string, mixed>> $sourceRows
* @return array<string, list<object>>
*/
private function loadShippingLookup(array $sourceRows): array
{
$connectionName = (string) config('jushuitan.connection', 'business_mirror');
if (! Schema::connection($connectionName)->hasTable('jst_oms_shipping')) {
return [];
}
$tokens = [];
foreach ($sourceRows as $source) {
foreach ($this->orderTokens($source['values']) as $token) {
// 保留字符串类型;数字订单号不能作为数组键,否则会变成整数,
// MySQL 与 varchar 索引比较时发生隐式数值转换并触发全表扫描。
$tokens[] = $token;
}
}
$tokens = array_values(array_unique($tokens));
$lookup = [];
$connection = $this->databases->connection($connectionName);
foreach (array_chunk($tokens, 400) as $chunk) {
$rows = $connection->table('jst_oms_shipping')
->whereIn('trade_no', $chunk)
->get([
'id',
'trade_no',
'barcode',
'product_code',
'receiver_name',
'receiver_state',
'receiver_city',
'receiver_district',
'receiver_address',
'receiver_mobile',
'receiver_phone',
'buyer_nick',
'buyer_memo',
'seller_memo',
'express_no',
'express_name1',
'freight',
]);
foreach ($rows as $row) {
$lookup[(string) $row->trade_no][] = $row;
}
}
return $lookup;
}
/**
* @param array<string, mixed> $values
* @return list<string>
*/
private function orderTokens(array $values): array
{
$tokens = [];
foreach (['线上订单号', '原始线上订单号'] as $field) {
$value = trim((string) ($values[$field] ?? ''));
if ($value === '') {
continue;
}
$tokens[] = $value;
foreach (preg_split('/[,,]/u', $value) ?: [] as $part) {
$part = trim($part);
if ($part !== '') {
$tokens[] = $part;
}
if (str_contains($part, ':')) {
$tokens[] = trim((string) substr($part, strrpos($part, ':') + 1));
}
}
}
return array_values(array_unique(array_filter($tokens)));
}
/**
* @param array<string, list<object>> $lookup
* @param array<string, mixed> $source
*/
private function resolveShipping(array $lookup, array $source): ?object
{
$values = $source['values'];
$candidates = [];
foreach ($this->orderTokens($values) as $token) {
foreach ($lookup[$token] ?? [] as $candidate) {
$candidates[] = $candidate;
}
}
if ($candidates === []) {
return null;
}
$productCode = trim((string) ($values['商品编码'] ?? ''));
$styleCode = trim((string) ($values['款式编码'] ?? ''));
$itemNumber = trim((string) ($values['货号'] ?? ''));
$best = null;
$bestScore = -1;
foreach ($candidates as $candidate) {
$barcode = trim((string) ($candidate->barcode ?? ''));
$candidateProduct = trim((string) ($candidate->product_code ?? ''));
$score = match (true) {
$productCode !== '' && $barcode === $productCode => 4,
$productCode !== '' && $candidateProduct === $productCode => 3,
$styleCode !== '' && $candidateProduct === $styleCode => 2,
$itemNumber !== '' && $candidateProduct === $itemNumber => 1,
default => 0,
};
if ($score > $bestScore) {
$best = $candidate;
$bestScore = $score;
}
}
return $best;
}
/**
* @return list<object>
*/
private function loadErpRecipients(int $companyId): array
{
if (! Schema::connection($this->connectionName())->hasTable('kuka_posting_erp_recipient_rows')) {
return [];
}
return $this->connection()
->table('kuka_posting_erp_recipient_rows')
->where('company_id', $companyId)
->orderBy('sort_order')
->orderBy('id')
->get([
'receiver_name',
'receiver_mobile',
'receiver_state',
'receiver_city',
'receiver_district',
'receiver_address',
'buyer_nick',
])
->all();
}
/**
* @param list<string> $materials
* @return array<string, array{account: string, name: string}>
*/
private function loadQuotations(
ConnectionInterface $connection,
int $companyId,
array $materials,
): array {
if ($materials === []
|| ! Schema::connection($this->connectionName())->hasTable('kuka_posting_quotation_rows')) {
return [];
}
$map = [];
foreach ($connection->table('kuka_posting_quotation_rows')
->where('company_id', $companyId)
->where('record_status', '生效')
->whereIn('material_number', $materials)
->get(['material_number', 'supplier_account', 'supplier_name']) as $row) {
$map[(string) $row->material_number] = [
'account' => trim((string) ($row->supplier_account ?? '')),
'name' => trim((string) ($row->supplier_name ?? '')),
];
}
return $map;
}
/**
* @return array<string, mixed>
*/
private function emptyResult(string $period, array $periods, int $page): array
{
$emptyPage = $this->paginate([], $page);
$views = [];
foreach ([
'posting-data',
'toc-orders',
'lingshan-virtual-posting',
'erp-product-import',
'invoice-entry-template',
'inventory-management-template',
'lingshan-statement',
'oberna-statement',
] as $slug) {
$views[$slug] = $emptyPage;
}
return [
'period' => $period,
'periods' => $periods,
'page' => $page,
'views' => $views,
'generated_at' => null,
'summary' => [
'source_rows' => 0,
'valid_material_rows' => 0,
'generated_rows' => 0,
'material_count' => 0,
'posting_material_count' => 0,
'posting_quantity_total' => '0',
'posting_supplier_amount_total' => '0.00',
'posting_sales_amount_total' => '0.00',
'posting_row_sales_amount_total' => '0.00',
'virtual_sales_rounding_adjustment' => '0.00',
'erp_quantity_total' => '0',
'erp_detail_amount_total' => '0.00',
'erp_amount_rounding_adjustment' => '0.00',
'erp_amount_total' => '0.00',
'erp_paid_amount_total' => '0.00',
'invoice_quantity_total' => '0',
'invoice_amount_total' => '0.00',
'toc_quantity_total' => '0',
'order_count' => 0,
'skipped_missing_material_rows' => 0,
'skipped_zero_quantity_rows' => 0,
'skipped_invalid_cost_rows' => 0,
'supplier_amount_total' => '0.00',
'sales_amount_total' => '0.00',
'shipping_matched_rows' => 0,
'receiver_phone_rows' => 0,
'receiver_address_rows' => 0,
],
'notices' => [],
'error' => null,
];
}
/**
* @param list<array<int, string>> $rows
* @return array{rows: list<array<int, string>>, total: int, page: int, per_page: int, last_page: int, from: int, to: int}
*/
private function paginate(array $rows, int $page, ?int $perPage = null): array
{
$total = count($rows);
$perPage = max(1, $perPage ?? self::PAGE_SIZE);
$lastPage = max(1, (int) ceil($total / $perPage));
$page = min(max(1, $page), $lastPage);
$offset = ($page - 1) * $perPage;
$pageRows = array_slice($rows, $offset, $perPage);
return [
'rows' => $pageRows,
'total' => $total,
'page' => $page,
'per_page' => $perPage,
'last_page' => $lastPage,
'from' => $total === 0 ? 0 : $offset + 1,
'to' => $total === 0 ? 0 : $offset + count($pageRows),
];
}
/**
* @param list<mixed> $values
*/
private function firstNonEmpty(array $values): string
{
foreach ($values as $value) {
$value = trim((string) $value);
if ($value !== '') {
return $value;
}
}
return '';
}
private function normalizeDecimal(mixed $value): ?string
{
$normalized = str_replace(',', '', trim((string) $value));
return $normalized !== '' && is_numeric($normalized) ? $normalized : null;
}
private function formatMoney(mixed $value): string
{
$number = $this->normalizeDecimal($value);
return $number === null ? '' : number_format((float) $number, 2, '.', '');
}
private function formatQuantity(mixed $value): string
{
$number = $this->normalizeDecimal($value);
if ($number === null) {
return '';
}
$formatted = rtrim(rtrim(number_format((float) $number, 4, '.', ''), '0'), '.');
return (float) $formatted === 0.0 ? '0' : $formatted;
}
private function multiplyMoney(string $left, string $right): string
{
$value = function_exists('bcmul')
? bcmul($left, $right, 4)
: (string) ((float) $left * (float) $right);
return number_format((float) $value, 2, '.', '');
}
private function divideMoney(string $left, string $right): string
{
if ((float) $right === 0.0) {
return '';
}
$value = function_exists('bcdiv')
? bcdiv($left, $right, 4)
: (string) ((float) $left / (float) $right);
return number_format((float) $value, 2, '.', '');
}
private function addDecimal(string $left, string $right): string
{
if (function_exists('bcadd')) {
return bcadd($left, $right, 4);
}
return (string) ((float) $left + (float) $right);
}
private function addMoney(string $left, string $right): string
{
return number_format(
(float) $this->addDecimal($left, $right),
2,
'.',
'',
);
}
private function subtractMoney(string $left, string $right): string
{
$value = function_exists('bcsub')
? bcsub($left, $right, 4)
: (string) ((float) $left - (float) $right);
return number_format((float) $value, 2, '.', '');
}
private function connection(): ConnectionInterface
{
return $this->databases->connection($this->connectionName());
}
private function connectionName(): string
{
return (string) config('upstream_mirrors.connection', 'business_mirror');
}
}