Files
boursecu_server/app/Services/AccountingLedgerService.php
T

74 lines
2.7 KiB
PHP

<?php
namespace App\Services;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Product;
use App\Models\TransactionsAdmin;
use Throwable;
/**
* دفترکل حسابداری داخلی (transactions_admins).
*
* اصل: گزارشات باید همیشه کامل باشد — مستقل از اینکه اپ به حسابداری بیرونی (ته‌حساب و …) وصل است یا نه.
* این سرویس تنها نقطهٔ متمرکز ثبت سند دفترکل برای معامله/کیف‌پول/پاداش است و idempotent عمل می‌کند.
*/
class AccountingLedgerService
{
/**
* ثبت سند دفترکل برای معاملهٔ خرید/فروش مشتری.
* idempotent بر اساس order_id — اگر قبلاً ثبت شده باشد همان را برمی‌گرداند.
*/
public function recordTrade(?Order $order): ?TransactionsAdmin
{
if (! $order || ! $order->id) {
return null;
}
$existing = TransactionsAdmin::where('order_id', $order->id)->first();
if ($existing) {
return $existing;
}
try {
return TransactionsAdmin::create([
'customer_id' => $order->customer_id,
'customer_to_id' => $order->customer_id,
'order_id' => $order->id,
'user_id' => $order->customer_id,
'wallet' => null,
'transaction_id' => null,
'cash' => (int) round((float) ($order->total_price ?? 0)),
'note' => $this->tradeNote((int) ($order->direction ?? 0), $order),
'type' => 1,
'gold' => (float) ($order->amount ?? 0),
'balance_cash' => 0,
'balance_gold' => 0,
]);
} catch (Throwable $e) {
report($e);
return null;
}
}
/** توضیح سند معامله — بر اساس نام محصول سفارش */
public function tradeNote(int $direction, ?Order $order = null): string
{
$productTitle = null;
if ($order) {
$productTitle = $order->product?->title;
if (! $productTitle && $order->product_id) {
$productTitle = Product::query()->whereKey($order->product_id)->value('title');
}
}
$productTitle = trim((string) $productTitle);
if ($productTitle === '') {
$productTitle = Controller::mainWalletProductLabel() ?: 'مس';
}
return $direction === 1 ? ('خرید ' . $productTitle) : ($direction === 2 ? ('فروش ' . $productTitle) : 'معامله');
}
}