CaiWuXiTong/modules/EcommerceFinance/Services/PlantingQuotaDimensions.php

181 lines
8.0 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 Modules\EcommerceFinance\Services;
use Illuminate\Support\Facades\Cache;
use Modules\EcommerceFinance\Repositories\GenericBusinessMirrorRepository;
use Throwable;
/**
* 种菜报销工作台的维度数据,直接只读查经营分析副本库(JSReportReplica.rpt,即「脉象」看板的同一数据源):
* - rpt.fys_shopInfo:ERP系统店铺名称 → 平台、店铺负责人、店铺所属利润中心(工作平台店铺信息明细);
* - rpt.op_TargetManagement:商品ID → ID负责人、部门负责人;
* - rpt.hr_employee_register:负责人花名 → 职级。
* 只按本批涉及的店铺 / 商品 / 人分块查询,量很小。
*/
class PlantingQuotaDimensions
{
private const SOURCE = 'operations_replica';
private const TIMEOUT_SECONDS = 60;
private const CHUNK = 500;
private const OWNER_CACHE = 'planting-quota:owner:v1:';
private const OWNER_CACHE_HOURS = 26;
public function __construct(private readonly UpstreamReadOnlyQueryFactory $queries) {}
/**
* 店铺信息。副本库连不上时退回财务系统每天同步的店铺资料镜像(只有利润中心可靠,平台 / 店长可能缺)。
*
* @param list<string> $shops
* @return array{shops:array<string,array{platform:string,shop_head:string,profit_center:string}>,source:string}
*/
public function shops(array $shops): array
{
$shops = self::clean($shops);
if ($shops === []) {
return ['shops' => [], 'source' => 'replica'];
}
try {
$map = [];
foreach (array_chunk($shops, self::CHUNK) as $chunk) {
$rows = $this->query()->select(
'SELECT erpShopName, platform, shopHead, responsibleDepartment FROM rpt.fys_shopInfo WHERE erpShopName IN ('
. self::placeholders($chunk) . ') ORDER BY Id DESC',
$chunk,
);
foreach ($rows as $row) {
self::addShop($map, $row['erpShopName'] ?? '', $row['platform'] ?? '', $row['shopHead'] ?? '', $row['responsibleDepartment'] ?? '');
}
}
return ['shops' => $map, 'source' => 'replica'];
} catch (Throwable $exception) {
report($exception);
}
$map = [];
try {
$table = app(BusinessMirrorDatasetRegistry::class)->get(\App\Business\PlantingWorkOrderSynchronizer::SHOP_INFO_DATASET)->targetTable();
$connection = app(GenericBusinessMirrorRepository::class)->connection();
if ($connection->getSchemaBuilder()->hasTable($table)) {
$columns = $connection->getSchemaBuilder()->getColumnListing($table);
$select = array_values(array_intersect(['erpShopName', 'platform', 'shopHead', 'responsibleDepartment'], $columns));
foreach (array_chunk($shops, self::CHUNK) as $chunk) {
foreach ($connection->table($table)->whereIn('erpShopName', $chunk)->get($select) as $row) {
$row = (array) $row;
self::addShop($map, $row['erpShopName'] ?? '', $row['platform'] ?? '', $row['shopHead'] ?? '', $row['responsibleDepartment'] ?? '');
}
}
}
} catch (Throwable $exception) {
report($exception);
}
return ['shops' => $map, 'source' => 'mirror'];
}
/**
* @param list<string> $productIds
* @return array<string,array{ider:?string,curr_cater:?string}> 商品ID → ID负责人 / 部门负责人(同一商品多行取 MAX,与看板一致)
*
* 2026-12-01 实测:按参数绑定 IN 查 2,271 个商品要 181 秒(参数按 nvarchar 绑定、shopproid 用不上索引)。
* 改为校验后内联成 varchar 字面量,并按商品缓存一天(负责人变动很少),同一批只查没缓存过的商品。
*/
public function owners(array $productIds): array
{
$ids = array_values(array_filter(self::clean($productIds), static fn (string $id): bool => preg_match('/^[0-9A-Za-z_-]{1,64}$/', $id) === 1));
$map = [];
$missing = [];
foreach ($ids as $id) {
$cached = Cache::get(self::OWNER_CACHE . $id);
if (is_array($cached)) {
$map[$id] = $cached;
} else {
$missing[] = $id;
}
}
foreach (array_chunk($missing, self::CHUNK) as $chunk) {
$rows = $this->query()->select(
"SELECT shopproid, MAX(NULLIF(LTRIM(RTRIM(ider)), N'')) AS ider, MAX(NULLIF(LTRIM(RTRIM(currCater)), N'')) AS curr_cater
FROM rpt.op_TargetManagement WHERE shopproid IN (" . implode(',', array_map(static fn (string $id): string => "'" . $id . "'", $chunk)) . ') GROUP BY shopproid',
);
$found = [];
foreach ($rows as $row) {
$found[trim((string) $row['shopproid'])] = [
'ider' => ($row['ider'] ?? null) !== null ? trim((string) $row['ider']) : null,
'curr_cater' => ($row['curr_cater'] ?? null) !== null ? trim((string) $row['curr_cater']) : null,
];
}
foreach ($chunk as $id) {
// 查不到负责人的商品也缓存(记为空),避免每次重查;新建的商品目标一般当天就有,缓存一天可接受。
$owner = $found[$id] ?? ['ider' => null, 'curr_cater' => null];
Cache::put(self::OWNER_CACHE . $id, $owner, now()->addHours(self::OWNER_CACHE_HOURS));
$map[$id] = $owner;
}
}
return array_filter($map, static fn (array $owner): bool => $owner['ider'] !== null || $owner['curr_cater'] !== null);
}
/**
* @param list<string> $names
* @return array<string,string> 花名 → 职级原文(同名取 MAX,与看板一致)
*/
public function levels(array $names): array
{
$map = [];
foreach (array_chunk(self::clean($names), self::CHUNK) as $chunk) {
$rows = $this->query()->select(
"SELECT [sys00-name] AS emp_name, MAX(NULLIF(LTRIM(RTRIM([sys01-positionLevel])), N'')) AS position_level
FROM rpt.hr_employee_register WHERE [sys00-name] IN (" . self::placeholders($chunk) . ') GROUP BY [sys00-name]',
$chunk,
);
foreach ($rows as $row) {
$level = trim((string) ($row['position_level'] ?? ''));
if ($level !== '') {
$map[trim((string) $row['emp_name'])] = $level;
}
}
}
return $map;
}
private function query(): UpstreamReadOnlyQuery
{
return $this->queries->forSourceWithTimeout(self::SOURCE, self::TIMEOUT_SECONDS);
}
/** @param array<string,array{platform:string,shop_head:string,profit_center:string}> $map */
private static function addShop(array &$map, mixed $name, mixed $platform, mixed $head, mixed $center): void
{
$name = trim((string) $name);
if ($name === '') {
return;
}
// 同名多行时按 Id 倒序取最新一行,后面的只补空字段。
$current = $map[$name] ?? ['platform' => '', 'shop_head' => '', 'profit_center' => ''];
foreach (['platform' => $platform, 'shop_head' => $head, 'profit_center' => $center] as $key => $value) {
if ($current[$key] === '' && trim((string) $value) !== '') {
$current[$key] = mb_substr(trim((string) $value), 0, 191);
}
}
$map[$name] = $current;
}
/** @return list<string> */
private static function clean(array $values): array
{
return array_values(array_unique(array_filter(array_map(static fn (mixed $v): string => trim((string) $v), $values), static fn (string $v): bool => $v !== '')));
}
private static function placeholders(array $values): string
{
return implode(',', array_fill(0, count($values), '?'));
}
}