161 lines
9.9 KiB
PHP
161 lines
9.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Business;
|
|
|
|
use App\Support\CourierBills\{Category, CourierBillStore, CourierFreightLink, FreightConfirmation, Rebooks, SurchargeSettlementMatcher};
|
|
use App\Support\DropshipFreight\{DropshipConfirmation, DropshipFreightStore, DropshipReconciler};
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Routing\Controller;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Modules\EcommerceFinance\Services\SupplierDingTalkNotifier;
|
|
use RuntimeException;
|
|
use Throwable;
|
|
final class FreightConfirmationController extends Controller
|
|
{
|
|
public static function courierData(int $id): array
|
|
{
|
|
$db = app(CourierBillStore::class)->db();
|
|
$statement = $db->table('courier_bill_statements')->find($id);
|
|
abort_if(!$statement, 404);
|
|
$group = $db->table('courier_bill_groups')->find($statement->group_id);
|
|
$party = (object) ['id' => $id, 'name' => $group->name];
|
|
$items = $db->table('courier_bill_summary_items')->where('statement_id', $id)->orderBy('sort')->get();
|
|
$items = app(SurchargeSettlementMatcher::class)->summaryItems($id, $items);
|
|
$items = app(Rebooks::class)->summaryItems($id, $items);
|
|
$sum = $db->table('courier_bill_lines')->where('statement_id', $id)->selectRaw('COUNT(*) as n, SUM(bill_amount) as bill, SUM(self_amount) as settle')->first();
|
|
$summary = ['billed' => (int) $sum->n, 'bill' => round((float) $sum->bill, 2), 'settle' => round((float) $sum->settle, 2), 'diff' => round((float) $sum->bill - (float) $sum->settle, 2), 'total' => round($items->sum(fn ($r) => (float) $r->self_amount), 2)];
|
|
$fees = $items->map(fn ($r) => ['label' => $r->label, 'amount' => (float) $r->self_amount])->all();
|
|
return compact('statement', 'party', 'summary', 'fees');
|
|
}
|
|
|
|
public function push(Request $request, int $statement)
|
|
{
|
|
$t = self::courierData($statement);
|
|
$company = (int) (company_id() ?: 1);
|
|
if ($t['statement']->status !== 'confirmed') {
|
|
throw ValidationException::withMessages(['confirmation' => '请先完成核对并确认结算,再推送本组账单。']);
|
|
}
|
|
$notifier = app(SupplierDingTalkNotifier::class);
|
|
if (!$notifier->configuration($t['party']->name)['configured']) {
|
|
throw ValidationException::withMessages(['confirmation' => '请先为这个对账分组配置钉钉群机器人。']);
|
|
}
|
|
$c = app(FreightConfirmation::class);
|
|
$month = $t['statement']->bill_month;
|
|
$db = app(CourierBillStore::class)->db();
|
|
$attention = $db->table('courier_bill_lines')->where('statement_id', $statement)->where('category', '<>', Category::MATCH)->count();
|
|
try {
|
|
if (!$c->state($month, $statement, $company)) {
|
|
$c->check($month, $t['party'], $t['summary'], true, $company, user()?->id, self::by());
|
|
}
|
|
$rows = (function () use ($db, $statement) {
|
|
foreach ($db->table('courier_bill_lines')->where('statement_id', $statement)->orderBy('id')->lazyById(500) as $r) {
|
|
yield ['waybill' => $r->waybill_no, 'ship_time' => $r->ship_time, 'express' => $r->express_name, 'bill' => $r->bill_amount === null ? null : (float) $r->bill_amount, 'final' => $r->self_amount === null ? null : (float) $r->self_amount, 'status' => $r->category, 'label' => Category::label($r->category, $r->category_month), 'note' => Category::RESOLUTIONS[$r->resolution ?? ''] ?? Category::label($r->category, $r->category_month)];
|
|
}
|
|
})();
|
|
$version = $db->transaction(function () use ($db, $statement, $c, $month, $t, $attention, $company, $rows) {
|
|
// Prevent an unconfirm/rematch from changing the source while this version is copied.
|
|
$locked = $db->table('courier_bill_statements')->lockForUpdate()->find($statement);
|
|
if (!$locked || $locked->status !== 'confirmed' || $locked->updated_at !== $t['statement']->updated_at) {
|
|
throw new RuntimeException('对账单已发生变化,请刷新后再推送。');
|
|
}
|
|
return $c->startPush($month, $t['party'], $t['summary'], $attention, $company, user()?->id, self::by(), $rows, $t['fees']);
|
|
});
|
|
} catch (RuntimeException $e) {
|
|
throw ValidationException::withMessages(['confirmation' => $e->getMessage()]);
|
|
}
|
|
try {
|
|
$url = app(CourierFreightLink::class)->pageUrl($company, $statement, $month, $version);
|
|
$notifier->pushFreightConfirmation($t['party']->name, $month, $t['summary'], $version, $url);
|
|
$c->markPushed($month, $statement, $company);
|
|
} catch (Throwable $e) {
|
|
$c->markFailed($month, $statement, $company, '群推送失败,请检查机器人后重试。');
|
|
report($e);
|
|
throw ValidationException::withMessages(['confirmation' => '群推送失败,账单已保留,可重新推送。']);
|
|
}
|
|
return back()->with('courier_bills_message', '已推送到「' . $t['party']->name . '」钉钉群,版本 V' . $version . '。');
|
|
}
|
|
|
|
public function review(Request $request, int $owner)
|
|
{
|
|
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'version' => ['required', 'integer', 'min:1'], 'waybill' => ['required', 'string', 'max:64'], 'decision' => ['required', 'in:accept,reject'], 'reply' => ['required', 'string', 'max:1000']]);
|
|
$kind = $request->route('kind');
|
|
$company = (int) (company_id() ?: 1);
|
|
[$c, $party] = $this->context($kind, $owner, $data['month']);
|
|
// Refresh only this owner's existing calculation. No source price or ledger changes are made by feedback.
|
|
if ($kind === 'dropship') {
|
|
$row = collect(app(DropshipReconciler::class)->factoryMonth($party, $data['month'])['rows'])->firstWhere('waybill', $data['waybill']);
|
|
$amount = $row['final'] ?? null;
|
|
} else {
|
|
$row = app(CourierBillStore::class)->db()->table('courier_bill_lines')->where('statement_id', $owner)->where('waybill_no', $data['waybill'])->selectRaw('SUM(self_amount) as amount')->first();
|
|
$amount = $row?->amount === null ? null : (float) $row->amount;
|
|
}
|
|
try {
|
|
$review = $c->review($data['month'], $owner, (int) $data['version'], $data['waybill'], $data['decision'], $data['reply'], $amount, $company, user()?->id, self::by());
|
|
} catch (RuntimeException $e) {
|
|
throw ValidationException::withMessages(['confirmation' => $e->getMessage()]);
|
|
}
|
|
$this->sendReview($c, $party->name, $kind, $owner, $data['month'], (int) $data['version'], $company, $review);
|
|
return back()->with($kind === 'dropship' ? 'dropship_message' : 'courier_bills_message', '已保存财务处理结果;金额有变化时请重新推送新版账单。');
|
|
}
|
|
|
|
public function retry(Request $request, int $owner)
|
|
{
|
|
$data = $request->validate(['month' => ['required', 'date_format:Y-m'], 'waybill' => ['nullable', 'string', 'max:64']]);
|
|
$kind = $request->route('kind');
|
|
$company = (int) (company_id() ?: 1);
|
|
[$c, $party] = $this->context($kind, $owner, $data['month']);
|
|
$state = $c->state($data['month'], $owner, $company);
|
|
abort_if(!$state, 404);
|
|
$version = (int) $state['version'];
|
|
if (!empty($data['waybill'])) {
|
|
$review = collect($c->disputes($data['month'], $owner, $company, $version))->firstWhere('waybill', $data['waybill']);
|
|
abort_if(!$review || !isset($review['decision']) || ($review['receipt_status'] ?? '') === 'sent', 422);
|
|
$this->sendReview($c, $party->name, $kind, $owner, $data['month'], $version, $company, $review);
|
|
} else {
|
|
abort_if(($state['receipt_status'] ?? '') !== 'failed', 422);
|
|
$disputes = array_column($c->disputes($data['month'], $owner, $company, $version), 'reason', 'waybill');
|
|
$error = null;
|
|
try {
|
|
$n = app(SupplierDingTalkNotifier::class);
|
|
$sent = $kind === 'dropship' ? $n->sendDropshipFreightReceipt($party->name, $data['month'], (float) $state['settle'], $disputes) : $n->sendFreightConfirmationReceipt($party->name, $data['month'], (float) $state['settle'], $disputes);
|
|
if (!$sent) {
|
|
throw new RuntimeException('未配置群机器人');
|
|
}
|
|
} catch (Throwable $e) {
|
|
report($e);
|
|
$error = '群回执发送失败,请检查机器人后重试。';
|
|
}
|
|
$c->markReceipt($data['month'], $owner, $version, $company, $error);
|
|
}
|
|
return back()->with($kind === 'dropship' ? 'dropship_message' : 'courier_bills_message', '回执发送已处理,请查看回执状态。');
|
|
}
|
|
|
|
private function context(string $kind, int $owner, string $month): array
|
|
{
|
|
if ($kind === 'dropship') {
|
|
$party = collect(app(DropshipFreightStore::class)->factories())->firstWhere('id', $owner);
|
|
abort_if(!$party, 404);
|
|
return [app(DropshipConfirmation::class), $party];
|
|
}
|
|
$t = self::courierData($owner);
|
|
abort_if($t['statement']->bill_month !== $month, 404);
|
|
return [app(FreightConfirmation::class), $t['party']];
|
|
}
|
|
|
|
private function sendReview(FreightConfirmation $c, string $name, string $kind, int $owner, string $month, int $version, int $company, array $review): void
|
|
{
|
|
$error = null;
|
|
try {
|
|
app(SupplierDingTalkNotifier::class)->sendFreightReview($name, $kind, $month, $version, $review);
|
|
} catch (Throwable $e) {
|
|
report($e);
|
|
$error = '群回复发送失败,请重试。';
|
|
}
|
|
$c->markReceipt($month, $owner, $version, $company, $error, $review['waybill']);
|
|
}
|
|
private static function by(): string
|
|
{
|
|
return (string) (user()?->name ?? user()?->email ?? 'system');
|
|
}
|
|
}
|