diff --git a/modules/EcommerceFinance/Http/Controllers/AccountBills.php b/modules/EcommerceFinance/Http/Controllers/AccountBills.php index 795c1315..3746ad3d 100644 --- a/modules/EcommerceFinance/Http/Controllers/AccountBills.php +++ b/modules/EcommerceFinance/Http/Controllers/AccountBills.php @@ -14,7 +14,9 @@ use Modules\EcommerceFinance\Repositories\StoreReceivingJdWalletBillRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDouyinBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingDewuBillMirrorRepository; use Modules\EcommerceFinance\Repositories\StoreReceivingPinduoduoBillMirrorRepository; +use Modules\EcommerceFinance\Repositories\PromotionMarketingExpenseRepository; use RuntimeException; +use Throwable; class AccountBills extends Controller { @@ -124,24 +126,38 @@ class AccountBills extends Controller $page = max(1, (int) $request->get('page', 1)); $limit = min(max((int) $request->get('limit', 10), 1), 100); - return response()->json([ - 'data' => [], - 'total' => 0, - 'current_page' => $page, - 'last_page' => 1, - 'per_page' => $limit, - 'summary' => [ - 'income' => 0, - 'expense' => 0, - 'balance' => 0, - 'count' => 0, - ], - 'columns' => [ - 'title' => '推广费(营销账户)', - 'groups' => [], - 'columns' => self::promotionExpenseDetailColumns(), - ], - ]); + try { + $result = app(PromotionMarketingExpenseRepository::class)->paginate( + $this->promotionMarketingFilters($request), + $page, + $limit, + ); + + return response()->json([ + 'data' => $result['rows'], + 'total' => $result['total'], + 'current_page' => $result['current_page'], + 'last_page' => $result['last_page'], + 'per_page' => $result['per_page'], + 'summary' => [ + 'income' => 0, + 'expense' => $result['summary']['expense'], + 'balance' => round(-$result['summary']['expense'], 2), + 'count' => $result['summary']['count'], + ], + 'columns' => [ + 'title' => '推广费(营销账户)', + 'groups' => [], + 'columns' => self::promotionExpenseDetailColumns(), + ], + ]); + } catch (Throwable $exception) { + report($exception); + + return response()->json([ + 'message' => '推广费(营销账户)数据暂时无法读取,请稍后重试。', + ], 503); + } } /** @@ -153,25 +169,71 @@ class AccountBills extends Controller abort_unless($bill_type === 'promotion-marketing', 404); $this->authorizeStoreReceivingBills(); - $request->validate([ + $page = max(1, (int) $request->get('page', 1)); + $limit = min(max((int) $request->get('limit', 20), 1), 100); + + try { + $result = app(PromotionMarketingExpenseRepository::class)->paginate( + $this->promotionMarketingFilters($request), + $page, + $limit, + ); + + return response()->json([ + 'data' => $result['rows'], + 'total' => $result['total'], + 'current_page' => $result['current_page'], + 'last_page' => $result['last_page'], + 'per_page' => $result['per_page'], + 'summary' => $result['summary'], + 'columns' => self::promotionExpenseDetailColumns(), + 'message' => $result['total'] === 0 ? '当前筛选范围内暂无推广费支出明细。' : '', + ]); + } catch (Throwable $exception) { + report($exception); + + return response()->json([ + 'message' => '店铺明细暂时无法读取,请稍后重试。', + ], 503); + } + } + + /** @return array{start:string,end:string,store_name:string} */ + private function promotionMarketingFilters(Request $request): array + { + $filters = $request->validate([ 'store_name' => ['nullable', 'string', 'max:255'], - 'ledger_remark' => ['nullable', 'string', 'max:191'], - 'bill_item' => ['nullable', 'string', 'max:255'], 'start' => ['nullable', 'date_format:Y-m-d'], 'end' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:start'], - 'keyword' => ['nullable', 'string', 'max:255'], ]); - return response()->json([ - 'data' => [], - 'total' => 0, - 'summary' => [ - 'expense' => 0, - 'count' => 0, - ], - 'columns' => self::promotionExpenseDetailColumns(), - 'message' => '推广费数据源尚未配置,接入后将按当前筛选显示店铺明细。', - ]); + return [ + 'start' => trim((string) ($filters['start'] ?? '')), + 'end' => trim((string) ($filters['end'] ?? '')), + 'store_name' => trim((string) ($filters['store_name'] ?? '')), + ]; + } + + private function promotionMarketingFilterOptions(Request $request) + { + try { + return response()->json([ + 'shops' => app(PromotionMarketingExpenseRepository::class)->storeOptions( + $this->promotionMarketingFilters($request), + ), + 'bill_items' => [], + 'ledger_remarks' => [], + ]); + } catch (Throwable $exception) { + report($exception); + + return response()->json([ + 'message' => '推广费店铺选项暂时无法读取。', + 'shops' => [], + 'bill_items' => [], + 'ledger_remarks' => [], + ], 503); + } } /** @return array */ @@ -221,6 +283,10 @@ class AccountBills extends Controller { $this->authorizeStoreReceivingBills(); + if ($bill_type === 'promotion-marketing') { + return $this->promotionMarketingFilterOptions(request()); + } + $ledgerRemarks = $this->ledgerRemarkMap()->remarksForTab($bill_type); if (in_array($bill_type, ['vipshop', 'vipshop-jx'], true)) { diff --git a/modules/EcommerceFinance/Repositories/PromotionMarketingExpenseRepository.php b/modules/EcommerceFinance/Repositories/PromotionMarketingExpenseRepository.php new file mode 100644 index 00000000..3cf3de7e --- /dev/null +++ b/modules/EcommerceFinance/Repositories/PromotionMarketingExpenseRepository.php @@ -0,0 +1,384 @@ + */ + private array $queries = []; + + public function __construct(private readonly UpstreamReadOnlyQueryFactory $factory) + { + } + + /** + * @return array{ + * rows:array>, + * total:int, + * current_page:int, + * last_page:int, + * per_page:int, + * summary:array{expense:float,count:int} + * } + */ + public function paginate(array $filters, int $page = 1, int $limit = 25): array + { + [$start, $end] = $this->dateRange($filters); + $store = trim((string) ($filters['store_name'] ?? '')); + $page = max(1, $page); + $limit = min(max($limit, 1), 100); + $cacheKey = 'promotion-marketing-expense:page:' . hash('sha256', json_encode([ + $start, $end, $store, $page, $limit, + ], JSON_UNESCAPED_UNICODE)); + + return Cache::remember($cacheKey, self::CACHE_SECONDS, function () use ($start, $end, $store, $page, $limit): array { + $histograms = []; + $countByDate = []; + $expenseByDate = []; + $total = 0; + $expenseTotal = 0.0; + + foreach ($this->sources() as $key => $source) { + $histograms[$key] = $this->histogram($source, $start, $end, $store); + foreach ($histograms[$key] as $date => $values) { + $countByDate[$date] = ($countByDate[$date] ?? 0) + $values['count']; + $expenseByDate[$date] = ($expenseByDate[$date] ?? 0.0) + $values['expense']; + $total += $values['count']; + $expenseTotal += $values['expense']; + } + } + + krsort($countByDate, SORT_STRING); + [$dates, $skip] = $this->pageWindow($countByDate, ($page - 1) * $limit, $limit); + $rows = $dates === [] ? [] : $this->rowsForDates($histograms, $dates, $start, $end, $store); + usort($rows, static function (array $left, array $right): int { + foreach ([ + strcmp($right['report_date'], $left['report_date']), + $left['source_order'] <=> $right['source_order'], + strcmp($left['store_name'], $right['store_name']), + strcmp($left['notes'], $right['notes']), + $right['expense'] <=> $left['expense'], + ] as $comparison) { + if ($comparison !== 0) { + return $comparison; + } + } + + return 0; + }); + + $rows = array_slice($rows, $skip, $limit); + foreach ($rows as $index => &$row) { + unset($row['report_date'], $row['source'], $row['source_order']); + $row['id'] = hash('sha256', $index . '|' . json_encode($row, JSON_UNESCAPED_UNICODE)); + } + unset($row); + + return [ + 'rows' => array_values($rows), + 'total' => $total, + 'current_page' => $page, + 'last_page' => max(1, (int) ceil($total / $limit)), + 'per_page' => $limit, + 'summary' => [ + 'expense' => round($expenseTotal, 2), + 'count' => $total, + ], + ]; + }); + } + + /** @return array */ + public function storeOptions(array $filters = []): array + { + [$start, $end] = $this->dateRange($filters); + $cacheKey = 'promotion-marketing-expense:stores:' . hash('sha256', $start . '|' . $end); + + return Cache::remember($cacheKey, 3600, function () use ($start, $end): array { + $stores = []; + foreach ($this->sources() as $source) { + [$where, $bindings] = $this->where($source, $start, $end, ''); + $sql = 'SELECT DISTINCT TOP (500) ' . $source['store'] . ' AS store_name' + . ' FROM ' . $source['table'] . ' c ' . $where + . ' AND ' . $source['store'] . " IS NOT NULL AND LTRIM(RTRIM(" . $source['store'] . ")) <> N''" + . ' ORDER BY store_name'; + foreach ($this->select($source['connection'], $sql, $bindings) as $row) { + $name = trim((string) ($row['store_name'] ?? '')); + if ($name !== '') { + $stores[$name] = true; + } + } + } + + $names = array_keys($stores); + sort($names, SORT_NATURAL); + + return array_slice($names, 0, 500); + }); + } + + private function histogram(array $source, string $start, string $end, string $store): array + { + [$where, $bindings] = $this->where($source, $start, $end, $store); + $date = 'CONVERT(varchar(10), ' . $source['date'] . ', 23)'; + $sql = 'SELECT ' . $date . ' AS report_date, COUNT(*) AS row_count,' + . ' COALESCE(SUM(' . $source['expense'] . '), 0) AS expense' + . ' FROM ' . $source['table'] . ' c ' . $where + . ' GROUP BY ' . $date; + + $result = []; + foreach ($this->select($source['connection'], $sql, $bindings) as $row) { + $dateValue = substr(trim((string) ($row['report_date'] ?? '')), 0, 10); + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateValue) !== 1) { + continue; + } + $result[$dateValue] = [ + 'count' => max(0, (int) ($row['row_count'] ?? 0)), + 'expense' => round((float) ($row['expense'] ?? 0), 2), + ]; + } + + return $result; + } + + /** + * @param array> $histograms + * @param array $dates + */ + private function rowsForDates(array $histograms, array $dates, string $start, string $end, string $store): array + { + $first = min($dates); + $last = max($dates); + $lastExclusive = CarbonImmutable::parse($last, 'Asia/Shanghai')->addDay()->toDateString(); + $rows = []; + + foreach ($this->sources() as $key => $source) { + if (! isset($histograms[$key]) || $histograms[$key] === []) { + continue; + } + [$where, $bindings] = $this->where($source, $first, $lastExclusive, $store, true); + $sql = 'SELECT ' . $source['row'] . ', ' + . 'CONVERT(varchar(10), ' . $source['date'] . ', 23) AS report_date, ' + . $source['store'] . ' AS store_name, ' + . $source['expense'] . ' AS expense' + . ' FROM ' . $source['table'] . ' c ' . $where; + foreach ($this->select($source['connection'], $sql, $bindings) as $row) { + $reportDate = substr(trim((string) ($row['report_date'] ?? '')), 0, 10); + if (! isset($histograms[$key][$reportDate])) { + continue; + } + $normalized = $this->normalize($key, $source, $row, $reportDate); + if ($normalized !== null) { + $rows[] = $normalized; + } + } + } + + return $rows; + } + + /** + * @param array $countByDate + * @return array{0:array,1:int} + */ + private function pageWindow(array $countByDate, int $offset, int $limit): array + { + $dates = []; + $skip = 0; + $cumulative = 0; + $target = $offset + $limit; + + foreach ($countByDate as $date => $count) { + $next = $cumulative + $count; + if ($next <= $offset) { + $cumulative = $next; + continue; + } + if ($dates === []) { + $skip = $offset - $cumulative; + } + $dates[] = $date; + $cumulative = $next; + if ($cumulative >= $target) { + break; + } + } + + return [$dates, max(0, $skip)]; + } + + private function normalize(string $key, array $source, array $row, string $reportDate): ?array + { + $expense = round((float) ($row['expense'] ?? 0), 2); + if ($expense <= 0) { + return null; + } + + $primary = trim((string) ($row['note_primary'] ?? '')); + $secondary = trim((string) ($row['note_secondary'] ?? '')); + if ($key === 'pinduoduo') { + $secondary = ['1' => '现金', '3' => '红包/券'][$secondary] ?? ''; + } + $notes = implode(' · ', array_values(array_filter( + [$primary, $secondary], + static fn (string $value): bool => $value !== '', + ))); + + return [ + 'source' => $key, + 'source_order' => $source['order'], + 'report_date' => $reportDate, + 'store_name' => trim((string) ($row['store_name'] ?? '')), + 'occurred_at' => trim((string) ($row['occurred_at'] ?? '')), + 'notes' => $notes, + 'expense' => $expense, + ]; + } + + /** + * @return array{0:string,1:array} + */ + private function where( + array $source, + string $start, + string $end, + string $store, + bool $endExclusive = false, + ): array { + $conditions = [$source['expense_condition']]; + $bindings = [$start]; + $conditions[] = $source['date'] . ' >= CAST(? AS date)'; + + if ($endExclusive) { + $conditions[] = $source['date'] . ' < CAST(? AS date)'; + $bindings[] = $end; + } else { + $conditions[] = $source['date'] . ' < DATEADD(day, 1, CAST(? AS date))'; + $bindings[] = $end; + } + + if ($store !== '') { + $conditions[] = $source['store'] . ' = ?'; + $bindings[] = $store; + } + + return [' WHERE ' . implode(' AND ', $conditions), $bindings]; + } + + /** @return array{0:string,1:string} */ + private function dateRange(array $filters): array + { + $start = trim((string) ($filters['start'] ?? '')); + $end = trim((string) ($filters['end'] ?? '')); + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $start) !== 1) { + $start = now('Asia/Shanghai')->startOfMonth()->toDateString(); + } + if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $end) !== 1) { + $end = now('Asia/Shanghai')->endOfMonth()->toDateString(); + } + if ($start > $end) { + throw new RuntimeException('推广费查询的结束日期不能早于开始日期。'); + } + + return [$start, $end]; + } + + /** @return array> */ + private function sources(): array + { + return [ + 'taobao' => [ + 'order' => 1, + 'connection' => 'jiansun', + 'table' => '[dbo].[tmall_spread_bills]', + 'date' => 'c.[transTime]', + 'store' => 'c.[shopName]', + 'expense' => '(CAST(c.[amount] AS decimal(18,2)) / 100.0)', + 'expense_condition' => "c.[finType] = 'CREDIT' AND ISNULL(c.[amount], 0) <> 0", + 'row' => "CONVERT(varchar(10), c.[transTime], 23) AS occurred_at, c.[comment] AS note_primary, NULL AS note_secondary", + ], + 'alibaba' => [ + 'order' => 2, + 'connection' => 'jiansun', + 'table' => '[dbo].[alibaba_bill]', + 'date' => 'CAST(c.[tradeDay] AS date)', + 'store' => 'c.[shopName]', + 'expense' => 'CAST(c.[tradeAMTOut] AS decimal(18,2))', + 'expense_condition' => 'ISNULL(c.[tradeAMTOut], 0) > 0', + 'row' => "CONVERT(varchar(10), CAST(c.[tradeDay] AS date), 23) AS occurred_at, c.[tradeTypeName] AS note_primary, NULL AS note_secondary", + ], + 'pinduoduo' => [ + 'order' => 3, + 'connection' => 'jiansun', + 'table' => '[dbo].[pdd_spread_bills]', + 'date' => 'c.[createTime]', + 'store' => 'c.[shopName]', + 'expense' => 'CAST(c.[amount] AS decimal(18,2))', + 'expense_condition' => 'c.[flowType] = 2 AND ISNULL(c.[amount], 0) <> 0', + 'row' => "CONVERT(varchar(19), c.[createTime], 120) AS occurred_at, c.[summary] AS note_primary, CONVERT(varchar(10), c.[toAdvertiserFundType]) AS note_secondary", + ], + 'jd' => [ + 'order' => 4, + 'connection' => 'js_data_middle_platform', + 'table' => '[JSDataMiddlePlatform].[dbo].[jd_jzt_finance_records]', + 'date' => 'CAST(c.[show_date] AS date)', + 'store' => 'c.[shop_name]', + 'expense' => 'CAST(c.[amount] AS decimal(18,2))', + 'expense_condition' => "c.[in_out_type] = 'OUT' AND ISNULL(c.[amount], 0) <> 0", + 'row' => "CONVERT(varchar(10), CAST(c.[show_date] AS date), 23) AS occurred_at, c.[remark] AS note_primary, c.[trade_type_name] AS note_secondary", + ], + 'douyin' => [ + 'order' => 5, + 'connection' => 'js_data_middle_platform', + 'table' => '[JSDataMiddlePlatform].[dbo].[dy_qianchuan_finance_transactions]', + 'date' => 'c.[statDate]', + 'store' => 'c.[shopName]', + 'expense' => 'CAST(c.[cost] AS decimal(18,2))', + 'expense_condition' => "c.[rowType] = N'daily' AND c.[status] = N'success' AND ISNULL(c.[cost], 0) <> 0", + 'row' => "CONVERT(varchar(10), c.[statDate], 23) AS occurred_at, c.[remark] AS note_primary, NULL AS note_secondary", + ], + 'dewu' => [ + 'order' => 6, + 'connection' => 'js_data_middle_platform', + 'table' => '[JSDataMiddlePlatform].[dbo].[dw_ad_finance_records]', + 'date' => 'c.[trade_date]', + 'store' => 'c.[shop_name]', + 'expense' => 'CAST(c.[trade_amount_yuan] AS decimal(18,2))', + 'expense_condition' => "c.[flow_type] = N'支出' AND ISNULL(c.[trade_amount_yuan], 0) <> 0", + 'row' => "CONVERT(varchar(10), c.[trade_date], 23) AS occurred_at, c.[remark] AS note_primary, c.[amount_type] AS note_secondary", + ], + 'vip' => [ + 'order' => 7, + 'connection' => 'js_data_middle_platform', + 'table' => '[JSDataMiddlePlatform].[dbo].[vip_marketingDailyReport]', + 'date' => 'c.[reportDate]', + 'store' => 'c.[accountName]', + 'expense' => 'CAST(c.[costYuan] AS decimal(18,2))', + 'expense_condition' => 'ISNULL(c.[costYuan], 0) <> 0', + 'row' => "CONVERT(varchar(10), c.[reportDate], 23) AS occurred_at, N'推广费' AS note_primary, NULL AS note_secondary", + ], + ]; + } + + /** @return array> */ + protected function select(string $connection, string $sql, array $bindings): array + { + $query = $this->queries[$connection] ??= $this->factory->forSourceWithTimeout($connection, 45); + + return $query->select($sql, $bindings); + } +} diff --git a/resources/assets/js/components/business/AccountBills.vue b/resources/assets/js/components/business/AccountBills.vue index cbbef0b4..4717a211 100644 --- a/resources/assets/js/components/business/AccountBills.vue +++ b/resources/assets/js/components/business/AccountBills.vue @@ -46,28 +46,37 @@ {{ promotionExpenseMessage || '当前筛选范围内暂无推广费明细。' }}
- - - - - - - - - - - -
{{ column.label }}
{{ promotionCellValue(row, column) }}
+
+ + + + + + + + + + + +
{{ column.label }}
{{ promotionCellValue(row, column) }}
+
+
+ 第 {{ promotionExpensePage }} / {{ promotionExpenseLastPage }} 页 · 共 {{ promotionExpenseTotal }} 条 +
+ + +
+
@@ -83,13 +92,13 @@ -
- +
@@ -212,7 +221,7 @@ const currentMonthRange = () => { const now = new Date(); const year = now.getFu const emptyFilters = billType => ({store_name:'',ledger_remark:'',bill_item:'',...currentMonthRange(),keyword:'',keyword_match:'contains'}); export default { name:'AccountBills', components:{ TableColumnSettings, flatPicker, [Select.name]:Select, [Option.name]:Option }, props:{ apiBase:{type:String,required:true}, billType:{type:String,required:true}, progressBase:{type:String,default:''}, userKey:{type:[String,Number],required:true} }, - data(){return{loading:false,loadError:false,sync:null,rows:[],sourceColumns:[],configuredColumns:[],columnsTitle:'',sourceGroups:[],summary:{income:0,expense:0,balance:0,count:0},total:0,currentPage:1,lastPage:1,perPage:20,filters:emptyFilters(this.billType),queryFilters:emptyFilters(this.billType),resultFilters:null,filterOptions:{shops:[],bill_items:[],ledger_remarks:[]},filterOptionsLoading:false,filterOptionsError:false,requestSerial:0,promotionRequestSerial:0,sort:{key:'occurred_at',dir:'desc'},exportMode:'filtered-visible',exporting:false,exportModalOpen:false,exportTasks:[],exportHint:'导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。',exportTimer:null,promotionModalOpen:false,promotionExpenseLoading:false,promotionExpenseError:false,promotionExpenseRows:[],promotionExpenseSummary:{expense:0,count:0},promotionExpenseMessage:'',promotionExpenseColumns:PROMOTION_DETAIL_COLUMNS};}, + data(){return{loading:false,loadError:false,sync:null,rows:[],sourceColumns:[],configuredColumns:[],columnsTitle:'',sourceGroups:[],summary:{income:0,expense:0,balance:0,count:0},total:0,currentPage:1,lastPage:1,perPage:20,filters:emptyFilters(this.billType),queryFilters:emptyFilters(this.billType),resultFilters:null,filterOptions:{shops:[],bill_items:[],ledger_remarks:[]},filterOptionsLoading:false,filterOptionsError:false,requestSerial:0,promotionRequestSerial:0,sort:{key:'occurred_at',dir:'desc'},exportMode:'filtered-visible',exporting:false,exportModalOpen:false,exportTasks:[],exportHint:'导出在后台生成,成功后点「下载」;期间可以继续查看其它页面。',exportTimer:null,promotionModalOpen:false,promotionExpenseLoading:false,promotionExpenseError:false,promotionExpenseRows:[],promotionExpenseSummary:{expense:0,count:0},promotionExpenseMessage:'',promotionExpenseColumns:PROMOTION_DETAIL_COLUMNS,promotionExpensePage:1,promotionExpenseLastPage:1,promotionExpenseTotal:0,promotionExpensePerPage:20};}, computed:{ isDouyin(){return this.billType==='douyin';}, isPromotionMarketing(){return this.billType==='promotion-marketing';}, @@ -225,7 +234,7 @@ export default { // Every account-bill tab uses the same explicit picker path. Keeping one // control avoids browser-native date inputs appearing on older tabs. usesStableDateControl(){return true;}, - usesMirrorOptions(){return ['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx'].indexOf(this.billType)!==-1;}, + usesMirrorOptions(){return ['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx','promotion-marketing'].indexOf(this.billType)!==-1;}, invalidDateRange(){return Boolean(this.filters.start&&this.filters.end&&this.filters.start>this.filters.end);}, startDateConfig(){return {...dateConfig,maxDate:this.filters.end||null};}, endDateConfig(){return {...dateConfig,minDate:this.filters.start||null};}, @@ -234,7 +243,7 @@ export default { visibleColumns(){return this.configuredColumns.filter(column=>column.visible);}, visibleGroups(){return this.visibleColumns.reduce((groups,column)=>{if(!column.group)return groups;const last=groups[groups.length-1];if(last&&last.label===column.group)last.span+=1;else groups.push({label:column.group,span:1});return groups;},[]);}, stats(){ - const netLabel=JD_BILL_TABS.concat(['vipshop-jx']).indexOf(this.billType)!==-1; + const netLabel=JD_BILL_TABS.concat(['vipshop-jx','promotion-marketing']).indexOf(this.billType)!==-1; const items=[ {label:'收入合计',value:this.moneyWan(this.summary.income),note:`${this.summary.count} 笔交易`,className:'is-income'}, {label:'支出合计',value:this.moneyWan(this.summary.expense),note:'按当前筛选',className:'is-expense'}, @@ -250,8 +259,8 @@ export default { }, mounted(){if(this.usesMirrorOptions)this.fetchFilterOptions();this.fetch();}, methods:{ - async fetchFilterOptions(){this.filterOptionsLoading=true;this.filterOptionsError=false;try{const response=await window.axios.get(`${this.apiBase}/filter-options`);const body=response.data||{};this.filterOptions={shops:Array.isArray(body.shops)?body.shops:[],bill_items:Array.isArray(body.bill_items)?body.bill_items:[],ledger_remarks:Array.isArray(body.ledger_remarks)?body.ledger_remarks:[]};}catch(error){this.filterOptionsError=true;}finally{this.filterOptionsLoading=false;}}, - async fetch(){const requestId=++this.requestSerial;const requestedFilters={...this.queryFilters};this.loading=true;this.loadError=false;try{const response=await window.axios.get(this.apiBase,{params:{...requestedFilters,sort:this.sort.key,dir:this.sort.dir,limit:this.perPage,page:this.currentPage}});if(requestId!==this.requestSerial)return;const body=response.data||{};this.resultFilters=requestedFilters;this.sync=body.sync||null;this.rows=body.data||[];this.total=body.total||0;this.currentPage=body.current_page||1;this.lastPage=body.last_page||1;this.perPage=body.per_page||this.perPage;this.summary=body.summary||{income:0,expense:0,balance:0,count:0};if(body.columns){this.columnsTitle=body.columns.title||'';this.sourceGroups=body.columns.groups||[];this.sourceColumns=this.attachGroups(body.columns.columns||body.columns||[],this.sourceGroups);}if(this.isPromotionMarketing)this.fetchPromotionExpenseDetails(requestedFilters);}catch(error){if(requestId!==this.requestSerial)return;this.rows=[];this.total=0;this.sync=null;this.summary={income:0,expense:0,balance:0,count:0};this.loadError=true;}finally{if(requestId===this.requestSerial)this.loading=false;}}, + async fetchFilterOptions(){this.filterOptionsLoading=true;this.filterOptionsError=false;try{const response=await window.axios.get(`${this.apiBase}/filter-options`,{params:{start:this.filters.start,end:this.filters.end}});const body=response.data||{};this.filterOptions={shops:Array.isArray(body.shops)?body.shops:[],bill_items:Array.isArray(body.bill_items)?body.bill_items:[],ledger_remarks:Array.isArray(body.ledger_remarks)?body.ledger_remarks:[]};}catch(error){this.filterOptionsError=true;}finally{this.filterOptionsLoading=false;}}, + async fetch(){const requestId=++this.requestSerial;const requestedFilters={...this.queryFilters};this.loading=true;this.loadError=false;try{const response=await window.axios.get(this.apiBase,{params:{...requestedFilters,sort:this.sort.key,dir:this.sort.dir,limit:this.perPage,page:this.currentPage}});if(requestId!==this.requestSerial)return;const body=response.data||{};this.resultFilters=requestedFilters;this.sync=body.sync||null;this.rows=body.data||[];this.total=body.total||0;this.currentPage=body.current_page||1;this.lastPage=body.last_page||1;this.perPage=body.per_page||this.perPage;this.summary=body.summary||{income:0,expense:0,balance:0,count:0};if(this.isPromotionMarketing){this.promotionExpenseSummary={expense:Number(this.summary.expense||0),count:Number(this.summary.count||0)};}if(body.columns){this.columnsTitle=body.columns.title||'';this.sourceGroups=body.columns.groups||[];this.sourceColumns=this.attachGroups(body.columns.columns||body.columns||[],this.sourceGroups);}}catch(error){if(requestId!==this.requestSerial)return;this.rows=[];this.total=0;this.sync=null;this.summary={income:0,expense:0,balance:0,count:0};this.loadError=true;}finally{if(requestId===this.requestSerial)this.loading=false;}}, attachGroups(columns,groups){let index=0;return columns.map((column,columnIndex)=>{while(groups[index]&&columnIndex>=groups.slice(0,index+1).reduce((sum,group)=>sum+Number(group.span||0),0))index+=1;return{...column,key:column.field||`column-${columnIndex}`,group:groups[index]?groups[index].label:''};});}, applyFilters(){if(this.invalidDateRange)return;this.queryFilters={...this.filters};this.currentPage=1;return this.fetch();},resetFilters(){this.filters=emptyFilters(this.billType);return this.applyFilters();},changePage(page){this.currentPage=page;this.fetch();this.$nextTick(()=>{if(this.$refs.scroll)this.$refs.scroll.scrollTop=0;});}, openDatePicker(refName){const picker=this.$refs[refName];if(picker&&picker.fp)picker.fp.open();}, @@ -262,10 +271,14 @@ export default { this.promotionExpenseError=false; this.promotionExpenseMessage=''; try{ - const response=await window.axios.get(`${this.apiBase}/promotion-expense-details`,{params:requestedFilters,headers:{Accept:'application/json'}}); + const response=await window.axios.get(`${this.apiBase}/promotion-expense-details`,{params:{...requestedFilters,page:this.promotionExpensePage,limit:this.promotionExpensePerPage},headers:{Accept:'application/json'}}); if(requestId!==this.promotionRequestSerial)return; const body=response.data||{}; this.promotionExpenseRows=Array.isArray(body.data)?body.data:[]; + this.promotionExpensePage=Number(body.current_page||1); + this.promotionExpenseLastPage=Number(body.last_page||1); + this.promotionExpenseTotal=Number(body.total||0); + this.promotionExpensePerPage=Number(body.per_page||this.promotionExpensePerPage); this.promotionExpenseSummary={ expense:Number((body.summary||{}).expense||0), count:Number((body.summary||{}).count||0), @@ -285,10 +298,12 @@ export default { }, openPromotionDetails(){ this.promotionModalOpen=true; + this.promotionExpensePage=1; this.fetchPromotionExpenseDetails(); this.$nextTick(()=>{if(this.$refs.promotionModal)this.$refs.promotionModal.focus();}); }, closePromotionDetails(){this.promotionModalOpen=false;}, + changePromotionExpensePage(page){if(page<1||page>this.promotionExpenseLastPage)return;this.promotionExpensePage=page;this.fetchPromotionExpenseDetails();}, promotionCellValue(row,column){return this.displayValue(row,column);}, // 选日期不自动查询:日期是一次选两个(开始/结束),中途触发会先按半截条件查全表,很慢。改完点「查询」再生效。 changeDate(field,value){const date=value||'';if(this.filters[field]===date)return;this.filters[field]=date;}, @@ -469,12 +484,16 @@ export default { .tw-promotion-modal{width:min(980px,100%)} .tw-promotion-state{display:flex;min-height:8rem;align-items:center;justify-content:center;gap:.75rem;border:1px dashed #d8d2c7;border-radius:.5rem;background:#fbfaf7;color:#595959;text-align:center} .tw-promotion-state.is-error{border-color:#b80000;background:#fff5f5;color:#b80000} -.tw-promotion-table-wrap{max-height:min(58vh,34rem);overflow:auto;border:1px solid #d8d2c7;border-radius:.5rem} +.tw-promotion-table-wrap{display:flex;max-height:min(58vh,34rem);flex-direction:column;overflow:hidden;border:1px solid #d8d2c7;border-radius:.5rem} +.tw-promotion-table-wrap>div:first-child{overflow:auto} .tw-promotion-table{min-width:100%} .tw-promotion-table th{top:0} .tw-promotion-table td:nth-child(3){max-width:26rem;white-space:normal} +.tw-promotion-pager{display:flex;align-items:center;justify-content:space-between;gap:.75rem;padding:.5rem .75rem;border-top:1px solid #d8d2c7;background:#fff;color:#595959;font-size:.75rem} +.tw-promotion-pager>div{display:flex;gap:.5rem} +.tw-promotion-pager .tw-button{height:1.75rem} .tw-promotion-total{margin-right:auto;color:#595959;font-size:.75rem} @container(max-width:1100px){.tw-stats--five{grid-template-columns:repeat(3,minmax(0,1fr))}} @media(max-width:900px){.tw-stats--five{grid-template-columns:repeat(2,minmax(0,1fr))}.tw-stat--promotion{grid-column:1/-1}} -@media(max-width:520px){.tw-stats--five{grid-template-columns:1fr}.tw-stat--promotion{grid-column:auto}.tw-modal__foot{align-items:stretch;flex-direction:column}.tw-promotion-total{margin-right:0;text-align:left}} +@media(max-width:520px){.tw-stats--five{grid-template-columns:1fr}.tw-stat--promotion{grid-column:auto}.tw-modal__foot{align-items:stretch;flex-direction:column}.tw-promotion-total{margin-right:0;text-align:left}.tw-promotion-pager{align-items:stretch;flex-direction:column}.tw-promotion-pager>div{justify-content:flex-end}} diff --git a/tests/Feature/Business/PromotionMarketingAccountBillsTest.php b/tests/Feature/Business/PromotionMarketingAccountBillsTest.php index 9301c980..b28fb670 100644 --- a/tests/Feature/Business/PromotionMarketingAccountBillsTest.php +++ b/tests/Feature/Business/PromotionMarketingAccountBillsTest.php @@ -2,6 +2,8 @@ namespace Tests\Feature\Business; +use Mockery; +use Modules\EcommerceFinance\Repositories\PromotionMarketingExpenseRepository; use Tests\Feature\FeatureTestCase; class PromotionMarketingAccountBillsTest extends FeatureTestCase @@ -28,15 +30,44 @@ class PromotionMarketingAccountBillsTest extends FeatureTestCase ->assertSeeText('推广费(营销账户)'); } - public function test_promotion_marketing_placeholder_keeps_the_detail_contract_stable(): void + public function test_promotion_marketing_page_and_details_share_contract(): void { + $repository = Mockery::mock(PromotionMarketingExpenseRepository::class); + $result = [ + 'rows' => [[ + 'id' => 'row-1', + 'store_name' => '测试推广店', + 'occurred_at' => '2026-10-23 09:00:00', + 'notes' => '商品推广', + 'expense' => 12.34, + ]], + 'total' => 1, + 'current_page' => 1, + 'last_page' => 1, + 'per_page' => 20, + 'summary' => ['expense' => 12.34, 'count' => 1], + ]; + $repository->shouldReceive('paginate')->once()->ordered()->with([ + 'start' => '', + 'end' => '', + 'store_name' => '', + ], 1, 10)->andReturn($result); + $repository->shouldReceive('paginate')->once()->ordered()->with([ + 'start' => '2026-10-01', + 'end' => '2026-10-31', + 'store_name' => '', + ], 1, 20)->andReturn($result); + $this->app->instance(PromotionMarketingExpenseRepository::class, $repository); + $this->loginAs() ->getJson(route('ecommerce-finance.account-bills.index', [ 'bill_type' => 'promotion-marketing', ])) ->assertOk() - ->assertJsonPath('total', 0) + ->assertJsonPath('total', 1) + ->assertJsonPath('summary.expense', 12.34) ->assertJsonPath('columns.title', '推广费(营销账户)') + ->assertJsonPath('data.0.store_name', '测试推广店') ->assertJsonPath('columns.columns.0.label', '店铺名称') ->assertJsonPath('columns.columns.1.label', '交易时间') ->assertJsonPath('columns.columns.2.label', '备注') @@ -49,13 +80,34 @@ class PromotionMarketingAccountBillsTest extends FeatureTestCase 'end' => '2026-10-31', ])) ->assertOk() - ->assertJsonPath('total', 0) - ->assertJsonPath('summary.expense', 0) - ->assertJsonPath('summary.count', 0) + ->assertJsonPath('total', 1) + ->assertJsonPath('summary.expense', 12.34) + ->assertJsonPath('summary.count', 1) + ->assertJsonPath('data.0.notes', '商品推广') ->assertJsonPath('columns.0.field', 'store_name') ->assertJsonPath('columns.1.field', 'occurred_at') ->assertJsonPath('columns.2.field', 'notes') - ->assertJsonPath('columns.3.field', 'expense') - ->assertJsonPath('message', '推广费数据源尚未配置,接入后将按当前筛选显示店铺明细。'); + ->assertJsonPath('columns.3.field', 'expense'); + } + + public function test_promotion_marketing_store_options_come_from_the_same_date_range(): void + { + $repository = Mockery::mock(PromotionMarketingExpenseRepository::class); + $repository->shouldReceive('storeOptions')->once()->with([ + 'start' => '2026-10-01', + 'end' => '2026-10-31', + 'store_name' => '', + ])->andReturn(['测试推广店', '另一推广店']); + $this->app->instance(PromotionMarketingExpenseRepository::class, $repository); + + $this->loginAs() + ->getJson(route('ecommerce-finance.account-bills.filter-options', [ + 'bill_type' => 'promotion-marketing', + 'start' => '2026-10-01', + 'end' => '2026-10-31', + ])) + ->assertOk() + ->assertJsonPath('shops.0', '测试推广店') + ->assertJsonPath('shops.1', '另一推广店'); } } diff --git a/tests/Unit/EcommerceFinance/PromotionMarketingExpenseRepositoryTest.php b/tests/Unit/EcommerceFinance/PromotionMarketingExpenseRepositoryTest.php new file mode 100644 index 00000000..a3078c8a --- /dev/null +++ b/tests/Unit/EcommerceFinance/PromotionMarketingExpenseRepositoryTest.php @@ -0,0 +1,136 @@ +repository(); + $repository->histogramRows = [ + 'tmall_spread_bills' => [['report_date' => '2026-10-23', 'row_count' => 1, 'expense' => 10]], + 'alibaba_bill' => [['report_date' => '2026-10-23', 'row_count' => 1, 'expense' => 20]], + 'pdd_spread_bills' => [['report_date' => '2026-10-23', 'row_count' => 1, 'expense' => 30]], + 'jd_jzt_finance_records' => [['report_date' => '2026-10-23', 'row_count' => 1, 'expense' => 40]], + 'dy_qianchuan_finance_transactions' => [['report_date' => '2026-10-23', 'row_count' => 1, 'expense' => 50]], + 'dw_ad_finance_records' => [['report_date' => '2026-10-23', 'row_count' => 1, 'expense' => 60]], + 'vip_marketingDailyReport' => [['report_date' => '2026-10-23', 'row_count' => 1, 'expense' => 70]], + ]; + $repository->detailRows = [ + 'tmall_spread_bills' => [$this->row('淘宝店', '2026-10-23 09:00:00', '淘宝备注', null, 10)], + 'alibaba_bill' => [$this->row('阿里店', '2026-10-23', '智能营销方案', null, 20)], + 'pdd_spread_bills' => [$this->row('拼多多店', '2026-10-23 09:30:00', '商品推广', '1', 30)], + 'jd_jzt_finance_records' => [$this->row('京东店', '2026-10-23', '快车扣费', '推广费', 40)], + 'dy_qianchuan_finance_transactions' => [$this->row('抖音店', '2026-10-23', '千川推广', null, 50)], + 'dw_ad_finance_records' => [$this->row('得物店', '2026-10-23', '得物推服务', '现金', 60)], + 'vip_marketingDailyReport' => [$this->row('唯品店', '2026-10-23', '推广费', null, 70)], + ]; + + $result = $repository->paginate([ + 'start' => '2026-10-01', + 'end' => '2026-10-31', + 'store_name' => '', + ], 2, 2); + + $this->assertSame(7, $result['total']); + $this->assertSame(280.0, $result['summary']['expense']); + $this->assertSame(4, $result['last_page']); + $this->assertSame(['拼多多店', '京东店'], array_column($result['rows'], 'store_name')); + $this->assertSame('商品推广 · 现金', $result['rows'][0]['notes']); + $this->assertSame('快车扣费 · 推广费', $result['rows'][1]['notes']); + $this->assertSame([30.0, 40.0], array_column($result['rows'], 'expense')); + $this->assertTrue($repository->sawSql('tmall_spread_bills', "finType] = 'CREDIT'")); + $this->assertTrue($repository->sawSql('pdd_spread_bills', 'flowType] = 2')); + $this->assertTrue($repository->sawSql('jd_jzt_finance_records', "in_out_type] = 'OUT'")); + $this->assertTrue($repository->sawSql('dw_ad_finance_records', 'trade_amount_yuan')); + $this->assertTrue($repository->sawSql('vip_marketingDailyReport', 'accountName')); + } + + public function test_store_options_are_merged_and_deduplicated(): void + { + $repository = $this->repository(); + $repository->storeRows = [ + 'tmall_spread_bills' => [['store_name' => '乙店'], ['store_name' => '甲店']], + 'alibaba_bill' => [['store_name' => '甲店']], + ]; + + $this->assertSame(['乙店', '甲店'], $repository->storeOptions([ + 'start' => '2026-10-01', + 'end' => '2026-10-31', + ])); + } + + private function repository(): PromotionMarketingExpenseRepository + { + return new class(Mockery::mock(UpstreamReadOnlyQueryFactory::class)) extends PromotionMarketingExpenseRepository { + public array $histogramRows = []; + + public array $detailRows = []; + + public array $storeRows = []; + + public array $queries = []; + + protected function select(string $connection, string $sql, array $bindings): array + { + $this->queries[] = compact('connection', 'sql', 'bindings'); + foreach (array_merge(array_keys($this->histogramRows), array_keys($this->detailRows), array_keys($this->storeRows)) as $table) { + if (! str_contains($sql, $table)) { + continue; + } + if (str_contains($sql, 'GROUP BY')) { + return $this->histogramRows[$table] ?? []; + } + if (str_contains($sql, 'DISTINCT TOP (500)')) { + return $this->storeRows[$table] ?? []; + } + + return $this->detailRows[$table] ?? []; + } + + return []; + } + + public function sawSql(string $table, string $fragment): bool + { + foreach ($this->queries as $query) { + if (str_contains($query['sql'], $table) && str_contains($query['sql'], $fragment)) { + return true; + } + } + + return false; + } + }; + } + + /** @return array */ + private function row( + string $store, + string $occurredAt, + string $primary, + ?string $secondary, + float $expense, + ): array { + return [ + 'report_date' => substr($occurredAt, 0, 10), + 'store_name' => $store, + 'occurred_at' => $occurredAt, + 'note_primary' => $primary, + 'note_secondary' => $secondary, + 'expense' => $expense, + ]; + } +} diff --git a/tests/Unit/View/AccountBillsTableTest.php b/tests/Unit/View/AccountBillsTableTest.php index d34b513e..b116a0c7 100644 --- a/tests/Unit/View/AccountBillsTableTest.php +++ b/tests/Unit/View/AccountBillsTableTest.php @@ -14,7 +14,7 @@ class AccountBillsTableTest extends TestCase $this->assertStringContainsString("usesStableDateControl(){return true;}", $source); $this->assertStringContainsString("{ 'is-stable-date': usesStableDateControl }", $source); $this->assertStringContainsString('.tw-date.is-stable-date .tw-date-control', $source); - $this->assertStringContainsString("['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx'].indexOf(this.billType)!==-1", $source); + $this->assertStringContainsString("['douyin','pinduoduo','dewu','taobao-wechat','jd-transactions','jingxi','jd-wallet','vipshop','vipshop-jx','promotion-marketing'].indexOf(this.billType)!==-1", $source); $this->assertStringContainsString('v-if="usesMirrorOptions && !filterOptionsError"', $source); $this->assertStringContainsString('page-key="store-receiving-bills"', $source); $this->assertStringContainsString(':tab-key="billType"', $source); @@ -49,7 +49,7 @@ class AccountBillsTableTest extends TestCase $this->assertStringContainsString("const DATE_FILTER_LABELS = {'jd-transactions':'费用结算时间','jingxi':'费用结算时间','jd-wallet':'费用结算时间','douyin':'结算时间','vipshop':'账单期间','vipshop-jx':'账单期间','promotion-marketing':'交易时间'};", $source); $this->assertStringContainsString('{{ dateFilterLabel }}', $source); $this->assertStringContainsString('v-if="isJdBillTab && sync"', $source); - $this->assertStringContainsString("netLabel=JD_BILL_TABS.concat(['vipshop-jx']).indexOf(this.billType)!==-1", $source); + $this->assertStringContainsString("netLabel=JD_BILL_TABS.concat(['vipshop-jx','promotion-marketing']).indexOf(this.billType)!==-1", $source); } public function test_promotion_marketing_card_opens_the_store_detail_modal(): void @@ -65,5 +65,7 @@ class AccountBillsTableTest extends TestCase $this->assertStringContainsString("label:'交易时间',field:'occurred_at'", $source); $this->assertStringContainsString("label:'备注',field:'notes'", $source); $this->assertStringContainsString("label:'支出金额',field:'expense'", $source); + $this->assertStringContainsString('changePromotionExpensePage', $source); + $this->assertStringContainsString('promotionExpenseLastPage', $source); } }