786 lines
28 KiB
PHP
786 lines
28 KiB
PHP
<?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\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 = '2430273709@qq.com';
|
||
|
||
private const INVOICE_MOBILE = '13162179171';
|
||
|
||
private const INVENTORY_SAP_CODE = 'OA01207289';
|
||
|
||
public function __construct(
|
||
private readonly DatabaseManager $databases,
|
||
private readonly KukaPostingBaseRepository $baseRepository,
|
||
) {
|
||
}
|
||
|
||
/**
|
||
* @return array<string, mixed>
|
||
*/
|
||
public function build(Request $request, int $companyId): 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 = [];
|
||
$inventory = [];
|
||
$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['业务员'] ?? '')),
|
||
];
|
||
$lineItems[] = $item;
|
||
|
||
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,
|
||
);
|
||
|
||
if (! isset($inventory[$materialNumber])) {
|
||
$inventory[$materialNumber] = [
|
||
'year' => $item['year'],
|
||
'month' => $item['month'],
|
||
'supplier_account' => $supplier['account'],
|
||
'supplier_name' => $supplierName,
|
||
'material_number' => $materialNumber,
|
||
'description' => $description,
|
||
'quantity' => '0',
|
||
'material_name' => $productName,
|
||
'model_spec' => $item['model_spec'],
|
||
'item_number' => $item['item_number'],
|
||
'salesperson' => $item['salesperson'],
|
||
];
|
||
}
|
||
$inventory[$materialNumber]['quantity'] = $this->addDecimal(
|
||
$inventory[$materialNumber]['quantity'],
|
||
$quantity,
|
||
);
|
||
$supplierAmountTotal = $this->addMoney($supplierAmountTotal, $supplierAmount);
|
||
$salesAmountTotal = $this->addMoney($salesAmountTotal, $salesAmount);
|
||
}
|
||
|
||
ksort($posting, SORT_NATURAL);
|
||
ksort($inventory, SORT_NATURAL);
|
||
$generatedAt = now()->format('Y-m-d H:i:s');
|
||
|
||
$postingRows = array_map(static fn (array $row): array => [
|
||
$row['year'],
|
||
$row['month'],
|
||
$row['material_number'],
|
||
$row['description'],
|
||
$row['quantity'],
|
||
$row['unit_price'],
|
||
$row['supplier_amount'],
|
||
], array_values($posting));
|
||
$inventoryRows = array_map(static fn (array $row): array => [
|
||
$row['year'],
|
||
$row['month'],
|
||
$row['supplier_account'],
|
||
self::INVENTORY_SAP_CODE,
|
||
$row['supplier_name'],
|
||
$row['material_number'],
|
||
$row['description'],
|
||
$row['quantity'],
|
||
$row['quantity'],
|
||
'',
|
||
'',
|
||
'',
|
||
'',
|
||
'',
|
||
'',
|
||
'',
|
||
$row['material_name'],
|
||
$row['model_spec'],
|
||
$row['item_number'],
|
||
$row['material_name'],
|
||
'',
|
||
'',
|
||
$row['salesperson'],
|
||
'',
|
||
'',
|
||
$generatedAt,
|
||
$row['quantity'],
|
||
$row['quantity'],
|
||
], array_values($inventory));
|
||
|
||
$views = [
|
||
'posting-data' => $this->paginate($postingRows, $page),
|
||
'toc-orders' => $this->paginate(array_map(static fn (array $row): array => [
|
||
$row['year'],
|
||
$row['month'],
|
||
$row['order_no'],
|
||
$row['material_number'],
|
||
$row['description'],
|
||
$row['quantity'],
|
||
], $lineItems), $page),
|
||
'lingshan-virtual-posting' => $this->paginate(
|
||
$this->virtualRows($lineItems, $generatedAt),
|
||
$page,
|
||
),
|
||
'erp-product-import' => $this->paginate($this->erpRows($lineItems), $page),
|
||
'invoice-entry-template' => $this->paginate(
|
||
$this->invoiceRows($lineItems),
|
||
$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($posting),
|
||
'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' => $phoneRows === 0
|
||
? '聚水潭收货人镜像当前没有手机或电话字段,ERP 导入的收货手机保持空白。'
|
||
: null,
|
||
];
|
||
|
||
return $empty;
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string, mixed>> $lineItems
|
||
* @return list<array<int, string>>
|
||
*/
|
||
private function virtualRows(array $lineItems, string $generatedAt): array
|
||
{
|
||
$rows = [];
|
||
foreach ($lineItems as $index => $row) {
|
||
$rows[] = [
|
||
$row['year'],
|
||
$row['month'],
|
||
(string) ($index + 1),
|
||
$row['material_number'],
|
||
$row['product_name'],
|
||
$row['quantity'],
|
||
$row['unit_price'],
|
||
$row['supplier_amount'],
|
||
$row['sales_unit_price'],
|
||
$row['sales_amount'],
|
||
$row['supplier_name'],
|
||
$row['supplier_account'],
|
||
$row['order_no'],
|
||
$row['internal_order_no'],
|
||
$row['express_no'],
|
||
$generatedAt,
|
||
];
|
||
}
|
||
|
||
return $rows;
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string, mixed>> $lineItems
|
||
* @return list<array<int, string>>
|
||
*/
|
||
private function erpRows(array $lineItems): array
|
||
{
|
||
return array_map(static fn (array $row): array => [
|
||
$row['year'],
|
||
$row['month'],
|
||
$row['store'],
|
||
$row['order_no'],
|
||
$row['product_code'],
|
||
$row['quantity'],
|
||
$row['internal_order_no'],
|
||
'0',
|
||
$row['sales_unit_price'],
|
||
$row['sales_amount'],
|
||
$row['sales_amount'],
|
||
$row['order_date'],
|
||
$row['payment_date'],
|
||
$row['shipping_date'],
|
||
$row['product_name'],
|
||
$row['product_spec'],
|
||
$row['receiver_name'],
|
||
$row['receiver_phone'],
|
||
$row['receiver_mobile'],
|
||
$row['buyer_memo'],
|
||
$row['receiver_zip'],
|
||
$row['receiver_state'],
|
||
$row['receiver_city'],
|
||
$row['receiver_district'],
|
||
'',
|
||
$row['receiver_address'],
|
||
$row['express_name'],
|
||
$row['freight'],
|
||
$row['order_status'],
|
||
$row['seller_memo'],
|
||
'',
|
||
$row['buyer_nick'],
|
||
$row['store'],
|
||
'',
|
||
], $lineItems);
|
||
}
|
||
|
||
/**
|
||
* @param list<array<string, mixed>> $lineItems
|
||
* @return list<array<int, string>>
|
||
*/
|
||
private function invoiceRows(array $lineItems): array
|
||
{
|
||
return array_map(static fn (array $row): array => [
|
||
$row['year'],
|
||
$row['month'],
|
||
self::INVOICE_COMPANY,
|
||
$row['order_no'],
|
||
'',
|
||
$row['product_name'],
|
||
$row['model_spec'],
|
||
self::INVOICE_TAX_CLASSIFICATION,
|
||
'套',
|
||
$row['quantity'],
|
||
$row['sales_amount'],
|
||
'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,
|
||
], $lineItems);
|
||
}
|
||
|
||
/**
|
||
* @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;
|
||
}
|
||
|
||
/**
|
||
* @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,
|
||
'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): array
|
||
{
|
||
$total = count($rows);
|
||
$lastPage = max(1, (int) ceil($total / self::PAGE_SIZE));
|
||
$page = min(max(1, $page), $lastPage);
|
||
$offset = ($page - 1) * self::PAGE_SIZE;
|
||
$pageRows = array_slice($rows, $offset, self::PAGE_SIZE);
|
||
|
||
return [
|
||
'rows' => $pageRows,
|
||
'total' => $total,
|
||
'page' => $page,
|
||
'per_page' => self::PAGE_SIZE,
|
||
'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 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 connection(): ConnectionInterface
|
||
{
|
||
return $this->databases->connection($this->connectionName());
|
||
}
|
||
|
||
private function connectionName(): string
|
||
{
|
||
return (string) config('upstream_mirrors.connection', 'business_mirror');
|
||
}
|
||
}
|