Compare commits

...
10 Commits
Author SHA1 Message Date
mohmdsdg 5c955a06a3 fixed bug of transaction 2026-09-06 15:29:11 +03:30
mohmdsdgandCursor c7ca410b31 fix(wallet): allow discharging leftover fractional count-product gold
Admin charge can now wipe the exact remaining balance when a count product has a leftover decimal amount.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 13:40:52 +03:30
mohmdsdgandCursor 034d18b690 fix(orders): cover with colleague only for main_wallet_products
Silver and other non-main products settle locally instead of posting to Montzar.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 11:49:20 +03:30
mohmdsdgandCursor 4ef2de8583 fix(products): force direct_price=1 when saving a manual price
Keeps weight-based live enrich from replacing an explicit stored mid price.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 11:38:46 +03:30
mohmdsdgandCursor 00b23ac404 feat(tahesab,colleague): push app balance to Tahesab and always wait callback
Add admin decision to write app wallet onto Tahesab even when zero, always await colleague callback regardless of the wait switch, and SMS admins on colleague reject.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 22:30:56 +03:30
mohmdsdgandCursor 8cee34bfba feat: landing settings, instant withdraw deduct, and OTP site URL
Add has_landing plus landing_* deploy keys, deduct balance on withdraw request, keep app_url for SMS login links, and clarify Zarin rial wallet document titles.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 17:01:39 +03:30
mohmdsdgandCursor 1c7ea16300 fix(sse): send per-product trade_open from server trading hours
The list stream must tell clients whether each product is open so the device clock cannot reopen a closed shop.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 12:58:14 +03:30
mohmdsdgandCursor 166764d6b8 fix(sse): isolate price stream inbox per tenant
Shared Redis global inbox mixed other shops' product lists into this catalog and made the grid jump.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 10:58:43 +03:30
mohmdsdgandCursor e4e9c74872 fix(product): separate list and TV visibility toggles
Product active toggle now drives show_in_list; TV has its own endpoint and no longer requires active.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-05 10:16:35 +03:30
mohmdsdgandCursor f3eaf91559 feat(pargar): prune inbound logs via MySQL INSERT trigger
Run one-time overflow cleanup on migrate and keep mande/document success
rows capped at 2000 with an AFTER INSERT trigger, without cron or manual SQL.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 20:24:44 +03:30
25 changed files with 850 additions and 168 deletions
@@ -117,6 +117,17 @@ class ProductController extends SuperController
public function store(Request $request)
{
$data = $this->filterProductData($request->all());
$formulaEnabled = Product::hasPriceFormulaColumns()
&& filter_var($data['price_formula_enabled'] ?? false, FILTER_VALIDATE_BOOLEAN);
if (isset($data['price']) && empty($data['app_price']) && ! $formulaEnabled) {
$data['reading_method'] = null;
if (Product::hasDirectPriceColumn()) {
$data['direct_price'] = 1;
}
if (Product::hasPriceOffsetColumn()) {
$data['price_offset_percent'] = 0;
}
}
$product = Product::create($data);
@@ -146,6 +157,10 @@ class ProductController extends SuperController
&& filter_var($data['price_formula_enabled'] ?? false, FILTER_VALIDATE_BOOLEAN);
if (isset($data['price']) && empty($data['app_price']) && ! $formulaEnabled) {
$data['reading_method'] = null;
// قیمت دستی ذخیره‌شده ⇒ وزن‌محور (مظنه زنده) نباید قیمت را عوض کند
if (Product::hasDirectPriceColumn()) {
$data['direct_price'] = 1;
}
if (Product::hasPriceOffsetColumn()) {
$data['price_offset_percent'] = 0;
}
@@ -227,7 +242,13 @@ class ProductController extends SuperController
}
// آبشده خانگی — کران قیمت را آپدیت می‌کند؛ list فقط از DB می‌خواند
$products = Product::with(['file'])->where('active', 1)->get();
$query = Product::with(['file']);
if (Product::hasShowInListColumn()) {
$query->where('show_in_list', 1);
} else {
$query->where('active', 1);
}
$products = $query->get();
if ($this->isCustomerApiRequest()) {
$products = $this->filterProductsForCustomerList($products);
@@ -255,7 +276,6 @@ class ProductController extends SuperController
}
$products = Product::with(['file'])
->where('active', 1)
->where('show_on_tv', true)
->get();
@@ -351,16 +371,40 @@ class ProductController extends SuperController
}
/**
* فعال/غیرفعال محصول — show باید با active هم‌گام باشد (اپ کاربر از show استفاده می‌کند).
* نمایش در لیست محصولات مشتری — با active/show هم‌گام می‌ماند (وضعیت باز/بسته جدول).
* تابلو TV جداست و با این متد عوض نمی‌شود.
*/
public function active($id)
{
$product = Product::findOrFail($id);
$active = !$product->active;
$on = ! $this->isProductShownInList($product);
$payload = [
'active' => $on,
'show' => $on,
];
if (Product::hasShowInListColumn()) {
$payload['show_in_list'] = $on;
}
$product->update($payload);
$this->broadcastPricesAfterResponse(true);
return response()->json(true);
}
/**
* نمایش در تابلو TV — مستقل از لیست محصولات و active.
*/
public function showOnTv($id)
{
if (! Product::hasShowOnTvColumn()) {
return response()->json(['message' => 'ستون show_on_tv موجود نیست'], 404);
}
$product = Product::findOrFail($id);
$product->update([
'active' => $active,
'show' => $active,
'show_on_tv' => ! (bool) $product->show_on_tv,
]);
$this->broadcastPricesAfterResponse(true);
return response()->json(true);
}
@@ -586,7 +630,13 @@ class ProductController extends SuperController
*/
public function customerStoreProductListPayload(): array
{
$products = Product::with(['file'])->where('active', 1)->get();
$query = Product::with(['file']);
if (Product::hasShowInListColumn()) {
$query->where('show_in_list', 1);
} else {
$query->where('active', 1);
}
$products = $query->get();
$products = $this->filterProductsForCustomerList($products);
$categoryService = app(CategoryService::class);
$products = $categoryService->filterProductsByVisibleCategories($products);
@@ -653,10 +703,19 @@ class ProductController extends SuperController
}
return $collection->filter(function (Product $product) {
return (bool) $product->show_in_list;
return $this->isProductShownInList($product);
})->values();
}
private function isProductShownInList(Product $product): bool
{
if (Product::hasShowInListColumn()) {
return (bool) $product->show_in_list;
}
return (bool) $product->active;
}
private function applyCustomerShow($products): void
{
$products = $products instanceof \Illuminate\Support\Collection
@@ -671,7 +730,10 @@ class ProductController extends SuperController
$displayPriceService = app(ProductDisplayPriceService::class);
$displayPriceService->warmLivePriceCache();
$displayPriceService->enrichForApi($products);
$products->each(function (Product $product) use ($displayPriceService) {
$config = app(ConfigService::class);
$products->each(function (Product $product) use ($displayPriceService, $config) {
$tradeOpen = $config->isProductWithinTradingHours($product);
$product->setAttribute('trade_open', $tradeOpen);
$product->setAttribute('show', $displayPriceService->resolveCustomerShow($product));
});
@@ -754,16 +816,19 @@ class ProductController extends SuperController
$data['show_in_assets'] = !empty($data['show_in_assets']);
}
if (!Product::hasShowOnTvColumn()) {
unset($data['show_on_tv']);
} elseif (array_key_exists('show_on_tv', $data)) {
$data['show_on_tv'] = !empty($data['show_on_tv']);
}
if (!Product::hasShowInListColumn()) {
unset($data['show_in_list']);
} elseif (array_key_exists('show_in_list', $data)) {
$data['show_in_list'] = !empty($data['show_in_list']);
// لیست و وضعیت باز/بسته یکی‌اند؛ TV جدا می‌ماند
$data['active'] = $data['show_in_list'];
$data['show'] = $data['show_in_list'];
}
if (!Product::hasShowOnTvColumn()) {
unset($data['show_on_tv']);
} elseif (array_key_exists('show_on_tv', $data)) {
$data['show_on_tv'] = !empty($data['show_on_tv']);
}
if (!Product::hasUseLastPriceIfZeroColumn()) {
@@ -235,7 +235,7 @@ class SettingsController extends Controller
}
/**
* تنظیمات پیشرفته: ۱۵ دسترسی از سوپرادمین + بقیهٔ can_edit=0 از DB لوکال.
* تنظیمات پیشرفته: ۱۶ دسترسی از سوپرادمین + بقیهٔ can_edit=0 از DB لوکال.
*/
private function composeSystemSettings($localRows)
{
@@ -319,7 +319,7 @@ class SettingsController extends Controller
/**
* get_settings ادمین (و پایهٔ publicIndex قبل از فیلتر show_to_user):
* can_edit=1 (+ runtime + local-owned) از DB لوکال
* فقط ۱۵ دسترسی سوپرادمین از overlay؛ بقیهٔ can_edit=0 از کپی لوکال
* فقط ۱۶ دسترسی سوپرادمین از overlay؛ بقیهٔ can_edit=0 از کپی لوکال
* اگر سوپرادمین در دسترس نباشد کل جدول لوکال برمی‌گردد.
*/
private function composeGetSettings($localRows)
@@ -807,7 +807,7 @@ class TahesabController extends Controller
/**
* همگام‌سازی مانده یک مشتری با ته‌حساب.
* body: overwrite=1 | keep=1 | ask_if_conflict=1 (پیش‌فرض ask برای جلوگیری از overwrite ناخواسته)
* body: overwrite=1 | keep=1 | push_to_tahesab=1 | ask_if_conflict=1
*/
public function syncCustomerWallet(Request $request, $customerId)
{
@@ -826,12 +826,26 @@ class TahesabController extends Controller
], 422);
}
$walletService = app(TahesabInboundWalletService::class);
if ($request->boolean('push_to_tahesab')) {
$result = $walletService->pushWalletToTahesab($customer);
$applied = (bool) ($result['applied'] ?? false);
return response()->json([
'ok' => $applied,
'needs_decision' => false,
'message' => $result['message'] ?? '',
'result' => $result,
], $applied ? 200 : 422);
}
$overwrite = $request->boolean('overwrite');
$keep = $request->boolean('keep');
$alwaysAsk = $request->boolean('always_ask');
$askIfConflict = $request->boolean('ask_if_conflict', ! $overwrite && ! $keep && ! $alwaysAsk);
$result = app(TahesabInboundWalletService::class)->syncWalletFromTahesab(
$result = $walletService->syncWalletFromTahesab(
$customer,
null,
[
@@ -275,6 +275,9 @@ class WalletController extends Controller
try {
$data['direction'] = $deposit ? 0 : 1;
$data['withdraw_id'] = $Withdraw->id;
if (!$deposit && trim((string) ($data['note'] ?? '')) === '') {
$data['note'] = 'برداشت وجه';
}
app(\App\Http\Controllers\Admin\ZarinController::class)->wallet($data);
} catch (\Exception $e) {
report($e);
@@ -557,10 +560,6 @@ class WalletController extends Controller
$deposit = $value > 0;
$payload = Controller::productUnitPayload($product);
if (Controller::isCountBasedProduct($payload) && abs($value - round($value)) > 0.000001) {
throw new UnprocessableEntityHttpException('برای محصول تعدادی فقط عدد صحیح مجاز است');
}
$isMainWalletProduct = Controller::isMainWalletProduct($productId);
if (!$deposit && $isMainWalletProduct) {
$this->consolidateOrphanedMainWalletGold((int) $customer->id, (int) $customer->type);
@@ -574,6 +573,18 @@ class WalletController extends Controller
$effectiveProductId
);
$wallet = $wallet_interface->wallet;
$availableGold = is_null($wallet) ? 0.0 : (float) $wallet->gold;
$wipingRemainder = !$deposit
&& $availableGold > 0
&& abs($availableGold - abs($value)) <= 1e-6;
if (
Controller::isCountBasedProduct($payload)
&& abs($value - round($value)) > 0.000001
&& ! $wipingRemainder
) {
throw new UnprocessableEntityHttpException('برای محصول تعدادی فقط عدد صحیح مجاز است');
}
if (!$deposit) {
$available = is_null($wallet) ? 0.0 : (float) $wallet->gold;
@@ -1446,6 +1457,10 @@ class WalletController extends Controller
$withdraw = Withdraw::findOrFail($request->id);
$withdraw->update($data);
if ($withdraw->customer) {
$this->broadcastCustomerWalletAssets($withdraw->customer);
}
// $tahesab = new TahesabController();
// $tahesab->wallet([
// 'customer_id' => $withdraw->customer_id,
+13 -4
View File
@@ -1861,12 +1861,21 @@ class ZarinController extends Controller
: ['korf' => 'k', 'parDar' => 1];
}
/** شرح سند ریالی زرین — همیشه با واریز/برداشت شروع شود تا «خرید فی» دیده نشود */
/**
* شرح سند ریالی زرین — همیشه «واریز وجه» یا «برداشت وجه».
* دشارژ ادمین و برداشت مشتری هر دو → «برداشت وجه» (پیشوند «واریز اینترنتی به» را زرین خودش می‌گذارد).
*/
private function zarinRialWalletSharh(bool $isDeposit, ?string $note): string
{
$base = $isDeposit ? 'واریز' : 'برداشت';
$base = $isDeposit ? 'واریز وجه' : 'برداشت وجه';
$normalized = self::accountingWalletDesc($isDeposit, $note);
if ($normalized === '' || $normalized === $base) {
$generic = [
'', 'واریز', 'برداشت', 'واریز وجه', 'برداشت وجه',
'واریز ریالی', 'برداشت ریالی',
'شارژ', 'دشارژ', 'شارژ حساب', 'کسر',
'واریز به کیف پول', 'برداشت از کیف پول', 'برداشت از حساب',
];
if (in_array($normalized, $generic, true) || in_array(trim((string) $note), $generic, true)) {
return $base;
}
if (str_starts_with($normalized, $base)) {
@@ -2029,7 +2038,7 @@ class ZarinController extends Controller
$data = array_merge($data, [
'customer_id' => $existing->customer_id,
'value' => $existing->amount,
'direction' => str_contains((string) $existing->desc, 'برداشت') ? 1 : 0,
'direction' => $this->sync()->rialWalletDirectionFromDesc((string) $existing->desc),
'withdraw_id' => $existing->withdraw_id,
]);
}
+2 -2
View File
@@ -227,13 +227,13 @@ class Controller extends BaseController
return app(ConfigService::class)->Config($name);
}
/** دامنهٔ عمومی سایت — فقط از درخواست HTTP فعلی */
/** دامنهٔ عمومی سایت — settings.app_url؛ نه هاست API */
protected static function publicHost(?\Illuminate\Http\Request $request = null): string
{
return app(ConfigService::class)->resolvePublicHost($request);
}
/** آدرس کامل وب‌اپ کاربر — مثلاً https://example.ir */
/** آدرس کامل وب‌اپ کاربر از settings.app_url — مثلاً https://example.ir */
protected static function publicSiteUrl(?\Illuminate\Http\Request $request = null): string
{
return app(ConfigService::class)->resolvePublicSiteUrl($request);
@@ -17,8 +17,11 @@ use App\Http\Controllers\Admin\TahesabController;
use App\Services\ConfigService;
use App\Services\AssetSummaryService;
use App\Services\WalletBalanceService;
use App\Services\WalletBroadcastService;
use App\Services\ZaarboxPriceService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Rooyesh\Wallet\interfaces\TransactionInterface;
@@ -372,43 +375,72 @@ class WalletController extends Controller
return response()->json(['message' => 'لطفا کارت بانکی را وارد کنید'], 422);
}
$bCart = BankAccount::where('id', $data['card_id'])->first();
if ($bCart->sts != 2) {
if (!$bCart || $bCart->sts != 2) {
return response()->json(['message' => 'کارت انتخاب شده نا معتبر است'], 422);
}
$wallet_interface_fund = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type);
if ($data['value'] < 0) {
$amount = (int) ($data['value'] ?? 0);
if ($amount <= 0) {
throw new UnprocessableEntityHttpException('مقدار برداشت باید مثبت باشد');
}
$this->validateWithdrawAmount((int) $data['value']);
$extraNote = trim((string) ($data['extra_note'] ?? ''));
if (strlen($extraNote) > 500) {
return response()->json(['message' => 'توضیحات اضافی حداکثر ۵۰۰ کاراکتر است'], 422);
}
$Withdraw = Withdraw::create([
'customer_id' => auth('customer')->id(),
"cash" => $data['value'],
"note" => "برداشت ریالی",
'extra_note' => $extraNote !== '' ? $extraNote : null,
"bank_account_id" => $data['card_id'],
'sts' => 1,
'type' => 2
]);
$transaction = new TransactionInterface($wallet_interface_fund, $_inp = [
"cash" => $data['value'],
'expire_at' => now(),
'withdraw_id' => $Withdraw->id,
'active' => true
], 4, false, false);
$otp = (string) ($request->otp ?? '');
if ($otp === '' || (string) ($customer->token_sms ?? '') !== $otp) {
return response()->json(['message' => 'رمز دوم اشتباه میباشد'], 422);
}
$lock = Cache::lock('customer-rial-withdraw:'.$customer->id, 20);
if (!$lock->get()) {
return response()->json(['message' => 'درخواست برداشت در حال انجام است'], 429);
}
try {
$customer->refresh();
if ((string) ($customer->token_sms ?? '') !== $otp) {
return response()->json(['message' => 'رمز دوم اشتباه میباشد'], 422);
}
$this->validateWithdrawAmount($amount);
$Withdraw = DB::transaction(function () use ($customer, $data, $amount, $extraNote) {
$withdraw = Withdraw::create([
'customer_id' => $customer->id,
'cash' => $amount,
'note' => 'برداشت ریالی',
'extra_note' => $extraNote !== '' ? $extraNote : null,
'bank_account_id' => $data['card_id'],
'sts' => 1,
'type' => 2,
]);
$this->debitCustomerRialWithdrawOnce($withdraw, $amount, $customer);
$customer->token_sms = null;
$customer->save();
return $withdraw;
});
} finally {
$lock->release();
}
try {
app(WalletBroadcastService::class)->broadcastForCustomer(
(int) $customer->id,
(int) $customer->type
);
} catch (\Throwable $e) {
report($e);
}
try {
app(\App\Services\PargarSyncService::class)->queueWalletDocument(
$customer,
'cash',
-1 * (float) $data['value'],
-1 * (float) $amount,
[
'withdraw_id' => $Withdraw->id,
'note' => 'برداشت ریالی',
@@ -421,18 +453,18 @@ class WalletController extends Controller
$userMobile = $customer->mobile; // User's mobile number
$userName = $customer->name; // User's name
$withdrawAmount = $data['value']; // amount
$withdrawAmount = $amount; // amount
if (app(ConfigService::class)->isTahesabAccounting()) {
try {
$result = app(TahesabController::class)->wallet([
"customer_id" => auth('customer')->id(),
"value" => $data['value'],
"value" => $amount,
"direction" => 1,
]);
\Log::info('Tahesab withdraw result', [
'customer_id' => auth('customer')->id(),
'value' => $data['value'],
'value' => $amount,
'result' => $result,
]);
} catch (\Exception $e) {
@@ -444,8 +476,10 @@ class WalletController extends Controller
try {
app(\App\Http\Controllers\Admin\ZarinController::class)->wallet([
"customer_id" => auth('customer')->id(),
"value" => $data['value'],
"value" => $amount,
"direction" => 1,
"withdraw_id" => $Withdraw->id,
"note" => 'برداشت ریالی',
]);
} catch (\Exception $e) {
report($e);
@@ -454,11 +488,6 @@ class WalletController extends Controller
$companyName = $this->Config('name_fa'); // Company name from configuration
$message = "کاربر $userName با شماره موبایل $userMobile درخواست برداشت مبلغ " . number_format($withdrawAmount) . " ریال را دارد. با تشکر، $companyName";
if (isset($request->otp)) {
if (Customer::where("id", $customer->id)->first()->token_sms != $request->otp) {
return response()->json(['message' => 'رمز دوم اشتباه میباشد'], 422);
}
}
User::where('send_sms', 1)->get()->each(function ($admin) use ($message) {
if (self::isSmsNotifEnabled('sms_notif_withdraw_admin')) {
$this->Send($admin->mobile, $message . ' ' . now()->format('H:i:s'));
@@ -675,6 +704,25 @@ class WalletController extends Controller
return response()->json(true);
}
private function debitCustomerRialWithdrawOnce(Withdraw $withdraw, int $amount, Customer $customer): void
{
$alreadyDebited = Transaction::query()
->where('withdraw_id', $withdraw->id)
->where('cash', '<', 0)
->exists();
if ($alreadyDebited) {
return;
}
$wallet = new WalletInterface((int) $customer->id, (int) $customer->type);
new TransactionInterface($wallet, [
'cash' => $amount,
'expire_at' => now(),
'withdraw_id' => $withdraw->id,
'active' => true,
], 4, false, false);
}
private function validateWithdrawAmount(int $value): void
{
$wallet_interface_fund = new WalletInterface(auth('customer')->id(), auth('customer')->user()->type);
@@ -32,6 +32,7 @@ use App\Services\ReferralGiftService;
use App\Services\WalletBalanceService;
use App\Services\WalletBroadcastService;
use App\Services\ColleagueOrderCallbackService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
@@ -974,9 +975,27 @@ class SingleOrderController extends Controller
\App\Services\Automation\AutomationEvents::fire($event, (int) $customer->id);
}
/**
* پوشش همکار فقط برای محصولات کیف اصلی (main_wallet_products).
* نقره/شمش/سکه و بقیه فقط محلی ثبت می‌شوند.
*/
private function shouldCoverOrderWithColleague(array $data): bool
{
if (! app(ConfigService::class)->usesMontzarPricing()) {
return false;
}
$productId = (int) ($data['product_id'] ?? $data['abshode_id'] ?? 0);
if ($productId <= 0) {
$productId = (int) (app(ConfigService::class)->mainProductId() ?? 0);
}
return $productId > 0 && app(ConfigService::class)->isMainWalletProduct($productId);
}
private function assertProviderOrderAccepted(array &$data): void
{
if (!app(ConfigService::class)->usesMontzarPricing()) {
if (! $this->shouldCoverOrderWithColleague($data)) {
return;
}
@@ -990,12 +1009,13 @@ class SingleOrderController extends Controller
/**
* اول رکورد محلی (در انتظار همکار)، بعد ارسال به لیمان، بعد کیف.
* اگر همکار رد کند یا کیف بترکد، همان رکورد با وضعیت ناموفق و شرح خطا می‌ماند.
* فقط main_wallet_products به همکار می‌روند.
*/
private function openOrderThenCoverWithProvider(array &$data): Order
{
$this->syncOrderProfitFields($data);
$montzar = app(ConfigService::class)->usesMontzarPricing();
if ($montzar) {
$cover = $this->shouldCoverOrderWithColleague($data);
if ($cover) {
$this->assertNoRecentDuplicateLocalOrder($data);
$data['sts'] = 4;
$data['payment_sts'] = 1;
@@ -1005,14 +1025,13 @@ class SingleOrderController extends Controller
$order = Order::create($data);
$data['order'] = $order;
if ($montzar) {
if ($cover) {
try {
$this->assertProviderOrderAccepted($data);
$this->finalizeProviderOrder($data);
$order->refresh();
if (app(ColleagueOrderCallbackService::class)->waitEnabled()) {
$data['_awaiting_callback'] = true;
}
// همیشه تا کالبک/استعلام همکار در انتظار می‌ماند (حتی اگر سوییچ خاموش باشد)
$data['_awaiting_callback'] = true;
} catch (\Throwable $e) {
$this->markOrderFailed($order, $e->getMessage());
throw $e instanceof UnprocessableEntityHttpException
@@ -1071,7 +1090,7 @@ class SingleOrderController extends Controller
private function finalizeProviderOrder(array &$data): void
{
if (!app(ConfigService::class)->usesMontzarPricing()) {
if (! $this->shouldCoverOrderWithColleague($data)) {
return;
}
@@ -2057,7 +2076,7 @@ class SingleOrderController extends Controller
$service = app(ColleagueOrderCallbackService::class);
$order = $service->pendingForCustomer((int) auth('customer')->id());
if ($order) {
$order = $service->refreshIfDue($order);
$order = $service->refreshIfDue($order, true);
}
return response()->json($service->publicStatusPayload($order));
@@ -2071,7 +2090,8 @@ class SingleOrderController extends Controller
->where('customer_id', auth('customer')->id())
->first();
if ($order) {
$order = $service->refreshIfDue($order);
// هر بار که کلاینت وضعیت می‌پرسد، استعلام همکار را اجباری کن
$order = $service->refreshIfDue($order, true);
}
return response()->json($service->publicStatusPayload($order));
@@ -2093,6 +2113,44 @@ class SingleOrderController extends Controller
public function rejectColleaguePendingOrder(Order $order, string $message): void
{
$this->markOrderFailed($order, $message);
$this->notifyAdminsColleagueOrderRejected($order, $message);
}
/**
* SMS ادمین وقتی سفارش در اپ ثبت شده ولی همکار رد کرده است.
*/
private function notifyAdminsColleagueOrderRejected(Order $order, string $rejectMessage): void
{
if (! self::isSmsNotifEnabled('sms_notif_order_admin')) {
return;
}
try {
$customer = Customer::query()->find((int) $order->customer_id);
$name = trim((string) ($customer->name ?? '')) ?: 'بدون نام';
$mobile = trim((string) ($customer->mobile ?? '')) ?: '—';
$dir = ((int) ($order->direction ?? 0) === 2) ? 'فروش' : 'خرید';
$amount = self::formatSmsGoldWeight((float) ($order->amount ?? 0));
$company = (string) ($this->Config('name_fa') ?: '');
$reason = trim($rejectMessage);
if ($reason === '') {
$reason = 'رد شده توسط همکار';
}
$message = "سفارش {$dir} کاربر {$name} ({$mobile}) به مقدار {$amount} گرم در اپ ثبت شد ولی از سمت همکار رد شد. علت: {$reason}";
if ($company !== '') {
$message .= " — {$company}";
}
User::where('send_sms', 1)->get()->each(function ($admin) use ($message) {
$this->send($admin->mobile, $message);
});
} catch (\Throwable $e) {
Log::warning('Colleague reject admin SMS failed', [
'order_id' => $order->id,
'error' => $e->getMessage(),
]);
}
}
public function finalizeColleaguePendingOrder(Order $order): void
+48 -12
View File
@@ -16,9 +16,8 @@ class ColleagueOrderCallbackService
public function waitEnabled(): bool
{
$config = app(ConfigService::class);
return $config->usesMontzarPricing() && $config->getBool('montzar_order_wait_callback', true);
// همیشه منتظر کالبک/استعلام همکار — سوییچ montzar_order_wait_callback دیگر مسیر «قطعی بلافاصله» را باز نمی‌کند
return app(ConfigService::class)->usesMontzarPricing();
}
public function callbackUrl(int $localOrderId): string
@@ -52,13 +51,13 @@ class ColleagueOrderCallbackService
return $this->applyProviderSts($order, $sts, $body);
}
public function refreshIfDue(Order $order): Order
public function refreshIfDue(Order $order, bool $force = false): Order
{
if ((int) $order->sts !== 4) {
return $order;
}
if (!$this->isPollDue($order)) {
if (!$force && !$this->isPollDue($order)) {
return $order;
}
@@ -95,9 +94,10 @@ class ColleagueOrderCallbackService
return ['ok' => true, 'state' => 'wait'];
}
// جدول سفارش همکار همان sts مدل است (۲ موفق / ۳ ناموفق / ۴ هنوز باز).
// کالبک جداست: آن‌جا ۴ و ۶ یعنی رد.
if (in_array($sts, [3, 6], true)) {
// جدول سفارش همکار: ۲ موفق / ۳ ناموفق / ۴ هنوز باز.
// بعضی پاسخ‌های تکی/کالبک‌مانند: ۴ و ۶ = رد.
// اگر sts_str هم صریحاً رد/ناموفق باشد، همان را قطعی می‌گیریم.
if ($this->providerBodyLooksRejected($body, $sts)) {
return $this->rejectPending($order, $body);
}
@@ -299,7 +299,13 @@ class ColleagueOrderCallbackService
*/
public function providerStsFromBody(array $body): ?int
{
$rows = [$body, $body['data'] ?? null, $body['order'] ?? null];
// اول ردیف سفارش تو‌در‌تو / rows — نه خودِ envelope که گاهی sts کهنه می‌گذارد
$rows = [];
foreach ([$body['order'] ?? null, $body['data'] ?? null] as $row) {
if (is_array($row)) {
$rows[] = $row;
}
}
if (isset($body['rows']) && is_array($body['rows'])) {
foreach ($body['rows'] as $row) {
if (is_array($row)) {
@@ -312,9 +318,14 @@ class ColleagueOrderCallbackService
continue;
}
$rows[] = $item;
$rows[] = $item['order'] ?? null;
$rows[] = $item['data'] ?? null;
if (isset($item['order']) && is_array($item['order'])) {
$rows[] = $item['order'];
}
if (isset($item['data']) && is_array($item['data'])) {
$rows[] = $item['data'];
}
}
$rows[] = $body;
foreach ($rows as $row) {
if (!is_array($row) || !array_key_exists('sts', $row) || $row['sts'] === null || $row['sts'] === '') {
@@ -327,12 +338,37 @@ class ColleagueOrderCallbackService
return null;
}
/**
* @param array<string, mixed> $body
*/
private function providerBodyLooksRejected(array $body, int $sts): bool
{
if (in_array($sts, [3, 6], true)) {
return true;
}
$str = mb_strtolower(trim((string) (
$body['sts_str']
?? $body['order']['sts_str']
?? $body['data']['sts_str']
?? $body['message']
?? ''
)));
if ($str !== '' && preg_match('/رد|ناموفق|reject|fail|cancel|لغو/u', $str)) {
// فقط وقتی sts هنوز «باز/در انتظار» نیست که با متن موفق قاطی شود
return $sts !== 2;
}
return false;
}
/**
* @param array<string, mixed> $body
*/
private function providerIdFromBody(array $body): int
{
foreach ([$body, $body['data'] ?? null, $body['order'] ?? null] as $row) {
foreach ([$body['order'] ?? null, $body['data'] ?? null, $body] as $row) {
if (!is_array($row)) {
continue;
}
+43 -14
View File
@@ -121,8 +121,11 @@ class ConfigService
try {
$row = Setting::where('key', $key)->first();
if ($row !== null && $row->is_active && $row->value !== null && $row->value !== '') {
return $row->value;
if ($row !== null && $row->value !== null && $row->value !== '') {
// app_url لینک ورود پیامک است — حتی اگر سوییچ is_active خاموش باشد باید خوانده شود
if ($key === 'app_url' || $row->is_active) {
return $row->value;
}
}
} catch (\Throwable $e) {
// DB در دسترس نیست (deploy / .env اشتباه) — از config/price_providers.php استفاده شود
@@ -1357,7 +1360,7 @@ class ConfigService
return '';
}
/** Full user-facing site URL, e.g. https://example.ir — prefers settings.app_url */
/** Full user-facing site URL, e.g. https://example.ir — فقط settings.app_url؛ هاست API جایگزین نمی‌شود */
public function resolvePublicSiteUrl(?\Illuminate\Http\Request $request = null): string
{
$fromAppUrl = $this->normalizedAppUrl();
@@ -1366,23 +1369,21 @@ class ConfigService
}
if ($request !== null) {
$origin = rtrim(trim((string) $request->getSchemeAndHttpHost()), '/');
$host = $this->parseHostFromUrl($origin);
if ($this->isUsableHost($host)) {
$origin = $this->originIfNotApiHost($request);
if ($origin !== '') {
return $origin;
}
}
if (! app()->runningInConsole() && request()) {
$origin = rtrim(trim((string) request()->getSchemeAndHttpHost()), '/');
$host = $this->parseHostFromUrl($origin);
if ($this->isUsableHost($host)) {
$origin = $this->originIfNotApiHost(request());
if ($origin !== '') {
return $origin;
}
}
$host = $this->resolvePublicHost($request);
if ($host !== '') {
if ($host !== '' && ! $this->hostMatchesLaravelAppUrl($host)) {
return 'https://' . $host;
}
@@ -1400,17 +1401,23 @@ class ConfigService
{
$candidates = [];
$appUrlHost = $this->parseHostFromUrl((string) $this->get('app_url', ''));
$appUrlHost = $this->parseHostFromUrl($this->getString('app_url', ''));
if ($appUrlHost !== '') {
$candidates[] = $appUrlHost;
}
if ($request !== null) {
$candidates[] = trim((string) $request->getHost());
$host = trim((string) $request->getHost());
if (! $this->hostMatchesLaravelAppUrl($host)) {
$candidates[] = $host;
}
}
if (! app()->runningInConsole() && request()) {
$candidates[] = trim((string) request()->getHost());
$host = trim((string) request()->getHost());
if (! $this->hostMatchesLaravelAppUrl($host)) {
$candidates[] = $host;
}
}
return $candidates;
@@ -1419,7 +1426,7 @@ class ConfigService
/** settings.app_url as https://host… without trailing slash; empty if unusable */
private function normalizedAppUrl(): string
{
$raw = trim((string) $this->get('app_url', ''));
$raw = $this->getString('app_url', '');
if ($raw === '') {
return '';
}
@@ -1443,6 +1450,28 @@ class ConfigService
return $origin;
}
/** هاست Laravel APP_URL همان بک‌اند است — نباید لینک ورود اپ شود */
private function hostMatchesLaravelAppUrl(string $host): bool
{
$apiHost = $this->parseHostFromUrl((string) config('app.url', ''));
if ($apiHost === '' || ! $this->isUsableHost($apiHost)) {
return false;
}
return $this->normalizeHost($host) === $this->normalizeHost($apiHost);
}
private function originIfNotApiHost(\Illuminate\Http\Request $request): string
{
$origin = rtrim(trim((string) $request->getSchemeAndHttpHost()), '/');
$host = $this->parseHostFromUrl($origin);
if (! $this->isUsableHost($host) || $this->hostMatchesLaravelAppUrl($host)) {
return '';
}
return $origin;
}
private function isUsableHost(string $host): bool
{
$host = strtolower(trim($host));
+12 -7
View File
@@ -148,12 +148,17 @@ class DatabaseLogPruneService
*
* @return array{mande: int, document: int}
*/
public function prunePargarInboundOverflow(int $maxDeletePerType = 0): array
/** هر بار حداکثر — برای afterResponse؛ تریگر MySQL هم LIMIT 4000 دارد */
private const PARAGAR_PRUNE_BATCH = 4000;
public function prunePargarInboundOverflow(?int $maxDeletePerType = null): array
{
if (! Schema::hasTable('pargar_sync_logs')) {
return ['mande' => 0, 'document' => 0];
}
$batch = $maxDeletePerType ?? self::PARAGAR_PRUNE_BATCH;
ignore_user_abort(true);
if (function_exists('set_time_limit')) {
@set_time_limit(180);
@@ -168,8 +173,8 @@ class DatabaseLogPruneService
try {
return [
'mande' => $this->pruneOldestSuccessBeyond(PargarSyncService::TYPE_MANDE, $maxDeletePerType),
'document' => $this->pruneOldestSuccessBeyond(PargarSyncService::TYPE_DOCUMENT, $maxDeletePerType),
'mande' => $this->pruneOldestSuccessBeyond(PargarSyncService::TYPE_MANDE, $batch),
'document' => $this->pruneOldestSuccessBeyond(PargarSyncService::TYPE_DOCUMENT, $batch),
];
} finally {
if ($locked === true) {
@@ -197,11 +202,11 @@ class DatabaseLogPruneService
->where('id', '<=', $cutoffId)
->orderBy('id');
if ($maxDelete > 0) {
return (int) $query->limit($maxDelete)->delete();
if ($maxDelete <= 0) {
$maxDelete = self::PARAGAR_PRUNE_BATCH;
}
return (int) $query->delete();
return (int) $query->limit($maxDelete)->delete();
}
private function ensureTypeStatusIndex(): void
@@ -224,7 +229,7 @@ class DatabaseLogPruneService
private function acquirePruneLock(): ?bool
{
try {
$row = DB::selectOne('SELECT GET_LOCK(?, 0) AS l', ['khanegi_pargar_inbound_prune']);
$row = DB::selectOne('SELECT GET_LOCK(?, 3) AS l', ['khanegi_pargar_inbound_prune']);
return (int) ($row->l ?? 0) === 1;
} catch (\Throwable) {
+1 -2
View File
@@ -627,8 +627,7 @@ class MontzarService
];
if (
$this->config()->getBool('montzar_order_wait_callback', true)
&& isset($data['order'])
isset($data['order'])
&& $data['order'] instanceof Order
) {
$payload['callback'] = app(ColleagueOrderCallbackService::class)->callbackUrl((int) $data['order']->id);
+13 -7
View File
@@ -52,7 +52,7 @@ class PriceBroadcastService
}
$lastChanged = is_array($lastPayload) && $lastPayload !== []
&& $this->rememberHashIfChanged(self::LAST_HASH_KEY, self::lastPriceIdentity($lastPayload));
&& $this->rememberHashIfChanged($this->cacheKey(self::LAST_HASH_KEY), self::lastPriceIdentity($lastPayload));
if ($lastChanged && is_array($lastPayload)) {
$stream->publish('last', $lastPayload);
@@ -106,7 +106,7 @@ class PriceBroadcastService
return;
}
if (! $this->rememberHashIfChanged(self::LAST_HASH_KEY, self::lastPriceIdentity($lastPayload))) {
if (! $this->rememberHashIfChanged($this->cacheKey(self::LAST_HASH_KEY), self::lastPriceIdentity($lastPayload))) {
return;
}
@@ -117,7 +117,7 @@ class PriceBroadcastService
public function buildListPayload(bool $allowCached = false): ?array
{
if ($allowCached) {
$cached = Cache::get(self::LIST_SNAPSHOT_KEY);
$cached = Cache::get($this->cacheKey(self::LIST_SNAPSHOT_KEY));
if (
is_array($cached)
&& is_array($cached['body'] ?? null)
@@ -130,7 +130,7 @@ class PriceBroadcastService
$body = $this->buildProductListPayload();
if ($body !== null && $body !== []) {
Cache::put(self::LIST_SNAPSHOT_KEY, [
Cache::put($this->cacheKey(self::LIST_SNAPSHOT_KEY), [
'body' => $body,
'stored_at' => now(),
], now()->addSeconds(self::LIST_SNAPSHOT_SECONDS + 5));
@@ -156,15 +156,15 @@ class PriceBroadcastService
return false;
}
if (! $force && ! $this->rememberHashIfChanged(self::LIST_HASH_KEY, self::listIdentity($listPayload))) {
if (! $force && ! $this->rememberHashIfChanged($this->cacheKey(self::LIST_HASH_KEY), self::listIdentity($listPayload))) {
return false;
}
if ($force) {
$this->rememberHashIfChanged(self::LIST_HASH_KEY, self::listIdentity($listPayload));
$this->rememberHashIfChanged($this->cacheKey(self::LIST_HASH_KEY), self::listIdentity($listPayload));
}
Cache::forget(self::LIST_SNAPSHOT_KEY);
Cache::forget($this->cacheKey(self::LIST_SNAPSHOT_KEY));
app(PriceStreamService::class)->publish('list', $listPayload);
return true;
@@ -207,6 +207,7 @@ class PriceBroadcastService
'reading_method' => (string) ($product['reading_method'] ?? ''),
'price_offset_percent' => (float) ($product['price_offset_percent'] ?? 0),
'show' => (bool) ($product['show'] ?? true),
'trade_open' => (bool) ($product['trade_open'] ?? $product['show'] ?? true),
'active' => (bool) ($product['active'] ?? true),
'reference_provider_active' => (bool) ($product['reference_provider_active'] ?? false),
];
@@ -218,6 +219,11 @@ class PriceBroadcastService
/**
* @param array<string, mixed>|array<int, mixed> $payload
*/
private function cacheKey(string $base): string
{
return $base.':'.app(PriceStreamService::class)->tenantScope();
}
private function rememberHashIfChanged(string $cacheKey, array $payload): bool
{
$hash = md5(json_encode($payload, JSON_UNESCAPED_UNICODE));
+25 -2
View File
@@ -126,14 +126,37 @@ class PriceStreamService
return $store;
}
/**
* چند مستأجر روی یک Redis با پیشوند یکسان inbox را قاطی می‌کردند
* (لیست شمش یک فروشگاه روی صفحهٔ فروشگاه دیگر).
*/
public function tenantScope(): string
{
$default = (string) config('database.default', 'mysql');
$db = (string) config("database.connections.{$default}.database");
$host = '';
try {
$host = app(ConfigService::class)->resolvePublicHost();
} catch (\Throwable) {
$host = '';
}
$parts = array_values(array_filter(
[$db, $host],
static fn (string $value): bool => $value !== ''
));
return $parts !== [] ? implode(':', $parts) : 'default';
}
private function inboxKey(): string
{
return self::INBOX_PREFIX.'global';
return self::INBOX_PREFIX.$this->tenantScope();
}
private function customerInboxKey(int $customerId): string
{
return self::CUSTOMER_INBOX_PREFIX.$customerId;
return self::CUSTOMER_INBOX_PREFIX.$this->tenantScope().':'.$customerId;
}
private function currentInboxSeq(string $key): int
@@ -11,7 +11,7 @@ use App\Models\Setting;
class SuperAdminProgramSettingsOverlay
{
/**
* فقط این ۱۵ دسترسی از سوپرادمین خوانده می‌شود.
* فقط این ۱۶ دسترسی از سوپرادمین خوانده می‌شود.
* هر کلید دیگری (قیمت، ساعت کاری، برندینگ، …) مال پنل خانگی است.
*/
public const SUPERADMIN_OWNED_KEYS = [
@@ -23,6 +23,7 @@ class SuperAdminProgramSettingsOverlay
'enable_gold_credit',
'enable_product_funds',
'group_sms',
'has_landing',
'has_page_earn_money',
'has_page_gift_card',
'has_page_notification',
@@ -40,6 +41,7 @@ class SuperAdminProgramSettingsOverlay
'enable_conditional_order',
'enable_gold_credit',
'enable_product_funds',
'has_landing',
'has_page_earn_money',
'has_page_gift_card',
'has_page_notification',
@@ -119,7 +121,7 @@ class SuperAdminProgramSettingsOverlay
}
/**
* آخرین مقادیر ۱۵ دسترسی را در settings لوکال ذخیره می‌کند (can_edit=0).
* آخرین مقادیر ۱۶ دسترسی را در settings لوکال ذخیره می‌کند (can_edit=0).
*
* @param array<string, array<string, mixed>> $map
*/
+112 -4
View File
@@ -19,10 +19,11 @@ use Rooyesh\Wallet\models\Wallet;
* MandeyeKolBePool → موجودی ریالی
*
* سیاست تصمیم ادمین:
* overwrite=true → اختلاف را اعمال کن
* keep=true → موجودی اپ را دست نزن
* ask_if_conflict → اگر اپ مانده دارد و با ته‌حساب فرق دارد، بدون نوشتن برگردان
* always_ask → هر اختلافی (حتی کیف خالی) بدون نوشتن برای تأیید ادمین برمی‌گردد
* overwrite=true → اختلاف را روی کیف اپ اعمال کن (ته‌حساب → اپ)
* keep=true → موجودی اپ را دست نزن
* push_to_tahesab → مانده اپ را با سند تعدیل روی ته‌حساب بنویس (حتی اگر اپ صفر باشد)
* ask_if_conflict → اگر اپ مانده دارد و با ته‌حساب فرق دارد، بدون نوشتن برگردان
* always_ask → هر اختلافی (حتی کیف خالی) بدون نوشتن برای تأیید ادمین برمی‌گردد
* جمع دو مانده هرگز انجام نمی‌شود تا موجودی دو برابر نشود.
*/
class TahesabInboundWalletService
@@ -190,6 +191,113 @@ class TahesabInboundWalletService
]);
}
/**
* ماندهٔ اپ → ته‌حساب (سند تعدیل در ته‌حساب؛ کیف اپ دست نخورده).
* حتی اگر اپ صفر باشد، مانده ته‌حساب با سند برداشت/واریز هم‌تراز اپ می‌شود.
*
* @param array{gold?: float, cash?: float}|null $mande
* @return array{
* applied: bool,
* gold_delta?: float,
* rial_delta?: float,
* app_gold?: float,
* app_cash?: float,
* tahesab_gold?: float,
* tahesab_cash?: float,
* message: string
* }
*/
public function pushWalletToTahesab(Customer $customer, ?array $mande = null): array
{
$code = (int) ($customer->moshtari_code ?? 0);
if ($code <= 0) {
return ['applied' => false, 'message' => 'کد ته‌حساب ندارد'];
}
if ($mande === null) {
$all = $this->fetchMandeByCodes([$code]);
$mande = $all[(string) $code] ?? null;
}
if ($mande === null) {
return ['applied' => false, 'message' => 'مانده از ته‌حساب دریافت نشد'];
}
$compared = $this->compareWithWallet($customer, $mande);
$comparison = $compared['comparison'];
$goldSame = $compared['gold_same'];
$rialSame = $compared['rial_same'];
if ($goldSame && $rialSame) {
return array_merge($comparison, [
'applied' => false,
'message' => 'مانده با ته‌حساب یکسان است',
]);
}
$controller = app(\App\Http\Controllers\Admin\TahesabController::class);
$note = 'تعدیل مانده از اپ به ته‌حساب';
$errors = [];
// gold_delta در مقایسه = ته‌حساب − اپ؛ برای رساندن ته‌حساب به اپ باید معکوس اعمال شود
if (! $goldSame) {
$goldToAdd = (float) $comparison['app_gold'] - (float) $comparison['tahesab_gold'];
$goldOk = $controller->walletGold([
'customer_id' => (int) $customer->id,
'value' => abs($goldToAdd),
'direction' => $goldToAdd > 0 ? 1 : 0,
'note' => $note,
]);
if ($goldOk === false || is_string($goldOk)) {
$errors[] = is_string($goldOk) && $goldOk !== ''
? $goldOk
: 'ثبت سند طلایی تعدیل در ته‌حساب ناموفق بود';
}
}
if (! $rialSame) {
$cashToAdd = (float) $comparison['app_cash'] - (float) $comparison['tahesab_cash'];
$cashOk = $controller->wallet([
'customer_id' => (int) $customer->id,
'value' => (int) round(abs($cashToAdd)),
'direction' => $cashToAdd > 0 ? 0 : 1,
'note' => $note,
]);
if ($cashOk === false || is_string($cashOk)) {
$errors[] = is_string($cashOk) && $cashOk !== ''
? $cashOk
: 'ثبت سند ریالی تعدیل در ته‌حساب ناموفق بود';
}
}
if ($errors !== []) {
Log::warning('Tahesab push wallet from app failed', [
'customer_id' => (int) $customer->id,
'moshtari_code' => $code,
'errors' => $errors,
]);
return array_merge($comparison, [
'applied' => false,
'message' => implode('؛ ', $errors),
]);
}
Log::info('Tahesab wallet pushed from app', [
'customer_id' => (int) $customer->id,
'moshtari_code' => $code,
'app_gold' => $comparison['app_gold'],
'app_cash' => $comparison['app_cash'],
'tahesab_gold_before' => $comparison['tahesab_gold'],
'tahesab_cash_before' => $comparison['tahesab_cash'],
]);
return array_merge($comparison, [
'applied' => true,
'message' => 'مانده اپ روی ته‌حساب اعمال شد (کیف اپ تغییر نکرد)',
]);
}
/**
* مقایسه بدون نوشتن — برای تأیید ادمین قبل از ست کردن کد.
*
+25 -1
View File
@@ -4,6 +4,7 @@ namespace App\Services;
use App\Http\Controllers\Admin\ZarinController;
use App\Models\Customer;
use App\Models\Withdraw;
use App\Models\Zarin;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
@@ -567,6 +568,29 @@ class ZarinSyncService
->all();
}
/**
* درخواست برداشت مشتری cash را مثبت ذخیره می‌کند (type=2) — علامت مبلغ برای جهت سند کافی نیست.
* 0 = واریز، 1 = برداشت
*/
public function rialWalletDirectionFromWithdraw(Withdraw $withdraw): int
{
if ((int) ($withdraw->type ?? 0) === 2) {
return 1;
}
$note = (string) ($withdraw->note ?? '');
if ($note !== '' && str_contains($note, 'برداشت')) {
return 1;
}
return ((float) ($withdraw->cash ?? 0)) >= 0 ? 0 : 1;
}
/** شرح محلی سند ریالی: «برداشت وجه» برداشت است؛ «واریز وجه» واریز. */
public function rialWalletDirectionFromDesc(string $desc): int
{
return str_contains($desc, 'برداشت') ? 1 : 0;
}
private function backfillWithdraw(ZarinController $controller, int $withdrawId): bool
{
$withdraw = \App\Models\Withdraw::query()->find($withdrawId);
@@ -581,7 +605,7 @@ class ZarinSyncService
$result = $controller->wallet([
'customer_id' => (int) $withdraw->customer_id,
'value' => abs($cash),
'direction' => $cash >= 0 ? 0 : 1,
'direction' => $this->rialWalletDirectionFromWithdraw($withdraw),
'withdraw_id' => $withdrawId,
'note' => $withdraw->note,
]);
@@ -0,0 +1,112 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* تریگر MySQL روی INSERT — بدون artisan/cron/SQL دستی.
* migrate یک‌بار: انباشت قدیمی mande/document را می‌بُرد + تریگر برای نگه‌داری ۲۰۰۰ تازه.
*/
return new class extends Migration
{
private const KEEP = 2000;
private const TRIGGER = 'pargar_sync_logs_prune_inbound_after_insert';
public function up(): void
{
if (! Schema::hasTable('pargar_sync_logs')) {
return;
}
$this->dropHourlyEvents();
$this->dropTrigger();
$this->pruneExistingOverflow('document');
$this->pruneExistingOverflow('mande');
$this->createInsertTrigger();
}
public function down(): void
{
$this->dropTrigger();
}
private function dropHourlyEvents(): void
{
try {
DB::unprepared('DROP EVENT IF EXISTS `khanegi_prune_pargar_inbound_docs`');
DB::unprepared('DROP EVENT IF EXISTS `khanegi_prune_pargar_inbound_mande`');
} catch (\Throwable) {
}
}
private function dropTrigger(): void
{
try {
DB::unprepared('DROP TRIGGER IF EXISTS `' . self::TRIGGER . '`');
} catch (\Throwable) {
}
}
private function pruneExistingOverflow(string $type): void
{
$keep = self::KEEP;
try {
DB::unprepared(<<<SQL
DELETE FROM `pargar_sync_logs`
WHERE `type` = '{$type}' AND `sync_status` = 'success'
AND `id` <= (
SELECT `cutoff` FROM (
SELECT `id` AS `cutoff` FROM `pargar_sync_logs`
WHERE `type` = '{$type}' AND `sync_status` = 'success'
ORDER BY `id` DESC
LIMIT 1 OFFSET {$keep}
) AS `keep`
)
SQL);
} catch (\Throwable) {
// اگر overflow نیست یا دسترسی محدود است، تریگر بعداً نگه می‌دارد
}
}
private function createInsertTrigger(): void
{
$keep = self::KEEP;
$trigger = self::TRIGGER;
DB::unprepared(<<<SQL
CREATE TRIGGER `{$trigger}`
AFTER INSERT ON `pargar_sync_logs`
FOR EACH ROW
BEGIN
IF NEW.`type` = 'document' AND NEW.`sync_status` = 'success' THEN
DELETE FROM `pargar_sync_logs`
WHERE `type` = 'document' AND `sync_status` = 'success'
AND `id` <= (
SELECT `cutoff` FROM (
SELECT `id` AS `cutoff` FROM `pargar_sync_logs`
WHERE `type` = 'document' AND `sync_status` = 'success'
ORDER BY `id` DESC
LIMIT 1 OFFSET {$keep}
) AS `keep`
)
LIMIT 4000;
ELSEIF NEW.`type` = 'mande' AND NEW.`sync_status` = 'success' THEN
DELETE FROM `pargar_sync_logs`
WHERE `type` = 'mande' AND `sync_status` = 'success'
AND `id` <= (
SELECT `cutoff` FROM (
SELECT `id` AS `cutoff` FROM `pargar_sync_logs`
WHERE `type` = 'mande' AND `sync_status` = 'success'
ORDER BY `id` DESC
LIMIT 1 OFFSET {$keep}
) AS `keep`
)
LIMIT 4000;
END IF;
END
SQL);
}
};
+105 -1
View File
@@ -348,7 +348,7 @@ WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'montzar_open_sell' LIM
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'montzar_order_wait_callback', 'true', 'انتظار کالبک سفارش همکار', 1, 1,
'روشن: سفارش همکار تا دریافت کالبک (یا استعلام مسیر وضعیت) در انتظار می‌ماند و کیف ثبت نمی‌شود. خاموش: مثل قبل بلافاصله با پاسخ HTTP همکار قطعی می‌شود.',
'با منبع قیمت همکار همیشه تا کالبک/استعلام وضعیت منتظر می‌ماند (خاموش بودن سوییچ مسیر قطعی بلافاصله را باز نمی‌کند). رد همکار → SMS به ادمین.',
'switch'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'montzar_order_wait_callback' LIMIT 1);
@@ -905,6 +905,66 @@ SELECT 'has_chat', 'true', 'چت پشتیبانی', 1, 1,
'روشن: چت پشتیبانی در اپ مشتری نمایش داده می‌شود (فقط وقتی show_to_users_chat هم روشن باشد). خاموش: دکمه و صفحه چت برای کاربر مخفی است.', 'switch'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'has_chat' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'has_landing', 'false', 'لندینگ وبسایت', 0, 1,
'روشن: منوی تنظیمات وبسایت در ادمین و تنظیمات لندینگ برای اپ کاربر فعال است. خاموش: منو مخفی است.', 'switch'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'has_landing' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_site', '', 'تنظیمات کلی سایت', 1, 1,
'محتوای تنظیمات کلی لندینگ وبسایت. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_site' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_header', '', 'هدر و ناوبری', 1, 1,
'محتوای هدر و ناوبری لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_header' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_hero', '', 'هیرو', 1, 1,
'محتوای سکشن هیرو لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_hero' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_live_price', '', 'لیبل‌های قیمت لحظه‌ای', 1, 1,
'لیبل‌ها و متن قیمت لحظه‌ای لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_live_price' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_calculator', '', 'عنوان ماشین حساب', 1, 1,
'عنوان و متن ماشین حساب لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_calculator' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_feature', '', 'امکانات (چرا نیازی طلا)', 1, 1,
'متن امکانات لندینگ (چرا نیازی طلا). در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_feature' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_steps', '', 'مراحل شروع', 1, 1,
'متن مراحل شروع لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_steps' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_trust', '', 'اعتماد و مجوزها', 1, 1,
'متن اعتماد و مجوزها (بدون اینماد). در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_trust' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_faq', '', 'سوالات متداول', 1, 1,
'سوالات متداول لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_faq' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_buttom_cta', '', 'سکشن پایین صفحه لندینگ برای معرفی', 1, 1,
'متن دعوت به اقدام پایین صفحه لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_buttom_cta' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'landing_footer', '', 'فوتر', 1, 1,
'محتوای فوتر لندینگ. در اپ کاربر با get_settings در دسترس است.', 'longtext'
WHERE NOT EXISTS (SELECT 1 FROM `settings` WHERE `key` = 'landing_footer' LIMIT 1);
INSERT INTO `settings` (`key`, `value`, `title_fa`, `can_edit`, `is_active`, `description`, `type`)
SELECT 'deposit_sms_support_number', '', 'شماره تماس پشتیبانی', 1, 1,
'شماره تماس پشتیبانی که در صفحه واریز، درباره ما و قوانین به مشتری نشان داده می‌شود. با کلیک، تماس تلفنی برقرار می‌شود.', 'number'
@@ -1888,6 +1948,9 @@ UPDATE `settings` SET `description` = 'مظنه واقعی سمت خرید از
UPDATE `settings` SET `description` = 'مظنه واقعی سمت فروش از همکار. توسط سیستم به‌روز می‌شود.' WHERE `key` = 'montzar_truly_sell_mazaneh';
UPDATE `settings` SET `description` = 'روشن: امکان ثبت سفارش خرید از طریق قیمت همکار باز است (طبق وضعیت سرویس خارجی).' WHERE `key` = 'montzar_open_buy';
UPDATE `settings` SET `description` = 'روشن: امکان ثبت سفارش فروش از طریق قیمت همکار باز است.' WHERE `key` = 'montzar_open_sell';
UPDATE `settings` SET
`description` = 'با منبع قیمت همکار همیشه تا کالبک/استعلام وضعیت منتظر می‌ماند (خاموش بودن سوییچ مسیر قطعی بلافاصله را باز نمی‌کند). رد همکار → SMS به ادمین‌های دارای ارسال پیامک (sms_notif_order_admin).'
WHERE `key` = 'montzar_order_wait_callback';
UPDATE `settings` SET `description` = 'روشن: سرویس همکار در حال حاضر بسته/غیرفعال گزارش شده است.' WHERE `key` = 'montzar_closed';
UPDATE `settings` SET `description` = 'پاسخ JSON آخرین سفارش ارسالی به همکار. برای عیب‌یابی؛ توسط سیستم پر می‌شود.' WHERE `key` = 'montzar_order_response';
UPDATE `settings` SET `description` = 'لاگ JSON آخرین محصول دریافت‌شده از API همکار. توسط سیستم پر می‌شود.' WHERE `key` = 'montzar_last_product_log';
@@ -2137,6 +2200,47 @@ UPDATE `settings` SET
`description` = 'روشن: چت پشتیبانی در اپ مشتری نمایش داده می‌شود (فقط وقتی show_to_users_chat هم روشن باشد). خاموش: دکمه و صفحه چت برای کاربر مخفی است.'
WHERE `key` = 'has_chat';
UPDATE `settings` SET
`title_fa` = 'لندینگ وبسایت',
`type` = 'switch',
`can_edit` = 0,
`description` = 'روشن: منوی تنظیمات وبسایت در ادمین و تنظیمات لندینگ برای اپ کاربر فعال است. خاموش: منو مخفی است.'
WHERE `key` = 'has_landing';
UPDATE `settings` SET `title_fa` = 'تنظیمات کلی سایت', `type` = 'longtext', `can_edit` = 1,
`description` = 'محتوای تنظیمات کلی لندینگ وبسایت. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_site';
UPDATE `settings` SET `title_fa` = 'هدر و ناوبری', `type` = 'longtext', `can_edit` = 1,
`description` = 'محتوای هدر و ناوبری لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_header';
UPDATE `settings` SET `title_fa` = 'هیرو', `type` = 'longtext', `can_edit` = 1,
`description` = 'محتوای سکشن هیرو لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_hero';
UPDATE `settings` SET `title_fa` = 'لیبل‌های قیمت لحظه‌ای', `type` = 'longtext', `can_edit` = 1,
`description` = 'لیبل‌ها و متن قیمت لحظه‌ای لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_live_price';
UPDATE `settings` SET `title_fa` = 'عنوان ماشین حساب', `type` = 'longtext', `can_edit` = 1,
`description` = 'عنوان و متن ماشین حساب لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_calculator';
UPDATE `settings` SET `title_fa` = 'امکانات (چرا نیازی طلا)', `type` = 'longtext', `can_edit` = 1,
`description` = 'متن امکانات لندینگ (چرا نیازی طلا). در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_feature';
UPDATE `settings` SET `title_fa` = 'مراحل شروع', `type` = 'longtext', `can_edit` = 1,
`description` = 'متن مراحل شروع لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_steps';
UPDATE `settings` SET `title_fa` = 'اعتماد و مجوزها', `type` = 'longtext', `can_edit` = 1,
`description` = 'متن اعتماد و مجوزها (بدون اینماد). در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_trust';
UPDATE `settings` SET `title_fa` = 'سوالات متداول', `type` = 'longtext', `can_edit` = 1,
`description` = 'سوالات متداول لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_faq';
UPDATE `settings` SET `title_fa` = 'سکشن پایین صفحه لندینگ برای معرفی', `type` = 'longtext', `can_edit` = 1,
`description` = 'متن دعوت به اقدام پایین صفحه لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_buttom_cta';
UPDATE `settings` SET `title_fa` = 'فوتر', `type` = 'longtext', `can_edit` = 1,
`description` = 'محتوای فوتر لندینگ. در اپ کاربر با get_settings در دسترس است.'
WHERE `key` = 'landing_footer';
-- [super-admin can_edit=0]
-- UPDATE `settings` SET
-- `title_fa` = 'نمایش چت به کاربران',
+2 -44
View File
@@ -41,47 +41,5 @@ WHERE `type` = 'mande' AND `sync_status` = 'success'
) AS `keep`
);
-- Event داخل خود MySQL — بدون کرون سیستم (Navicat → Events)
DROP EVENT IF EXISTS `khanegi_prune_pargar_inbound_docs`;
DROP EVENT IF EXISTS `khanegi_prune_pargar_inbound_mande`;
CREATE EVENT `khanegi_prune_pargar_inbound_docs`
ON SCHEDULE EVERY 1 HOUR
STARTS CURRENT_TIMESTAMP
ON COMPLETION PRESERVE
ENABLE
DO
DELETE FROM `pargar_sync_logs`
WHERE `type` = 'document' AND `sync_status` = 'success'
AND `id` <= (
SELECT `cutoff` FROM (
SELECT `id` AS `cutoff` FROM `pargar_sync_logs`
WHERE `type` = 'document' AND `sync_status` = 'success'
ORDER BY `id` DESC
LIMIT 1 OFFSET 2000
) AS `keep`
)
LIMIT 4000;
CREATE EVENT `khanegi_prune_pargar_inbound_mande`
ON SCHEDULE EVERY 1 HOUR
STARTS CURRENT_TIMESTAMP
ON COMPLETION PRESERVE
ENABLE
DO
DELETE FROM `pargar_sync_logs`
WHERE `type` = 'mande' AND `sync_status` = 'success'
AND `id` <= (
SELECT `cutoff` FROM (
SELECT `id` AS `cutoff` FROM `pargar_sync_logs`
WHERE `type` = 'mande' AND `sync_status` = 'success'
ORDER BY `id` DESC
LIMIT 1 OFFSET 2000
) AS `keep`
)
LIMIT 4000;
-- اگر دسترسی SUPER داری:
-- SET GLOBAL event_scheduler = ON;
-- SHOW VARIABLES LIKE 'event_scheduler';
-- SHOW EVENTS;
-- جایگزین: مایگریشن 2026_09_03_000002 (تریگر INSERT + prune یک‌بار روی migrate).
-- EVENT ساعتی دیگر لازم نیست.
@@ -72,8 +72,10 @@ UPDATE `settings` SET `menu` = CASE
'products_site_link_enabled', 'products_site_link_url', 'products_site_link_text', 'has_chat',
'enable_conditional_order', 'enable_product_funds', 'has_page_price_trigger', 'has_page_notification',
'has_page_gift_card', 'enable_customer_level_profit', 'jibit_enabled', 'customer_direct_sms',
'has_page_earn_money', 'group_sms', 'customer_special_pricing', 'permision__enabled', 'show_to_users_chat'
'has_page_earn_money', 'group_sms', 'customer_special_pricing', 'permision__enabled', 'show_to_users_chat',
'has_landing'
) THEN 'customer_features'
WHEN `key` LIKE 'landing_%' THEN 'website_settings'
ELSE 'misc'
END;
@@ -108,6 +110,7 @@ UPDATE `settings` SET `show_to_user` = 1 WHERE `key` IN (
'fee_deduct_from_gold',
'fee_service_charge_percentage',
'has_chat',
'has_landing',
'has_page_earn_money',
'has_page_gift_card',
'has_page_notification',
@@ -148,3 +151,5 @@ UPDATE `settings` SET `show_to_user` = 1 WHERE `key` IN (
'wss_path',
'zaarbox_api_url'
);
UPDATE `settings` SET `show_to_user` = 1 WHERE `key` LIKE 'landing_%';
+1
View File
@@ -96,6 +96,7 @@ Route::middleware('auth:user')->group(function (){
Route::post('/product/archive/table', [ProductController::class, 'archiveTable']);
Route::get('/product/archive/{id}', [ProductController::class, 'archive']);
Route::get('/product/active/{id}',[ProductController::class, 'active']);
Route::get('/product/show_on_tv/{id}',[ProductController::class, 'showOnTv']);
Route::get('/product/hide/{id}',[ProductController::class, 'hide']);
Route::get('/product/credit',[ProductController::class, 'listProductCredit']);
Route::get('/product/list',[ProductController::class, 'listProduct']);
+10
View File
@@ -60,6 +60,16 @@ class ConfigServiceOtpHostTest extends TestCase
$this->assertSame('https://my.goldarvin.ir', $cfg->resolvePublicSiteUrl($request));
}
public function test_does_not_fall_back_to_laravel_api_host(): void
{
config(['app.url' => 'https://goldarvin.gholaktala.ir/server']);
$request = Request::create('https://goldarvin.gholaktala.ir/server/admin/customer', 'POST');
$this->app->instance('request', $request);
$this->assertSame('', $this->cfgWithAppUrl(null)->resolvePublicSiteUrl($request));
$this->assertSame('', $this->cfgWithAppUrl(null)->resolvePublicHost($request));
}
public function test_app_url_without_scheme_gets_https(): void
{
$request = Request::create('https://goldarvin.gholaktala.ir/server/auth/login', 'POST');
@@ -19,6 +19,7 @@ class SuperAdminProgramSettingsOverlayTest extends TestCase
'enable_gold_credit',
'enable_product_funds',
'group_sms',
'has_landing',
'has_page_earn_money',
'has_page_gift_card',
'has_page_notification',
@@ -29,7 +30,7 @@ class SuperAdminProgramSettingsOverlayTest extends TestCase
];
$this->assertSame($expected, SuperAdminProgramSettingsOverlay::SUPERADMIN_OWNED_KEYS);
$this->assertCount(15, SuperAdminProgramSettingsOverlay::SUPERADMIN_OWNED_KEYS);
$this->assertCount(16, SuperAdminProgramSettingsOverlay::SUPERADMIN_OWNED_KEYS);
}
public function test_overlay_keeps_only_access_keys(): void
@@ -0,0 +1,50 @@
<?php
namespace Tests\Unit;
use App\Models\Withdraw;
use App\Services\ZarinSyncService;
use Tests\TestCase;
class ZarinRialWalletDirectionTest extends TestCase
{
public function test_customer_rial_withdraw_is_direction_one_even_if_cash_positive(): void
{
$withdraw = new Withdraw([
'type' => 2,
'cash' => 200000000,
'note' => 'برداشت ریالی',
]);
$this->assertSame(1, app(ZarinSyncService::class)->rialWalletDirectionFromWithdraw($withdraw));
}
public function test_admin_deposit_with_positive_cash_is_direction_zero(): void
{
$withdraw = new Withdraw([
'type' => null,
'cash' => 200000000,
'note' => 'افزایش موجودی',
]);
$this->assertSame(0, app(ZarinSyncService::class)->rialWalletDirectionFromWithdraw($withdraw));
}
public function test_admin_deduction_with_negative_cash_is_direction_one(): void
{
$withdraw = new Withdraw([
'cash' => -50000000,
'note' => 'کسر',
]);
$this->assertSame(1, app(ZarinSyncService::class)->rialWalletDirectionFromWithdraw($withdraw));
}
public function test_desc_bardasht_is_withdraw_and_variz_is_deposit(): void
{
$svc = app(ZarinSyncService::class);
$this->assertSame(1, $svc->rialWalletDirectionFromDesc('برداشت وجه'));
$this->assertSame(0, $svc->rialWalletDirectionFromDesc('واریز وجه'));
$this->assertSame(0, $svc->rialWalletDirectionFromDesc('واریز — افزایش موجودی'));
}
}