Compare commits

...
39 Commits
Author SHA1 Message Date
safavimohadeseh78andCursor 97d1077db6 fix(wallet): absorb cash left on old owner type
Deposits credited before customer type was set stayed on owner_type 0 and assets ignored them.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-14 14:41:24 +03:30
safavimohadeseh78 bdf70a4c05 feat: automatic instant Jibit verification on customer profile update without admin manual approval 2026-11-10 14:33:09 +03:30
safavimohadeseh78andCursor 487d899ded feat(admin): gift card codes usage report API
Expose codes-usage-report endpoint with per-code usage counts and filter-aware summary for admin reporting.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 11:48:23 +03:30
safavimohadeseh78 885e51a79b feat: add deposit receipt upload and admin approval/rejection workflow with SMS 2026-11-08 13:26:28 +03:30
safavimohadeseh78 808c272e0c fix: resolve copper unit kilogram display and asset valuation calculations 2026-11-07 12:24:19 +03:30
safavimohadeseh78 7dd5304638 feat: shayegan inbound charges workflow and copper kilogram unit enforcement 2026-11-05 17:15:38 +03:30
safavimohadeseh78andCursor e65b8053fd fix(customer): use next free id instead of stale AUTO_INCREMENT after manual id edits
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-05 11:20:24 +03:30
safavimohadeseh78 9ec71efcbb change accounting-number 2026-11-04 11:56:53 +03:30
safavimohadeseh78andCursor 21da78943c feat(price): broadcast world copper and free-dollar ton and kilo quotes
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 19:57:36 +03:30
safavimohadeseh78andCursor 9769f2ffad feat(convert): let customers list and change pending requests
History is limited to the signed-in customer. Update and delete only apply while the request is still pending.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-03 13:04:08 +03:30
safavimohadeseh78andCursor 7b81adc096 fix(price-trigger): store the selected product instead of defaulting to gold
Only a real numeric product id is saved, and an empty alert title no longer falls back to gold.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 18:20:13 +03:30
safavimohadeseh78andCursor e0216d35a6 fix(shayegan): return the document list in the shared table shape
The admin table expects rows and query from TableEngine instead of a custom page payload.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 13:24:01 +03:30
safavimohadeseh78andCursor 97865a98fc fix(shayegan): register customers as floating detail jobs
Customer accounts are not sub-accounts of moin 12101. Send Job/Put with JobNumber moin plus customer id.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 13:05:53 +03:30
safavimohadeseh78andCursor 3b689a24f6 fix(shayegan): build the account number as moin plus customer id
Customer 530 with moin 12101 is sent as 12101530 again.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 11:49:47 +03:30
safavimohadeseh78andCursor 77a448e4e1 fix(shayegan): send the account number as customer id plus moin
Hesabgar kept generating a number when UpdateKind was 3. Insert with account type 1 and send 53012101.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 11:35:33 +03:30
safavimohadeseh78 8ccdea99c8 . 2026-11-02 11:21:36 +03:30
safavimohadeseh78andCursor 1cd6c61e0f fix(shayegan): send the customer detail code on account create
Hesabgar fails when it must invent the account number. Send the subsidiary code plus the customer id as AccountNumber.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-02 10:57:57 +03:30
safavimohadeseh78andCursor c96e5820fe feat(convert): text the customer when a convert request is approved or rejected
The message goes out after the result is saved, and a send failure does not undo the approval or rejection.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-01 13:44:48 +03:30
safavimohadeseh78 3f59af5a6d change copperConvertPage 2026-11-01 12:42:14 +03:30
safavimohadeseh78 9528056036 feat(shayegan): per-product item code and auto customer Account/Put 2026-10-28 16:51:47 +03:30
safavimohadeseh78 25ee47b473 digipay 2026-10-20 10:11:03 -04:00
safavimohadeseh78 f26fd1d86e changes of giftCard page 2026-10-20 12:09:20 +03:30
safavimohadeseh78 755243bfa2 Administrator Access 2026-10-20 10:52:02 +03:30
safavimohadeseh78 a5f3b3b4b3 . 2026-10-20 10:26:45 +03:30
safavimohadeseh78 4d0f0f8c8d fix(auth): require verified identity for wallet and gift card 2026-10-20 09:10:01 +03:30
safavimohadeseh78 b91dbccb3d final changes 2026-10-19 12:50:26 +03:30
safavimohadeseh78 489662eb38 fix bug of main-page for guest 2026-10-17 14:10:11 +03:30
safavimohadeseh78 8b13908bac shayegan 2026-10-17 11:23:03 +03:30
safavimohadeseh78 5b431c64a6 set log for test shayegan 2026-10-17 10:28:01 +03:30
safavimohadeseh78 f1c68d955d . 2026-10-06 13:40:00 +03:30
safavimohadeseh78andCursor a42261c06e feat(accounting): add Shayegan as fixed boursecu provider
Wire outbound Invoice/Document sync after confirmed ops, store sync status with timeout lock, and keep SQL credentials out of frontend responses.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-05 17:12:43 +03:30
safavimohadeseh78 698fbed805 change gift-card 2026-09-21 11:09:40 +03:30
safavimohadeseh78 ba2ac5aefe change the giftcard logic 2026-09-20 15:48:53 +03:30
safavimohadeseh78 aecbd5b3bf changes of giftcard 2026-09-12 10:12:43 +03:30
safavimohadeseh78 f3202ee89e feat(giftcard): redeem metal unit=2 into main wallet gold 2026-09-09 20:58:24 +03:30
safavimohadeseh78 0fa2b4d1f5 feat(giftcard): add customer giftcard/mine endpoint; fix admin/app password digit normalization 2026-09-09 16:57:20 +03:30
safavimohadeseh78 741faa38fb . 2026-09-08 14:06:28 +03:30
safavimohadeseh78 7cd7261055 mamad 2026-09-06 20:07:26 +03:30
safavimohadeseh78andCursor 37b94ed32a Add create migrations for giftcards and giftcard_codes so new installs get both tables.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:22:53 +03:30
76 changed files with 6519 additions and 179 deletions
+177
View File
@@ -0,0 +1,177 @@
---
description: دستورالعمل اجباری AI — پروژه ابشوده/خانگی (توکن کم، پچ محدود)
alwaysApply: true
---
# دستورالعمل اجباری برای هوش مصنوعی — پروژه ابشوده / خانگی
این فایل را کامل به AI بده (Project Rules / Custom Instructions / System prompt).
هدف: **توکن کمتر، یادگیری پایدار، حل سریع اصل کار، بدون تغییر الکی.**
---
## ۱) با هر پرامپت کاربر — همین ترتیب
1. اصل قضیه را **یک خط** مشخص کن (یک باگ / یک UI / یک فیچر).
2. مسیر را از **نقشه و یادداشت** بگیر — کل ریپو را سرچ نکن.
3. فقط **۱ تا ۳ فایل** مربوط را باز/پچ کن.
4. تمام کن؛ جواب کوتاه بده.
5. یک خط **یادداشت بخش** بنویس (پایین ببین) تا دفعهٔ بعد فراموش نشود.
```
پرامپت → اصل کار → نقشه/یادداشت → Grep فقط همان پوشه → پچ محدود → یادداشت → تمام
```
### ممنوع (سوخت توکن)
- دوباره پیدا کردن فایلی که در نقشه/یادداشت هست
- explore / گشت سراسری برای «X کجاست؟»
- خواندن کل فایل بلند وقتی چند ده خط کافی است
- refactor یا «درست کردن» فایل‌های هم‌جوار بدون درخواست
- کپی پچ به سیستم/اپ دیگر «برای کامل بودن»
---
## ۲) محدودهٔ تغییر — حساس
- **فقط** همان چیزی که کاربر گفته؛ جای بی‌ربط را دست نزن.
- مبهم بود (هدف، اپ، برنچ، سیستم حسابداری) → **بپرس**؛ حدس نزن.
- روی **برنچ فعلی** بمان؛ checkout/merge به برنچ دیگر بدون اجازه ممنوع.
- هر زیرپروژه git جدا دارد؛ فقط همان ریپوی مربوط را عوض کن.
| کار | فقط این ریپو |
|-----|----------------|
| ادمین | `khaneghi_admin` |
| API / SQL | `khaneghi_server` |
| اپ کاربر | `khaneghi_user` + تم + `ghatreh_user` (هر سه اگر رفتاری است) |
| سوپرادمین | `controlpanel_server` / `controlpanel_user` |
| بورس مس | فقط با درخواست صریح |
---
## ۳) حسابداری — قانون سخت
سیستم‌ها **جدا** هستند: زرین (`zarin`) / ته‌حساب (`tahesab`) / پرگار (`pargar`).
1. اگر گفت حسابداری/سند/سینک مشتری و **نام نبرد** → اول بپرس کدام؟
2. تا جواب ندادی کد نزن و فایل سیستم دیگر را باز نکن.
3. پچ یک سیستم را به بقیه کپی نکن مگر در همان پیام صریح بگوید.
---
## ۴) یادگیری قوی — یادداشت بخش‌ها
هر کار تمام‌شده را در دفتر پروژه ثبت کن (اگر در این ریپو هست:
`.cursor/skills/abshode-domain-lookup/learned-notes.md`):
```
- YYYY-MM-DD | موضوع | مسیر فایل(ها) | نکتهٔ ۱ خطی
```
قبل از هر Grep سراسری: **یادداشت‌ها را بخوان.**
اگر مسیر آنجا بود، دوباره سرچ نکن.
---
## ۵) نقشهٔ سریع مسیرها
| موضوع | کجا |
|-------|-----|
| تنظیمات ادمین | `khaneghi_admin/src/pages/menuPages/configuration/` |
| فلگ منو از settings | `khaneghi_admin/src/utils/config.ts` |
| مشتریان | `khaneghi_admin/src/pages/menuPages/customers/` |
| همگام ته‌حساب | `…/accounting/components/TahesabCustomerSync.vue`, `TahesabWalletBulkSync.vue` |
| کد حساب همکار | `…/colleagueOrders/components/ColleagueAccountingAccounts.vue` |
| API ته‌حساب (فرانت) | `khaneghi_admin/src/api/tahesab.ts` |
| تنظیمات سرور / overlay سوپرادمین | `SuperAdminProgramSettingsOverlay`, `SettingsController` |
| deploy settings | `khaneghi_server/database/sql/deploy_settings_const.sql` — **value موجود را UPDATE نکن** |
| قیمت ویژه مشتری | `customer_special_pricing` + منوی `customers/special-price` |
نقشهٔ کامل‌تر (اگر موجود): `.cursor/skills/abshode-domain-lookup/project-map.md`
---
## ۶) فرانت — زیاد از Ant + UnoCSS + lodash استفاده کن
اولویت:
1. **BasicPacks** پروژه (دکمه/آیکون/اینپوت/مدال) اگر هست
2. **Ant Design Vue** (`a-button`, `a-input`, `a-table`, `a-spin`, `a-form`, …)
3. **UnoCSS** برای layout و فاصله (`flex`, `grid`, `gap-*`, `w-full`, `min-w-0`, `sm:`)
4. **lodash** برای داده (`get`, `debounce`, `cloneDeep`, `isEmpty`, …) — helper تکراری ننویس
5. CSS/`<style>` فقط وقتی utility کافی نیست (توکن تم، انیمیشن خاص)
```text
❌ button خام + CSS بزرگ برای layout
✅ Ant/Basic + کلاس‌های Uno روی تمپلیت + lodash برای منطق داده
```
- `BasicButton` را با `:deep` برای عوض کردن layout داخلی خراب نکن.
- رنگ: توکن تم؛ از `bg-primary/10` روی CSS variable پرهیز کن (اغلب می‌شکند).
---
## ۷) UI حرفه‌ای — عینک گرافیک‌کار
- هر بلوک جدید: **عنوان + یک خط راهنما** (این کار چیست / دکمه کی زده شود).
- **باکس‌بندی خوب است؛ فضای مرده بد است** — کارت عریض با محتوا فقط در یک گوشه ممنوع.
- یا `sm:grid-cols-2` / `flex` تا پر شود، یا عرض باکس را محدود کن.
- موبایل: اکشن **زیر** توضیح (`flex-col`).
- دسکتاپ: کنار یا ستون دوم پر (`sm:flex-row` / `sm:grid`).
- **نسبت سرچ و دکمه:**
- موبایل: سرچ `w-full`؛ بعد دکمه‌ها با عرض مساوی (`grid` / `1fr`).
- اینپوت باریک کنار دکمهٔ پهن در یک ردیف wrap = زشت → ممنوع.
- بنر گرادیان جیغ و دکمهٔ `block` تمام‌عرض الکی ممنوع مگر اکشن اصلی صفحه باشد.
- فشرده باش: `p-2.5` / `gap-2`؛ عدد و padding غول‌پیکر نگذار.
---
## ۸) مهندسی بک‌اند / فرانت — بدون باگ الکی
- یک مسئولیت در هر کامپوننت / متد / سرویس؛ خدا-فایل نساز.
- UI نازک؛ منطق سنگین در composable یا Service.
- Controller نازک → Service؛ SQL و business را قاطی نکن.
- خطا، خالی، timeout، دوبار کلیک / race را طراحی کن (`running` قفل، early return).
- الگوی همان پوشه را کپی کن؛ اختراع ساختار جدید نکن مگر لازم باشد.
- نام‌گذاری گویا؛ قرارداد API فرانت و بک یکی باشد.
---
## ۹) سوپرادمین / تنظیمات دسترسی
- کلیدهای دسترسی مشتری (`customer_special_pricing`, `has_page_*`, …) مال سوپرادمین‌اند؛ در پنل خانگی معمولاً فقط‌خواندنی.
- منوی وابسته به فلگ باید از `get_settings` / overlay زنده بیاید؛ کش کهنه برای این کلیدها مطلوب نیست.
- دکمهٔ بروزرسانی تنظیمات پیشرفته باید همگام زنده از سوپرادمین را هم بزند اگر فلگ منو می‌خواهد عوض شود.
---
## ۱۰) چک قبل از اتمام
- [ ] diff فقط به درخواست مربوط است؟
- [ ] سیستم حسابداری / اپ / برنچ اشتباه درگیر نشده؟
- [ ] اگر مبهم بود سؤال شد؟
- [ ] یادداشت یک‌خطی نوشته شد؟
- [ ] UI: راهنما + بدون فضای مرده + نسبت سرچ/دکمه درست؟
- [ ] Ant / Uno / lodash به‌جای reinvent؟
- [ ] جواب کوتاه است؛ توضیح اضافه نداری؟
---
## ۱۱) نمونهٔ رفتار درست / غلط
```text
❌ «همگام‌سازی مشتری خراب» → هر سه زرین/ته‌حساب/پرگار را عوض کند
✅ بپرسد کدام؟ بعد فقط همان
❌ UI یک کارت → کل صفحه accounting را redesign کند
✅ فقط همان کارت / همان فایل
❌ هر بار از صفر Grep مونوریپو
✅ learned-notes + project-map → مستقیم فایل
❌ CSS سفارشی ۵۰ خط برای flex ساده
✅ class="flex flex-col gap-2 sm:grid sm:grid-cols-2"
```
---
**پایان.** این سند را به‌روز نگه دار؛ نکات جدید حساس را همین‌جا یا در `learned-notes.md` اضافه کن.
@@ -0,0 +1,41 @@
# یادداشت‌های یادگیری — abshode-domain-lookup
فرمت هر خط:
- YYYY-MM-DD | موضوع | مسیر فایل(ها) | نکتهٔ ۱ خطی
- 2026-11-14 | کیف ریال owner_type ناهماهنگ | `WalletBalanceService::absorbMismatchedOwnerTypeBalances` + `WalletInterface` | واریز روی owner_type=0 در دارایی نوع مشتری دیده نمی‌شود؛ با باز شدن کیف به نوع فعلی منتقل می‌شود
- 2026-11-05 | کد کاربری مشتری بعدی | `Customer::nextSequentialId` در `creating` | کد کاربری=`customers.id`؛ بعد از UPDATE دستی id، AUTO_INCREMENT پایین نمی‌آید (۵۵۱ به‌جای ۲۴). ایجاد مشتری = اولین id خالی، نه شمارندهٔ InnoDB
- 2026-11-04 | فرمت کد تفصیلی شایگان | `ShayeganSyncService::customerTafsilNumber` | کل `shayegan_kol_customer` (121) + کد کاربر ۷رقمی: مشتری 1 → `1210000001`. کد ذخیره‌شدهٔ قبلی عوض نمی‌شود
- 2026-11-02 | جدول اسناد شایگان | `shayeganTable.vue` + `ShayeganController::table` | BaseTable؛ پاسخ بدون `query` را خود فرانت به `{rows,query}` برمی‌گرداند. ستون عملیات `ops` است تا در RTL هشدار fixed ندهد
- 2026-11-02 | ویرایش کد حسابداری شایگان | `CustomerAccountingCodeModal.vue` | provider شایگان هم `moshtari_code` ذخیره می‌کند؛ قبلاً فقط پرگار/ته‌حساب/زرین قبول می‌شد و پیام «حسابداری فعال نیست» می‌آمد
- 2026-11-02 | مشتری تفصیلی شناور | `ShayeganSyncService::registerCustomer` → `Job/Put` | معین 12101 حساب جدا نمی‌سازد؛ `JobNumber` = معین+کد (`12101530`). گروه: setting `shayegan_job_group`
- 2026-11-02 | دیباگ تبادل شایگان | `ShayeganClient::request` + `registerCustomer` / health / retry | پاسخ ادمین `client_request` و `server_response` دارد؛ رمز DB و Auth برابر `***`
- 2026-11-02 | سه سطح شایگان | `ShayeganSyncService::registerCustomer` + migration `2026_11_02_000001` | کل 121، معین `12101`، تفصیلی = معین+کد کاربری (`12101530`). `1210101` غلط است
- 2026-11-01 | پیامک تبدیل | `CopperConvertRequestService::notifyCustomer` | بعد از تأیید یا رد، پیامک جدا به موبایل مشتری؛ خطا پیامک سفارش را برنمی‌گرداند
- 2026-11-01 | درخواست تبدیل مس | `CopperConvertRequestService` + `copper_convert_requests` + `POST customer/copper-convert-request` + `admin/copper-convert-request/{id}/approve` | تأیید = فروش دارایی و خرید حلقه با quote_unit_price؛ مهاجرت `2026_11_01_000001`
- 2026-10-28 | شایگان کالا/مشتری | `products.shayegan_item_number` + `ShayeganSyncService::registerCustomer` Account/Put + `ensureCustomerAccountNumber` | بانک 10001 و معین 12101 در settings؛ ItemNumber per-product
- 2026-10-17 | لاگ ترافیک شایگان | `ShayeganClient::request` | `Log::info` با کلید `shayegan.http_request` / `shayegan.http_response`; رمز `***`; خاموش: setting `shayegan_log_traffic=0`
- 2026-10-17 | گروه شایگان در تنظیمات پیشرفته | `settingGroups.resolveSettingMenu` + migration `2026_10_17_000001` | اگر `menu=misc` ولی کلید `shayegan_*` → گروه accounting_shayegan؛ نه «سایر»
- 2026-10-19 | Auth وب‌سرویس شایگان | `shayegan_auth_user` / `shayegan_auth_password` | کاربر وب جدا از sa؛ Domain خالی باید JSON `{}` باشد نه `[]`
- 2026-09-06 | گیفت‌کارت | `database/migrations/2026_09_06_000001_create_giftcards_tables.php` | create جداول giftcards و giftcard_codes اگر نباشند؛ drop در down ندارد
- 2026-09-08 | خطای «محدودیت فیلد قیمت» در گیفت‌کارت | `app/Exceptions/Handler.php` + `GiftCardController::redeem` | پیام عمومی MySQL ۱۲۶۴ (Out of range) است؛ معمولاً `amount`/`total=count*amount` از ظرفیت ستون بیشتر است، نه باگ فرم ادمین
- 2026-09-08 | widen مبلغ گیفت‌کارت | `migrations/2026_09_08_000001_widen_giftcard_amount_columns.php` + `deploy_safe_schema.sql` | `amount`/`total` → DECIMAL(20,4) تا مبالغ ≥۱۰۰ میلیون ریال جا شود
- 2026-09-08 | لیست گیفت کاربر | `GiftCardController::mine` + `GET customer/giftcard/mine` + `GiftCardCodes::giftcard` | available=اختصاصی+عمومی تک‌کد use_once=0؛ history از assigned_to
- 2026-09-09 | «کد قابل استفاده» خالی در اپ | `routes/customer.php` + `GiftCardController::mine` | مسیر `GET customer/giftcard/mine` هنوز کامیت/دیپلوی نشده؛ سرور واقعی ۴۰۴ می‌دهد (use و me → ۴۰۱) پس لیست همیشه خالی است
- 2026-09-09 | کارت هدیه فلزی | `GiftCardController::useGiftCard` | unit=2 دیگر «در دست ساخت» نیست؛ شارژ gold کیف اصلی + سینک ته‌حساب/زرین/پرگار؛ used_count فقط بعد از موفقیت
- 2026-09-12 | واریز کیف‌پول + هدیه ریالی | `Withdraw::scopeDeposits` | note«کارت هدیه» با cash>0 در لیست واریز می‌آید؛ هدیه مسی (فقط gold) نه
- 2026-09-12 | پیامک کارت هدیه | `GiftCardController::useGiftCard` | پسوند SMS: ریالی→«قلک ریال»، فلزی→«قلک مس» (نه name_fa / قلک طلا)
- 2026-09-16 | تعداد کد هدیه | `GiftCardController::redeem` | count=N → یک رکورد giftcards با count=N + N ردیف giftcard_codes؛ مثل storeRedeem
- 2026-09-12 | انقضای کارت هدیه | `GiftCardController::validateGiftExpiryDate` + `GiftCardEditorFormBody` | تاریخ قبل از امروز → ۴۰۰ / خطای فرم؛ امروز مجاز
- 2026-09-09 | رمز ادمین ≠ لاگین اپ | `Customer::setPasswordAttribute` + `AuthController` + `updateAdmin` | قبل از هش/لاگین ارقام فارسی→انگلیسی؛ jwt hash=false؛ آنلاین فقط password غیرخالی بفرست
- 2026-10-20 | خرید اقساطی دیجی‌پی | `DigipayInstallmentService` + جداول `digipay_credits`/`digipay_orders` + migration `2026_10_20_000002` | فلگ پیش‌فرض خاموش؛ اعتبار را ادمین ست می‌کند نه وب‌هوک دیجی‌پی
- 2026-10-20 | دسترسی صفحات مدیر | `users.page_access` + `AdminPageAccess` + ادمین `adminPageAccess.ts` / ویرایش مدیران | null=کامل؛ درخت مشاهده/ویرایش/حذف؛ ورود=اولین صفحه مجاز؛ منوی ممنوع=«شما به این صفحه دسترسی ندارید»
- 2026-11-10 | گزارش استفاده کدهای هدیه | `POST /admin/giftcard/codes-usage-report` + ادمین `GiftCardCodesUsageReportSheet.vue` | ردیف=giftcard_codes؛ usage_count؛ خلاصه کل/مصرف‌شده/فعال؛ اکسل از BaseTable
- 2026-10-20 | ویرایش/حذف کارت هدیه | `GiftCardController::update/destroy` + `giftCards/components/table.vue` | PUT/DELETE `/admin/giftcard/{id}`؛ کارت استفاده‌شده حذف نمی‌شود و مقدار/تعدادش عوض نمی‌شود
- 2026-10-20 | دکمه ویرایش/حذف گیفت | `allowsPageFlag` + `giftCards/components/table.vue` | بدون edit/delete روی giftCardMain دکمه و دیالوگ باز نمی‌شود
- 2026-10-20 | دسترسی عملیات جدول | `PAGE_TABLE_ACTIONS` + `usePageActionAccess` + `AdminPageAccess::ACTIONS` | هر صفحه فقط عملیات ستون خودش؛ مشاهده جدا؛ رکورد قدیمی بدون actions ویرایش/حذف را از همان فیلد و بقیه را از مشاهده می‌گیرد
- 2026-10-20 | چیدمان درخت دسترسی | `users/components/ManagerPageAccessTree.vue` | هر صفحه یک کالپس؛ وضعیت روی هدر؛ عملیات جدول داخل همان صفحه
- 2026-10-20 | مشخصات کارت هدیه | `giftCards/index.vue` تابع `info` | کدهای یکتا در مودال مشخصات نیست؛ همان جدول کدها
- 2026-10-20 | کپی کد هدیه | `giftCards/components/GiftCardCodesSheet.vue` | کنار کد هر ردیف آیکون کپی؛ پیام «کد کپی شد»
- 2026-11-03 | کد کاربری مشتری | `customers.id` + `customerColumns.tsx` | کد کاربری همان `customers.id` است (type=1)؛ `users` ادمین است. `code` و `moshtari_code` و `referral_id` ستون‌های دیگرند
- 2026-11-03 | چهار قیمت هیرو | `ZaarboxPriceService::copperDollarReferences` | فید تابلو: مس جهانی کلید `basemetal_london_copper`، دلار آزاد `tgju_usd`؛ تن=ضرب، کیلو=تن/۱۰۰۰ روی payload آخر قیمت
+173
View File
@@ -0,0 +1,173 @@
# دستورالعمل اجباری برای هوش مصنوعی — پروژه ابشوده / خانگی
این فایل را کامل به AI بده (Project Rules / Custom Instructions / System prompt).
هدف: **توکن کمتر، یادگیری پایدار، حل سریع اصل کار، بدون تغییر الکی.**
---
## ۱) با هر پرامپت کاربر — همین ترتیب
1. اصل قضیه را **یک خط** مشخص کن (یک باگ / یک UI / یک فیچر).
2. مسیر را از **نقشه و یادداشت** بگیر — کل ریپو را سرچ نکن.
3. فقط **۱ تا ۳ فایل** مربوط را باز/پچ کن.
4. تمام کن؛ جواب کوتاه بده.
5. یک خط **یادداشت بخش** بنویس (پایین ببین) تا دفعهٔ بعد فراموش نشود.
```
پرامپت → اصل کار → نقشه/یادداشت → Grep فقط همان پوشه → پچ محدود → یادداشت → تمام
```
### ممنوع (سوخت توکن)
- دوباره پیدا کردن فایلی که در نقشه/یادداشت هست
- explore / گشت سراسری برای «X کجاست؟»
- خواندن کل فایل بلند وقتی چند ده خط کافی است
- refactor یا «درست کردن» فایل‌های هم‌جوار بدون درخواست
- کپی پچ به سیستم/اپ دیگر «برای کامل بودن»
---
## ۲) محدودهٔ تغییر — حساس
- **فقط** همان چیزی که کاربر گفته؛ جای بی‌ربط را دست نزن.
- مبهم بود (هدف، اپ، برنچ، سیستم حسابداری) → **بپرس**؛ حدس نزن.
- روی **برنچ فعلی** بمان؛ checkout/merge به برنچ دیگر بدون اجازه ممنوع.
- هر زیرپروژه git جدا دارد؛ فقط همان ریپوی مربوط را عوض کن.
| کار | فقط این ریپو |
|-----|----------------|
| ادمین | `khaneghi_admin` |
| API / SQL | `khaneghi_server` |
| اپ کاربر | `khaneghi_user` + تم + `ghatreh_user` (هر سه اگر رفتاری است) |
| سوپرادمین | `controlpanel_server` / `controlpanel_user` |
| بورس مس | فقط با درخواست صریح |
---
## ۳) حسابداری — قانون سخت
سیستم‌ها **جدا** هستند: زرین (`zarin`) / ته‌حساب (`tahesab`) / پرگار (`pargar`).
1. اگر گفت حسابداری/سند/سینک مشتری و **نام نبرد** → اول بپرس کدام؟
2. تا جواب ندادی کد نزن و فایل سیستم دیگر را باز نکن.
3. پچ یک سیستم را به بقیه کپی نکن مگر در همان پیام صریح بگوید.
---
## ۴) یادگیری قوی — یادداشت بخش‌ها
هر کار تمام‌شده را در دفتر پروژه ثبت کن (اگر در این ریپو هست:
`.cursor/skills/abshode-domain-lookup/learned-notes.md`):
```
- YYYY-MM-DD | موضوع | مسیر فایل(ها) | نکتهٔ ۱ خطی
```
قبل از هر Grep سراسری: **یادداشت‌ها را بخوان.**
اگر مسیر آنجا بود، دوباره سرچ نکن.
---
## ۵) نقشهٔ سریع مسیرها
| موضوع | کجا |
|-------|-----|
| تنظیمات ادمین | `khaneghi_admin/src/pages/menuPages/configuration/` |
| فلگ منو از settings | `khaneghi_admin/src/utils/config.ts` |
| مشتریان | `khaneghi_admin/src/pages/menuPages/customers/` |
| همگام ته‌حساب | `…/accounting/components/TahesabCustomerSync.vue`, `TahesabWalletBulkSync.vue` |
| کد حساب همکار | `…/colleagueOrders/components/ColleagueAccountingAccounts.vue` |
| API ته‌حساب (فرانت) | `khaneghi_admin/src/api/tahesab.ts` |
| تنظیمات سرور / overlay سوپرادمین | `SuperAdminProgramSettingsOverlay`, `SettingsController` |
| deploy settings | `khaneghi_server/database/sql/deploy_settings_const.sql` — **value موجود را UPDATE نکن** |
| قیمت ویژه مشتری | `customer_special_pricing` + منوی `customers/special-price` |
نقشهٔ کامل‌تر (اگر موجود): `.cursor/skills/abshode-domain-lookup/project-map.md`
---
## ۶) فرانت — زیاد از Ant + UnoCSS + lodash استفاده کن
اولویت:
1. **BasicPacks** پروژه (دکمه/آیکون/اینپوت/مدال) اگر هست
2. **Ant Design Vue** (`a-button`, `a-input`, `a-table`, `a-spin`, `a-form`, …)
3. **UnoCSS** برای layout و فاصله (`flex`, `grid`, `gap-*`, `w-full`, `min-w-0`, `sm:`)
4. **lodash** برای داده (`get`, `debounce`, `cloneDeep`, `isEmpty`, …) — helper تکراری ننویس
5. CSS/`<style>` فقط وقتی utility کافی نیست (توکن تم، انیمیشن خاص)
```text
❌ button خام + CSS بزرگ برای layout
✅ Ant/Basic + کلاس‌های Uno روی تمپلیت + lodash برای منطق داده
```
- `BasicButton` را با `:deep` برای عوض کردن layout داخلی خراب نکن.
- رنگ: توکن تم؛ از `bg-primary/10` روی CSS variable پرهیز کن (اغلب می‌شکند).
---
## ۷) UI حرفه‌ای — عینک گرافیک‌کار
- هر بلوک جدید: **عنوان + یک خط راهنما** (این کار چیست / دکمه کی زده شود).
- **باکس‌بندی خوب است؛ فضای مرده بد است** — کارت عریض با محتوا فقط در یک گوشه ممنوع.
- یا `sm:grid-cols-2` / `flex` تا پر شود، یا عرض باکس را محدود کن.
- موبایل: اکشن **زیر** توضیح (`flex-col`).
- دسکتاپ: کنار یا ستون دوم پر (`sm:flex-row` / `sm:grid`).
- **نسبت سرچ و دکمه:**
- موبایل: سرچ `w-full`؛ بعد دکمه‌ها با عرض مساوی (`grid` / `1fr`).
- اینپوت باریک کنار دکمهٔ پهن در یک ردیف wrap = زشت → ممنوع.
- بنر گرادیان جیغ و دکمهٔ `block` تمام‌عرض الکی ممنوع مگر اکشن اصلی صفحه باشد.
- فشرده باش: `p-2.5` / `gap-2`؛ عدد و padding غول‌پیکر نگذار.
---
## ۸) مهندسی بک‌اند / فرانت — بدون باگ الکی
- یک مسئولیت در هر کامپوننت / متد / سرویس؛ خدا-فایل نساز.
- UI نازک؛ منطق سنگین در composable یا Service.
- Controller نازک → Service؛ SQL و business را قاطی نکن.
- خطا، خالی، timeout، دوبار کلیک / race را طراحی کن (`running` قفل، early return).
- الگوی همان پوشه را کپی کن؛ اختراع ساختار جدید نکن مگر لازم باشد.
- نام‌گذاری گویا؛ قرارداد API فرانت و بک یکی باشد.
---
## ۹) سوپرادمین / تنظیمات دسترسی
- کلیدهای دسترسی مشتری (`customer_special_pricing`, `has_page_*`, …) مال سوپرادمین‌اند؛ در پنل خانگی معمولاً فقط‌خواندنی.
- منوی وابسته به فلگ باید از `get_settings` / overlay زنده بیاید؛ کش کهنه برای این کلیدها مطلوب نیست.
- دکمهٔ بروزرسانی تنظیمات پیشرفته باید همگام زنده از سوپرادمین را هم بزند اگر فلگ منو می‌خواهد عوض شود.
---
## ۱۰) چک قبل از اتمام
- [ ] diff فقط به درخواست مربوط است؟
- [ ] سیستم حسابداری / اپ / برنچ اشتباه درگیر نشده؟
- [ ] اگر مبهم بود سؤال شد؟
- [ ] یادداشت یک‌خطی نوشته شد؟
- [ ] UI: راهنما + بدون فضای مرده + نسبت سرچ/دکمه درست؟
- [ ] Ant / Uno / lodash به‌جای reinvent؟
- [ ] جواب کوتاه است؛ توضیح اضافه نداری؟
---
## ۱۱) نمونهٔ رفتار درست / غلط
```text
❌ «همگام‌سازی مشتری خراب» → هر سه زرین/ته‌حساب/پرگار را عوض کند
✅ بپرسد کدام؟ بعد فقط همان
❌ UI یک کارت → کل صفحه accounting را redesign کند
✅ فقط همان کارت / همان فایل
❌ هر بار از صفر Grep مونوریپو
✅ learned-notes + project-map → مستقیم فایل
❌ CSS سفارشی ۵۰ خط برای flex ساده
✅ class="flex flex-col gap-2 sm:grid sm:grid-cols-2"
```
---
**پایان.** این سند را به‌روز نگه دار؛ نکات جدید حساس را همین‌جا یا در `learned-notes.md` اضافه کن.
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Services\CopperConvertRequestService;
class CopperConvertRequestController extends Controller
{
public function index(CopperConvertRequestService $service)
{
return response()->json($service->listForAdmin());
}
public function approve(int $id, CopperConvertRequestService $service)
{
$row = $service->approve($id, (int) auth('user')->id());
return response()->json($row);
}
public function reject(int $id, CopperConvertRequestService $service)
{
$row = $service->reject($id, (int) auth('user')->id());
return response()->json($row);
}
}
@@ -16,6 +16,7 @@ use App\Services\BalanceReportService;
use App\Services\ConfigService;
use App\Services\CustomerPresenceService;
use App\Services\ReferralGiftService;
use App\Services\ShayeganSyncService;
use App\Services\WalletBalanceService;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
@@ -150,6 +151,8 @@ class CustomerController extends SuperController
if (array_key_exists('password', $data) && trim((string) ($data['password'] ?? '')) === '') {
unset($data['password']);
} elseif (array_key_exists('password', $data)) {
$data['password'] = Customer::normalizeCredentialDigits(trim((string) $data['password']));
}
if (isset($data['mobile']) && ! is_null($data['mobile']) && $data['mobile'] !== '') {
@@ -196,6 +199,23 @@ class CustomerController extends SuperController
$updated = $data === [] ? false : $customer->update($data);
// همگام‌سازی با شایگان در صورت تغییر دستی کد حسابداری
if (array_key_exists('moshtari_code', $data) && app(ConfigService::class)->isShayeganAccounting()) {
$newCode = $data['moshtari_code'];
if ($newCode !== null && $newCode !== '') {
try {
$shayeganSync = app(ShayeganSyncService::class);
$shayeganSync->registerCustomer($customer, $newCode);
} catch (\Throwable $e) {
\Illuminate\Support\Facades\Log::warning('shayegan.manual_code_sync_failed', [
'customer_id' => $customer->id,
'code' => $newCode,
'error' => $e->getMessage(),
]);
}
}
}
return response()->json([
'g' => $goldUpdated,
'u' => $updated,
@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Services\DigipayInstallmentService;
use Illuminate\Http\Request;
class DigipayInstallmentController extends Controller
{
public function __construct(private DigipayInstallmentService $service)
{
}
public function setCredit(Request $request)
{
$this->ensureEnabled();
$data = $request->validate([
'mobile' => 'required|string|max:20',
'plan4_toman' => 'required|integer|min:0',
'plan12_toman' => 'required|integer|min:0',
]);
return response()->json($this->service->setCredit(
$data['mobile'],
(int) $data['plan4_toman'],
(int) $data['plan12_toman']
));
}
public function orders()
{
$this->ensureEnabled();
return response()->json(['data' => $this->service->recentOrders()]);
}
private function ensureEnabled(): void
{
if (! $this->service->enabled()) {
abort(403, 'خرید اقساطی فعال نیست');
}
}
}
+734 -98
View File
@@ -13,6 +13,9 @@ use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use App\Services\ConfigService;
use App\Services\PargarSyncService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class GiftCardController extends Controller
@@ -24,55 +27,30 @@ class GiftCardController extends Controller
}
$user = auth()->user();
$count = $request->count;
$count = (int) $request->count;
$amount = $request->amount;
if(!$user){
throw new UnprocessableEntityHttpException('auth failed!');
}
$codes = [];
if((!is_numeric($count) || $count < 0) || (!is_numeric($amount) || $amount <= 0)){
if((!is_numeric($request->count) || $count < 1) || (!is_numeric($amount) || $amount <= 0)){
return response()->json(['message' => 'تعداد کد را چک کنید!'], 400);
}
$customer = Customer::select('id', 'name', 'mobile')->where('mobile', $request->mobile)->first();
$gift = GiftCard::create([
'customer_id' => $customer->id ?? null,
'count' => $count,
'amount' => $amount,
'mobile' => $request->mobile ?? null,
'name' => ($customer ? $customer->name : $request->name) ?? null,
'amount' => $amount,
'total' => $count*$amount,
'sts' => 1,
'unit' => $request->unit,
'expiry_date' => $request->expiry_date,
'created_at' => now(),
'updated_at' => now(),
'description' => $request->description,
]);
for ($i = 0; $i < $count; $i++) {
do {
$unique_code = strtoupper(bin2hex(random_bytes(4)));
} while (GiftCardCodes::where('code', $unique_code)->exists());
$codes[] = [
'giftcard_id' => $gift->id,
'code' => $unique_code,
'sts' => 1,
'unit' => $request->unit,
'amount' => $amount,
'expiry_date' => $request->expiry_date,
'created_at' => now(),
];
$expiryError = $this->validateGiftExpiryDate($request->expiry_date);
if ($expiryError !== null) {
return response()->json(['message' => $expiryError], 400);
}
GiftCardCodes::insert($codes);
$customer = $this->resolveGiftCardCustomerForCreate($request);
$gift = $this->createGiftCardWithUniqueCodes($request, $customer);
$createdCodes = $gift->giftcardcodes->pluck('code')->all();
return response()->json([
'customer' => $customer ?? null,
'order' => $gift,
'codes' => $gift->giftcardcodes,
'total' => $count*$amount,
'orders' => [$gift],
'codes' => $createdCodes,
'total' => $count * $amount,
]);
}
@@ -81,6 +59,7 @@ class GiftCardController extends Controller
if(!$user){
throw new UnprocessableEntityHttpException('auth failed!');
}
self::assertCustomerIdentityVerified($user instanceof Customer ? $user : null);
if (!app(ConfigService::class)->getBool('has_page_gift_card', false)) {
throw new UnprocessableEntityHttpException('قابلیت کارت هدیه غیرفعال است.');
@@ -88,20 +67,17 @@ class GiftCardController extends Controller
$redeem = $request->code;
$giftcode = GiftCardCodes::where('code', $redeem)->first();
$gift = GiftCard::find($giftcode->giftcard_id);
if(!$giftcode){
return response()->json(['message' => 'کد هدیه یافت نشد!'], 404);
}
//gift order update
$gift = GiftCard::find($giftcode->giftcard_id);
if(!$gift){
return response()->json(['message' => 'کد هدیه یافت نشد!'], 404);
}
if($gift->used_count+1 === $gift->count){
$gift->sts = 2;
}elseif($gift->expiry_date <= now()){
if($gift->expiry_date && $gift->expiry_date <= now()){
$gift->sts = 3;
$giftcode->sts = 3;
$giftcode->save();
$gift->save();
@@ -109,19 +85,18 @@ class GiftCardController extends Controller
return response()->json(['message' => 'کد هدیه منقضی شده است!'], 400);
}
$gift->used_count += 1;
$gift->save();
if($giftcode->sts != 1){
if((int) $giftcode->sts !== 1){
return response()->json(['message' => 'کد هدیه قبلا استفاده شده است!'], 400);
}
if((int) $gift->count > 0 && (int) $gift->used_count >= (int) $gift->count){
return response()->json(['message' => 'کد هدیه قبلا استفاده شده است!'], 400);
}
$unit = (int) $giftcode->unit;
$message = null;
//tranaction
if($giftcode->unit === 1){
if($unit === 1){
//add IRR to user wallet
$Withdraw = Withdraw::create([
'customer_id' => auth('customer')->id(),
@@ -148,7 +123,7 @@ class GiftCardController extends Controller
], 3, false, true);
try {
app(\App\Services\PargarSyncService::class)->queueWalletDocument(
app(PargarSyncService::class)->queueWalletDocument(
$user,
'cash',
(float) $giftcode->amount,
@@ -163,28 +138,130 @@ class GiftCardController extends Controller
}
}
//set text for sms to customer
$amount = number_format($giftcode->amount);
$amount = number_format((float) $giftcode->amount);
$message = "$user->name عزیز
کیف پول شما به مقدار $amount ریال
به واسطه کارت هدیه از طرف $gift->name شارژ شد.
قلک طلا";
قلک ریال";
}elseif ($giftcode->unit === 2){
//add Gold to user wallet
return response()->json(['message'=> 'در دست ساخت👷🏻🚧'], 400);
}elseif ($unit === 2){
// شارژ کیف فلزی (طلا / مس — فیلد gold کیف اصلی)
$goldAmount = (float) $giftcode->amount;
if ($goldAmount <= 0) {
return response()->json(['message' => 'مقدار کارت هدیه نامعتبر است!'], 400);
}
$configService = app(ConfigService::class);
$representative = $configService->mainWalletRepresentativeProduct();
$Withdraw = Withdraw::create([
'customer_id' => $user->id,
'gold' => $goldAmount,
'note' => 'کارت هدیه',
'sts' => 6,
'tracked_number' => $giftcode->id,
]);
$wallet_interface = new WalletInterface($user->id, $user->type);
new TransactionInterface($wallet_interface, [
'cash' => 0,
'gold' => $goldAmount,
'expire_at' => now(),
'note' => 'کارت هدیه',
'withdraw_id' => $Withdraw->id,
'product_id' => $representative?->id,
'active' => true,
], 7, true, false);
$syncPayload = [
'customer_id' => $user->id,
'value' => $goldAmount,
'direction' => 1,
'withdraw_id' => $Withdraw->id,
'note' => 'کارت هدیه',
];
if ($representative) {
$syncPayload['product_id'] = $representative->id;
$syncPayload['product'] = [
'id' => $representative->id,
'title' => $representative->title,
'group_type' => $representative->group_type,
'metal_id' => $representative->metal_id,
'amount' => $representative->amount,
'unit' => $representative->unit,
'trade_by_quantity' => $representative->trade_by_quantity,
];
}
if ($configService->isTahesabAccounting()) {
try {
app(TahesabController::class)->walletGold($syncPayload);
} catch (\Throwable $e) {
report($e);
}
}
if ($configService->isZarinAccounting()) {
try {
app(ZarinController::class)->walletGold($syncPayload);
} catch (\Throwable $e) {
report($e);
}
}
try {
app(PargarSyncService::class)->queueWalletDocument(
$user,
'gold',
$goldAmount,
[
'withdraw_id' => $Withdraw->id,
'note' => 'کارت هدیه',
'product_id' => $representative?->id,
'source' => 'gift_card',
]
);
} catch (\Throwable $e) {
report($e);
}
$weightUnit = self::tradeWeightUnit();
$metalLabel = self::mainWalletMetalLabel();
$formattedGold = self::formatSmsGoldWeight($goldAmount);
$message = "$user->name عزیز
کیف $metalLabel شما به مقدار $formattedGold $weightUnit
به واسطه کارت هدیه از طرف $gift->name شارژ شد.
قلک مس";
try {
app(\App\Services\CustomerAppNotifyService::class)->notifyCustomer(
(int) $user->id,
'واریز کارت هدیه',
"کیف $metalLabel شما به اندازه $formattedGold $weightUnit شارژ شد.",
'success'
);
} catch (\Throwable $e) {
report($e);
}
} else {
return response()->json(['message' => 'نوع کارت هدیه پشتیبانی نمی‌شود.'], 400);
}
if((int) $gift->used_count + 1 >= (int) $gift->count){
$gift->sts = 2;
}
$gift->used_count = (int) $gift->used_count + 1;
$gift->save();
//gift code update
$giftcode->assigned_to = $user->id;
$giftcode->sts = 2;
$giftcode->used_at = now();
$giftcode->save();
$this->Send($user->mobile, $message);
if ($message) {
$this->Send($user->mobile, $message);
}
return response()->json([
'message' => 'کد هدیه با موفقیت استفاده شد!',
@@ -194,6 +271,324 @@ class GiftCardController extends Controller
]);
}
/**
* لیست کدهای قابل‌استفاده (اختصاصی + عمومی تک‌کد) و تاریخچهٔ مصرف‌شدهٔ مشتری.
*/
public function mine(Request $request)
{
$user = auth()->user();
if (! $user) {
throw new UnprocessableEntityHttpException('auth failed!');
}
if (! app(ConfigService::class)->getBool('has_page_gift_card', false)) {
throw new UnprocessableEntityHttpException('قابلیت کارت هدیه غیرفعال است.');
}
$customerId = (int) $user->id;
$mobile = $user->mobile ?? null;
$available = [];
$seenCodes = [];
$personalGifts = GiftCard::query()
->where(function ($q) use ($customerId, $mobile) {
$q->where('customer_id', $customerId);
if ($mobile) {
$q->orWhere('mobile', $mobile);
}
})
->where(function ($q) {
$q->whereNull('sts')->orWhere('sts', '!=', 3);
})
->where(function ($q) {
$q->whereNull('expiry_date')->orWhere('expiry_date', '>', now());
})
->with(['giftcardcodes' => function ($q) {
$q->where('sts', 1);
}])
->orderByDesc('id')
->get();
foreach ($personalGifts as $gift) {
foreach ($gift->giftcardcodes as $code) {
if ($this->isCodeExpired($code, $gift)) {
continue;
}
if (isset($seenCodes[$code->code])) {
continue;
}
$seenCodes[$code->code] = true;
$available[] = $this->mapCustomerGiftItem($gift, $code, 'personal');
}
}
$publicGifts = GiftCard::query()
->where(function ($q) {
$q->whereNull('customer_id')->orWhere('customer_id', 0);
})
->where(function ($q) {
$q->whereNull('mobile')->orWhere('mobile', '');
})
->where('use_once', 0)
->where(function ($q) {
$q->whereNull('sts')->orWhere('sts', '!=', 3);
})
->where(function ($q) {
$q->whereNull('expiry_date')->orWhere('expiry_date', '>', now());
})
->with('giftcardcodes')
->orderByDesc('id')
->get();
foreach ($publicGifts as $gift) {
if ((int) $gift->count > 0 && (int) $gift->used_count >= (int) $gift->count) {
continue;
}
if (! $this->isPublicGiftVisibleInApp($gift)) {
continue;
}
$codes = $gift->giftcardcodes
->filter(function ($code) use ($gift) {
return (int) $code->sts !== 2
&& (int) $code->sts !== 3
&& ! $this->isCodeExpired($code, $gift);
})
->values();
foreach ($codes as $code) {
if ($this->customerAlreadyUsedCode($code, $customerId, $gift)) {
continue;
}
if (isset($seenCodes[$code->code])) {
continue;
}
$seenCodes[$code->code] = true;
$available[] = $this->mapCustomerGiftItem($gift, $code, 'public');
}
}
$history = [];
$historyCodes = GiftCardCodes::query()
->whereNotNull('assigned_to')
->where('assigned_to', '!=', '')
->where(function ($q) use ($customerId) {
$id = (string) $customerId;
$q->where('assigned_to', $customerId)
->orWhere('assigned_to', $id)
->orWhere('assigned_to', '['.$id.']')
->orWhere('assigned_to', 'like', '%"'.$id.'"%')
->orWhere('assigned_to', 'like', '%['.$id.',%')
->orWhere('assigned_to', 'like', '%,'.$id.']%')
->orWhere('assigned_to', 'like', '%,'.$id.',%');
})
->with('giftcard')
->orderByDesc('used_at')
->orderByDesc('updated_at')
->limit(100)
->get();
foreach ($historyCodes as $code) {
$gift = $code->giftcard;
if (! $gift || ! $this->customerAlreadyUsedCode($code, $customerId, $gift)) {
continue;
}
$history[] = $this->mapCustomerGiftItem($gift, $code, $this->resolveCodeScope($gift, $customerId, $mobile));
}
return response()->json([
'available' => $available,
'history' => $history,
]);
}
private function resolveGiftCardCustomer(Request $request): ?Customer
{
if ($request->filled('customer_id')) {
return Customer::select('id', 'name', 'mobile')->find((int) $request->customer_id);
}
if ($request->filled('mobile')) {
return Customer::select('id', 'name', 'mobile')->where('mobile', $request->mobile)->first();
}
return null;
}
/**
* کارت عمومی: show_in_app=1 → در لیست اپ همه؛ ۰ → فقط با وارد کردن دستی کد.
* سازگاری با رکوردهای قبل از ستون show_in_app: تک‌کد مشترک مثل قبل در اپ می‌آید.
*/
private function isPublicGiftVisibleInApp(GiftCard $gift): bool
{
if (! isset($gift->show_in_app)) {
$codesCount = $gift->relationLoaded('giftcardcodes')
? $gift->giftcardcodes->count()
: $gift->giftcardcodes()->count();
return $codesCount === 1 || ! empty($gift->unique_code);
}
return (int) $gift->show_in_app === 1;
}
private function resolveGiftCardCustomerForCreate(Request $request): ?Customer
{
$customer = $this->resolveGiftCardCustomer($request);
if ($request->filled('customer_id') && ! $customer) {
throw new UnprocessableEntityHttpException('مشتری انتخاب‌شده یافت نشد!');
}
return $customer;
}
/**
* یک رکورد giftcards + N کد یکتا در giftcard_codes (نه N رکورد جدا).
*/
private function createGiftCardWithUniqueCodes(Request $request, ?Customer $customer = null): GiftCard
{
if ($customer === null) {
$customer = $this->resolveGiftCardCustomer($request);
}
$count = (int) $request->count;
$amount = $request->amount;
$unit = (int) $request->unit;
$unitAmount = $unit === 3 ? $amount / 100 : $amount;
$giftData = [
'customer_id' => $customer?->id,
'use_once' => $request->use_once ? 1 : 0,
'count' => $count,
'amount' => $unitAmount,
'mobile' => $customer?->mobile ?? $request->mobile ?? null,
'name' => ($customer ? $customer->name : $request->name) ?? null,
'total' => $unit === 3 ? null : $count * $amount,
'sts' => 1,
'unit' => $request->unit,
'expiry_date' => $request->expiry_date,
'created_at' => now(),
'updated_at' => now(),
'description' => $request->description,
];
if (Schema::hasColumn('giftcards', 'show_in_app')) {
$giftData['show_in_app'] = $customer ? 0 : ($request->boolean('show_in_app') ? 1 : 0);
}
$gift = GiftCard::create($giftData);
$codeRows = [];
for ($i = 0; $i < $count; $i++) {
do {
$uniqueCode = strtoupper(bin2hex(random_bytes(4)));
} while (GiftCardCodes::where('code', $uniqueCode)->exists());
$codeRows[] = [
'giftcard_id' => $gift->id,
'use_once' => $request->use_once ? 1 : 0,
'code' => $uniqueCode,
'sts' => 1,
'unit' => $request->unit,
'amount' => $unitAmount,
'expiry_date' => $request->expiry_date,
'created_at' => now(),
];
}
GiftCardCodes::insert($codeRows);
if ($count === 1) {
$gift->unique_code = $codeRows[0]['code'];
$gift->save();
}
return $gift->load(['giftcardcodes', 'customer']);
}
/**
* تاریخ انقضا نباید قبل از امروز باشد (امروز مجاز است).
*/
private function validateGiftExpiryDate(mixed $expiryDate): ?string
{
if ($expiryDate === null || $expiryDate === '') {
return 'تاریخ انقضا الزامی است.';
}
try {
$expiryDay = \Carbon\Carbon::parse($expiryDate)->startOfDay();
} catch (\Throwable $e) {
return 'تاریخ انقضا نامعتبر است.';
}
if ($expiryDay->lt(now()->startOfDay())) {
return 'تاریخ انقضا نمی‌تواند قبل از امروز باشد.';
}
return null;
}
private function isCodeExpired(GiftCardCodes $code, GiftCard $gift): bool
{
if ($code->expiry_date && $code->expiry_date <= now()) {
return true;
}
if ($gift->expiry_date && $gift->expiry_date <= now()) {
return true;
}
return false;
}
private function customerAlreadyUsedCode(GiftCardCodes $code, int $customerId, GiftCard $gift): bool
{
$assigned = $code->assigned_to;
if ($assigned === null || $assigned === '') {
return false;
}
if ((int) $gift->unit === 3 || (is_string($assigned) && str_starts_with(trim($assigned), '['))) {
$ids = json_decode($assigned, true);
if (! is_array($ids)) {
return false;
}
return in_array($customerId, $ids, false) || in_array((string) $customerId, $ids, false);
}
return (string) $assigned === (string) $customerId;
}
private function resolveCodeScope(GiftCard $gift, int $customerId, ?string $mobile): string
{
if ((int) $gift->customer_id === $customerId) {
return 'personal';
}
if ($mobile && $gift->mobile && (string) $gift->mobile === (string) $mobile) {
return 'personal';
}
return 'public';
}
private function mapCustomerGiftItem(GiftCard $gift, GiftCardCodes $code, string $scope): array
{
$unit = (int) ($code->unit ?? $gift->unit);
return [
'id' => $code->id,
'giftcard_id' => $gift->id,
'code' => $code->code,
'name' => $gift->name,
'description' => $gift->description,
'amount' => $code->amount ?? $gift->amount,
'unit' => $unit,
'kind' => $unit === 3 ? 'discount' : 'gift',
'scope' => $scope,
'sts' => (int) $code->sts,
'expiry_date' => $code->expiry_date ?? $gift->expiry_date,
'used_at' => $code->used_at,
];
}
public function useDiscount(Request $request)
{
if (! app(ConfigService::class)->isStore()) {
@@ -226,55 +621,37 @@ class GiftCardController extends Controller
private function storeRedeem(Request $request)
{
$user = auth()->user();
$count = $request->count;
$count = (int) $request->count;
$amount = $request->amount;
if (! $user) {
throw new UnprocessableEntityHttpException('auth failed!');
}
if ((! is_numeric($count) || $count < 0) || (! is_numeric($amount) || $amount <= 0)) {
if ((! is_numeric($request->count) || $count < 1) || (! is_numeric($amount) || $amount <= 0)) {
return response()->json(['message' => 'تعداد کد را چک کنید!'], 400);
}
$expiryError = $this->validateGiftExpiryDate($request->expiry_date);
if ($expiryError !== null) {
return response()->json(['message' => $expiryError], 400);
}
if (isset($request->code) && GiftCardCodes::where('code', $request->code)->where('unit', $request->unit)->exists()) {
return response()->json(['message' => 'کد تکراری میباشد!'], 400);
}
$codes = [];
$unitAmount = $request->unit == 3 ? $amount / 100 : $amount;
$unit = (int) $request->unit;
// کارت هدیه (ریالی/فلزی): همیشه N کد یکتا؛ تخفیف با use_once=0 می‌تواند تک‌کد مشترک باشد
$createUniqueCodes = $request->use_once || $unit === 1 || $unit === 2;
if ($request->use_once) {
$gift = GiftCard::create([
'use_once' => $request->use_once ? 1 : 0,
'count' => $count,
'amount' => $unitAmount,
'name' => $request->name,
'total' => $request->unit == 3 ? null : $count * $amount,
'sts' => 1,
'unit' => $request->unit,
'expiry_date' => $request->expiry_date,
'created_at' => now(),
'updated_at' => now(),
'description' => $request->description,
]);
for ($i = 0; $i < $count; $i++) {
do {
$unique_code = strtoupper(bin2hex(random_bytes(4)));
} while (GiftCardCodes::where('code', $unique_code)->exists());
$codes[] = [
'giftcard_id' => $gift->id,
'use_once' => $request->use_once ? 1 : 0,
'code' => $unique_code,
'sts' => 1,
'unit' => $request->unit,
'amount' => $unitAmount,
'expiry_date' => $request->expiry_date,
'created_at' => now(),
];
if ($createUniqueCodes) {
try {
$customer = $this->resolveGiftCardCustomerForCreate($request);
} catch (UnprocessableEntityHttpException $e) {
return response()->json(['message' => $e->getMessage()], 400);
}
GiftCardCodes::insert($codes);
$gift = $this->createGiftCardWithUniqueCodes($request, $customer);
} else {
do {
$unique_code = strtoupper(bin2hex(random_bytes(4)));
@@ -391,6 +768,162 @@ class GiftCardController extends Controller
return $giftcode;
}
public function update(Request $request, $id)
{
$user = auth()->user();
if (! $user) {
throw new UnprocessableEntityHttpException('auth failed!');
}
$gift = GiftCard::with('giftcardcodes')->findOrFail($id);
$count = (int) $request->count;
$amount = $request->amount;
if ((! is_numeric($request->count) || $count < 1) || (! is_numeric($amount) || $amount <= 0)) {
return response()->json(['message' => 'تعداد یا مقدار را چک کنید!'], 400);
}
$expiryError = $this->validateGiftExpiryDate($request->expiry_date);
if ($expiryError !== null) {
return response()->json(['message' => $expiryError], 400);
}
$unit = (int) $request->unit;
if (! in_array($unit, [1, 2, 3], true)) {
return response()->json(['message' => 'نوع کارت هدیه نامعتبر است.'], 400);
}
try {
$customer = $request->filled('customer_id')
? $this->resolveGiftCardCustomerForCreate($request)
: null;
} catch (UnprocessableEntityHttpException $e) {
return response()->json(['message' => $e->getMessage()], 400);
}
$requestedCustomer = $customer?->id ? (int) $customer->id : null;
$currentCustomer = $gift->customer_id ? (int) $gift->customer_id : null;
$structuralChange = $count !== (int) $gift->count
|| abs((float) $amount - (float) $gift->amount) > 0.0001
|| $unit !== (int) $gift->unit
|| $requestedCustomer !== $currentCustomer;
if ($this->giftCardIsUsed($gift) && $structuralChange) {
return response()->json([
'message' => 'این کارت استفاده شده است؛ فقط توضیحات، تاریخ انقضا و نمایش در اپ قابل ویرایش است.',
], 400);
}
$unitAmount = $unit === 3 ? $amount / 100 : $amount;
DB::transaction(function () use ($gift, $request, $customer, $count, $amount, $unit, $unitAmount, $structuralChange) {
$gift->description = $request->description;
$gift->expiry_date = $request->expiry_date;
if (Schema::hasColumn('giftcards', 'show_in_app')) {
$gift->show_in_app = $customer ? 0 : ($request->boolean('show_in_app') ? 1 : 0);
}
if (! $structuralChange) {
$gift->save();
GiftCardCodes::where('giftcard_id', $gift->id)
->where('sts', '!=', 2)
->update([
'expiry_date' => $request->expiry_date,
'updated_at' => now(),
]);
return;
}
$gift->customer_id = $customer?->id;
$gift->mobile = $customer?->mobile;
$gift->name = $customer?->name;
$gift->count = $count;
$gift->amount = $unitAmount;
$gift->unit = $unit;
$gift->total = $unit === 3 ? null : $count * $amount;
$gift->save();
$this->syncUnusedGiftCodes($gift, $count, $unit, $unitAmount, $request->expiry_date);
});
return response()->json($gift->fresh(['giftcardcodes', 'customer']));
}
public function destroy($id)
{
$user = auth()->user();
if (! $user) {
throw new UnprocessableEntityHttpException('auth failed!');
}
$gift = GiftCard::with('giftcardcodes')->findOrFail($id);
if ($this->giftCardIsUsed($gift)) {
return response()->json(['message' => 'این کارت هدیه استفاده شده و قابل حذف نیست.'], 400);
}
DB::transaction(function () use ($gift) {
GiftCardCodes::where('giftcard_id', $gift->id)->delete();
$gift->delete();
});
return response()->json(true);
}
private function giftCardIsUsed(GiftCard $gift): bool
{
if ((int) $gift->used_count > 0) {
return true;
}
return $gift->giftcardcodes->contains(function ($code) {
return (int) $code->sts === 2 || ! empty($code->used_at);
});
}
private function syncUnusedGiftCodes(GiftCard $gift, int $count, int $unit, $unitAmount, $expiryDate): void
{
$existing = GiftCardCodes::where('giftcard_id', $gift->id)->orderBy('id')->get();
$current = $existing->count();
if ($count < $current) {
$removeIds = $existing->slice($count)->pluck('id');
GiftCardCodes::whereIn('id', $removeIds)->delete();
} elseif ($count > $current) {
$rows = [];
for ($i = 0; $i < $count - $current; $i++) {
do {
$uniqueCode = strtoupper(bin2hex(random_bytes(4)));
} while (GiftCardCodes::where('code', $uniqueCode)->exists());
$rows[] = [
'giftcard_id' => $gift->id,
'use_once' => $gift->use_once ? 1 : 0,
'code' => $uniqueCode,
'sts' => 1,
'unit' => $unit,
'amount' => $unitAmount,
'expiry_date' => $expiryDate,
'created_at' => now(),
'updated_at' => now(),
];
}
if ($rows !== []) {
GiftCardCodes::insert($rows);
}
}
GiftCardCodes::where('giftcard_id', $gift->id)->update([
'unit' => $unit,
'amount' => $unitAmount,
'expiry_date' => $expiryDate,
'updated_at' => now(),
]);
$firstCode = GiftCardCodes::where('giftcard_id', $gift->id)->orderBy('id')->value('code');
$gift->unique_code = $count === 1 ? $firstCode : null;
$gift->save();
}
public function table(Request $request)
{
$user = auth()->user();
@@ -398,8 +931,9 @@ class GiftCardController extends Controller
throw new UnprocessableEntityHttpException('auth failed!');
}
$records = GiftCard::with([
'customer',
'giftcardcodes',
'giftcardcodes.assignedTo'
'giftcardcodes.assignedTo',
]);
TableEngine::create($records, $request->all())
->initSearch([])
@@ -409,4 +943,106 @@ class GiftCardController extends Controller
return response()->json($records);
}
/** گزارش استفاده از هر کد هدیه/تخفیف — ردیف به‌ردیف giftcard_codes */
public function codesUsageReport(Request $request)
{
$user = auth()->user();
if (! $user) {
throw new UnprocessableEntityHttpException('auth failed!');
}
$records = GiftCardCodes::query()
->leftJoin('giftcards', 'giftcards.id', '=', 'giftcard_codes.giftcard_id')
->with(['giftcard.customer', 'assignedTo'])
->select('giftcard_codes.*');
$engine = TableEngine::create($records, $request->all());
$engine->initSearch([
'giftcard_codes.code',
'giftcards.name',
'giftcards.mobile',
]);
$summary = [
'total_codes' => (clone $records)->count(),
'used_codes' => (clone $records)->where(function ($q) {
$q->where('giftcard_codes.sts', 2)
->orWhereNotNull('giftcard_codes.used_at')
->orWhere(function ($q2) {
$q2->whereNotNull('giftcard_codes.assigned_to')
->where('giftcard_codes.assigned_to', '!=', '');
});
})->count(),
'active_codes' => (clone $records)->where('giftcard_codes.sts', 1)->count(),
'expired_codes' => (clone $records)->where('giftcard_codes.sts', 3)->count(),
];
$summary['unused_codes'] = max(0, $summary['total_codes'] - $summary['used_codes']);
$result = [];
$engine->select(['giftcard_codes.*'])->export($result);
if (! empty($result['rows'])) {
$mapped = [];
foreach ($result['rows'] as $row) {
if (! $row instanceof GiftCardCodes) {
continue;
}
$row->loadMissing(['giftcard', 'assignedTo']);
$gift = $row->giftcard;
$usageCount = $this->resolveGiftCodeUsageCount($row, $gift);
$mapped[] = [
'id' => $row->id,
'giftcard_id' => $row->giftcard_id,
'code' => $row->code,
'sts' => (int) $row->sts,
'sts_str' => GiftCardCodes::$STS[(int) $row->sts] ?? '-',
'unit' => (int) ($row->unit ?? $gift?->unit ?? 0),
'amount' => $row->amount ?? $gift?->amount,
'expiry_date' => $row->expiry_date ?? $gift?->expiry_date,
'used_at' => $row->used_at,
'usage_count' => $usageCount,
'campaign_name' => $gift?->name,
'campaign_count' => (int) ($gift?->count ?? 0),
'campaign_used_count' => (int) ($gift?->used_count ?? 0),
'assigned_to' => $row->assignedTo,
'giftcard' => $gift ? [
'id' => $gift->id,
'name' => $gift->name,
'customer' => $gift->customer,
] : null,
];
}
$result['rows'] = $mapped;
}
$result['summary'] = $summary;
return response()->json($result);
}
private function resolveGiftCodeUsageCount(GiftCardCodes $code, ?GiftCard $gift): int
{
if ($gift && (int) $gift->use_once === 0 && (int) $gift->count > 0) {
return (int) $gift->used_count;
}
if (is_string($code->assigned_to) && str_starts_with(trim($code->assigned_to), '[')) {
$ids = json_decode($code->assigned_to, true);
if (is_array($ids)) {
return count($ids);
}
}
if ((int) $code->sts === 2 || ! empty($code->used_at)) {
return 1;
}
if ($code->assigned_to !== null && $code->assigned_to !== '') {
return 1;
}
return 0;
}
}
@@ -979,6 +979,13 @@ class ProductController extends SuperController
unset($data['cash_fee_buy_is_percent'], $data['cash_fee_sell_is_percent']);
}
if (! Product::hasShayeganItemColumn()) {
unset($data['shayegan_item_number']);
} elseif (array_key_exists('shayegan_item_number', $data)) {
$item = trim((string) $data['shayegan_item_number']);
$data['shayegan_item_number'] = $item === '' ? null : $item;
}
return $data;
}
@@ -81,7 +81,7 @@ class SettingsController extends Controller
->orderBy('key')
->get();
return response()->json($rows);
return response()->json($this->maskSecretSettingValues($rows));
}
/**
@@ -162,7 +162,19 @@ class SettingsController extends Controller
$previousValue = $setting->exists ? (string) ($setting->value ?? '') : null;
$setting->value = $request->value;
$incomingValue = $request->value;
if (
in_array($key, ['shayegan_db_password', 'shayegan_auth_password'], true)
&& is_string($incomingValue)
&& ($incomingValue === '********' || $incomingValue === '')
&& $previousValue !== null
&& $previousValue !== ''
) {
// ماسک frontend را به‌جای رمز واقعی ذخیره نکن
$incomingValue = $previousValue;
}
$setting->value = $incomingValue;
$setting->description = $request->description;
if ($request->has('is_active')) {
$setting->is_active = filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN) ? 1 : 0;
@@ -327,7 +339,7 @@ class SettingsController extends Controller
$overlay = app(SuperAdminProgramSettingsOverlay::class);
$saMap = $overlay->catalogMap();
if ($saMap === null) {
return $localRows;
return $this->maskSecretSettingValues($localRows);
}
$localByKey = [];
@@ -380,7 +392,53 @@ class SettingsController extends Controller
}
}
return collect(array_values($byKey))->sortBy(fn ($row) => (string) ($row->key ?? ''))->values();
return $this->maskSecretSettingValues(
collect(array_values($byKey))->sortBy(fn ($row) => (string) ($row->key ?? ''))->values()
);
}
/**
* رمزهای شایگان و مشابه در پاسخ frontend برنگردند (فقط پر/خالی بودن).
*
* @param mixed $rows
* @return mixed
*/
private function maskSecretSettingValues($rows)
{
$secretKeys = [
'shayegan_db_password',
'shayegan_auth_password',
];
$maskOne = function ($row) use ($secretKeys) {
if (is_array($row)) {
$key = (string) ($row['key'] ?? '');
if (in_array($key, $secretKeys, true)) {
$val = (string) ($row['value'] ?? '');
$row['value'] = $val !== '' ? '********' : '';
}
return $row;
}
if (is_object($row) && isset($row->key)) {
$key = (string) $row->key;
if (in_array($key, $secretKeys, true)) {
$val = (string) ($row->value ?? '');
$row->value = $val !== '' ? '********' : '';
}
}
return $row;
};
if ($rows instanceof \Illuminate\Support\Collection) {
return $rows->map($maskOne)->values();
}
if (is_array($rows)) {
return array_map($maskOne, $rows);
}
return $rows;
}
private function isEditableCanEdit(mixed $canEdit): bool
@@ -0,0 +1,311 @@
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Shayegan;
use App\Models\ShayeganInboundCharge;
use App\Services\ConfigService;
use App\Services\ShayeganClient;
use App\Services\ShayeganInboundChargeService;
use App\Services\ShayeganSyncService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
class ShayeganController extends Controller
{
/** @var ShayeganSyncService */
private $sync;
/** @var ShayeganClient */
private $client;
public function __construct(ShayeganSyncService $sync, ShayeganClient $client)
{
$this->sync = $sync;
$this->client = $client;
}
public function healthCheck()
{
$result = $this->client->healthCheck();
$status = ! empty($result['ok']) ? 200 : 422;
return response()->json(array_merge([
'ok' => ! empty($result['ok']),
'message' => $result['message'] ?? null,
'http_status' => $result['http_status'] ?? null,
'timeout' => ! empty($result['timeout']),
'body' => $this->sanitizeBodyForAdmin($result['body'] ?? null),
], $this->client->debugExchange($result)), $status);
}
/**
* @param array<string, mixed> $data
*/
public function storeTrade(array $data)
{
return $this->sync->recordTrade($data);
}
/**
* @param array<string, mixed> $data
*/
public function wallet(array $data)
{
return $this->sync->recordWalletCash($data);
}
/**
* @param array<string, mixed> $data
*/
public function walletGold(array $data)
{
return $this->sync->recordWalletGold($data);
}
public function registerCustomer($customerId)
{
if (! app(\App\Services\ConfigService::class)->isShayeganAccounting()) {
return response()->json(['ok' => false, 'message' => 'حسابداری شایگان فعال نیست'], 422);
}
$customer = \App\Models\Customer::findOrFail($customerId);
$result = $this->sync->registerCustomer($customer);
return response()->json($result, ($result['ok'] ?? false) ? 200 : 422);
}
public function table(Request $request)
{
if (! Schema::hasTable('shayegan')) {
return response()->json([
'rows' => [],
'query' => [
'limit' => (int) $request->input('limit', 20),
'page' => 1,
'total' => 0,
'filters' => $request->input('filters', []),
'search' => $request->input('search'),
],
]);
}
$query = Shayegan::with('customer')->orderByDesc('id');
\App\DB\Te\TableEngine::create($query, $request)
->initSearch(['desc', 'type', 'shayegan_number', 'sync_status'])
->select(['*'])
->export($query);
return response()->json($query);
}
public function show($id)
{
$row = Shayegan::with('customer')->findOrFail($id);
return response()->json($row);
}
/**
* Manual retry — refuses timeout rows unless force=1 after operator verified remote.
*/
public function retrySanad(Request $request, $id)
{
$row = Shayegan::findOrFail($id);
if ($row->sync_status === ShayeganSyncService::STATUS_SUCCESS) {
return response()->json(['ok' => true, 'message' => 'already synced', 'row' => $row]);
}
if ($row->sync_status === ShayeganSyncService::STATUS_TIMEOUT && ! $request->boolean('force')) {
return response()->json([
'ok' => false,
'message' => 'این سند timeout شده؛ بدون بررسی نتیجه در حسابگر دوباره ارسال نکنید. در صورت تایید force=1 بفرستید.',
], 422);
}
$payload = json_decode((string) $row->data, true);
$put = is_array($payload) ? ($payload['PutObject'] ?? null) : null;
$endpoint = (string) ($row->endpoint ?: 'Document/Put');
if (! is_array($put) || $put === []) {
return response()->json(['ok' => false, 'message' => 'payload خالی است'], 422);
}
// Clear timeout lock only when force retry requested
if ($row->sync_status === ShayeganSyncService::STATUS_TIMEOUT) {
$row->sync_status = ShayeganSyncService::STATUS_PENDING;
$row->save();
}
$result = $this->client->put($endpoint, $put);
$exchange = $this->client->debugExchange($result);
if (! empty($result['timeout'])) {
$row->sync_status = ShayeganSyncService::STATUS_TIMEOUT;
$row->sync_log = (string) ($result['message'] ?? 'timeout');
$row->res = json_encode(['timeout' => true], JSON_UNESCAPED_UNICODE);
$row->save();
return response()->json(array_merge(['ok' => false, 'message' => 'timeout', 'row' => $row], $exchange), 422);
}
if (! empty($result['ok'])) {
$row->sync_status = ShayeganSyncService::STATUS_SUCCESS;
$row->sync_log = null;
$row->shayegan_number = $result['number'] ?? null;
$row->shayegan_guid = $result['guid'] ?? null;
$row->res = json_encode($result['body'] ?? [], JSON_UNESCAPED_UNICODE);
$row->save();
return response()->json(array_merge(['ok' => true, 'row' => $row], $exchange));
}
$row->sync_status = ShayeganSyncService::STATUS_FAILED;
$row->sync_log = (string) ($result['message'] ?? 'failed');
$row->res = json_encode($result['body'] ?? [], JSON_UNESCAPED_UNICODE);
$row->save();
return response()->json(array_merge(['ok' => false, 'message' => $row->sync_log, 'row' => $row], $exchange), 422);
}
/**
* وب‌هوک دریافت شارژ حساب مشتری از پنل حسابداری شایگان
*/
public function inboundWebhook(Request $request, ShayeganInboundChargeService $inboundService)
{
$secret = app(ConfigService::class)->getString('shayegan_webhook_secret', '');
$key = $request->header('X-Shayegan-Key') ?: $request->input('secret');
if ($secret !== '' && $key !== $secret) {
return response()->json([
'ok' => false,
'message' => 'کلید امنیتی وب‌هوک شایگان نامعتبر است (X-Shayegan-Key).',
], 403);
}
$res = $inboundService->registerCharge($request->all(), 'webhook');
return response()->json($res, ($res['ok'] ?? false) ? 200 : 422);
}
/**
* دریافت لیست شارژهای در انتظار تایید برای نمایش اعلان در پنل ادمین
*/
public function pendingCharges()
{
if (! Schema::hasTable('shayegan_inbound_charges')) {
return response()->json(['ok' => true, 'charges' => []]);
}
$charges = ShayeganInboundCharge::with('customer')
->where('status', 'pending')
->orderByDesc('id')
->limit(20)
->get();
return response()->json([
'ok' => true,
'charges' => $charges,
]);
}
/**
* جدول شارژهای دریافتی از شایگان
*/
public function chargesTable(Request $request)
{
if (! Schema::hasTable('shayegan_inbound_charges')) {
return response()->json([
'rows' => [],
'query' => [
'limit' => (int) $request->input('limit', 20),
'page' => 1,
'total' => 0,
'filters' => $request->input('filters', []),
'search' => $request->input('search'),
],
]);
}
$query = ShayeganInboundCharge::with(['customer', 'approver'])->orderByDesc('id');
if ($request->filled('status')) {
$query->where('status', $request->input('status'));
}
if ($request->filled('search')) {
$s = trim((string) $request->input('search'));
$query->where(function ($q) use ($s) {
$q->where('shayegan_number', 'like', "%{$s}%")
->orWhere('customer_tafsil', 'like', "%{$s}%")
->orWhereHas('customer', function ($cq) use ($s) {
$cq->where('name', 'like', "%{$s}%")
->orWhere('mobile', 'like', "%{$s}%")
->orWhere('n_code', 'like', "%{$s}%");
});
});
}
$limit = max(1, (int) $request->input('limit', 20));
$page = max(1, (int) $request->input('page', 1));
$total = $query->count();
$rows = $query->skip(($page - 1) * $limit)->take($limit)->get();
return response()->json([
'rows' => $rows,
'query' => [
'page' => $page,
'limit' => $limit,
'total' => $total,
],
]);
}
/**
* تایید شارژ و افزایش کیف پول مشتری در بورس مس
*/
public function approveCharge(Request $request, $id, ShayeganInboundChargeService $inboundService)
{
$charge = ShayeganInboundCharge::with('customer')->findOrFail($id);
$res = $inboundService->approveCharge($charge, auth()->user());
return response()->json($res, ($res['ok'] ?? false) ? 200 : 422);
}
/**
* رد درخواست شارژ
*/
public function rejectCharge(Request $request, $id, ShayeganInboundChargeService $inboundService)
{
$charge = ShayeganInboundCharge::findOrFail($id);
$reason = $request->input('reason');
$res = $inboundService->rejectCharge($charge, auth()->user(), $reason);
return response()->json($res, ($res['ok'] ?? false) ? 200 : 422);
}
/**
* استعلام اسناد جدید از شایگان
*/
public function syncChargesFromShayegan(ShayeganInboundChargeService $inboundService)
{
$res = $inboundService->pollFromShayegan();
return response()->json($res, ($res['ok'] ?? false) ? 200 : 422);
}
/**
* @param mixed $body
* @return mixed
*/
private function sanitizeBodyForAdmin($body)
{
if (! is_array($body)) {
return $body;
}
// Drop huge Result lists from health if present
if (isset($body['Result']) && is_array($body['Result'])) {
$body['Result'] = array_slice($body['Result'], 0, 3);
}
return $body;
}
}
@@ -8,7 +8,9 @@ use App\Models\Permission;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\Setting;
use App\Services\AdminPageAccess;
use App\Services\SmsBilling\SmsWalletService;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class UserController extends SuperController
{
@@ -25,6 +27,41 @@ class UserController extends SuperController
}
public function store(Request $request)
{
$this->applyPageAccessInput($request, true);
return parent::store($request);
}
public function update(Request $request, $id)
{
$this->applyPageAccessInput($request, false);
return parent::update($request, $id);
}
private function applyPageAccessInput(Request $request, bool $creating): void
{
$actor = auth('user')->user();
if (!$actor instanceof User || !AdminPageAccess::hasFullAccess($actor)) {
if ($creating && $actor instanceof User) {
$request->merge(['page_access' => $actor->page_access]);
} else {
$request->replace($request->except('page_access'));
}
return;
}
if (!$request->exists('page_access')) {
return;
}
$normalized = AdminPageAccess::normalize($request->input('page_access'));
if (is_array($normalized) && !AdminPageAccess::hasAnyView($normalized)) {
throw new UnprocessableEntityHttpException('حداقل مشاهدهٔ یک صفحه را انتخاب کنید');
}
$request->merge(['page_access' => $normalized]);
}
public function me(){
$user = User::with($this->with)
->select($this->select)
@@ -284,6 +284,16 @@ class WalletController extends Controller
}
}
if (app(ConfigService::class)->isShayeganAccounting()) {
try {
$data['direction'] = $deposit ? 0 : 1;
$data['withdraw_id'] = $Withdraw->id;
app(\App\Http\Controllers\Admin\ShayeganController::class)->wallet($data);
} catch (\Exception $e) {
report($e);
}
}
try {
app(PargarSyncService::class)->queueWalletDocument(
$customer,
@@ -430,6 +440,16 @@ class WalletController extends Controller
}
}
if (app(ConfigService::class)->isShayeganAccounting()) {
try {
$data['direction'] = $deposit ? 1 : 0;
$data['withdraw_id'] = $Withdraw->id;
app(\App\Http\Controllers\Admin\ShayeganController::class)->walletGold($data);
} catch (\Exception $e) {
report($e);
}
}
try {
app(PargarSyncService::class)->queueWalletDocument(
$customer,
@@ -669,6 +689,17 @@ class WalletController extends Controller
}
}
if (app(ConfigService::class)->isShayeganAccounting()) {
try {
$data['direction'] = $deposit ? 1 : 0;
$data['withdraw_id'] = $Withdraw->id;
$data['product_id'] = $productId;
app(\App\Http\Controllers\Admin\ShayeganController::class)->walletGold($data);
} catch (\Exception $e) {
report($e);
}
}
try {
// فقط محصول متصل به کیف اصلی → سند طلای پرگار
app(PargarSyncService::class)->queueWalletDocument(
@@ -1504,4 +1535,167 @@ class WalletController extends Controller
);
}
public function approveDeposit(Request $request)
{
$request->validate([
'id' => 'required|integer|exists:withdraws,id',
'tracked_number' => 'nullable|string|max:100',
]);
$withdraw = Withdraw::with(['customer', 'Transaction'])->findOrFail($request->id);
if ((int) $withdraw->sts === 2) {
return response()->json(['message' => 'این تراکنش قبلاً تایید شده است.'], 422);
}
$customer = $withdraw->customer ?: Customer::find($withdraw->customer_id);
if (!$customer) {
return response()->json(['message' => 'مشتری مربوطه یافت نشد.'], 404);
}
$adminId = auth('user')->id() ?: auth()->id();
$amount = (float) $withdraw->cash;
DB::transaction(function () use ($withdraw, $customer, $adminId, $amount, $request) {
$withdraw->sts = 2; // واریز شد
$withdraw->user_id = $adminId;
if ($request->filled('tracked_number')) {
$withdraw->tracked_number = trim((string) $request->tracked_number);
}
if (empty($withdraw->date_at)) {
$withdraw->date_at = now();
}
$withdraw->save();
$hasExistingCredit = Transaction::where('withdraw_id', $withdraw->id)
->where('cash', '>', 0)
->exists();
if (!$hasExistingCredit && $amount > 0) {
$walletInterface = new WalletInterface((int) $customer->id, (int) $customer->type);
new TransactionInterface($walletInterface, [
'gold' => 0,
'cash' => $amount,
'expire_at' => now(),
'note' => $withdraw->note ?: 'واریز نقدی (فیش بانکی)',
'withdraw_id' => $withdraw->id,
'active' => true,
], 3, true, true);
$this->recordAccountingTransaction(
$customer,
$withdraw,
(int) $adminId,
$amount,
0,
$withdraw->note ?: 'واریز نقدی (فیش بانکی)'
);
if (app(ConfigService::class)->isTahesabAccounting()) {
try {
app(TahesabController::class)->wallet([
'customer_id' => $customer->id,
'value' => $amount,
'direction' => 0,
'withdraw_id' => $withdraw->id,
'note' => $withdraw->note ?: 'شارژ حساب (فیش بانکی)',
]);
} catch (\Throwable $e) { report($e); }
}
if (app(ConfigService::class)->isZarinAccounting()) {
try {
app(\App\Http\Controllers\Admin\ZarinController::class)->wallet([
'customer_id' => $customer->id,
'value' => $amount,
'direction' => 0,
'withdraw_id' => $withdraw->id,
'note' => $withdraw->note ?: 'شارژ حساب (فیش بانکی)',
]);
} catch (\Throwable $e) { report($e); }
}
if (app(ConfigService::class)->isShayeganAccounting()) {
try {
app(\App\Http\Controllers\Admin\ShayeganController::class)->wallet([
'customer_id' => $customer->id,
'value' => $amount,
'direction' => 0,
'withdraw_id' => $withdraw->id,
'note' => $withdraw->note ?: 'شارژ حساب (فیش بانکی)',
]);
} catch (\Throwable $e) { report($e); }
}
try {
app(PargarSyncService::class)->queueWalletDocument(
$customer,
'cash',
$amount,
[
'withdraw_id' => $withdraw->id,
'note' => $withdraw->note ?: 'واریز نقدی',
'source' => 'deposit_receipt',
]
);
} catch (\Throwable $e) { report($e); }
}
});
$this->broadcastCustomerWalletAssets($customer);
try {
$appName = app(ConfigService::class)->getString('name_fa', 'سامانه');
$amountFormatted = number_format((int) $amount);
$trackedInfo = $withdraw->tracked_number ? "\nکد پیگیری: {$withdraw->tracked_number}" : '';
$smsMsg = "مشتری گرامی {$customer->name}\nدرخواست واریز شما به مبلغ {$amountFormatted} ریال تایید و به موجودی کیف پول شما افزوده شد.{$trackedInfo}\n{$appName}";
Controller::SendMessage($customer->mobile, $smsMsg, true, 'sms');
} catch (\Throwable $e) {
report($e);
}
return response()->json([
'message' => 'درخواست واریز با موفقیت تایید و مبلغ به کیف پول مشتری واریز شد.',
'withdraw' => $withdraw->fresh(['customer', 'Transaction']),
]);
}
public function rejectDeposit(Request $request)
{
$request->validate([
'id' => 'required|integer|exists:withdraws,id',
'reject_reason' => 'nullable|string|max:500',
]);
$withdraw = Withdraw::with('customer')->findOrFail($request->id);
if ((int) $withdraw->sts === 2) {
return response()->json(['message' => 'این تراکنش قبلاً تایید شده و امکان رد آن وجود ندارد.'], 422);
}
$adminId = auth('user')->id() ?: auth()->id();
$withdraw->sts = 3; // رد شده
$withdraw->user_id = $adminId;
$withdraw->reject_reason = $request->reject_reason ? trim((string) $request->reject_reason) : null;
$withdraw->save();
$customer = $withdraw->customer ?: Customer::find($withdraw->customer_id);
if ($customer) {
try {
$appName = app(ConfigService::class)->getString('name_fa', 'سامانه');
$amountFormatted = number_format((int) $withdraw->cash);
$reasonText = $withdraw->reject_reason ? "\nعلت رد: {$withdraw->reject_reason}" : '';
$smsMsg = "مشتری گرامی {$customer->name}\nدرخواست واریز شما به مبلغ {$amountFormatted} ریال متأسفانه رد شد.{$reasonText}\n{$appName}";
Controller::SendMessage($customer->mobile, $smsMsg, true, 'sms');
} catch (\Throwable $e) {
report($e);
}
}
return response()->json([
'message' => 'درخواست واریز رد شد و پیامک به مشتری ارسال گردید.',
'withdraw' => $withdraw->fresh(['customer']),
]);
}
}
@@ -54,6 +54,12 @@ class AuthController extends Controller
protected function _loginWithPassword($credentials, $provider)
{
if (isset($credentials['password'])) {
$credentials['password'] = Customer::normalizeCredentialDigits(
trim((string) $credentials['password'])
);
}
if (
$provider === 'customer'
&& isset($credentials['mobile'], $credentials['password'])
+13 -6
View File
@@ -500,23 +500,30 @@ class Controller extends BaseController
return self::isMainWalletProduct($productId) ? null : $productId;
}
/** واحد وزن معاملات فلز — از ستینگ unit؛ پیش‌فرض گرم */
/** واحد وزن معاملات فلز — در بورس مس پیش‌فرض کیلوگرم است */
public static function tradeWeightUnit(): string
{
return self::resolveTradeWeightUnit(
app(ConfigService::class)->getString('unit')
);
$value = app(ConfigService::class)->getString('unit');
$resolved = self::resolveTradeWeightUnit($value);
// در بورس مس واحد پایه همیشه کیلوگرم است
if ($resolved === 'گرم' || empty($value)) {
return 'کیلوگرم';
}
return $resolved;
}
public static function resolveTradeWeightUnit(?string $value): string
{
$unit = trim((string) $value);
if ($unit === 'کیلوگرم' || $unit === 'kilogram' || $unit === 'kg') {
if ($unit === 'کیلوگرم' || $unit === 'kg' || $unit === 'kilogram') {
return 'کیلوگرم';
}
return 'گرم';
// در بورس مس واحد مبنا کیلوگرم است
return 'کیلوگرم';
}
public static function weightToGrams(float $value, ?string $fromUnit = null): float
@@ -421,6 +421,9 @@ class CartController extends Controller
'amount' => $product->amount,
'unit' => $product->unit,
'trade_by_quantity' => $product->trade_by_quantity,
'shayegan_item_number' => Product::hasShayeganItemColumn()
? ($product->shayegan_item_number ?? null)
: null,
],
'line' => $lineIndex + 1,
'order' => [
@@ -445,6 +448,14 @@ class CartController extends Controller
report($e);
}
}
if ($config->isShayeganAccounting()) {
try {
app(\App\Http\Controllers\Admin\ShayeganController::class)->storeTrade($payload);
} catch (\Throwable $e) {
report($e);
}
}
}
if ($config->isPargarAccounting()) {
@@ -0,0 +1,89 @@
<?php
namespace App\Http\Controllers\Customer;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use App\Services\CopperConvertRequestService;
use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class CopperConvertRequestController extends Controller
{
public function index(CopperConvertRequestService $service)
{
$customer = auth('customer')->user();
if (!$customer instanceof Customer) {
throw new UnprocessableEntityHttpException('مشتری یافت نشد.');
}
return response()->json($service->listForCustomer($customer));
}
public function store(Request $request, CopperConvertRequestService $service)
{
$customer = auth('customer')->user();
if (!$customer instanceof Customer) {
throw new UnprocessableEntityHttpException('مشتری یافت نشد.');
}
self::assertCustomerIdentityVerified($customer);
if (!$customer->trade_active) {
throw new UnprocessableEntityHttpException('امکان سفارش برای شما غیرفعال است.');
}
$source = (string) $request->input('source');
if (!in_array($source, ['katod', 'maftoul', 'shamsh'], true)) {
throw new UnprocessableEntityHttpException('نوع دارایی نامعتبر است.');
}
$row = $service->submit(
$customer,
$source,
max(0, (int) $request->input('rings15')),
max(0, (int) $request->input('rings25'))
);
return response()->json($row);
}
public function update(Request $request, int $id, CopperConvertRequestService $service)
{
$customer = $this->customer();
self::assertCustomerIdentityVerified($customer);
if (!$customer->trade_active) {
throw new UnprocessableEntityHttpException('امکان سفارش برای شما غیرفعال است.');
}
$source = (string) $request->input('source');
if (!in_array($source, ['katod', 'maftoul', 'shamsh'], true)) {
throw new UnprocessableEntityHttpException('نوع دارایی نامعتبر است.');
}
$row = $service->update(
$customer,
$id,
$source,
max(0, (int) $request->input('rings15')),
max(0, (int) $request->input('rings25'))
);
return response()->json($row);
}
public function destroy(int $id, CopperConvertRequestService $service)
{
$service->remove($this->customer(), $id);
return response()->json(['ok' => true]);
}
private function customer(): Customer
{
$customer = auth('customer')->user();
if (!$customer instanceof Customer) {
throw new UnprocessableEntityHttpException('مشتری یافت نشد.');
}
return $customer;
}
}
@@ -208,7 +208,7 @@ class CustomerController extends Controller
// $tah = new TahesabController();
// $tah->store(["customer_id" => $customer->id]);
$cfg = app(ConfigService::class);
if (!$wasLegal && $cfg->isRegisterJibitVerifyEnabled()) {
if (!$wasLegal && !empty($customer->n_code)) {
$nCodeError = JibitIdentityService::nationalCodeError($customer->n_code);
if ($nCodeError !== null) {
return response()->json([
@@ -226,7 +226,7 @@ class CustomerController extends Controller
]);
return response()->json([
'message' => 'ارتباط با سرویس احراز هویت جیبیت برقرار نشد. اطلاعات پروفایل ذخیره شد اما هویت تأیید نشد.',
'message' => 'ارتباط با سرویس احراز هویت جیبیت برقرار نشد. لطفاً دقایقی دیگر مجدداً تلاش فرمایید.',
'code' => 'jibit_unreachable',
], 422);
}
@@ -257,12 +257,6 @@ class CustomerController extends Controller
'code' => $jibit['code'],
], 422);
}
} elseif (!$customer->is_legal && !$cfg->isRegisterJibitVerifyEnabled()) {
return response()->json([
'ok' => true,
'pending_admin' => true,
'message' => 'اطلاعات کاربری شما ثبت شد و پس از تایید ادمین فعال سازی خواهد شد',
]);
}
return response()->json(true);
} catch (QueryException $e) {
@@ -0,0 +1,53 @@
<?php
namespace App\Http\Controllers\Customer;
use App\Http\Controllers\Controller;
use App\Services\DigipayInstallmentService;
use Illuminate\Http\Request;
class DigipayInstallmentController extends Controller
{
public function __construct(private DigipayInstallmentService $service)
{
}
public function show()
{
$this->ensureEnabled();
return response()->json($this->service->statusFor((int) auth('customer')->id()));
}
public function start()
{
$this->ensureEnabled();
$this->service->markStarted((int) auth('customer')->id());
return response()->json($this->service->statusFor((int) auth('customer')->id()));
}
public function buy(Request $request)
{
$this->ensureEnabled();
$data = $request->validate([
'plan' => 'required|integer|in:4,12',
'amount_toman' => 'required|integer|min:1000',
]);
$result = $this->service->buy(
(int) auth('customer')->id(),
(int) $data['plan'],
(int) $data['amount_toman']
);
return response()->json($result);
}
private function ensureEnabled(): void
{
if (! $this->service->enabled()) {
abort(403, 'خرید اقساطی فعال نیست');
}
}
}
@@ -58,8 +58,8 @@ class PriceTriggerController extends SuperController
return;
}
$productId = $request->input('product_id');
if ($productId === null || $productId === '') {
$productId = $this->normalizeProductId($request->input('product_id'));
if ($productId === null) {
if ($required) {
throw new UnprocessableEntityHttpException('محصول را انتخاب کنید');
}
@@ -69,7 +69,7 @@ class PriceTriggerController extends SuperController
}
$exists = Product::query()
->where('id', (int) $productId)
->where('id', $productId)
->where('active', 1)
->exists();
@@ -77,6 +77,25 @@ class PriceTriggerController extends SuperController
throw new UnprocessableEntityHttpException('محصول نامعتبر است');
}
$request->merge(['product_id' => (int) $productId]);
$request->merge(['product_id' => $productId]);
}
private function normalizeProductId($productId): ?int
{
if (is_array($productId)) {
$productId = $productId['id'] ?? $productId['product_id'] ?? null;
}
if (is_object($productId)) {
$productId = $productId->id ?? null;
}
if ($productId === null || $productId === '' || ! is_numeric($productId)) {
return null;
}
$id = (int) $productId;
return $id > 0 ? $id : null;
}
}
@@ -89,6 +89,7 @@ class WalletController extends Controller
$customer = auth('customer')->user();
$customerId = (int) $customer->id;
$ownerType = (int) $customer->type;
$balanceService->absorbMismatchedOwnerTypeBalances($customerId, $ownerType);
$wallets = Wallet::query()
->where('owner', $customerId)
@@ -370,6 +371,7 @@ class WalletController extends Controller
public function withdraw(Request $request)
{
$customer = auth('customer')->user();
self::assertCustomerIdentityVerified($customer instanceof Customer ? $customer : null);
$data = $request->all();
if (!isset($data['card_id'])) {
return response()->json(['message' => 'لطفا کارت بانکی را وارد کنید'], 422);
@@ -486,6 +488,20 @@ class WalletController extends Controller
}
}
if (app(ConfigService::class)->isShayeganAccounting()) {
try {
app(\App\Http\Controllers\Admin\ShayeganController::class)->wallet([
'customer_id' => auth('customer')->id(),
'value' => $amount,
'direction' => 1,
'withdraw_id' => $Withdraw->id,
'note' => 'برداشت ریالی',
]);
} catch (\Exception $e) {
report($e);
}
}
$companyName = $this->Config('name_fa'); // Company name from configuration
$message = "کاربر $userName با شماره موبایل $userMobile درخواست برداشت مبلغ " . number_format($withdrawAmount) . " ریال را دارد. با تشکر، $companyName";
User::where('send_sms', 1)->get()->each(function ($admin) use ($message) {
@@ -509,6 +525,96 @@ class WalletController extends Controller
return response()->json($Withdraw);
}
public function depositRequest(Request $request)
{
$customer = auth('customer')->user();
if (!$customer) {
throw new UnprocessableEntityHttpException('کاربر یافت نشد.');
}
$request->validate([
'cash' => 'required|numeric|min:1000',
'receipt' => 'required|file|mimes:jpeg,jpg,png,webp,pdf|max:10240',
'tracked_number' => 'nullable|string|max:100',
'extra_note' => 'nullable|string|max:500',
], [
'cash.required' => 'مبلغ واریزی الزامی است.',
'cash.numeric' => 'مبلغ واریزی باید به صورت عددی باشد.',
'cash.min' => 'حداقل مبلغ واریزی معتبر نیست.',
'receipt.required' => 'بارگذاری تصویر فیش واریزی الزامی است.',
'receipt.file' => 'فایل فیش ارسالی نامعتبر است.',
'receipt.mimes' => 'فرمت فیش واریزی باید یکی از فرمت‌های jpg, png, webp یا pdf باشد.',
'receipt.max' => 'حجم فایل فیش واریزی نباید بیش از ۱۰ مگابایت باشد.',
]);
$uploaded = $request->file('receipt');
$now = verta();
$dirPath = 'receipts/' . $now->year . '/' . sprintf('%02d', $now->month);
$disk = \Illuminate\Support\Facades\Storage::disk('public');
if (! $disk->exists($dirPath)) {
$disk->makeDirectory($dirPath);
}
$ext = $uploaded->getClientOriginalExtension() ?: 'jpg';
$fileName = md5(time() . '_' . $uploaded->getClientOriginalName() . '_' . $customer->id) . '.' . $ext;
$stored = $disk->putFileAs($dirPath, $uploaded, $fileName);
if (! $stored) {
throw new UnprocessableEntityHttpException('خطا در ذخیره تصویر فیش واریزی.');
}
$relativePath = 'storage/' . $stored;
try {
\App\Models\File::create([
'original_name' => $uploaded->getClientOriginalName(),
'ext' => $ext,
'title' => 'فیش واریز ' . ($customer->name ?? ''),
'has_thumb' => false,
'size' => $uploaded->getSize(),
'src' => $relativePath,
'user_id' => $customer->id,
]);
} catch (\Throwable $e) {
report($e);
}
$nationalCode = trim((string) ($customer->n_code ?? ''));
$withdraw = Withdraw::create([
'customer_id' => $customer->id,
'cash' => (float) $request->cash,
'gold' => 0,
'type' => 1,
'sts' => 1,
'tracked_number' => $request->tracked_number ? trim((string) $request->tracked_number) : null,
'deposit_identifier' => $nationalCode ?: null,
'receipt' => $relativePath,
'extra_note' => $request->extra_note ? trim((string) $request->extra_note) : null,
'note' => 'درخواست واریز نقدی (فیش بانکی)',
'date_at' => now(),
]);
try {
$companyName = $this->Config('name_fa');
$amountFormatted = number_format((int) $request->cash);
$userName = $customer->name ?? 'مشتری';
$userMobile = $customer->mobile ?? '';
$message = "کاربر $userName با شماره موبایل $userMobile درخواست واریز مبلغ {$amountFormatted} ریال با شناسه واریز {$nationalCode} ثبت نمود. با تشکر، $companyName";
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'));
}
});
} catch (\Throwable $e) {
report($e);
}
return response()->json([
'message' => 'درخواست واریز شما با موفقیت ثبت شد و پس از بررسی تایید خواهد شد.',
'withdraw' => $withdraw->loadMissing('customer'),
]);
}
private function formatDeliveryQuantity(float $value): string
{
$rounded = round($value, 3);
@@ -692,6 +798,7 @@ class WalletController extends Controller
$this->validateWithdrawAmount((int) $data['value']);
$customer = auth('customer')->user();
self::assertCustomerIdentityVerified($customer instanceof Customer ? $customer : null);
$otp = rand(1000, 9999);
$customer->token_sms = $otp;
$customer->save();
@@ -122,7 +122,9 @@ class SingleOrderController extends Controller
// Check if the user wants to transact with a product or non-product (gold)
if (isset($data['product_id']) and $data['product'] = Product::find($data['product_id'])) {
$config->assertProductTradingOpen($data['product']);
if (empty($data['quote_unit_price'])) {
$config->assertProductTradingOpen($data['product']);
}
// Check if the user wants to buy
if ($data['direction'] == 1) {
@@ -353,6 +355,7 @@ class SingleOrderController extends Controller
$data['total_price'] = $data['amount'] * $data['price'];
$data['payment_amount'] = $data['total_price'] + $data['service_charge_price'];
$data['fee_asset'] = 'rial';
$this->applyConvertQuote($data);
$this->enforceProductOrderLimits($data, (float) $data['total_price']);
@@ -366,7 +369,7 @@ class SingleOrderController extends Controller
if ($wallet->cash < $data['payment_amount']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
if (!$data['product']['open_buy']) {
if (empty($data['quote_unit_price']) && !$data['product']['open_buy']) {
throw new UnprocessableEntityHttpException('خرید این محصول در این لحظه مقدور نمیباشد');
}
$this->syncOrderProfitFields($data);
@@ -647,6 +650,7 @@ class SingleOrderController extends Controller
$data['total_price'] = $data['amount'] * $data['price'] - $data['service_charge_price'];
$data['payment_amount'] = $data['total_price'];
$data['fee_asset'] = 'rial';
$this->applyConvertQuote($data);
if ($data['total_price'] < 0) {
throw new UnprocessableEntityHttpException(
'مبلغ دریافتی فروش پس از کارمزد منفی شد. درصد کارمزد سفارش را بررسی کنید (باید اعشاری باشد؛ مثلاً ۰٫۰۱ برای ۱٪).'
@@ -659,7 +663,7 @@ class SingleOrderController extends Controller
if ($wallet_interface_product->wallet->gold < $data['number']) {
throw new UnprocessableEntityHttpException('موجودی شما کمتر از میزان سفارش است');
}
if (!$data['product']['open_sell']) {
if (empty($data['quote_unit_price']) && !$data['product']['open_sell']) {
throw new UnprocessableEntityHttpException('فروش این محصول در این لحظه مقدور نمیباشد');
}
$this->syncOrderProfitFields($data);
@@ -1403,6 +1407,32 @@ class SingleOrderController extends Controller
* اگر قیمت واحد سفارش حدود قیمت مثقال باشد، به قیمت هر گرم برگردان.
* جلوگیری از ۱۰ میلیون تومان → ۱۰۵ سوت وقتی مثقال در فیلد «هر گرم» نشسته.
*/
/** قیمت قفل‌شدهٔ تبدیل: تعداد × قیمت واحد، بدون کارمزد و بدون ضرب در وزن واحد. */
private function applyConvertQuote(array &$data): void
{
$quote = (float) ($data['quote_unit_price'] ?? 0);
if ($quote <= 0) {
return;
}
$number = (float) ($data['number'] ?? 0);
$data['amount'] = $number;
$data['price'] = $quote;
$data['price_original'] = $quote;
$data['difference'] = 0;
$data['fee'] = 0;
$data['total_fee'] = 0;
$data['service_charge'] = 0;
$data['service_charge_price'] = 0;
$data['service_charge_percentage'] = 0;
$data['total_amount'] = $number;
$data['total_price'] = $number * $quote;
$data['payment_amount'] = $data['total_price'];
$data['fee_asset'] = 'rial';
$data['fee_free'] = true;
$data['first_buy'] = false;
}
private function ensureOrderUnitPriceIsPerGram(array &$data): void
{
$live = $this->liveGramQuoteRial();
@@ -2362,6 +2392,14 @@ class SingleOrderController extends Controller
}
}
if ($config->isShayeganAccounting()) {
try {
$data['shayegan'] = app(\App\Http\Controllers\Admin\ShayeganController::class)->storeTrade($data);
} catch (\Throwable $e) {
report($e);
}
}
if (isset($data['order'])) {
try {
app(\App\Services\ColleagueAccountingService::class)->recordCoveredTrade($data);
@@ -53,6 +53,7 @@ class WalletPaymentController extends Controller
}
$customer = auth('customer')->user();
self::assertCustomerIdentityVerified($customer instanceof \App\Models\Customer ? $customer : null);
$withdraw = Withdraw::create([
'customer_id' => $customer->id,
'cash' => $amount,
@@ -72,6 +72,7 @@ class paypingController extends Controller
public function startTransation(Request $request)
{
$user = auth()->user();
self::assertCustomerIdentityVerified($user instanceof \App\Models\Customer ? $user : null);
$finalPriseP = $request->value;
if ($user->id == 4) {
$finalPriseP = 10700;
+1
View File
@@ -71,5 +71,6 @@ class Kernel extends HttpKernel
'sms.panel.super' => \App\Http\Middleware\EnsureSmsPanelSuperAdmin::class,
'customer.active' => \App\Http\Middleware\EnsureCustomerIsActive::class,
'superadmin.remote' => \App\Http\Middleware\EnsureSuperAdminRemoteToken::class,
'admin.page' => \App\Http\Middleware\EnsureAdminPageAccess::class,
];
}
@@ -0,0 +1,54 @@
<?php
namespace App\Http\Middleware;
use App\Services\AdminPageAccess;
use Closure;
use Illuminate\Http\Request;
class EnsureAdminPageAccess
{
public function handle(Request $request, Closure $next)
{
$user = auth('user')->user();
if (!$user || AdminPageAccess::hasFullAccess($user)) {
return $next($request);
}
$path = strtolower(trim($request->path(), '/'));
if (str_starts_with($path, 'admin/')) {
$path = substr($path, strlen('admin/'));
}
if ($path === 'me' || $path === 'me/update') {
return $next($request);
}
$method = strtoupper($request->method());
$action = null;
if (in_array($method, ['GET', 'HEAD', 'OPTIONS'], true)) {
if (preg_match('#/active(/|$)#', $path)) {
$action = 'edit';
}
} elseif ($method === 'DELETE') {
$action = 'delete';
} elseif (in_array($method, ['PUT', 'PATCH'], true)) {
$action = 'edit';
} elseif ($method === 'POST' && !AdminPageAccess::isReadPost($path)) {
$action = 'edit';
}
if ($action === null) {
return $next($request);
}
$page = (string) $request->header('X-Admin-Page', '');
if ($page === '' || !AdminPageAccess::allows($user, $page, $action)) {
$message = $action === 'delete'
? 'شما مجوز حذف در این صفحه را ندارید'
: 'شما مجوز ویرایش در این صفحه را ندارید';
return response()->json(['message' => $message], 403);
}
return $next($request);
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CopperConvertRequest extends Model
{
protected $fillable = [
'customer_id',
'status',
'source',
'source_product_id',
'asset_unit',
'consumed_amount',
'leftover_amount',
'source_unit_price',
'wire15_product_id',
'wire15_rings',
'wire15_unit_price',
'wire25_product_id',
'wire25_rings',
'wire25_unit_price',
'sell_order_id',
'buy15_order_id',
'buy25_order_id',
'admin_id',
];
protected $casts = [
'consumed_amount' => 'float',
'leftover_amount' => 'float',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
+49 -2
View File
@@ -5,6 +5,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
use Rooyesh\Wallet\models\Wallet;
@@ -129,12 +130,32 @@ class Customer extends Authenticatable implements JWTSubject
->first();
}
// hash password
// hash password — ارقام فارسی/عربی را قبل از هش انگلیسی کن (لاگین اپ هم انگلیسی می‌فرستد)
public function setPasswordAttribute($value){
if ($value === null || $value === '') {
return;
}
$this->attributes['password'] = Hash::make($value);
$value = trim((string) $value);
if ($value === '') {
return;
}
// اگر از قبل bcrypt است دوباره هش نکن
if (preg_match('/^\$2[ayb]\$.{56}$/', $value) === 1) {
$this->attributes['password'] = $value;
return;
}
$this->attributes['password'] = Hash::make(self::normalizeCredentialDigits($value));
}
/** ارقام فارسی/عربی → لاتین (برای رمز و موبایل در احراز هویت) */
public static function normalizeCredentialDigits(string $value): string
{
$persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
$arabic = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];
$latin = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
return str_replace(array_merge($persian, $arabic), array_merge($latin, $latin), $value);
}
public function setBirthDateAttribute($value): void
@@ -180,6 +201,16 @@ class Customer extends Authenticatable implements JWTSubject
protected static function booted(): void
{
// کد کاربری = customers.id. AUTO_INCREMENT بعد از UPDATE دستی id پایین نمی‌آید
// (مثلاً ۱..۲۳ اصلاح شد ولی شمارنده روی ۵۵۱ ماند). همیشه اولین id خالی.
static::creating(function (self $customer) {
if (! empty($customer->id)) {
return;
}
$customer->id = self::nextSequentialId();
$customer->incrementing = false;
});
static::saving(function (self $customer) {
$mobile = self::normalizeMobile($customer->mobile);
if ($mobile === null) {
@@ -191,6 +222,22 @@ class Customer extends Authenticatable implements JWTSubject
});
}
/** کوچک‌ترین id آزاد، شامل ردیف‌های soft-deleted تا PK تکراری نشود. */
public static function nextSequentialId(): int
{
$table = (new static)->getTable();
$row = DB::selectOne(
"SELECT t.id + 1 AS next_id
FROM (SELECT 0 AS id UNION ALL SELECT id FROM `{$table}`) t
LEFT JOIN `{$table}` c ON c.id = t.id + 1
WHERE c.id IS NULL
ORDER BY t.id
LIMIT 1"
);
return max(1, (int) ($row->next_id ?? 1));
}
public static function normalizeMobile(?string $mobile): ?string
{
$digits = preg_replace('/\D+/', '', trim((string) $mobile));
+7
View File
@@ -4,6 +4,7 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Customer;
use App\Models\GiftCardCodes;
class GiftCard extends Model
@@ -15,6 +16,7 @@ class GiftCard extends Model
protected $fillable = [
'customer_id',
'use_once',
'show_in_app',
'count',
'amount',
'total',
@@ -33,6 +35,11 @@ class GiftCard extends Model
return $this->hasMany(GiftCardCodes::class, 'giftcard_id', 'id');
}
public function customer()
{
return $this->belongsTo(Customer::class, 'customer_id', 'id')->select('id', 'name', 'mobile');
}
static $STS = [
1 => "فعال",
2 => "تمام شده",
+5
View File
@@ -40,4 +40,9 @@ class GiftCardCodes extends Model
return $this->belongsTo(Customer::class, 'assigned_to', 'id')->select('id', 'name', 'mobile');
}
public function giftcard()
{
return $this->belongsTo(GiftCard::class, 'giftcard_id', 'id');
}
}
+20
View File
@@ -33,6 +33,7 @@ class Product extends Model
private static ?bool $karatColumnExists = null;
private static ?bool $tvPriceFormulaColumnsExist = null;
private static ?bool $priceFormulaColumnsExist = null;
private static ?bool $shayeganItemColumnExists = null;
protected static function booted(): void
{
@@ -104,9 +105,27 @@ class Product extends Model
$product->attributes['tv_price_formula']
);
}
if (!static::hasShayeganItemColumn()) {
unset($product->attributes['shayegan_item_number']);
}
});
}
public static function hasShayeganItemColumn(): bool
{
if (static::$shayeganItemColumnExists !== null) {
return static::$shayeganItemColumnExists;
}
try {
static::$shayeganItemColumnExists = Schema::hasColumn((new static)->getTable(), 'shayegan_item_number');
} catch (\Throwable) {
static::$shayeganItemColumnExists = false;
}
return static::$shayeganItemColumnExists;
}
public static function hasTvPriceFormulaColumns(): bool
{
if (static::$tvPriceFormulaColumnsExist !== null) {
@@ -497,6 +516,7 @@ class Product extends Model
'unit', // The unit of the item.
'group_type', // The unit of the item.
'finance_p_name', // کد کار زرین (idKar)
'shayegan_item_number', // ItemNumber در فاکتور شایگان
'file_id', // The ID of the associated file.
'can_canceled', // Whether the record can be canceled (boolean).
'active', // The active status of the record (boolean).
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Shayegan extends Model
{
protected $table = 'shayegan';
protected $guarded = [];
protected $casts = [
'date' => 'datetime',
'amount' => 'float',
];
public function customer(): BelongsTo
{
return $this->belongsTo(Customer::class);
}
}
+59
View File
@@ -0,0 +1,59 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class ShayeganInboundCharge extends Model
{
use HasFactory;
protected $table = 'shayegan_inbound_charges';
protected $fillable = [
'customer_id',
'customer_tafsil',
'shayegan_number',
'amount',
'description',
'source',
'status',
'raw_data',
'approved_by',
'approved_at',
'rejected_by',
'rejected_at',
'reject_reason',
'withdraw_id',
'transaction_id',
];
protected $casts = [
'amount' => 'float',
'approved_at' => 'datetime',
'rejected_at' => 'datetime',
'raw_data' => 'array',
];
public function customer()
{
return $this->belongsTo(Customer::class, 'customer_id');
}
public function approver()
{
return $this->belongsTo(User::class, 'approved_by');
}
public function rejecter()
{
return $this->belongsTo(User::class, 'rejected_by');
}
public function withdraw()
{
return $this->belongsTo(Withdraw::class, 'withdraw_id');
}
}
+3 -1
View File
@@ -35,7 +35,8 @@ class User extends Authenticatable implements JWTSubject
'send_sms',
'avatar_id',
'email',
'sts'
'sts',
'page_access',
];
/**
@@ -56,6 +57,7 @@ class User extends Authenticatable implements JWTSubject
protected $casts = [
'active'=> 'boolean',
'send_sms'=> 'boolean',
'page_access' => 'array',
];
/**
* Get the identifier that will be stored in the subject claim of the JWT.
+22 -5
View File
@@ -23,15 +23,27 @@ class Withdraw extends Model
'date_at',
'sts',
'type',
'receipt',
'deposit_identifier',
'reject_reason',
];
protected $appends = [
'receipt_url',
];
public function getReceiptUrlAttribute(): ?string
{
return File::publicUrl($this->receipt);
}
static $STS = [
1 => 'در انتظار واریز',
1 => 'در انتظار تایید',
2 => 'واریز شد',
4 => 'واریز توسط ادمین',
5 => 'پاداش معرفی',
9 => 'سود زیر مجموعه',
3 => 'واریز ناموفق',
3 => 'رد شده',
50 => 'در انتظار ارسال',
51 => 'ارسال شده',
52 => 'لغو شده',
@@ -40,7 +52,7 @@ class Withdraw extends Model
public function customer()
{
return $this->belongsTo('App\Models\Customer')->select(['id', 'name', 'mobile']);
return $this->belongsTo('App\Models\Customer')->select(['id', 'name', 'mobile', 'n_code']);
}
public function address()
@@ -109,14 +121,19 @@ class Withdraw extends Model
});
}
/** واریز: ورود پول/طلا به کیف (درگاه، شارژ ادمین، پاداش) — بدون کسر ادمین */
/** واریز: ورود پول/طلا به کیف (درگاه، شارژ ادمین، پاداش، کارت هدیه ریالی) — بدون کسر ادمین */
public static function scopeDeposits($query)
{
return $query->where(function ($q) {
$q->where(function ($inner) {
$inner->where('note', 'like', '%واریز%')
->orWhere('type', 1)
->orWhereIn('sts', [4, 5, 9]);
->orWhereIn('sts', [4, 5, 9])
// کارت هدیه ریالی (نه فلزی/مسی)
->orWhere(function ($gift) {
$gift->where('note', 'like', '%کارت هدیه%')
->where('cash', '>', 0);
});
})->where(function ($excludeWithdrawNotes) {
$excludeWithdrawNotes->whereNull('note')
->orWhere('note', 'not like', '%برداشت%');
+1
View File
@@ -14,5 +14,6 @@ class CustomerObserver
app(TahesabSyncService::class)->registerOnCreate($customer);
app(ZarinSyncService::class)->registerOnCreate($customer);
app(PargarSyncService::class)->registerOnCreate($customer);
app(\App\Services\ShayeganSyncService::class)->registerOnCreate($customer);
}
}
+8
View File
@@ -59,5 +59,13 @@ class AccountingWalletPush
report($e);
}
}
if ($config->isShayeganAccounting()) {
try {
app(\App\Http\Controllers\Admin\ShayeganController::class)->walletGold($payload);
} catch (\Throwable $e) {
report($e);
}
}
}
}
+302
View File
@@ -0,0 +1,302 @@
<?php
namespace App\Services;
use App\Models\User;
class AdminPageAccess
{
public const DEPLOY_ADMIN_MOBILE_CORE = '9128081392';
/** کلید برگ‌ها؛ با ADMIN_PAGE_TREE در ادمین یکی بماند. */
public const LEAF_KEYS = [
'dashboardMain',
'customerMain_limitedOrder',
'customerMain_archive',
'customerMain_online',
'customerMain_specialPrice',
'customerMain_goldCredit',
'customerMain_digipayInstallment',
'productsMain_limitedOrder',
'productsMain_archive',
'productsMain_categories',
'ordersMain',
'copperConvertMain',
'transactionsMain',
'accountsMain',
'walletMain',
'physicalWithdrawMain',
'withdrawMain',
'pricingMain',
'priceTriggers',
'conditionalOrders',
'colleagueOrdersMain',
'accountingMain',
'supportMain',
'websiteLandingSite',
'websiteLandingHeader',
'websiteLandingHero',
'websiteLandingLivePrice',
'websiteLandingCalculator',
'websiteLandingFeature',
'websiteLandingSteps',
'websiteLandingTrust',
'websiteLandingFaq',
'websiteLandingBottomCta',
'websiteLandingFooter',
'configuration',
'captureSitesMain',
'advancedConfiguration',
'smsPanelMain',
'tradingHours',
'banners',
'appNotifications',
'automations',
'smsMain',
'giftCardMain',
'discounts',
'usersMain',
];
/** کلید عملیات ستون هر صفحه؛ با PAGE_TABLE_ACTIONS ادمین یکی بماند. */
public const ACTIONS = [
'customerMain_limitedOrder' => ['charge', 'tahesab', 'zarin', 'pargar', 'accountingCode', 'info', 'edit', 'referral', 'sms', 'approve', 'archive', 'active', 'trade'],
'customerMain_archive' => ['restore', 'info'],
'customerMain_specialPrice' => ['edit', 'toggle', 'delete'],
'customerMain_goldCredit' => ['detail', 'edit', 'approve', 'reject'],
'customerMain_digipayInstallment' => ['edit'],
'productsMain_limitedOrder' => ['buy', 'sell', 'list', 'tv', 'edit', 'archive'],
'productsMain_archive' => ['restore', 'info'],
'ordersMain' => ['info'],
'transactionsMain' => ['info'],
'accountsMain' => ['toggle', 'delete'],
'walletMain' => ['info'],
'physicalWithdrawMain' => ['amount', 'approve', 'status', 'factor'],
'withdrawMain' => ['confirm', 'factor', 'status', 'weight', 'tahesab', 'zarin'],
'pricingMain' => ['details'],
'priceTriggers' => ['edit', 'toggle', 'delete'],
'conditionalOrders' => ['edit', 'toggle', 'delete'],
'accountingMain' => ['doc', 'register', 'send'],
'appNotifications' => ['recipients', 'readers', 'edit', 'toggle', 'delete'],
'automations' => ['preview', 'log', 'edit', 'toggle', 'delete'],
'giftCardMain' => ['info', 'codes', 'usageReport', 'edit', 'delete'],
'discounts' => ['edit'],
'usersMain' => ['info', 'edit', 'delete'],
];
private const ALIASES = [
'dashboard' => 'dashboardMain',
'main' => 'dashboardMain',
'orders' => 'ordersMain',
'copperConvert' => 'copperConvertMain',
'transactions' => 'transactionsMain',
'support' => 'supportMain',
'factor' => 'withdrawMain',
];
public static function hasFullAccess(?User $user): bool
{
if (!$user) {
return false;
}
if (self::isDeployAdmin($user)) {
return true;
}
$access = $user->page_access;
return $access === null;
}
public static function isDeployAdmin(?User $user): bool
{
if (!$user) {
return false;
}
return self::normalizeMobile($user->mobile ?? '') === self::DEPLOY_ADMIN_MOBILE_CORE;
}
/**
* null = دسترسی کامل. آرایه = فقط کلیدهای شناخته‌شده.
*/
public static function normalize($value): ?array
{
if ($value === null || $value === '' || $value === false) {
return null;
}
if (is_string($value)) {
$decoded = json_decode($value, true);
$value = is_array($decoded) ? $decoded : null;
if ($value === null) {
return null;
}
}
if (!is_array($value)) {
return null;
}
$out = [];
foreach (self::LEAF_KEYS as $key) {
$row = $value[$key] ?? null;
if (!is_array($row)) {
continue;
}
$view = self::toBool($row['view'] ?? false);
$edit = self::toBool($row['edit'] ?? false);
$delete = self::toBool($row['delete'] ?? false);
$actions = null;
if (is_array($row['actions'] ?? null)) {
$actions = [];
foreach (self::ACTIONS[$key] ?? [] as $actionKey) {
$actions[$actionKey] = self::toBool($row['actions'][$actionKey] ?? false);
}
if (array_key_exists('edit', $actions)) {
$edit = $actions['edit'];
}
if (array_key_exists('delete', $actions)) {
$delete = $actions['delete'];
}
}
if ($edit || $delete || ($actions && in_array(true, $actions, true))) {
$view = true;
}
if (!$view) {
$edit = false;
$delete = false;
if (is_array($actions)) {
foreach ($actions as $actionKey => $enabled) {
$actions[$actionKey] = false;
}
}
}
if (!$view && !$edit && !$delete && !($actions && in_array(true, $actions, true))) {
continue;
}
$stored = [
'view' => $view,
'edit' => $edit,
'delete' => $delete,
];
if (is_array($actions) && $actions) {
$stored['actions'] = $actions;
}
$out[$key] = $stored;
}
return $out;
}
public static function hasAnyView(?array $access): bool
{
if ($access === null) {
return true;
}
foreach ($access as $row) {
if (!empty($row['view'])) {
return true;
}
}
return false;
}
public static function allows(?User $user, string $routeName, string $action): bool
{
if (self::hasFullAccess($user)) {
return true;
}
$leaf = self::ALIASES[$routeName] ?? $routeName;
if (!in_array($leaf, self::LEAF_KEYS, true)) {
return false;
}
$access = $user->page_access;
if (!is_array($access)) {
return false;
}
$row = $access[$leaf] ?? null;
if (!is_array($row)) {
return false;
}
if ($action === 'delete' || $action === 'edit') {
$actions = $row['actions'] ?? null;
if (is_array($actions) && array_key_exists($action, $actions)) {
return !empty($actions[$action]);
}
return !empty($row[$action]);
}
return !empty($row['view']);
}
public static function isReadPost(string $path): bool
{
$path = strtolower(trim($path, '/'));
if (str_contains($path, '/table') || substr($path, -5) === 'table') {
return true;
}
if (str_contains($path, 'preview')) {
return true;
}
if (str_contains($path, 'get_customer_list') || str_contains($path, 'products-by-categories')) {
return true;
}
if (str_contains($path, 'mande-by-codes')) {
return true;
}
$exact = [
'getbalance',
'prices',
'prices/chart',
'gateway',
'finance',
'check_card',
'dashboard',
'dashboard/finance',
'dashboard/customer/all_sell',
'dashboard/customer/single/all_sell',
'dashboard/customer/flow',
'dashboard/customer/order-peak-hours',
'dashboard/profit-conversions',
'dashboard/montzar-reconcile',
];
if (in_array($path, $exact, true)) {
return true;
}
if (preg_match('#^customers/\d+/(referrals|funds|piggy-funds)$#', $path)) {
return true;
}
if (preg_match('#^customers/\d+/assets/\d+/(piggy-funds|transactions)$#', $path)) {
return true;
}
if (preg_match('#^customers/\d+/piggy-funds/\d+/transactions$#', $path)) {
return true;
}
if (preg_match('#^customers/\d+/gold_credit/installments$#', $path)) {
return true;
}
if (preg_match('#^chat/(focus|unfocus|ensure-webhook)$#', $path)) {
return true;
}
return false;
}
private static function toBool($value): bool
{
if (is_bool($value)) {
return $value;
}
if (is_numeric($value)) {
return (int) $value === 1;
}
$text = strtolower(trim((string) $value));
return in_array($text, ['1', 'true', 'yes', 'on'], true);
}
private static function normalizeMobile(?string $mobile): string
{
$digits = preg_replace('/\D+/', '', (string) $mobile) ?? '';
if (str_starts_with($digits, '98') && strlen($digits) >= 12) {
$digits = substr($digits, 2);
}
if (strlen($digits) === 11 && str_starts_with($digits, '0')) {
$digits = substr($digits, 1);
}
return $digits;
}
}
+63 -20
View File
@@ -26,6 +26,10 @@ class AssetSummaryService
public function buildForCustomer(int $customerId, int $ownerType, bool $includeInactiveProducts = false): array
{
if ($customerId > 0 && $ownerType > 0) {
$this->walletBalanceService->absorbMismatchedOwnerTypeBalances($customerId, $ownerType);
}
$catalogQuery = Product::query()->with('file');
if (!$includeInactiveProducts) {
$catalogQuery->where('active', 1);
@@ -148,11 +152,17 @@ class AssetSummaryService
float $assetsRialValue,
float $totalRialValue
): array {
$goldMetal = collect($metalTotals)->first(fn (array $row) => (int) ($row['metal_id'] ?? 0) === 1);
$goldWeight = (float) ($goldMetal['total_weight'] ?? 0);
$liveGoldPrice = $this->resolveLivePricePerUnit(1);
$goldRialValue = $goldWeight > 0 && $liveGoldPrice > 0
? round($goldWeight * $liveGoldPrice, 0)
$mainMetalId = $this->walletBalanceService->resolveMainWalletMetalId();
$primaryMetal = collect($metalTotals)->first(fn (array $row) => (int) ($row['metal_id'] ?? 0) === (int) $mainMetalId)
?? collect($metalTotals)->first(fn (array $row) => (int) ($row['metal_id'] ?? 0) === 3)
?? collect($metalTotals)->first(fn (array $row) => (int) ($row['metal_id'] ?? 0) === 1)
?? collect($metalTotals)->first();
$activeMetalId = (int) ($primaryMetal['metal_id'] ?? $mainMetalId);
$metalWeight = (float) ($primaryMetal['total_weight'] ?? 0);
$livePrice = $this->resolveLivePricePerUnit($activeMetalId);
$metalRialValue = $metalWeight > 0 && $livePrice > 0
? round($metalWeight * $livePrice, 0)
: 0.0;
$averageBuyPrice = null;
@@ -161,7 +171,7 @@ class AssetSummaryService
$unrealizedProfitPercent = null;
$unrealizedProfitGold = null;
if ($goldWeight > 0) {
if ($metalWeight > 0) {
$buyOrders = Order::query()
->where('customer_id', $customerId)
->where('direction', 1)
@@ -174,14 +184,14 @@ class AssetSummaryService
if ($totalBought > 0 && $weightedSum > 0) {
$averageBuyPrice = round($weightedSum / $totalBought, 0);
$costBasisRial = round($averageBuyPrice * $goldWeight, 0);
$unrealizedProfitRial = round($goldRialValue - $costBasisRial, 0);
$costBasisRial = round($averageBuyPrice * $metalWeight, 0);
$unrealizedProfitRial = round($metalRialValue - $costBasisRial, 0);
if ($costBasisRial > 0) {
$unrealizedProfitPercent = round(($unrealizedProfitRial / $costBasisRial) * 100, 2);
}
// سود طلایی: همان سود ریالی تبدیل‌شده به وزن طلا با قیمت زندهٔ امروز
if ($liveGoldPrice > 0) {
$unrealizedProfitGold = round($unrealizedProfitRial / $liveGoldPrice, 4);
// سود وزنی: همان سود ریالی تبدیل‌شده به وزن فلز با قیمت زندهٔ امروز
if ($livePrice > 0) {
$unrealizedProfitGold = round($unrealizedProfitRial / $livePrice, 4);
}
}
}
@@ -190,14 +200,17 @@ class AssetSummaryService
'total_rial_value' => round($totalRialValue, 0),
'cash_rial' => round($cashWallet, 0),
'metal_rial_value' => round($assetsRialValue, 0),
'gold_weight' => round($goldWeight, 3),
'gold_rial_value' => $goldRialValue,
'gold_weight' => round($metalWeight, 3),
'gold_rial_value' => $metalRialValue,
'copper_weight' => round($metalWeight, 3),
'copper_rial_value' => $metalRialValue,
'average_buy_price' => $averageBuyPrice,
'cost_basis_rial' => $costBasisRial,
'unrealized_profit_rial' => $unrealizedProfitRial,
'unrealized_profit_percent' => $unrealizedProfitPercent,
'unrealized_profit_gold' => $unrealizedProfitGold,
'live_gold_price' => round($liveGoldPrice, 0),
'live_gold_price' => round($livePrice, 0),
'live_copper_price' => round($livePrice, 0),
];
}
@@ -717,6 +730,8 @@ class AssetSummaryService
$meltedWeight = round(Controller::gramsToTradeUnit($meltedGrams), 3);
$totalWeight = round($productWeight + $meltedWeight, 3);
$metalUnit = ((int) $metalId === 3 || $weightUnit === 'کیلوگرم') ? 'کیلوگرم' : $weightUnit;
$totals[] = [
'metal_id' => (int) $metalId,
'metal_label' => self::METAL_LABELS[$metalId] ?? 'فلز',
@@ -724,7 +739,7 @@ class AssetSummaryService
'product_weight' => $productWeight,
'melted_weight' => $meltedWeight,
'total_weight' => $totalWeight,
'unit' => $weightUnit,
'unit' => $metalUnit,
];
}
@@ -741,11 +756,9 @@ class AssetSummaryService
return 0.0;
}
if (count($catalogMetalIds) === 1) {
return (int) $catalogMetalIds[0] === (int) $metalId ? $mainWalletGrams : 0.0;
}
$mainMetalId = $this->walletBalanceService->resolveMainWalletMetalId();
return (int) $metalId === 1 ? $mainWalletGrams : 0.0;
return (int) $metalId === (int) $mainMetalId ? $mainWalletGrams : 0.0;
}
/**
@@ -795,8 +808,33 @@ class AssetSummaryService
private function resolveLivePricePerUnit(int $metalId): float
{
$prices = app(ProductDisplayPriceService::class);
$mainMetalId = $this->walletBalanceService->resolveMainWalletMetalId();
if ($metalId === 3 || $metalId === $mainMetalId) {
$copperProduct = Product::query()
->where('active', 1)
->where('metal_id', $metalId)
->orderBy('id')
->first();
if ($copperProduct) {
$base = (float) $prices->resolveOrderBasePrice($copperProduct);
if ($base > 0) {
return $base;
}
}
$live = (float) $prices->resolveAppBasePrice();
if ($live > 0) {
return $live;
}
return (float) (Price::latest('id')->value('price') ?? 0);
}
if ($metalId === 1) {
$live = (int) app(ProductDisplayPriceService::class)->resolveAppBasePrice();
$live = (int) $prices->resolveAppBasePrice();
if ($live > 0) {
return (float) $live;
}
@@ -815,6 +853,11 @@ class AssetSummaryService
return 0.0;
}
$base = (float) $prices->resolveOrderBasePrice($product);
if ($base > 0) {
return $base;
}
$unitPrice = $this->productDisplayUnitPrice($product);
$amount = (float) ($product->amount ?? 1);
+11 -14
View File
@@ -1261,6 +1261,7 @@ class ConfigService
public const ACCOUNTING_TAHESAB = 'tahesab';
public const ACCOUNTING_PARGAR = 'pargar';
public const ACCOUNTING_ZARIN = 'zarin';
public const ACCOUNTING_SHAYEGAN = 'shayegan';
public function isConditionalOrderEnabled(): bool
{
@@ -1311,22 +1312,13 @@ class ConfigService
return max(0, $this->getInt('fee_conditional_order', 0));
}
/** none | tahesab | pargar | zarin — از setting accounting_provider */
/**
* بورس مس: حسابداری بیرونی همیشه شایگان است (مستقل از accounting_provider / legacy flags).
* ارسال واقعی فقط وقتی shayegan_* در settings کامل باشد (ShayeganSyncService::isSyncEnabled).
*/
public function accountingProvider(): string
{
$provider = strtolower(trim($this->getString('accounting_provider', '')));
if (in_array($provider, [self::ACCOUNTING_NONE, self::ACCOUNTING_TAHESAB, self::ACCOUNTING_PARGAR, self::ACCOUNTING_ZARIN], true)) {
return $provider;
}
if ($this->getString('send_to_pargar', 'false') === 'true') {
return self::ACCOUNTING_PARGAR;
}
if ($this->getString('send_to_tahesab', 'false') === 'true') {
return self::ACCOUNTING_TAHESAB;
}
return self::ACCOUNTING_NONE;
return self::ACCOUNTING_SHAYEGAN;
}
public function isTahesabAccounting(): bool
@@ -1344,6 +1336,11 @@ class ConfigService
return $this->accountingProvider() === self::ACCOUNTING_ZARIN;
}
public function isShayeganAccounting(): bool
{
return $this->accountingProvider() === self::ACCOUNTING_SHAYEGAN;
}
/**
* Hostname for WebOTP SMS (@domain #code) and other public links.
* Prefer settings.app_url (دامنهٔ اپ کاربر) over the API request host —
@@ -0,0 +1,427 @@
<?php
namespace App\Services;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Single\SingleOrderController;
use App\Models\CopperConvertRequest;
use App\Models\Customer;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class CopperConvertRequestService
{
public function submit(Customer $customer, string $source, int $rings15, int $rings25): CopperConvertRequest
{
if ($rings15 < 1 && $rings25 < 1) {
throw new UnprocessableEntityHttpException('حداقل یک حلقه انتخاب کنید.');
}
$pending = CopperConvertRequest::query()
->where('customer_id', $customer->id)
->where('status', 'pending')
->exists();
if ($pending) {
throw new UnprocessableEntityHttpException('یک درخواست تبدیل در انتظار تأیید دارید.');
}
$quote = $this->quote($customer, $source, $rings15, $rings25);
return CopperConvertRequest::query()->create(
$this->quoteAttributes($customer, $source, $rings15, $rings25, $quote)
);
}
public function update(Customer $customer, int $id, string $source, int $rings15, int $rings25): CopperConvertRequest
{
if ($rings15 < 1 && $rings25 < 1) {
throw new UnprocessableEntityHttpException('حداقل یک حلقه انتخاب کنید.');
}
return DB::transaction(function () use ($customer, $id, $source, $rings15, $rings25) {
$row = $this->ownedPending($customer, $id);
$quote = $this->quote($customer, $source, $rings15, $rings25);
$row->fill($this->quoteAttributes($customer, $source, $rings15, $rings25, $quote));
$row->save();
return $row;
});
}
public function remove(Customer $customer, int $id): void
{
DB::transaction(function () use ($customer, $id) {
$this->ownedPending($customer, $id)->delete();
});
}
public function listForAdmin(): array
{
return CopperConvertRequest::query()
->with('customer:id,fname,lname,name,mobile')
->orderByDesc('id')
->limit(200)
->get()
->map(function (CopperConvertRequest $row) {
$customer = $row->customer;
$name = trim((string) ($customer->name ?? ''));
if ($name === '') {
$name = trim(((string) ($customer->fname ?? '')).' '.((string) ($customer->lname ?? '')));
}
return [
'id' => $row->id,
'status' => $row->status,
'source' => $row->source,
'customer_name' => $name !== '' ? $name : 'مشتری',
'customer_mobile' => $customer->mobile ?? '',
'asset_unit' => $row->asset_unit,
'consumed_amount' => $row->consumed_amount,
'leftover_amount' => $row->leftover_amount,
'source_unit_price' => $row->source_unit_price,
'wire15_rings' => $row->wire15_rings,
'wire15_unit_price' => $row->wire15_unit_price,
'wire25_rings' => $row->wire25_rings,
'wire25_unit_price' => $row->wire25_unit_price,
'created_at' => optional($row->created_at)->toDateTimeString(),
];
})
->all();
}
public function listForCustomer(Customer $customer): array
{
return CopperConvertRequest::query()
->where('customer_id', $customer->id)
->orderByDesc('id')
->limit(50)
->get()
->map(function (CopperConvertRequest $row) {
return [
'id' => $row->id,
'status' => $row->status,
'source' => $row->source,
'asset_unit' => $row->asset_unit,
'consumed_amount' => $row->consumed_amount,
'leftover_amount' => $row->leftover_amount,
'wire15_rings' => $row->wire15_rings,
'wire25_rings' => $row->wire25_rings,
'created_at' => optional($row->created_at)->toDateTimeString(),
];
})
->all();
}
public function approve(int $id, int $adminId): CopperConvertRequest
{
$row = DB::transaction(function () use ($id, $adminId) {
$row = CopperConvertRequest::query()->lockForUpdate()->findOrFail($id);
if ($row->status !== 'pending') {
throw new UnprocessableEntityHttpException('این درخواست قبلاً تعیین‌تکلیف شده است.');
}
$customer = Customer::query()->findOrFail($row->customer_id);
$available = $this->availableQuantity($customer, (int) $row->source_product_id);
if ($available + 0.0001 < (float) $row->consumed_amount) {
throw new UnprocessableEntityHttpException('موجودی مشتری برای این تبدیل کافی نیست.');
}
$note = 'درخواست تبدیل #'.$row->id;
$sellId = $this->placeLeg($customer, (int) $row->source_product_id, 2, (float) $row->consumed_amount, (float) $row->source_unit_price, $note);
$buy15 = (int) $row->wire15_rings > 0
? $this->placeLeg($customer, (int) $row->wire15_product_id, 1, (float) $row->wire15_rings, (float) $row->wire15_unit_price, $note)
: null;
$buy25 = (int) $row->wire25_rings > 0
? $this->placeLeg($customer, (int) $row->wire25_product_id, 1, (float) $row->wire25_rings, (float) $row->wire25_unit_price, $note)
: null;
$row->status = 'approved';
$row->admin_id = $adminId;
$row->sell_order_id = $sellId;
$row->buy15_order_id = $buy15;
$row->buy25_order_id = $buy25;
$row->save();
return $row;
});
$this->notifyCustomer($row, true);
return $row;
}
public function reject(int $id, int $adminId): CopperConvertRequest
{
$row = CopperConvertRequest::query()->findOrFail($id);
if ($row->status !== 'pending') {
throw new UnprocessableEntityHttpException('این درخواست قبلاً تعیین‌تکلیف شده است.');
}
$row->status = 'rejected';
$row->admin_id = $adminId;
$row->save();
$this->notifyCustomer($row, false);
return $row;
}
private function notifyCustomer(CopperConvertRequest $row, bool $approved): void
{
try {
$customer = Customer::query()->find($row->customer_id);
$mobile = trim((string) ($customer?->mobile ?? ''));
if ($mobile === '') {
return;
}
$company = trim((string) Controller::Config('name_fa'));
$source = $this->sourceLabel((string) $row->source);
$lines = [$company !== '' ? $company : 'درخواست تبدیل'];
if ($approved) {
$lines[] = 'درخواست تبدیل #'.$row->id.' تأیید شد.';
$lines[] = 'دارایی '.$source.' به مقدار '.$row->consumed_amount.' '.$row->asset_unit.' فروخته شد.';
if ((int) $row->wire15_rings > 0) {
$lines[] = 'حلقه ۱.۵: '.$row->wire15_rings;
}
if ((int) $row->wire25_rings > 0) {
$lines[] = 'حلقه ۲.۵: '.$row->wire25_rings;
}
} else {
$lines[] = 'درخواست تبدیل #'.$row->id.' رد شد.';
$lines[] = 'دارایی '.$source.' شما بدون تغییر ماند.';
}
Controller::Send($mobile, implode("\n", $lines));
} catch (\Throwable $e) {
report($e);
}
}
private function ownedPending(Customer $customer, int $id): CopperConvertRequest
{
$row = CopperConvertRequest::query()
->where('customer_id', $customer->id)
->lockForUpdate()
->find($id);
if (!$row) {
throw new UnprocessableEntityHttpException('درخواست تبدیل پیدا نشد.');
}
if ($row->status !== 'pending') {
throw new UnprocessableEntityHttpException('فقط درخواست در انتظار تایید قابل تغییر است.');
}
return $row;
}
private function quoteAttributes(Customer $customer, string $source, int $rings15, int $rings25, array $quote): array
{
return [
'customer_id' => $customer->id,
'status' => 'pending',
'source' => $source,
'source_product_id' => $quote['source']->id,
'asset_unit' => $quote['unit'],
'consumed_amount' => $quote['consumed'],
'leftover_amount' => $quote['leftover'],
'source_unit_price' => $quote['source_unit_price'],
'wire15_product_id' => $quote['wire15']?->id,
'wire15_rings' => $rings15,
'wire15_unit_price' => $quote['price15'],
'wire25_product_id' => $quote['wire25']?->id,
'wire25_rings' => $rings25,
'wire25_unit_price' => $quote['price25'],
];
}
private function sourceLabel(string $source): string
{
if ($source === 'katod') {
return 'کاتد';
}
if ($source === 'maftoul') {
return 'مفتول';
}
if ($source === 'shamsh') {
return 'شمش';
}
return $source;
}
private function placeLeg(Customer $customer, int $productId, int $direction, float $number, float $unitPrice, string $note): int
{
if ($productId < 1 || $number <= 0 || $unitPrice <= 0) {
throw new UnprocessableEntityHttpException('اطلاعات سفارش تبدیل ناقص است.');
}
auth('customer')->setUser($customer);
try {
$response = app(SingleOrderController::class)->store(Request::create('/admin/single/order', 'POST', [
'customer_id' => $customer->id,
'product_id' => $productId,
'direction' => $direction,
'number' => $number,
'method' => 'cash',
'price' => $unitPrice,
'difference' => 0,
'quote_unit_price' => $unitPrice,
'description' => $note,
]));
} finally {
auth('customer')->forgetUser();
}
$body = $response->getData(true);
$orderId = (int) ($body[1]['order']['id'] ?? 0);
if ($orderId < 1) {
throw new UnprocessableEntityHttpException('ثبت سفارش تبدیل انجام نشد.');
}
return $orderId;
}
private function quote(Customer $customer, string $source, int $rings15, int $rings25): array
{
$products = Product::query()->where('active', 1)->get();
$sourceProduct = $this->findSource($products, $source);
if (!$sourceProduct) {
throw new UnprocessableEntityHttpException('محصول این دارایی پیدا نشد.');
}
$wire15 = $rings15 > 0 ? $this->findWire($products, '1.5') : null;
$wire25 = $rings25 > 0 ? $this->findWire($products, '2.5') : null;
if ($rings15 > 0 && !$wire15) {
throw new UnprocessableEntityHttpException('محصول سیم ۱.۵ پیدا نشد.');
}
if ($rings25 > 0 && !$wire25) {
throw new UnprocessableEntityHttpException('محصول سیم ۲.۵ پیدا نشد.');
}
$prices = app(ProductDisplayPriceService::class);
$sourcePerKg = (float) $prices->resolveOrderTradePrice($sourceProduct, 1);
$price15 = $wire15 ? (int) round((float) $prices->resolveOrderTradePrice($wire15, 1)) : 0;
$price25 = $wire25 ? (int) round((float) $prices->resolveOrderTradePrice($wire25, 1)) : 0;
if ($sourcePerKg <= 0 || ($rings15 > 0 && $price15 <= 0) || ($rings25 > 0 && $price25 <= 0)) {
throw new UnprocessableEntityHttpException('قیمت تبدیل در دسترس نیست.');
}
$unit = trim((string) ($sourceProduct->unit ?: 'کیلوگرم'));
if ($unit === '') {
$unit = 'کیلوگرم';
}
$available = $this->availableQuantity($customer, (int) $sourceProduct->id);
$availableValue = $this->toKg($available, $unit, $sourceProduct) * $sourcePerKg;
$spent = ($rings15 * $price15) + ($rings25 * $price25);
if ($spent > $availableValue + 1) {
throw new UnprocessableEntityHttpException('تعداد حلقه از ارزش دارایی بیشتر است.');
}
$consumedKg = $spent / $sourcePerKg;
$consumed = round($this->fromKg($consumedKg, $unit, $sourceProduct), 4);
if ($consumed <= 0) {
throw new UnprocessableEntityHttpException('مقدار قابل تبدیل صفر است.');
}
if ($consumed > $available + 0.0001) {
throw new UnprocessableEntityHttpException('موجودی این دارایی کافی نیست.');
}
$leftover = round(max(0, $available - $consumed), 4);
$sourceUnitPrice = (int) ceil($spent / $consumed);
return [
'source' => $sourceProduct,
'wire15' => $wire15,
'wire25' => $wire25,
'unit' => $unit,
'consumed' => $consumed,
'leftover' => $leftover,
'source_unit_price' => max(1, $sourceUnitPrice),
'price15' => (int) round($price15),
'price25' => (int) round($price25),
];
}
private function availableQuantity(Customer $customer, int $productId): float
{
return (float) app(AssetSummaryService::class)->productDisplayQuantity(
(int) $customer->id,
(int) ($customer->type ?? 2),
$productId
);
}
private function findSource(Collection $products, string $source): ?Product
{
return $products->first(function (Product $product) use ($source) {
$group = trim((string) $product->group_type);
$title = (string) $product->title;
if ($source === 'katod') {
return $group === 'کاتد مس' || str_contains($title, 'کاتد');
}
if ($source === 'maftoul') {
return $group === 'مفتول مس' || str_contains($title, 'مفتول');
}
if ($source === 'shamsh') {
return str_contains($group, 'شمش') || str_contains($title, 'شمش');
}
return false;
});
}
private function findWire(Collection $products, string $section): ?Product
{
return $products->first(function (Product $product) use ($section) {
$title = (string) $product->title;
$pattern = $section === '1.5' ? '/1\.5|۱\.۵/u' : '/2\.5|۲\.۵/u';
return preg_match($pattern, $title) === 1;
});
}
private function toKg(float $quantity, string $unit, Product $product): float
{
if ($quantity <= 0) {
return 0;
}
if (str_contains($unit, 'کیلو')) {
return $quantity;
}
if (str_contains($unit, 'گرم')) {
return $quantity / 1000;
}
$perPiece = (float) ($product->amount ?? 0);
if ($perPiece <= 0) {
return $quantity;
}
$pieceUnit = trim((string) $product->unit);
$grams = str_contains($pieceUnit, 'کیلو') ? $perPiece * 1000 : $perPiece;
return ($quantity * $grams) / 1000;
}
private function fromKg(float $kg, string $unit, Product $product): float
{
if ($kg <= 0) {
return 0;
}
if (str_contains($unit, 'کیلو')) {
return $kg;
}
if (str_contains($unit, 'گرم')) {
return $kg * 1000;
}
$perPiece = (float) ($product->amount ?? 0);
if ($perPiece <= 0) {
return $kg;
}
$pieceUnit = trim((string) $product->unit);
$grams = str_contains($pieceUnit, 'کیلو') ? $perPiece * 1000 : $perPiece;
if ($grams <= 0) {
return $kg;
}
return ($kg * 1000) / $grams;
}
}
+253
View File
@@ -0,0 +1,253 @@
<?php
namespace App\Services;
use App\Models\Customer;
use App\Models\Price;
use App\Models\Withdraw;
use Illuminate\Support\Facades\DB;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class DigipayInstallmentService
{
public function enabled(): bool
{
return app(ConfigService::class)->getBool('enable_digipay_installment', false);
}
public function publicConfig(): array
{
$cfg = app(ConfigService::class);
return [
'onboarding_url' => trim($cfg->getString('digipay_onboarding_url', '')),
'fee_shop_percent' => (float) $cfg->getString('digipay_fee_shop_percent', '8'),
'fee_gateway_percent' => (float) $cfg->getString('digipay_fee_gateway_percent', '5.7'),
'fee_extra_percent' => (float) $cfg->getString('digipay_fee_extra_percent', '2.3'),
'plan4_cap_toman' => (int) $cfg->getString('digipay_plan4_cap_toman', '30000000'),
'plan12_cap_toman' => (int) $cfg->getString('digipay_plan12_cap_toman', '200000000'),
];
}
public function statusFor(int $customerId): array
{
$credit = DB::table('digipay_credits')->where('customer_id', $customerId)->first();
$config = $this->publicConfig();
return [
'enabled' => true,
'status' => $credit->status ?? 'none',
'plan4_remaining_toman' => (int) floor(((int) ($credit->plan4_remaining_rial ?? 0)) / 10),
'plan12_remaining_toman' => (int) floor(((int) ($credit->plan12_remaining_rial ?? 0)) / 10),
'gram_price_rial' => $this->gramPriceRial(),
'config' => $config,
];
}
public function markStarted(int $customerId): void
{
$config = $this->publicConfig();
if ($config['onboarding_url'] === '') {
throw new UnprocessableEntityHttpException('لینک دیجی‌پی در تنظیمات ثبت نشده است');
}
$existing = DB::table('digipay_credits')->where('customer_id', $customerId)->first();
if ($existing && $existing->status === 'active') {
return;
}
if ($existing) {
DB::table('digipay_credits')->where('id', $existing->id)->update([
'status' => 'pending',
'updated_at' => now(),
]);
return;
}
DB::table('digipay_credits')->insert([
'customer_id' => $customerId,
'status' => 'pending',
'plan4_remaining_rial' => 0,
'plan12_remaining_rial' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
}
public function setCredit(string $mobile, int $plan4Toman, int $plan12Toman): array
{
$customer = Customer::findActiveByMobile($mobile);
if (! $customer) {
throw new UnprocessableEntityHttpException('مشتری با این موبایل پیدا نشد');
}
$row = [
'status' => 'active',
'plan4_remaining_rial' => max(0, $plan4Toman) * 10,
'plan12_remaining_rial' => max(0, $plan12Toman) * 10,
'updated_at' => now(),
];
$existing = DB::table('digipay_credits')->where('customer_id', $customer->id)->first();
if ($existing) {
DB::table('digipay_credits')->where('id', $existing->id)->update($row);
} else {
$row['customer_id'] = $customer->id;
$row['created_at'] = now();
DB::table('digipay_credits')->insert($row);
}
return [
'customer_id' => (int) $customer->id,
'name' => $customer->name,
'plan4_remaining_toman' => max(0, $plan4Toman),
'plan12_remaining_toman' => max(0, $plan12Toman),
];
}
public function buy(int $customerId, int $plan, int $amountToman): array
{
if (! in_array($plan, [4, 12], true)) {
throw new UnprocessableEntityHttpException('طرح اقساط نامعتبر است');
}
if ($amountToman < 1000) {
throw new UnprocessableEntityHttpException('مبلغ خرید را وارد کنید');
}
$price = $this->gramPriceRial();
if ($price <= 0) {
throw new UnprocessableEntityHttpException('قیمت لحظه‌ای در دسترس نیست');
}
$config = $this->publicConfig();
$cap = $plan === 4 ? $config['plan4_cap_toman'] : $config['plan12_cap_toman'];
if ($amountToman > $cap) {
throw new UnprocessableEntityHttpException('مبلغ از سقف این طرح بیشتر است');
}
$feePercent = $config['fee_shop_percent'] + $config['fee_gateway_percent'] + $config['fee_extra_percent'];
$amountRial = $amountToman * 10;
$chargeRial = (int) round($amountRial * (1 + ($feePercent / 100)));
$feeRial = $chargeRial - $amountRial;
$grams = round($amountRial / $price, 4);
if ($grams <= 0) {
throw new UnprocessableEntityHttpException('مقدار مس محاسبه‌شده نامعتبر است');
}
$column = $plan === 4 ? 'plan4_remaining_rial' : 'plan12_remaining_rial';
return DB::transaction(function () use ($customerId, $plan, $amountRial, $feeRial, $grams, $price, $chargeRial, $column) {
$credit = DB::table('digipay_credits')->where('customer_id', $customerId)->lockForUpdate()->first();
if (! $credit || $credit->status !== 'active') {
throw new UnprocessableEntityHttpException('اعتبار اقساطی شما هنوز فعال نشده است');
}
if ((int) $credit->{$column} < $chargeRial) {
throw new UnprocessableEntityHttpException('مانده اعتبار این طرح کافی نیست');
}
DB::table('digipay_credits')->where('id', $credit->id)->update([
$column => (int) $credit->{$column} - $chargeRial,
'updated_at' => now(),
]);
$orderId = DB::table('digipay_orders')->insertGetId([
'customer_id' => $customerId,
'plan' => $plan,
'amount_rial' => $amountRial,
'fee_rial' => $feeRial,
'grams' => $grams,
'gram_price_rial' => $price,
'status' => 'done',
'created_at' => now(),
'updated_at' => now(),
]);
$this->creditMetal($customerId, $grams, (int) $orderId);
return [
'order_id' => (int) $orderId,
'grams' => $grams,
'plan' => $plan,
'charge_toman' => (int) floor($chargeRial / 10),
];
});
}
public function recentOrders(int $limit = 50): array
{
return DB::table('digipay_orders as o')
->leftJoin('customers as c', 'c.id', '=', 'o.customer_id')
->orderByDesc('o.id')
->limit($limit)
->get([
'o.id',
'o.customer_id',
'c.name',
'c.mobile',
'o.plan',
'o.amount_rial',
'o.fee_rial',
'o.grams',
'o.created_at',
])
->map(function ($row) {
return [
'id' => (int) $row->id,
'customer_id' => (int) $row->customer_id,
'name' => $row->name,
'mobile' => $row->mobile,
'plan' => (int) $row->plan,
'amount_toman' => (int) floor(((int) $row->amount_rial) / 10),
'fee_toman' => (int) floor(((int) $row->fee_rial) / 10),
'grams' => (float) $row->grams,
'created_at' => $row->created_at,
];
})
->all();
}
private function gramPriceRial(): int
{
return (int) (Price::query()->orderByDesc('id')->value('price') ?? 0);
}
private function creditMetal(int $customerId, float $grams, int $orderId): void
{
$user = Customer::query()->find($customerId);
if (! $user) {
throw new UnprocessableEntityHttpException('مشتری پیدا نشد');
}
$withdraw = Withdraw::create([
'customer_id' => $user->id,
'gold' => $grams,
'note' => 'خرید اقساطی',
'sts' => 6,
'tracked_number' => $orderId,
]);
$wallet = new WalletInterface($user->id, $user->type);
new TransactionInterface($wallet, [
'cash' => 0,
'gold' => $grams,
'expire_at' => now(),
'note' => 'خرید اقساطی',
'withdraw_id' => $withdraw->id,
'active' => true,
], 7, true, false);
try {
app(ShayeganSyncService::class)->recordWalletGold([
'customer_id' => $user->id,
'value' => $grams,
'direction' => 1,
'withdraw_id' => $withdraw->id,
'note' => 'خرید اقساطی',
]);
} catch (\Throwable $e) {
report($e);
}
}
}
@@ -125,5 +125,13 @@ class WalletDepositCreditor
report($e);
}
}
if ($this->config->isShayeganAccounting()) {
try {
app(\App\Http\Controllers\Admin\ShayeganController::class)->wallet($payload);
} catch (\Throwable $e) {
report($e);
}
}
}
}
+4
View File
@@ -80,6 +80,10 @@ class PriceBroadcastService
'main_product' => (int) ($payload['main_product'] ?? 0),
'montzar' => (int) ($payload['montzar'] ?? 0),
'zaarbox' => (int) ($payload['zaarbox'] ?? 0),
'copper_world' => (int) ($payload['copper_world'] ?? 0),
'dollar_free' => (int) ($payload['dollar_free'] ?? 0),
'copper_ton' => (string) ($payload['copper_ton'] ?? '0'),
'copper_kilo' => (string) ($payload['copper_kilo'] ?? '0'),
'gold_ounce_price' => round((float) ($goldOunce['price'] ?? 0), 2),
];
}
+4 -1
View File
@@ -160,7 +160,10 @@ class PriceTriggerService
{
$title = trim((string) ($product?->title ?? ''));
if ($title === '') {
$title = 'طلا';
$title = trim((string) app(ConfigService::class)->getString('metal_type', ''));
}
if ($title === '') {
$title = 'محصول';
}
$shopName = (string) app(ConfigService::class)->getString('name_fa');
+393
View File
@@ -0,0 +1,393 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
/**
* HTTP client for Shayegan Cyber Account webservice (REST JSON).
* Contract from vendor PDF: Config + Domain|PutObject; always inspect ErrorMessage.
*/
class ShayeganClient
{
/** @var ConfigService */
private $config;
public function __construct(ConfigService $config)
{
$this->config = $config;
}
public function isConfigured(): bool
{
return $this->baseUrl() !== ''
&& $this->config->getString('shayegan_sql_server', '') !== ''
&& $this->config->getString('shayegan_database', '') !== ''
&& $this->config->getString('shayegan_db_user', '') !== '';
}
public function baseUrl(): string
{
return rtrim(trim($this->config->getString('shayegan_base_url', '')), '/');
}
/**
* @return array<string, mixed>
*/
public function buildConfig(): array
{
$authUser = trim($this->config->getString('shayegan_auth_user', ''));
$authPass = (string) $this->config->getString('shayegan_auth_password', '');
return [
'Server' => $this->config->getString('shayegan_sql_server', ''),
'AllowRowSecurity' => false,
'Level' => 0,
'DBUserName' => $this->config->getString('shayegan_db_user', ''),
'DBPassword' => (string) $this->config->getString('shayegan_db_password', ''),
'DataBaseName' => $this->config->getString('shayegan_database', ''),
'AuthUser' => $authUser !== '' ? $authUser : '',
'AuthPassword' => $authUser !== '' ? $authPass : '',
'Language' => $this->config->getInt('shayegan_language', 3),
];
}
/**
* Read-only smoke test: Account/Get one page.
*
* @return array{ok:bool,message:string,http_status:?int,body:?array,timeout?:bool}
*/
public function healthCheck(): array
{
if (! $this->isConfigured()) {
return [
'ok' => false,
'message' => 'تنظیمات اتصال شایگان ناقص است (base_url / Server / DataBase / DBUser).',
'http_status' => null,
'body' => null,
];
}
return $this->get('Account/Get', [], 0, 1);
}
/**
* @param array<string, mixed> $domain
* @return array{ok:bool,message:string,http_status:?int,body:?array,timeout?:bool}
*/
public function get(string $endpoint, array $domain = [], int $rowStart = 0, int $rowCount = 1): array
{
$payload = [
'Config' => $this->buildConfig(),
// JSON object {} — empty PHP array encodes as [] and Shayegan .NET null-refs
'Domain' => $domain === [] ? new \stdClass() : $domain,
];
return $this->request('GET_STYLE', $endpoint, $payload, [
'RowStart' => $rowStart,
'RowCount' => $rowCount,
]);
}
/**
* @param array<int, array<string, mixed>> $putObject
* @return array{ok:bool,message:string,http_status:?int,body:?array,timeout?:bool,number:?string,guid:?string}
*/
public function put(string $endpoint, array $putObject): array
{
$payload = [
'Config' => $this->buildConfig(),
'PutObject' => array_values($putObject),
];
$result = $this->request('PUT_STYLE', $endpoint, $payload, []);
if (! empty($result['body']) && is_array($result['body'])) {
$first = $this->firstResultRow($result['body']);
$result['number'] = isset($first['Number']) ? (string) $first['Number'] : null;
$result['guid'] = isset($first['GuId']) ? (string) $first['GuId'] : (isset($first['Guid']) ? (string) $first['Guid'] : null);
} else {
$result['number'] = null;
$result['guid'] = null;
}
return $result;
}
/**
* @param array<string, mixed> $payload
* @param array<string, int|string> $query
* @return array{ok:bool,message:string,http_status:?int,body:?array,timeout?:bool}
*/
private function request(string $style, string $endpoint, array $payload, array $query): array
{
$url = $this->endpointUrl($endpoint, $query);
$timeout = max(5, $this->config->getInt('shayegan_timeout_seconds', 30));
$clientRequest = [
'endpoint' => $endpoint,
'url' => $url,
'query' => $query,
'payload' => $this->redactPayload($payload),
];
$this->logTraffic('request', [
'style' => $style,
'endpoint' => $endpoint,
'url' => $url,
'timeout_seconds' => $timeout,
'payload' => $clientRequest['payload'],
]);
try {
$response = Http::timeout($timeout)
->withHeaders(['Content-Type' => 'application/json', 'Accept' => 'application/json'])
->post($url, $payload);
$status = $response->status();
$json = $response->json();
if (! is_array($json)) {
$raw = (string) $response->body();
$decoded = json_decode($raw, true);
$json = is_array($decoded) ? $decoded : ['raw' => Str::limit($raw, 2000)];
}
$error = $this->extractErrorMessage($json);
$serverResponse = $this->serverResponse($status, $error !== '' ? $error : 'OK', $json);
if ($status >= 400) {
$result = $this->withExchange([
'ok' => false,
'message' => $error !== '' ? $error : ('HTTP ' . $status),
'http_status' => $status,
'body' => $json,
], $clientRequest, $serverResponse);
$this->logTraffic('response', [
'style' => $style,
'endpoint' => $endpoint,
'url' => $url,
'ok' => false,
'http_status' => $status,
'error_message' => $error,
'body' => $this->redactBodyForLog($json),
]);
return $result;
}
if ($error !== '') {
$result = $this->withExchange([
'ok' => false,
'message' => $error,
'http_status' => $status,
'body' => $json,
], $clientRequest, $serverResponse);
$this->logTraffic('response', [
'style' => $style,
'endpoint' => $endpoint,
'url' => $url,
'ok' => false,
'http_status' => $status,
'error_message' => $error,
'body' => $this->redactBodyForLog($json),
]);
return $result;
}
$result = $this->withExchange([
'ok' => true,
'message' => 'OK',
'http_status' => $status,
'body' => $json,
], $clientRequest, $serverResponse);
$this->logTraffic('response', [
'style' => $style,
'endpoint' => $endpoint,
'url' => $url,
'ok' => true,
'http_status' => $status,
'error_message' => '',
'body' => $this->redactBodyForLog($json),
]);
return $result;
} catch (\Illuminate\Http\Client\ConnectionException $e) {
Log::warning('shayegan.timeout_or_connection', [
'endpoint' => $endpoint,
'style' => $style,
'url' => $url,
'message' => $e->getMessage(),
'payload' => $this->redactPayload($payload),
]);
return $this->withExchange([
'ok' => false,
'message' => 'timeout/connection: ' . $e->getMessage(),
'http_status' => null,
'body' => null,
'timeout' => true,
], $clientRequest, $this->serverResponse(null, 'timeout/connection: ' . $e->getMessage(), null));
} catch (\Throwable $e) {
Log::warning('shayegan.request_failed', [
'endpoint' => $endpoint,
'style' => $style,
'url' => $url,
'message' => $e->getMessage(),
'payload' => $this->redactPayload($payload),
]);
return $this->withExchange([
'ok' => false,
'message' => $e->getMessage(),
'http_status' => null,
'body' => null,
], $clientRequest, $this->serverResponse(null, $e->getMessage(), null));
}
}
/**
* @param array<string, mixed> $result
* @return array{client_request:mixed,server_response:mixed}
*/
public function debugExchange(array $result): array
{
return [
'client_request' => $result['client_request'] ?? null,
'server_response' => $result['server_response'] ?? null,
];
}
/**
* @param array<string, mixed> $result
* @param array<string, mixed> $clientRequest
* @param array<string, mixed> $serverResponse
* @return array<string, mixed>
*/
private function withExchange(array $result, array $clientRequest, array $serverResponse): array
{
$result['client_request'] = $clientRequest;
$result['server_response'] = $serverResponse;
return $result;
}
/**
* @param mixed $body
* @return array<string, mixed>
*/
private function serverResponse(?int $status, ?string $message, $body): array
{
$response = [
'message' => $message,
'http_status' => $status,
];
if (is_array($body)) {
$response['body'] = $body;
}
return $response;
}
/**
* @param array<string, int|string> $query
*/
private function endpointUrl(string $endpoint, array $query): string
{
$endpoint = ltrim(str_replace('\\', '/', $endpoint), '/');
$url = $this->baseUrl() . '/api/' . $endpoint;
if ($query !== []) {
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($query);
}
return $url;
}
/**
* @param array<string, mixed> $body
*/
public function extractErrorMessage(array $body): string
{
$top = trim((string) ($body['ErrorMessage'] ?? ''));
if ($top !== '') {
return $top;
}
$row = $this->firstResultRow($body);
if ($row !== null) {
$rowError = trim((string) ($row['ErrorMessage'] ?? ''));
if ($rowError !== '') {
return $rowError;
}
}
return '';
}
/**
* @param array<string, mixed> $body
* @return array<string, mixed>|null
*/
private function firstResultRow(array $body): ?array
{
$result = $body['Result'] ?? null;
if (! is_array($result) || $result === []) {
return null;
}
$first = isset($result[0]) && is_array($result[0]) ? $result[0] : null;
if ($first !== null) {
return $first;
}
return is_array($result) && ! isset($result[0]) ? $result : null;
}
/**
* Strip secrets before logging / storing in admin-visible res when needed.
*
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
public function redactPayload(array $payload): array
{
if (isset($payload['Config']) && is_array($payload['Config'])) {
foreach (['DBPassword', 'AuthPassword'] as $key) {
if (array_key_exists($key, $payload['Config']) && $payload['Config'][$key] !== '' && $payload['Config'][$key] !== null) {
$payload['Config'][$key] = '***';
}
}
}
return $payload;
}
/**
* @param array<string, mixed> $context
*/
private function logTraffic(string $phase, array $context): void
{
if ($this->config->getInt('shayegan_log_traffic', 1) === 0) {
return;
}
Log::info('shayegan.http_' . $phase, $context);
}
/**
* @param array<string, mixed> $body
* @return array<string, mixed>
*/
private function redactBodyForLog(array $body): array
{
if (isset($body['Result']) && is_array($body['Result'])) {
$count = count($body['Result']);
$body['Result'] = array_slice($body['Result'], 0, 2);
if ($count > 2) {
$body['Result_truncated'] = $count - 2;
}
}
return $body;
}
}
@@ -0,0 +1,367 @@
<?php
namespace App\Services;
use App\Models\Customer;
use App\Models\ShayeganInboundCharge;
use App\Models\Transaction;
use App\Models\TransactionsAdmin;
use App\Models\User;
use App\Models\Withdraw;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;
class ShayeganInboundChargeService
{
private ConfigService $config;
private ShayeganClient $client;
private WalletBroadcastService $walletBroadcast;
public function __construct(
ConfigService $config,
ShayeganClient $client,
WalletBroadcastService $walletBroadcast
) {
$this->config = $config;
$this->client = $client;
$this->walletBroadcast = $walletBroadcast;
}
/**
* پیدا کردن مشتری با اولویت: شناسه مستقیم، کد تفصیلی، موبایل، کد ملی
*/
public function resolveCustomer(array $params): ?Customer
{
// 1. با شناسه مشتری در بورس مس
if (! empty($params['customer_id'])) {
$customer = Customer::find((int) $params['customer_id']);
if ($customer) {
return $customer;
}
}
// 2. با کد تفصیلی شایگان (moshtari_code)
$tafsil = trim((string) ($params['customer_tafsil'] ?? $params['moshtari_code'] ?? $params['job_number'] ?? ''));
if ($tafsil !== '') {
$customer = Customer::where('moshtari_code', $tafsil)->first();
if ($customer) {
return $customer;
}
// بررسی فرمول احتمالی کد کل + کد کاربر ۷ رقمی
$kol = trim($this->config->getString('shayegan_kol_customer', '121'));
if ($kol !== '' && str_starts_with($tafsil, $kol)) {
$subId = (int) substr($tafsil, strlen($kol));
if ($subId > 0) {
$customer = Customer::find($subId);
if ($customer) {
return $customer;
}
}
}
}
// 3. با شماره موبایل
$mobile = trim((string) ($params['mobile'] ?? ''));
if ($mobile !== '') {
$customer = Customer::findActiveByMobile($mobile);
if ($customer) {
return $customer;
}
}
// 4. با کد ملی
$nCode = trim((string) ($params['n_code'] ?? $params['national_code'] ?? $params['mellicode'] ?? ''));
if ($nCode !== '') {
$customer = Customer::where('n_code', $nCode)->first();
if ($customer) {
return $customer;
}
}
return null;
}
/**
* ثبت درخواست شارژ ورودی از شایگان در وضعیت pending
*/
public function registerCharge(array $data, string $source = 'webhook'): array
{
$customer = $this->resolveCustomer($data);
if (! $customer) {
return [
'ok' => false,
'message' => 'مشتری با مشخصات ارسالی (کد مشتری، کد تفصیلی، موبایل یا کد ملی) یافت نشد.',
];
}
$amount = (float) ($data['amount'] ?? $data['value'] ?? $data['RialBes'] ?? $data['AmountBes'] ?? 0);
if ($amount <= 0) {
return [
'ok' => false,
'message' => 'مبلغ شارژ باید مقداری مثبت و بزرگتر از صفر باشد.',
];
}
$shayeganNumber = trim((string) ($data['shayegan_number'] ?? $data['Number'] ?? $data['doc_number'] ?? ''));
$tafsil = trim((string) ($data['customer_tafsil'] ?? $data['moshtari_code'] ?? $customer->moshtari_code ?? ''));
$description = trim((string) ($data['description'] ?? $data['desc'] ?? $data['note'] ?? 'شارژ از طریق پنل حسابداری شایگان'));
// جلوگیری از ثبت تکراری اگر قبلاً سند با همین شماره برای این مشتری ثبت شده است
if ($shayeganNumber !== '') {
$existing = ShayeganInboundCharge::where('shayegan_number', $shayeganNumber)
->where('customer_id', $customer->id)
->first();
if ($existing) {
return [
'ok' => true,
'message' => 'این سند شایگان قبلاً ثبت شده است.',
'charge' => $existing->load('customer'),
'duplicate' => true,
];
}
}
$charge = ShayeganInboundCharge::create([
'customer_id' => $customer->id,
'customer_tafsil' => $tafsil ?: null,
'shayegan_number' => $shayeganNumber ?: null,
'amount' => $amount,
'description' => $description,
'source' => $source,
'status' => 'pending',
'raw_data' => $data,
]);
Log::info('shayegan.inbound_charge_registered', [
'charge_id' => $charge->id,
'customer_id' => $customer->id,
'amount' => $amount,
'shayegan_number' => $shayeganNumber,
'source' => $source,
]);
return [
'ok' => true,
'message' => "حساب شخص {$customer->name} از طریق پنل حسابداری مقدار " . number_format($amount) . " ریال شارژ شد.",
'charge' => $charge->load('customer'),
];
}
/**
* تایید شارژ و افزایش کیف پول ریالی مشتری در بورس مس
*/
public function approveCharge(ShayeganInboundCharge $charge, ?User $adminUser = null): array
{
return DB::transaction(function () use ($charge, $adminUser) {
$charge = ShayeganInboundCharge::where('id', $charge->id)->lockForUpdate()->firstOrFail();
if ($charge->status === 'approved') {
return [
'ok' => true,
'message' => 'این شارژ قبلاً تایید شده است.',
'charge' => $charge->load(['customer', 'approver']),
];
}
if ($charge->status !== 'pending') {
throw new UnprocessableEntityHttpException('وضعیت این شارژ برای تایید معتبر نیست (' . $charge->status . ').');
}
$customer = $charge->customer;
if (! $customer) {
throw new UnprocessableEntityHttpException('مشتری مرتبط با این شارژ یافت نشد.');
}
$adminId = $adminUser ? (int) $adminUser->id : 1;
$note = $charge->description ?: ('شارژ تایید شده از پنل حسابداری شایگان' . ($charge->shayegan_number ? " (سند {$charge->shayegan_number})" : ''));
// 1. ثبت Withdraw (واریز ریالی با sts = 4)
$withdraw = Withdraw::create([
'user_id' => $adminId,
'customer_id' => $customer->id,
'cash' => $charge->amount,
'note' => $note,
'sts' => 4,
]);
// 2. افزایش موجودی در کیف پول (Rooyesh Wallet)
$walletInterface = new WalletInterface((int) $customer->id, (int) $customer->type);
new TransactionInterface($walletInterface, [
'gold' => 0,
'cash' => $charge->amount,
'expire_at' => now(),
'note' => $note,
'withdraw_id' => $withdraw->id,
'active' => true,
], 3, true, true, 0); // type 3 = deposit, deposit = true
// 3. ثبت لاگ تراکنش ادمین
$lastTx = Transaction::where('withdraw_id', $withdraw->id)->latest('id')->first();
TransactionsAdmin::create([
'customer_id' => $customer->id,
'customer_to_id' => $customer->id,
'user_id' => $adminId,
'wallet' => null,
'transaction_id' => $lastTx?->id,
'cash' => $charge->amount,
'note' => $note,
'type' => 1,
'gold' => 0,
'balance_cash' => 0,
]);
// 4. به‌روزرسانی وضعیت رکورد شارژ شایگان
$charge->status = 'approved';
$charge->approved_by = $adminId;
$charge->approved_at = now();
$charge->withdraw_id = $withdraw->id;
$charge->transaction_id = $lastTx?->id;
$charge->save();
// 5. برودکست ریل‌تایم موجودی کیف پول کاربر
try {
$this->walletBroadcast->broadcastForCustomer((int) $customer->id, (int) $customer->type);
} catch (\Throwable $e) {
Log::warning('shayegan.wallet_broadcast_failed', ['error' => $e->getMessage()]);
}
// 6. تریگر اتوماسیون
try {
\App\Services\Automation\AutomationEvents::fire('wallet.rial_charge', (int) $customer->id);
} catch (\Throwable $e) {
Log::warning('shayegan.automation_failed', ['error' => $e->getMessage()]);
}
Log::info('shayegan.inbound_charge_approved', [
'charge_id' => $charge->id,
'customer_id' => $customer->id,
'amount' => $charge->amount,
'withdraw_id' => $withdraw->id,
'admin_id' => $adminId,
]);
return [
'ok' => true,
'message' => "کیف پول شخص {$customer->name} به مبلغ " . number_format($charge->amount) . " ریال با موفقیت شارژ شد.",
'charge' => $charge->load(['customer', 'approver']),
];
});
}
/**
* رد درخواست شارژ
*/
public function rejectCharge(ShayeganInboundCharge $charge, ?User $adminUser = null, ?string $reason = null): array
{
if ($charge->status === 'approved') {
throw new UnprocessableEntityHttpException('شارژ تایید شده را نمی‌توان رد کرد.');
}
$adminId = $adminUser ? (int) $adminUser->id : 1;
$charge->status = 'rejected';
$charge->rejected_by = $adminId;
$charge->rejected_at = now();
$charge->reject_reason = $reason;
$charge->save();
Log::info('shayegan.inbound_charge_rejected', [
'charge_id' => $charge->id,
'customer_id' => $charge->customer_id,
'admin_id' => $adminId,
'reason' => $reason,
]);
return [
'ok' => true,
'message' => 'درخواست شارژ رد شد.',
'charge' => $charge->load(['customer', 'rejecter']),
];
}
/**
* استعلام اسناد جدید از وب‌سرویس شایگان (Sync / Polling)
*/
public function pollFromShayegan(): array
{
if (! $this->client->isConfigured()) {
return [
'ok' => false,
'message' => 'تنظیمات اتصال وب‌سرویس شایگان در سیستم پیکربندی نشده است.',
'new_count' => 0,
];
}
try {
// استعلام از وب‌سرویس شایگان (مانند Document/Get با فیلتر بستانکاری تفصیلی مشتریان)
$res = $this->client->get('Document/Get', [], 0, 50);
if (empty($res['ok']) || empty($res['body']['Result']) || ! is_array($res['body']['Result'])) {
return [
'ok' => true,
'message' => 'سند جدیدی در استعلام شایگان یافت نشد.',
'new_count' => 0,
];
}
$count = 0;
foreach ($res['body']['Result'] as $doc) {
$docNumber = (string) ($doc['Number'] ?? $doc['DocNumber'] ?? '');
if ($docNumber === '') {
continue;
}
$rows = $doc['Body'] ?? [];
if (! is_array($rows)) {
continue;
}
foreach ($rows as $row) {
$amountBes = (float) ($row['AmountBes'] ?? $row['RialBes'] ?? 0);
$accountNumber = trim((string) ($row['AccountNumber'] ?? ''));
if ($amountBes <= 0 || $accountNumber === '') {
continue;
}
// جستجوی مشتری با شماره تفصیلی
$customer = Customer::where('moshtari_code', $accountNumber)->first();
if (! $customer) {
continue;
}
// آیا قبلا این شماره سند ثبت شده؟
$already = ShayeganInboundCharge::where('shayegan_number', $docNumber)
->where('customer_id', $customer->id)
->exists();
if (! $already) {
$this->registerCharge([
'customer_id' => $customer->id,
'customer_tafsil' => $accountNumber,
'shayegan_number' => $docNumber,
'amount' => $amountBes,
'description' => (string) ($row['DocRowDesc'] ?? $doc['DocDescription'] ?? 'استعلام خودکار از شایگان'),
], 'sync');
$count++;
}
}
}
return [
'ok' => true,
'message' => $count > 0 ? "تعداد {$count} شارژ جدید از شایگان واکشی شد." : 'سند شارژ جدیدی یافت نشد.',
'new_count' => $count,
];
} catch (\Throwable $e) {
Log::warning('shayegan.poll_failed', ['error' => $e->getMessage()]);
return [
'ok' => false,
'message' => 'خطا در ارتباط با وب‌سرویس شایگان: ' . $e->getMessage(),
'new_count' => 0,
];
}
}
}
+764
View File
@@ -0,0 +1,764 @@
<?php
namespace App\Services;
use App\Models\Customer;
use App\Models\Product;
use App\Models\Shayegan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
/**
* Outbound Shayegan sync — does not mutate wallets.
* Timeout rows stay timeout and are never auto-retried.
*/
class ShayeganSyncService
{
public const STATUS_PENDING = 'pending';
public const STATUS_SUCCESS = 'success';
public const STATUS_FAILED = 'failed';
public const STATUS_TIMEOUT = 'timeout';
public const TYPE_TRADE = 'trade';
public const TYPE_WALLET_CASH = 'wallet_cash';
public const TYPE_WALLET_GOLD = 'wallet_gold';
public const TYPE_CUSTOMER = 'customer';
/** InvTyp from Shayegan PDF (company view). */
public const INV_SALE = 2;
public const INV_PURCHASE = 3;
public const INV_HAVALE = 4;
public const INV_RECEIPT = 5;
/** @var ConfigService */
private $config;
/** @var ShayeganClient */
private $client;
public function __construct(ConfigService $config, ShayeganClient $client)
{
$this->config = $config;
$this->client = $client;
}
public function isSyncEnabled(): bool
{
return $this->config->isShayeganAccounting()
&& $this->client->isConfigured();
}
public function tradeMappingReady(): bool
{
return $this->config->getString('shayegan_stock_number', '') !== '';
}
public function customerMappingReady(): bool
{
return trim($this->config->getString('shayegan_moin_customer', '')) !== '';
}
public function registerOnCreate(Customer $customer): void
{
if (! empty($customer->moshtari_code) || ! $this->isSyncEnabled() || ! $this->customerMappingReady()) {
return;
}
$customerId = (int) $customer->id;
dispatch(function () use ($customerId) {
$service = app(self::class);
$customer = Customer::find($customerId);
if ($customer === null || ! empty($customer->moshtari_code) || ! $service->isSyncEnabled()) {
return;
}
try {
$result = $service->registerCustomer($customer);
if (! ($result['ok'] ?? false)) {
Log::warning('shayegan.auto_register_on_create_failed', [
'customer_id' => $customerId,
'message' => $result['message'] ?? null,
]);
}
} catch (\Throwable $e) {
Log::warning('shayegan.auto_register_on_create_threw', [
'customer_id' => $customerId,
'error' => $e->getMessage(),
]);
}
})->afterResponse();
}
/**
* @return array{ok:bool,message:string,moshtari_code?:string}
*/
public function registerCustomer(Customer $customer, ?string $customJobNumber = null): array
{
$customer->refresh();
$customJobNumber = $customJobNumber !== null ? trim($customJobNumber) : null;
if ($customJobNumber === '') {
$customJobNumber = null;
}
if ($customJobNumber === null && ! empty($customer->moshtari_code)) {
return [
'ok' => true,
'message' => 'مشتری قبلاً در شایگان ثبت شده است',
'moshtari_code' => (string) $customer->moshtari_code,
];
}
if (! $this->isSyncEnabled()) {
return ['ok' => false, 'message' => 'حسابداری شایگان فعال نیست یا تنظیمات اتصال ناقص است'];
}
if (! $this->customerMappingReady()) {
return ['ok' => false, 'message' => 'شماره معین مشتریان (shayegan_moin_customer) در تنظیمات خالی است'];
}
$name = trim((string) ($customer->name ?? ''));
if ($name === '') {
$name = 'مشتری ' . $customer->id;
}
// تفصیلی شناور: اگر کد دستی ارسال شده باشد همان کد استفاده می‌شود، در غیر این صورت فرمول پیش‌فرض
$requestedAccountNumber = $customJobNumber ?? $this->customerTafsilNumber((int) $customer->id);
$guid = (string) Str::uuid();
$put = [[
'JobNumber' => $requestedAccountNumber,
'JobName' => mb_substr($name, 0, 200),
'Mobile' => trim((string) ($customer->mobile ?? '')) ?: null,
'mellicode' => trim((string) ($customer->n_code ?? '')) ?: null,
'GuId' => $guid,
'UpdateKind' => 0,
]];
$jobGroup = trim($this->config->getString('shayegan_job_group', ''));
if ($jobGroup !== '') {
$put[0]['JobGroupNumber'] = $jobGroup;
}
$result = $this->client->put('Job/Put', $put);
$accountNumber = trim((string) ($result['number'] ?? ''));
if ($accountNumber === '' && $customJobNumber !== null && ! empty($result['ok'])) {
$accountNumber = $customJobNumber;
}
$exchange = $this->client->debugExchange($result);
if (! empty($result['timeout'])) {
$this->logCustomerRegistrationDoc(
$customer,
$requestedAccountNumber,
$guid,
$put,
$result,
self::STATUS_TIMEOUT,
(string) ($result['message'] ?? 'timeout')
);
return array_merge([
'ok' => false,
'message' => (string) ($result['message'] ?? 'timeout'),
], $exchange);
}
if (empty($result['ok']) || $accountNumber === '') {
$errorMsg = (string) ($result['message'] ?? 'ثبت حساب مشتری در شایگان ناموفق بود');
$this->logCustomerRegistrationDoc(
$customer,
$requestedAccountNumber,
$guid,
$put,
$result,
self::STATUS_FAILED,
$errorMsg
);
return array_merge([
'ok' => false,
'message' => $errorMsg,
], $exchange);
}
$customer->moshtari_code = $accountNumber;
$customer->save();
$this->logCustomerRegistrationDoc(
$customer,
$accountNumber,
$guid,
$put,
$result,
self::STATUS_SUCCESS,
null
);
return array_merge([
'ok' => true,
'message' => 'تفصیلی شناور مشتری در شایگان ایجاد شد',
'moshtari_code' => $accountNumber,
], $exchange);
}
/**
* @param array<int, mixed> $put
* @param array<string, mixed> $result
*/
private function logCustomerRegistrationDoc(
Customer $customer,
string $accountNumber,
string $guid,
array $put,
array $result,
string $status,
?string $logMessage = null
): Shayegan {
$row = new Shayegan();
$row->customer_id = (int) $customer->id;
$row->order_id = null;
$row->withdraw_id = null;
$row->product_id = null;
$row->amount = null;
$row->desc = 'ثبت تفصیلی شناور مشتری';
$row->type = self::TYPE_CUSTOMER;
$row->date = now();
$row->endpoint = 'Job/Put';
$row->request_guid = $guid;
$row->shayegan_number = $accountNumber;
$row->shayegan_guid = $result['guid'] ?? null;
$row->sync_status = $status;
$row->sync_log = $logMessage;
$row->data = json_encode($this->client->redactPayload([
'Config' => $this->client->buildConfig(),
'PutObject' => $put,
]), JSON_UNESCAPED_UNICODE);
$row->res = json_encode($result['body'] ?? [], JSON_UNESCAPED_UNICODE);
$row->save();
return $row;
}
/**
* @param array<string, mixed> $data
*/
public function resolveItemNumber(array $data): string
{
$productPayload = is_array($data['product'] ?? null) ? $data['product'] : [];
$fromPayload = trim((string) ($productPayload['shayegan_item_number'] ?? ''));
if ($fromPayload !== '') {
return $fromPayload;
}
$productId = (int) ($data['product_id'] ?? ($productPayload['id'] ?? 0));
if ($productId > 0 && Product::hasShayeganItemColumn()) {
$product = Product::query()->select('id', 'shayegan_item_number')->find($productId);
if ($product) {
$item = trim((string) ($product->shayegan_item_number ?? ''));
if ($item !== '') {
return $item;
}
}
}
return trim($this->config->getString('shayegan_item_copper', ''));
}
public function cashMappingReady(): bool
{
return $this->config->getString('shayegan_bank_account', '') !== '';
}
public function metalWalletMode(): string
{
$mode = strtolower(trim($this->config->getString('shayegan_metal_wallet_mode', 'skip')));
if (in_array($mode, ['skip', 'document', 'receipt_havale'], true)) {
return $mode;
}
return 'skip';
}
/**
* After confirmed trade: one Invoice only (no duplicate Document).
* Customer buy → company sale (InvTyp 2); customer sell → company purchase (InvTyp 3).
*
* @param array<string, mixed> $data
*/
public function recordTrade(array $data): ?Shayegan
{
if (! $this->isSyncEnabled()) {
return null;
}
if (! $this->tradeMappingReady()) {
Log::info('shayegan.trade_skipped_mapping', ['order_id' => $data['order']->id ?? null]);
return null;
}
$order = $data['order'] ?? null;
$orderId = $order ? (int) $order->id : (int) ($data['order_id'] ?? 0);
$customerId = (int) ($data['customer_id'] ?? ($order->customer_id ?? 0));
if ($customerId <= 0) {
return null;
}
$productId = (int) ($data['product_id'] ?? ($data['order']['product_id'] ?? 0));
$existing = $this->findExisting(
self::TYPE_TRADE,
$orderId > 0 ? $orderId : null,
null,
$customerId,
$productId > 0 ? $productId : null
);
if ($existing && $this->shouldSkipSend($existing)) {
return $existing;
}
$customer = Customer::find($customerId);
$accountNumber = $this->ensureCustomerAccountNumber($customer);
if ($accountNumber === '') {
$msg = $this->customerMappingReady()
? 'ثبت حساب تفصیلی مشتری در شایگان ناموفق بود.'
: 'کد حساب مشتری خالی است؛ shayegan_moin_customer را در تنظیمات پر کنید.';
return $this->markLocalFailed($existing, $customerId, $orderId, null, self::TYPE_TRADE, $msg, null);
}
$itemNumber = $this->resolveItemNumber($data);
if ($itemNumber === '') {
return $this->markLocalFailed(
$existing,
$customerId,
$orderId,
null,
self::TYPE_TRADE,
'کد کالای شایگان برای این محصول تنظیم نشده (محصول یا shayegan_item_copper).',
null
);
}
$isBuy = (int) ($data['direction'] ?? 0) === 1;
$invTyp = $isBuy ? self::INV_SALE : self::INV_PURCHASE;
$quan = $this->scaleWeight((float) ($data['number'] ?? $data['amount'] ?? 0));
$price = $this->scaleAmount((float) ($data['price'] ?? $data['fee'] ?? 0));
if ($quan <= 0) {
return $this->markLocalFailed($existing, $customerId, $orderId, null, self::TYPE_TRADE, 'مقدار وزن معامله برای شایگان صفر است.', null);
}
$guid = $existing && $existing->request_guid
? (string) $existing->request_guid
: (string) Str::uuid();
$today = date('Ymd');
$put = [[
'Body' => [[
'STNumber' => $this->config->getString('shayegan_stock_number', ''),
'STGuId' => null,
'ItemNumber' => $itemNumber,
'ItemGuId' => null,
'Quan' => $quan,
'Quan2' => null,
'Price' => $price > 0 ? $price : null,
'Price2' => null,
'LineDiscAmount' => null,
'LineItemDesc' => $isBuy ? 'خرید مس مشتری' : 'فروش مس مشتری',
'UpdateKind' => 0,
]],
'Expense' => [],
'InvTyp' => $invTyp,
'InvNo' => null,
'InvDescription' => $isBuy ? 'فروش مس به مشتری' : 'خرید مس از مشتری',
'InvDate' => $today,
'InvPayDue' => $today,
'AccountNumber' => $accountNumber,
'AccountGuId' => null,
'GeneralRef' => $orderId > 0 ? ('order:' . $orderId) : null,
'GuId' => $guid,
'UpdateKind' => 0,
]];
$row = $existing ?: new Shayegan();
$row->customer_id = $customerId;
$row->order_id = $orderId > 0 ? $orderId : null;
if (Schema::hasColumn('shayegan', 'product_id')) {
$row->product_id = $productId > 0 ? $productId : null;
}
$row->withdraw_id = null;
$row->amount = $this->scaleAmount((float) ($data['total'] ?? $data['total_price'] ?? ($quan * $price)));
$row->desc = $put[0]['InvDescription'];
$row->type = self::TYPE_TRADE;
$row->date = now();
$row->endpoint = 'Invoice/Put';
$row->request_guid = $guid;
$row->data = json_encode($this->client->redactPayload([
'Config' => $this->client->buildConfig(),
'PutObject' => $put,
]), JSON_UNESCAPED_UNICODE);
$row->sync_status = self::STATUS_PENDING;
$row->sync_log = null;
$row->save();
return $this->dispatchPut($row, 'Invoice/Put', $put);
}
/**
* Rial wallet: Document only (not Invoice).
* direction: 0 deposit, 1 withdraw (same as Zarin/Tahesab wallet cash).
*
* @param array<string, mixed> $data
*/
public function recordWalletCash(array $data): ?Shayegan
{
if (! $this->isSyncEnabled()) {
return null;
}
if (! $this->cashMappingReady()) {
Log::info('shayegan.cash_skipped_mapping', ['withdraw_id' => $data['withdraw_id'] ?? null]);
return null;
}
$customerId = (int) ($data['customer_id'] ?? 0);
$withdrawId = isset($data['withdraw_id']) ? (int) $data['withdraw_id'] : null;
$customer = Customer::find($customerId);
$accountNumber = $this->ensureCustomerAccountNumber($customer);
if ($accountNumber === '') {
return null;
}
$existing = $this->findExisting(self::TYPE_WALLET_CASH, null, $withdrawId, $customerId);
if ($existing && $this->shouldSkipSend($existing)) {
return $existing;
}
$isDeposit = (int) ($data['direction'] ?? 0) === 0;
$amount = $this->scaleAmount(abs((float) ($data['value'] ?? 0)));
if ($amount <= 0) {
return null;
}
$bank = $this->config->getString('shayegan_bank_account', '');
$guid = $existing && $existing->request_guid
? (string) $existing->request_guid
: (string) Str::uuid();
// Deposit: bank debit + customer credit. Withdraw: customer debit + bank credit.
if ($isDeposit) {
$body = [
['AccountNumber' => $bank, 'AmountBed' => $amount, 'AmountBes' => 0, 'RialBed' => $amount, 'RialBes' => 0, 'DocRowDesc' => 'واریز ریالی'],
['AccountNumber' => $accountNumber, 'AmountBed' => 0, 'AmountBes' => $amount, 'RialBed' => 0, 'RialBes' => $amount, 'DocRowDesc' => 'واریز ریالی مشتری'],
];
$desc = 'واریز ریالی';
} else {
$body = [
['AccountNumber' => $accountNumber, 'AmountBed' => $amount, 'AmountBes' => 0, 'RialBed' => $amount, 'RialBes' => 0, 'DocRowDesc' => 'برداشت ریالی مشتری'],
['AccountNumber' => $bank, 'AmountBed' => 0, 'AmountBes' => $amount, 'RialBed' => 0, 'RialBes' => $amount, 'DocRowDesc' => 'برداشت ریالی'],
];
$desc = 'برداشت ریالی';
}
$put = [[
'Body' => $body,
'DocDescription' => trim((string) ($data['note'] ?? '')) !== '' ? (string) $data['note'] : $desc,
'DocDate' => date('Ymd'),
'DocReference' => $withdrawId ? ('withdraw:' . $withdrawId) : null,
'GuId' => $guid,
'UpdateKind' => 0,
]];
$row = $existing ?: new Shayegan();
$row->customer_id = $customerId;
$row->order_id = null;
$row->withdraw_id = $withdrawId;
$row->amount = $amount;
$row->desc = $desc;
$row->type = self::TYPE_WALLET_CASH;
$row->date = now();
$row->endpoint = 'Document/Put';
$row->request_guid = $guid;
$row->data = json_encode($this->client->redactPayload([
'Config' => $this->client->buildConfig(),
'PutObject' => $put,
]), JSON_UNESCAPED_UNICODE);
$row->sync_status = self::STATUS_PENDING;
$row->sync_log = null;
$row->save();
return $this->dispatchPut($row, 'Document/Put', $put);
}
/**
* Product / metal wallet movement — never invent warehouse unless mode says so.
* direction: 1 deposit, 0 withdraw (walletGold convention).
*
* @param array<string, mixed> $data
*/
public function recordWalletGold(array $data): ?Shayegan
{
if (! $this->isSyncEnabled()) {
return null;
}
$mode = $this->metalWalletMode();
if ($mode === 'skip') {
return null;
}
$customerId = (int) ($data['customer_id'] ?? 0);
$withdrawId = isset($data['withdraw_id']) ? (int) $data['withdraw_id'] : null;
$customer = Customer::find($customerId);
$accountNumber = $this->ensureCustomerAccountNumber($customer);
if ($accountNumber === '') {
return null;
}
$existing = $this->findExisting(self::TYPE_WALLET_GOLD, null, $withdrawId, $customerId);
if ($existing && $this->shouldSkipSend($existing)) {
return $existing;
}
$isDeposit = (int) ($data['direction'] ?? 1) === 1;
$quan = $this->scaleWeight(abs((float) ($data['value'] ?? 0)));
if ($quan <= 0) {
return null;
}
$guid = $existing && $existing->request_guid
? (string) $existing->request_guid
: (string) Str::uuid();
if ($mode === 'receipt_havale') {
if (! $this->tradeMappingReady()) {
return null;
}
$invTyp = $isDeposit ? self::INV_RECEIPT : self::INV_HAVALE;
$itemNumber = $this->resolveItemNumber($data);
if ($itemNumber === '') {
return null;
}
$put = [[
'Body' => [[
'STNumber' => $this->config->getString('shayegan_stock_number', ''),
'ItemNumber' => $itemNumber,
'Quan' => $quan,
'Price' => null,
'LineItemDesc' => $isDeposit ? 'واریز محصول' : 'برداشت محصول',
'UpdateKind' => 0,
]],
'Expense' => [],
'InvTyp' => $invTyp,
'InvNo' => null,
'InvDescription' => $isDeposit ? 'رسید انبار (واریز محصول)' : 'حواله (برداشت محصول)',
'InvDate' => date('Ymd'),
'AccountNumber' => $accountNumber,
'GeneralRef' => $withdrawId ? ('withdraw:' . $withdrawId) : null,
'GuId' => $guid,
'UpdateKind' => 0,
]];
$endpoint = 'Invoice/Put';
$desc = $put[0]['InvDescription'];
} else {
// document mode: accounting note only — no stock invoice
$bank = $this->config->getString('shayegan_bank_account', '');
if ($bank === '') {
Log::info('shayegan.gold_document_needs_bank_or_switch_mode');
return null;
}
// Placeholder balanced zero-amount skip — without operator chart of accounts for metal,
// document mode requires explicit counterpart accounts; refuse rather than invent.
Log::info('shayegan.gold_document_needs_account_map', [
'hint' => 'Provide metal counterpart accounts or use receipt_havale after confirming warehouse semantics.',
]);
return null;
}
$row = $existing ?: new Shayegan();
$row->customer_id = $customerId;
$row->order_id = null;
$row->withdraw_id = $withdrawId;
$row->amount = $quan;
$row->desc = $desc;
$row->type = self::TYPE_WALLET_GOLD;
$row->date = now();
$row->endpoint = $endpoint;
$row->request_guid = $guid;
$row->data = json_encode($this->client->redactPayload([
'Config' => $this->client->buildConfig(),
'PutObject' => $put,
]), JSON_UNESCAPED_UNICODE);
$row->sync_status = self::STATUS_PENDING;
$row->sync_log = null;
$row->save();
return $this->dispatchPut($row, $endpoint, $put);
}
/**
* @param array<int, array<string, mixed>> $putObject
*/
private function dispatchPut(Shayegan $row, string $endpoint, array $putObject): Shayegan
{
$result = $this->client->put($endpoint, $putObject);
if (! empty($result['timeout'])) {
$row->sync_status = self::STATUS_TIMEOUT;
$row->sync_log = (string) ($result['message'] ?? 'timeout');
$row->res = json_encode(['timeout' => true, 'message' => $result['message'] ?? null], JSON_UNESCAPED_UNICODE);
$row->save();
return $row;
}
if (! empty($result['ok'])) {
$row->sync_status = self::STATUS_SUCCESS;
$row->sync_log = null;
$row->shayegan_number = $result['number'] ?? null;
$row->shayegan_guid = $result['guid'] ?? null;
$row->res = json_encode($result['body'] ?? [], JSON_UNESCAPED_UNICODE);
$row->save();
return $row;
}
$row->sync_status = self::STATUS_FAILED;
$row->sync_log = (string) ($result['message'] ?? 'failed');
$row->res = json_encode($result['body'] ?? ['message' => $result['message'] ?? null], JSON_UNESCAPED_UNICODE);
$row->save();
return $row;
}
private function shouldSkipSend(Shayegan $row): bool
{
$status = (string) $row->sync_status;
if ($status === self::STATUS_SUCCESS) {
return true;
}
// Never auto-resend after timeout without manual verification.
if ($status === self::STATUS_TIMEOUT) {
return true;
}
return false;
}
private function findExisting(
string $type,
?int $orderId,
?int $withdrawId,
int $customerId,
?int $productId = null
): ?Shayegan {
if (! Schema::hasTable('shayegan')) {
return null;
}
$q = Shayegan::query()->where('type', $type)->where('customer_id', $customerId);
if ($orderId) {
$q->where('order_id', $orderId);
}
if ($withdrawId) {
$q->where('withdraw_id', $withdrawId);
}
if ($productId && Schema::hasColumn('shayegan', 'product_id')) {
$q->where('product_id', $productId);
}
if (! $orderId && ! $withdrawId) {
return null;
}
return $q->orderByDesc('id')->first();
}
private function ensureCustomerAccountNumber(?Customer $customer): string
{
$code = $this->customerAccountNumber($customer);
if ($code !== '' || ! $customer) {
return $code;
}
if (! $this->customerMappingReady()) {
return '';
}
$result = $this->registerCustomer($customer);
if (! ($result['ok'] ?? false)) {
Log::info('shayegan.ensure_customer_failed', [
'customer_id' => $customer->id,
'message' => $result['message'] ?? null,
]);
return '';
}
$customer->refresh();
return $this->customerAccountNumber($customer);
}
private function customerAccountNumber(?Customer $customer): string
{
if (! $customer) {
return '';
}
return trim((string) ($customer->moshtari_code ?? ''));
}
/** کد کل (پیش‌فرض 121) + کد کاربری با صفر تا ۷ رقم. */
private function customerTafsilNumber(int $customerId): string
{
$kol = trim($this->config->getString('shayegan_kol_customer', '121'));
if ($kol === '') {
$kol = '121';
}
return $kol . str_pad((string) $customerId, 7, '0', STR_PAD_LEFT);
}
private function scaleAmount(float $amount): float
{
$scale = (float) $this->config->getString('shayegan_amount_scale', '1');
if ($scale <= 0) {
$scale = 1.0;
}
return round($amount * $scale, 4);
}
private function scaleWeight(float $weight): float
{
$scale = (float) $this->config->getString('shayegan_weight_scale', '1');
if ($scale <= 0) {
$scale = 1.0;
}
return round($weight * $scale, 6);
}
private function markLocalFailed(
?Shayegan $existing,
int $customerId,
?int $orderId,
?int $withdrawId,
string $type,
string $message,
$amount
): Shayegan {
$row = $existing ?: new Shayegan();
$row->customer_id = $customerId;
$row->order_id = $orderId;
$row->withdraw_id = $withdrawId;
$row->amount = $amount;
$row->type = $type;
$row->date = now();
$row->sync_status = self::STATUS_FAILED;
$row->sync_log = $message;
$row->save();
return $row;
}
}
+101 -1
View File
@@ -7,6 +7,8 @@ use App\Models\Price;
use App\Models\Product;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Rooyesh\Wallet\interfaces\TransactionInterface;
use Rooyesh\Wallet\interfaces\WalletInterface;
use Rooyesh\Wallet\models\Wallet;
/**
@@ -17,6 +19,11 @@ use Rooyesh\Wallet\models\Wallet;
*/
class WalletBalanceService
{
/** @var array<string, true> */
private static array $absorbedOwnerTypes = [];
private static bool $absorbingOwnerType = false;
public function __construct(
private ConfigService $configService,
private BalanceReportService $balanceReportService
@@ -161,6 +168,85 @@ class WalletBalanceService
return true;
}
/**
* ماندهٔ کیف‌هایی که owner_typeشان با نوع فعلی مشتری یکی نیست
* (مثلاً واریز وقتی type هنوز ۰ بوده) به کیف همان محصول/قلک روی نوع فعلی منتقل می‌شود.
*/
public function absorbMismatchedOwnerTypeBalances(int $ownerId, int $canonicalType): bool
{
if ($ownerId <= 0 || $canonicalType <= 0 || self::$absorbingOwnerType) {
return false;
}
$key = $ownerId.':'.$canonicalType;
if (isset(self::$absorbedOwnerTypes[$key])) {
return false;
}
self::$absorbedOwnerTypes[$key] = true;
$foreign = Wallet::query()
->where('owner', $ownerId)
->where('owner_type', '!=', $canonicalType)
->where(function ($query) {
$query->where('cash', '!=', 0)->orWhere('gold', '!=', 0);
})
->get();
if ($foreign->isEmpty()) {
return false;
}
self::$absorbingOwnerType = true;
try {
foreach ($foreign as $row) {
DB::transaction(function () use ($row, $ownerId, $canonicalType) {
$locked = Wallet::query()->whereKey($row->id)->lockForUpdate()->first();
if (!$locked) {
return;
}
$cash = (int) round((float) $locked->cash);
$gold = (float) $locked->gold;
if ($cash === 0 && abs($gold) < 0.0000001) {
return;
}
$from = new WalletInterface($ownerId, (int) $locked->owner_type, $locked->fund_id, $locked->product_id);
$to = new WalletInterface($ownerId, $canonicalType, $locked->fund_id, $locked->product_id);
$note = 'انتقال مانده به کیف اصلی مشتری';
if ($cash !== 0) {
$payload = [
'cash' => abs($cash),
'gold' => 0,
'note' => $note,
'expire_at' => now(),
'active' => true,
];
new TransactionInterface($from, $payload, 7, false, $cash < 0);
new TransactionInterface($to, $payload, 7, false, $cash > 0);
}
if (abs($gold) >= 0.0000001) {
$payload = [
'gold' => abs($gold),
'cash' => 0,
'note' => $note,
'expire_at' => now(),
'active' => true,
];
new TransactionInterface($from, $payload, 7, $gold < 0, false);
new TransactionInterface($to, $payload, 7, $gold > 0, false);
}
});
}
} finally {
self::$absorbingOwnerType = false;
}
return true;
}
/** ادغام همهٔ کیف‌های legacy محصولات main_wallet_products برای یک کاربر */
public function consolidateAllMainWalletProductsForOwner(int $ownerId, int $ownerType): void
{
@@ -317,10 +403,24 @@ class WalletBalanceService
->orderBy('id')
->first();
return max(1, (int) ($product?->metal_id ?? 1));
if ($product && (int) ($product->metal_id ?? 0) > 0) {
return (int) $product->metal_id;
}
}
// در بورس مس، مس فلز اصلی پلتفرم است
$hasCopperProduct = Product::query()
->where('active', 1)
->where('metal_id', 3)
->exists();
if ($hasCopperProduct) {
return 3;
}
$metalIds = $this->catalogMetalIds();
if (in_array(3, $metalIds, true)) {
return 3;
}
return count($metalIds) === 1 ? (int) $metalIds[0] : 1;
}
+138
View File
@@ -410,10 +410,148 @@ class ZaarboxPriceService
public function attachGoldOunceToPayload(array $payload): array
{
$payload['gold_ounce'] = $this->clientGoldOuncePayload();
$refs = $this->copperDollarReferences();
$payload['copper_world'] = $refs['copper'];
$payload['dollar_free'] = $refs['dollar'];
$payload['copper_ton'] = $refs['ton'];
$payload['copper_kilo'] = $refs['kilo'];
return $payload;
}
/**
* مس جهانی و دلار آزاد از همان فید شناسه ردیف تابلو.
* تن = ضرب این دو؛ کیلوگرم = تن / ۱۰۰۰.
*
* @return array{copper: int, dollar: int, ton: string, kilo: string}
*/
public function copperDollarReferences(): array
{
$empty = ['copper' => 0, 'dollar' => 0, 'ton' => '0', 'kilo' => '0'];
$prices = $this->getCachedPriceListOnly();
if (!is_array($prices) || $prices === []) {
$prices = $this->fetchPriceList();
if (is_array($prices) && $prices !== []) {
$this->storePriceListCache($prices);
}
}
if (!is_array($prices) || $prices === []) {
return $empty;
}
$copper = 0;
$dollar = 0;
$copperScore = PHP_INT_MAX;
$dollarScore = PHP_INT_MAX;
foreach ($prices as $row) {
if (!is_array($row)) {
continue;
}
$total = $this->resolveReferenceProviderTotal($row);
if ($total <= 0) {
continue;
}
$rowCopperScore = $this->worldCopperRowScore($row);
if ($rowCopperScore !== null && $rowCopperScore < $copperScore) {
$copperScore = $rowCopperScore;
$copper = $total;
}
$rowDollarScore = $this->freeDollarRowScore($row);
if ($rowDollarScore !== null && $rowDollarScore < $dollarScore) {
$dollarScore = $rowDollarScore;
$dollar = $total;
}
}
$ton = ($copper > 0 && $dollar > 0) ? $this->decimalProduct($copper, $dollar) : '0';
return [
'copper' => $copper,
'dollar' => $dollar,
'ton' => $ton,
'kilo' => $this->divideDecimalByThousand($ton),
];
}
/** @param array<string, mixed> $row */
private function worldCopperRowScore(array $row): ?int
{
$key = strtolower(trim((string) ($row['key'] ?? '')));
$name = trim((string) ($row['name'] ?? ''));
if (str_contains($key, 'basemetal_london_copper')) {
return 0;
}
if ($name === 'TGJU فلز مس') {
return 1;
}
if (mb_strpos($name, 'مس جهانی') !== false) {
return 2;
}
return null;
}
/**
* دلار آزاد تابلو — نه کاتد دلاری و نه نرخ تومانی فروشگاه‌ها.
*
* @param array<string, mixed> $row
*/
private function freeDollarRowScore(array $row): ?int
{
$key = strtolower(trim((string) ($row['key'] ?? '')));
$name = trim((string) ($row['name'] ?? ''));
if (
str_contains($key, 'copper')
|| mb_strpos($name, 'کاتد') !== false
|| mb_strpos($name, 'مس') !== false
) {
return null;
}
if ($key === 'tgju_usd') {
return 0;
}
if ($name === 'TGJU دلار' || $name === 'tgju دلار آمریکا') {
return 1;
}
if (mb_strpos($name, 'دلار') !== false && mb_strpos($name, 'آزاد') !== false) {
return 2;
}
return null;
}
private function decimalProduct(int $left, int $right): string
{
if (function_exists('bcmul')) {
return bcmul((string) $left, (string) $right, 0);
}
return sprintf('%.0f', $left * $right);
}
private function divideDecimalByThousand(string $value): string
{
if ($value === '' || $value === '0') {
return '0';
}
if (strlen($value) <= 3) {
$kilo = ((int) $value) / 1000;
return rtrim(rtrim(number_format($kilo, 3, '.', ''), '0'), '.');
}
$whole = ltrim(substr($value, 0, -3), '0');
$fraction = rtrim(substr($value, -3), '0');
if ($whole === '') {
$whole = '0';
}
return $fraction === '' ? $whole : $whole.'.'.$fraction;
}
/**
* @return array{price: int, order_price: int, raw: array<string, mixed>|null}
*/
+6 -6
View File
@@ -40,15 +40,15 @@ return [
'driver' => 'session',
'provider' => 'users',
],
'user' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => true,
],
'customer' => [
'driver' => 'jwt',
'provider' => 'customers',
'hash' => true,
'hash' => false,
],
'user' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
],
@@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('giftcards')) {
Schema::create('giftcards', function (Blueprint $table) {
$table->increments('id');
$table->integer('customer_id')->nullable();
$table->unsignedTinyInteger('use_once')->default(0);
$table->integer('count')->nullable();
$table->decimal('amount', 20, 4)->nullable();
$table->decimal('total', 20, 4)->nullable();
$table->integer('unit')->nullable();
$table->string('unique_code')->nullable();
$table->timestamp('created_at')->nullable();
$table->unsignedTinyInteger('sts')->nullable();
$table->timestamp('expiry_date')->nullable();
$table->integer('used_count')->nullable();
$table->timestamp('updated_at')->nullable();
$table->text('description')->nullable();
$table->string('name')->nullable();
$table->string('mobile')->nullable();
});
}
if (! Schema::hasTable('giftcard_codes')) {
Schema::create('giftcard_codes', function (Blueprint $table) {
$table->increments('id');
$table->integer('giftcard_id')->nullable();
$table->unsignedTinyInteger('use_once')->default(0);
$table->string('code')->nullable();
$table->unsignedTinyInteger('sts')->nullable();
$table->unsignedTinyInteger('unit')->nullable();
$table->decimal('amount', 20, 4)->nullable();
$table->text('assigned_to')->nullable();
$table->timestamp('used_at')->nullable();
$table->timestamp('expiry_date')->nullable();
$table->timestamps();
});
}
}
public function down(): void
{
// جدول ممکن است از قبل روی نصب‌های قدیمی بوده باشد؛ drop نمی‌کنیم.
}
};
@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* سقف قبلی amount (مثلاً FLOAT/DECIMAL با precision کم) جلوی مبالغ ~۱۰۰ میلیون ریال را می‌گرفت (خطای ۱۲۶۴).
*/
public function up(): void
{
if (Schema::hasTable('giftcards') && Schema::hasColumn('giftcards', 'amount')) {
DB::statement('ALTER TABLE `giftcards` MODIFY `amount` DECIMAL(20,4) NULL');
}
if (Schema::hasTable('giftcards') && Schema::hasColumn('giftcards', 'total')) {
DB::statement('ALTER TABLE `giftcards` MODIFY `total` DECIMAL(20,4) NULL');
}
if (Schema::hasTable('giftcard_codes') && Schema::hasColumn('giftcard_codes', 'amount')) {
DB::statement('ALTER TABLE `giftcard_codes` MODIFY `amount` DECIMAL(20,4) NULL');
}
}
public function down(): void
{
if (Schema::hasTable('giftcards') && Schema::hasColumn('giftcards', 'amount')) {
DB::statement('ALTER TABLE `giftcards` MODIFY `amount` FLOAT NULL');
}
if (Schema::hasTable('giftcards') && Schema::hasColumn('giftcards', 'total')) {
DB::statement('ALTER TABLE `giftcards` MODIFY `total` BIGINT NULL');
}
if (Schema::hasTable('giftcard_codes') && Schema::hasColumn('giftcard_codes', 'amount')) {
DB::statement('ALTER TABLE `giftcard_codes` MODIFY `amount` FLOAT NULL');
}
}
};
@@ -0,0 +1,22 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (Schema::hasTable('giftcards') && ! Schema::hasColumn('giftcards', 'show_in_app')) {
Schema::table('giftcards', function (Blueprint $table) {
$table->unsignedTinyInteger('show_in_app')->default(0)->after('use_once');
});
}
}
public function down(): void
{
// ستون ممکن است روی نصب‌های قدیمی استفاده شود؛ drop نمی‌کنیم.
}
};
@@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('shayegan')) {
Schema::create('shayegan', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id')->nullable()->index();
$table->unsignedBigInteger('order_id')->nullable()->index();
$table->unsignedBigInteger('withdraw_id')->nullable()->index();
$table->decimal('amount', 18, 4)->nullable();
$table->string('desc')->nullable();
$table->string('type', 32)->nullable()->index();
$table->timestamp('date')->nullable();
$table->string('endpoint', 64)->nullable();
$table->string('request_guid', 64)->nullable()->index();
$table->string('shayegan_number')->nullable()->index();
$table->string('shayegan_guid')->nullable()->index();
$table->longText('data')->nullable();
$table->longText('res')->nullable();
// pending|success|failed|timeout — timeout must not auto-resend
$table->string('sync_status', 20)->default('pending')->index();
$table->text('sync_log')->nullable();
$table->timestamps();
});
}
}
public function down(): void
{
Schema::dropIfExists('shayegan');
}
};
@@ -0,0 +1,168 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* تنظیمات اتصال شایگان — value ردیف موجود را UPDATE نمی‌کند.
* رمزها را در Git نگذار؛ بعد از migrate در DB پر کن.
*/
return new class extends Migration
{
private const KEYS = [
'shayegan_base_url' => [
'value' => 'http://2.180.4.172:2030',
'title_fa' => 'آدرس پایه وب‌سرویس شایگان',
'description' => 'بدون /api در انتها. عمومی دفتر: http://2.180.4.172:2030 — داخلی LAN: http://192.168.109.222:2030 — اگر 404 شد /WsServer اضافه کنید. نام SQL را اینجا نگذارید.',
'type' => 'text',
],
'shayegan_sql_server' => [
'value' => 'P-SERVER',
'title_fa' => 'نام SQL Server شایگان (Config.Server)',
'description' => 'Config.Server — فقط برای بدنهٔ وب‌سرویس، نه آدرس HTTP. (نمونهٔ بورس مس: P-SERVER)',
'type' => 'text',
],
'shayegan_database' => [
'value' => 'CYPRSD04',
'title_fa' => 'نام دیتابیس حسابگر (Config.DataBaseName)',
'description' => 'نمونهٔ عملیاتی بورس مس: CYPRSD04 — برای تست ثبت از دیتابیس آزمایشی استفاده کنید.',
'type' => 'text',
],
'shayegan_db_user' => [
'value' => 'sa',
'title_fa' => 'کاربر SQL Server شایگان',
'description' => 'Config.DBUserName — فقط backend؛ در پاسخ API ماسک می‌شود.',
'type' => 'text',
],
'shayegan_db_password' => [
'value' => '',
'title_fa' => 'رمز SQL Server شایگان',
'description' => 'Config.DBPassword — فقط backend؛ در لاگ و frontend برنمی‌گردد.',
'type' => 'password',
],
'shayegan_auth_user' => [
'value' => '',
'title_fa' => 'AuthUser وب‌سرویس شایگان',
'description' => 'خالی = بدون تایید هویت، یا کاربر حسابگر/شایگان طبق حالت نصب.',
'type' => 'text',
],
'shayegan_auth_password' => [
'value' => '',
'title_fa' => 'AuthPassword وب‌سرویس شایگان',
'description' => 'فقط backend؛ در لاگ و frontend برنمی‌گردد.',
'type' => 'password',
],
'shayegan_language' => [
'value' => '3',
'title_fa' => 'Language شایگان',
'description' => 'Config.Language — نمونه مستندات معمولاً 3 است.',
'type' => 'number',
],
'shayegan_timeout_seconds' => [
'value' => '30',
'title_fa' => 'Timeout HTTP شایگان (ثانیه)',
'description' => 'پس از timeout وضعیت timeout ذخیره می‌شود و ارسال خودکار تکرار نمی‌شود.',
'type' => 'number',
],
'shayegan_item_copper' => [
'value' => '',
'title_fa' => 'کد کالای مس در حسابگر (ItemNumber)',
'description' => 'برای فاکتور خرید/فروش مس.',
'type' => 'text',
],
'shayegan_stock_number' => [
'value' => '',
'title_fa' => 'شماره انبار مس (STNumber)',
'description' => 'انبار ردیف فاکتور خرید/فروش.',
'type' => 'text',
],
'shayegan_bank_account' => [
'value' => '',
'title_fa' => 'شماره حساب بانک/صندوق ریالی',
'description' => 'طرف حساب بانک در Document واریز/برداشت ریالی.',
'type' => 'text',
],
'shayegan_moin_customer' => [
'value' => '',
'title_fa' => 'شماره معین مشتریان (MoinNumber)',
'description' => 'برای Account/Put هنگام ساخت حساب مشتری در حسابگر.',
'type' => 'text',
],
'shayegan_amount_scale' => [
'value' => '1',
'title_fa' => 'ضریب مبلغ به شایگان',
'description' => 'مبلغ پنل ریال است. اگر حسابگر تومان است 0.1 بگذارید؛ اگر ریال است 1.',
'type' => 'text',
],
'shayegan_weight_scale' => [
'value' => '1',
'title_fa' => 'ضریب وزن به Quan شایگان',
'description' => 'وزن پنل را به واحد کالای حسابگر تبدیل می‌کند (مثلاً گرم→کیلو = 0.001).',
'type' => 'text',
],
'shayegan_metal_wallet_mode' => [
'value' => 'skip',
'title_fa' => 'حالت واریز/برداشت محصول به شایگان',
'description' => 'skip=ارسال نشود | document=فقط سند حسابداری | receipt_havale=رسید(5)/حواله(4). تغییر کیف را ورود/خروج انبار فرض نکنید مگر صریح.',
'type' => 'text',
],
];
public function up(): void
{
$hasMenu = Schema::hasColumn('settings', 'menu');
foreach (self::KEYS as $key => $meta) {
$exists = DB::table('settings')->where('key', $key)->exists();
if (! $exists) {
$row = [
'key' => $key,
'value' => $meta['value'],
'title_fa' => $meta['title_fa'],
'can_edit' => 0,
'is_active' => 1,
'description' => $meta['description'],
'type' => $meta['type'],
];
if ($hasMenu) {
$row['menu'] = 'accounting_shayegan';
}
DB::table('settings')->insert($row);
continue;
}
$update = [
'title_fa' => $meta['title_fa'],
'description' => $meta['description'],
'type' => $meta['type'],
'can_edit' => 0,
'is_active' => 1,
];
if ($hasMenu) {
$update['menu'] = 'accounting_shayegan';
}
DB::table('settings')->where('key', $key)->update($update);
}
$provider = DB::table('settings')->where('key', 'accounting_provider')->first();
if ($provider) {
$desc = (string) ($provider->description ?? '');
if (strpos($desc, 'shayegan') === false) {
if (strpos($desc, 'none,pargar,tahesab,zarin') !== false) {
$newDesc = str_replace('none,pargar,tahesab,zarin', 'none,pargar,tahesab,zarin,shayegan', $desc);
} else {
$newDesc = trim($desc) === '' ? 'none,pargar,tahesab,zarin,shayegan' : ($desc . ',shayegan');
}
DB::table('settings')->where('key', 'accounting_provider')->update([
'description' => $newDesc,
]);
}
}
}
public function down(): void
{
DB::table('settings')->whereIn('key', array_keys(self::KEYS))->delete();
}
};
@@ -0,0 +1,44 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
/**
* بورس مس: مقدار accounting_provider فقط وقتی خالی/none است → shayegan (valueهای دیگر دست نمی‌خورد).
*/
return new class extends Migration
{
public function up(): void
{
if (! DB::getSchemaBuilder()->hasTable('settings')) {
return;
}
DB::table('settings')
->where('key', 'accounting_provider')
->where(function ($q) {
$q->whereNull('value')
->orWhere('value', '')
->orWhere('value', 'none');
})
->update(['value' => 'shayegan']);
$row = DB::table('settings')->where('key', 'accounting_provider')->first();
if (! $row) {
DB::table('settings')->insert([
'key' => 'accounting_provider',
'value' => 'shayegan',
'title_fa' => 'سیستم حسابداری',
'can_edit' => 0,
'is_active' => 1,
'description' => 'boursecu: shayegan (ثابت در کد)',
'type' => 'select',
]);
}
}
public function down(): void
{
// عمداً برنمی‌گردانیم — بورس مس همیشه شایگان است.
}
};
@@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* ردیف‌های shayegan_* گاهی menu=misc دارند → در ادمین زیر «سایر» می‌روند نه «حسابداری شایگان».
*/
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('settings') || ! Schema::hasColumn('settings', 'menu')) {
return;
}
DB::table('settings')
->where('key', 'like', 'shayegan\_%')
->update(['menu' => 'accounting_shayegan']);
}
public function down(): void
{
// عمداً برنمی‌گردانیم — misc قبلی نامشخص بود
}
};
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (!Schema::hasTable('users') || Schema::hasColumn('users', 'page_access')) {
return;
}
Schema::table('users', function (Blueprint $table) {
$table->json('page_access')->nullable()->comment('null=دسترسی کامل؛ در غیر این صورت مشاهده/ویرایش/حذف هر صفحه');
});
}
public function down(): void
{
if (!Schema::hasTable('users') || !Schema::hasColumn('users', 'page_access')) {
return;
}
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('page_access');
});
}
};
@@ -0,0 +1,130 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('digipay_credits')) {
Schema::create('digipay_credits', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id')->unique();
$table->string('status', 20)->default('pending');
$table->unsignedBigInteger('plan4_remaining_rial')->default(0);
$table->unsignedBigInteger('plan12_remaining_rial')->default(0);
$table->timestamps();
});
}
if (! Schema::hasTable('digipay_orders')) {
Schema::create('digipay_orders', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id')->index();
$table->unsignedTinyInteger('plan');
$table->unsignedBigInteger('amount_rial');
$table->unsignedBigInteger('fee_rial');
$table->decimal('grams', 16, 4);
$table->unsignedBigInteger('gram_price_rial');
$table->string('status', 20)->default('done');
$table->timestamps();
});
}
if (! Schema::hasTable('settings')) {
return;
}
$rows = [
[
'key' => 'enable_digipay_installment',
'value' => 'false',
'title_fa' => 'خرید اقساطی مس',
'description' => 'روشن: منوی خرید اقساطی در اپ و صفحه اعتبار دیجی‌پی در ادمین.',
'type' => 'switch',
'show' => 1,
],
[
'key' => 'digipay_onboarding_url',
'value' => '',
'title_fa' => 'لینک احراز دیجی‌پی',
'description' => 'لینکی که دیجی‌پی بعد از قرارداد می‌دهد. کاربر برای احراز هویت به همین آدرس می‌رود.',
'type' => 'text',
'show' => 0,
],
[
'key' => 'digipay_fee_shop_percent',
'value' => '8',
'title_fa' => 'کارمزد خرید اقساطی (درصد)',
'description' => '',
'type' => 'number',
'show' => 1,
],
[
'key' => 'digipay_fee_gateway_percent',
'value' => '5.7',
'title_fa' => 'کارمزد دیجی‌پی (درصد)',
'description' => '',
'type' => 'number',
'show' => 1,
],
[
'key' => 'digipay_fee_extra_percent',
'value' => '2.3',
'title_fa' => 'کارمزد جانبی اقساط (درصد)',
'description' => '',
'type' => 'number',
'show' => 1,
],
[
'key' => 'digipay_plan4_cap_toman',
'value' => '30000000',
'title_fa' => 'سقف اعتبار ۴ قسط (تومان)',
'description' => '',
'type' => 'number',
'show' => 1,
],
[
'key' => 'digipay_plan12_cap_toman',
'value' => '200000000',
'title_fa' => 'سقف وام ۱۲ قسط (تومان)',
'description' => '',
'type' => 'number',
'show' => 1,
],
];
$hasType = Schema::hasColumn('settings', 'type');
$hasShow = Schema::hasColumn('settings', 'show_to_user');
foreach ($rows as $row) {
if (DB::table('settings')->where('key', $row['key'])->exists()) {
continue;
}
$insert = [
'key' => $row['key'],
'value' => $row['value'],
'title_fa' => $row['title_fa'],
'description' => $row['description'],
'can_edit' => 1,
'is_active' => 1,
];
if ($hasType) {
$insert['type'] = $row['type'];
}
if ($hasShow) {
$insert['show_to_user'] = $row['show'];
}
DB::table('settings')->insert($insert);
}
}
public function down(): void
{
Schema::dropIfExists('digipay_orders');
Schema::dropIfExists('digipay_credits');
}
};
@@ -0,0 +1,73 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (Schema::hasTable('products') && ! Schema::hasColumn('products', 'shayegan_item_number')) {
Schema::table('products', function (Blueprint $table) {
$table->string('shayegan_item_number', 32)->nullable()->after('finance_p_name');
});
}
if (Schema::hasTable('shayegan') && ! Schema::hasColumn('shayegan', 'product_id')) {
Schema::table('shayegan', function (Blueprint $table) {
$table->unsignedBigInteger('product_id')->nullable()->after('order_id')->index();
});
}
if (! Schema::hasTable('settings')) {
return;
}
$this->insertSettingIfMissing('shayegan_kol_customer', [
'value' => '121',
'title_fa' => 'کد کل حساب دریافتنی مشتری (شایگان)',
'description' => 'طبق راهنمای حسابداری بورس مس: کل 121 — معین در shayegan_moin_customer (12101). فعلاً فقط مستند؛ Account/Put از MoinNumber استفاده می‌کند.',
'type' => 'text',
'menu' => 'accounting_shayegan',
]);
}
public function down(): void
{
if (Schema::hasTable('products') && Schema::hasColumn('products', 'shayegan_item_number')) {
Schema::table('products', function (Blueprint $table) {
$table->dropColumn('shayegan_item_number');
});
}
if (Schema::hasTable('shayegan') && Schema::hasColumn('shayegan', 'product_id')) {
Schema::table('shayegan', function (Blueprint $table) {
$table->dropColumn('product_id');
});
}
}
/**
* @param array{value:string,title_fa:string,description:string,type:string,menu:string} $meta
*/
private function insertSettingIfMissing(string $key, array $meta): void
{
$exists = DB::table('settings')->where('key', $key)->exists();
if ($exists) {
return;
}
DB::table('settings')->insert([
'key' => $key,
'value' => $meta['value'],
'title_fa' => $meta['title_fa'],
'description' => $meta['description'],
'type' => $meta['type'],
'menu' => $meta['menu'],
'created_at' => now(),
'updated_at' => now(),
]);
}
};
@@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (Schema::hasTable('copper_convert_requests')) {
return;
}
Schema::create('copper_convert_requests', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id')->index();
$table->string('status', 20)->default('pending')->index();
$table->string('source', 20);
$table->unsignedBigInteger('source_product_id');
$table->string('asset_unit', 32);
$table->decimal('consumed_amount', 16, 4);
$table->decimal('leftover_amount', 16, 4)->default(0);
$table->unsignedBigInteger('source_unit_price');
$table->unsignedBigInteger('wire15_product_id')->nullable();
$table->unsignedInteger('wire15_rings')->default(0);
$table->unsignedBigInteger('wire15_unit_price')->default(0);
$table->unsignedBigInteger('wire25_product_id')->nullable();
$table->unsignedInteger('wire25_rings')->default(0);
$table->unsignedBigInteger('wire25_unit_price')->default(0);
$table->unsignedBigInteger('sell_order_id')->nullable();
$table->unsignedBigInteger('buy15_order_id')->nullable();
$table->unsignedBigInteger('buy25_order_id')->nullable();
$table->unsignedBigInteger('admin_id')->nullable();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('copper_convert_requests');
}
};
@@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* سه سطح: کل 121، معین 12101، تفصیلی = معین + کد کاربری (12101530).
* مقدار 1210101 اشتباه بود و به 12101 برمی‌گردد. مقدار دیگر دست نمی‌خورد.
*/
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('settings')) {
return;
}
$row = DB::table('settings')->where('key', 'shayegan_moin_customer')->first();
if (! $row) {
return;
}
$current = trim((string) ($row->value ?? ''));
$update = [
'description' => 'معین Account/Put. شماره تفصیلی = این مقدار + کد کاربری. مثال: 12101 و مشتری 530 → 12101530.',
'updated_at' => now(),
];
if ($current === '' || $current === '1210101') {
$update['value'] = '12101';
}
DB::table('settings')->where('key', 'shayegan_moin_customer')->update($update);
}
public function down(): void
{
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* تفصیلی = کد کل + کد کاربری ۷رقمی. مثال: 121 و مشتری 1 → 1210000001.
* مقدار تنظیمات عوض نمی‌شود.
*/
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('settings')) {
return;
}
DB::table('settings')->where('key', 'shayegan_kol_customer')->update([
'description' => 'ابتدای ثابت کد تفصیلی. کد = این مقدار + کد کاربری ۷رقمی با صفر. مثال: 121 و مشتری 1 → 1210000001.',
'updated_at' => now(),
]);
DB::table('settings')->where('key', 'shayegan_moin_customer')->update([
'description' => 'معین مشتریان. به شماره تفصیلی چسبانده نمی‌شود؛ شماره = کد کل + کد کاربری ۷رقمی.',
'updated_at' => now(),
]);
}
public function down(): void
{
}
};
@@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('shayegan_inbound_charges')) {
Schema::create('shayegan_inbound_charges', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('customer_id')->nullable()->index();
$table->string('customer_tafsil', 64)->nullable()->index();
$table->string('shayegan_number', 64)->nullable()->index();
$table->decimal('amount', 18, 4);
$table->text('description')->nullable();
$table->string('source', 32)->default('webhook')->index();
$table->string('status', 20)->default('pending')->index(); // pending, approved, rejected
$table->longText('raw_data')->nullable();
$table->unsignedBigInteger('approved_by')->nullable()->index();
$table->timestamp('approved_at')->nullable();
$table->unsignedBigInteger('rejected_by')->nullable()->index();
$table->timestamp('rejected_at')->nullable();
$table->string('reject_reason', 255)->nullable();
$table->unsignedBigInteger('withdraw_id')->nullable()->index();
$table->unsignedBigInteger('transaction_id')->nullable()->index();
$table->timestamps();
});
}
}
public function down(): void
{
Schema::dropIfExists('shayegan_inbound_charges');
}
};
@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('settings')) {
return;
}
$exists = DB::table('settings')->where('key', 'shayegan_webhook_secret')->exists();
if (! $exists) {
$hasMenu = Schema::hasColumn('settings', 'menu');
$row = [
'key' => 'shayegan_webhook_secret',
'value' => 'shayegan_sec_' . bin2hex(random_bytes(12)),
'title_fa' => 'کلید امنیتی وب‌هوک شایگان (X-Shayegan-Key)',
'description' => 'کلید محرمانه جهت احراز هویت درخواست‌های وب‌هوک شارژ از شایگان به بورس مس.',
'can_edit' => 0,
'is_active' => 1,
'type' => 'password',
];
if ($hasMenu) {
$row['menu'] = 'accounting_shayegan';
}
DB::table('settings')->insert($row);
}
}
public function down(): void
{
if (Schema::hasTable('settings')) {
DB::table('settings')->where('key', 'shayegan_webhook_secret')->delete();
}
}
};
@@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('settings')) {
return;
}
$row = DB::table('settings')->where('key', 'unit')->first();
if ($row) {
$val = trim((string) ($row->value ?? ''));
if ($val === '' || $val === 'گرم') {
DB::table('settings')->where('key', 'unit')->update([
'value' => 'کیلوگرم',
'updated_at' => now(),
]);
}
} else {
DB::table('settings')->insert([
'key' => 'unit',
'value' => 'کیلوگرم',
'title_fa' => 'واحد وزن معاملات',
'description' => 'واحد اصلی وزن در بورس مس (کیلوگرم).',
'can_edit' => 0,
'is_active' => 1,
'type' => 'text',
'created_at' => now(),
'updated_at' => now(),
]);
}
}
public function down(): void
{
}
};
@@ -0,0 +1,51 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('withdraws')) {
return;
}
Schema::table('withdraws', function (Blueprint $table) {
if (! Schema::hasColumn('withdraws', 'receipt')) {
$table->string('receipt', 500)->nullable()->after('tracked_number');
}
if (! Schema::hasColumn('withdraws', 'deposit_identifier')) {
$table->string('deposit_identifier', 50)->nullable()->after('receipt');
}
if (! Schema::hasColumn('withdraws', 'reject_reason')) {
$table->text('reject_reason')->nullable()->after('deposit_identifier');
}
});
}
public function down(): void
{
if (! Schema::hasTable('withdraws')) {
return;
}
Schema::table('withdraws', function (Blueprint $table) {
$cols = [];
if (Schema::hasColumn('withdraws', 'reject_reason')) {
$cols[] = 'reject_reason';
}
if (Schema::hasColumn('withdraws', 'deposit_identifier')) {
$cols[] = 'deposit_identifier';
}
if (Schema::hasColumn('withdraws', 'receipt')) {
$cols[] = 'receipt';
}
if ($cols !== []) {
$table->dropColumn($cols);
}
});
}
};
@@ -0,0 +1,45 @@
<?php
use App\Models\Setting;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
if (! Schema::hasTable('settings')) {
return;
}
Setting::updateOrCreate(
['key' => 'auto_active_customer'],
[
'value' => 'true',
'title_fa' => 'فعال‌سازی خودکار کاربر پس از ثبت‌نام',
'description' => 'روشن: بعد از ثبت‌نام کاربر می‌تواند وارد اپ شود بدون نیاز به تأیید دستی ادمین.',
'can_edit' => 1,
'is_active' => 1,
'type' => 'switch',
]
);
Setting::updateOrCreate(
['key' => 'register_jibit_verify'],
[
'value' => 'true',
'title_fa' => 'احراز هویت جیبیت در ثبت‌نام و پروفایل',
'description' => 'روشن: تطبیق کد ملی با شماره همراه از طریق سامانه جیبیت.',
'can_edit' => 1,
'is_active' => 1,
'type' => 'switch',
]
);
}
public function down(): void
{
// No destructive rollback needed
}
};
+41
View File
@@ -771,6 +771,47 @@ SET @sql = IF(
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- ---------------------------------------------------------------------------
-- giftcards: ظرفیت مبلغ ریالی (خطای 1264 روی amount ~۱۰۰ میلیون)
-- ---------------------------------------------------------------------------
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@db AND TABLE_NAME='giftcards' AND COLUMN_NAME='amount') > 0
AND (SELECT IFNULL(NUMERIC_PRECISION, 0) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@db AND TABLE_NAME='giftcards' AND COLUMN_NAME='amount') < 20,
'ALTER TABLE `giftcards` MODIFY `amount` DECIMAL(20,4) NULL',
'SELECT ''skip giftcards.amount widen'' AS info'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@db AND TABLE_NAME='giftcards' AND COLUMN_NAME='total') > 0
AND (SELECT IFNULL(NUMERIC_PRECISION, 0) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@db AND TABLE_NAME='giftcards' AND COLUMN_NAME='total') < 20,
'ALTER TABLE `giftcards` MODIFY `total` DECIMAL(20,4) NULL',
'SELECT ''skip giftcards.total widen'' AS info'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@db AND TABLE_NAME='giftcards' AND COLUMN_NAME='show_in_app') = 0,
'ALTER TABLE `giftcards` ADD COLUMN `show_in_app` TINYINT UNSIGNED NOT NULL DEFAULT 0 AFTER `use_once`',
'SELECT ''skip giftcards.show_in_app'' AS info'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
SET @sql = IF(
(SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@db AND TABLE_NAME='giftcard_codes' AND COLUMN_NAME='amount') > 0
AND (SELECT IFNULL(NUMERIC_PRECISION, 0) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA=@db AND TABLE_NAME='giftcard_codes' AND COLUMN_NAME='amount') < 20,
'ALTER TABLE `giftcard_codes` MODIFY `amount` DECIMAL(20,4) NULL',
'SELECT ''skip giftcard_codes.amount widen'' AS info'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
-- ---------------------------------------------------------------------------
-- پایان — برای بورس‌مس (اختیاری، جدا اجرا کنید):
-- UPDATE `settings` SET `value` = 'کیلوگرم' WHERE `key` = 'unit';
+7
View File
@@ -0,0 +1,7 @@
shayegan.pdf
Sample_Shygun.postman_collection.json
pdf_*.txt
put_endpoints.txt
node_modules/
package.json
package-lock.json
+84
View File
@@ -0,0 +1,84 @@
# Shayegan webservice notes (PDF + Sample_Shygun Postman)
Do not store real credentials in this file or in Git.
## Known for boursecu (operator, 2026-10-05)
Store panel (`app.boursemes.com`) is the **Laravel API**, not Shayegan:
- Shop domain: `app.boursemes.com`
- `node_server`: `https://app.boursemes.com/server`
- Listed LAN IP on that panel: `192.168.70.189` — different from Shayegan host; do not use as WsServer unless confirmed.
Shayegan webservice hosts (operator):
- Public/static (Mashhad office): `2.180.4.172`
- Internal LAN: `192.168.109.222`
- Port: `2030`
- Candidate `shayegan_base_url` (no `/api` suffix):
- From internet / remote app server: `http://2.180.4.172:2030`
- From same LAN as حسابگر: `http://192.168.109.222:2030`
- If 404, retry with `/WsServer` appended (Postman samples).
SQL Config for Shayegan Put/Get (inside JSON `Config`, not HTTP host):
- `Server`: `P-SERVER`
- `DataBaseName`: `CYPRSD04`
- `DBUserName`: `sa`
- Password: set only in DB `settings.shayegan_db_password` (never commit).
Still useful from operator: Auth*, ItemNumber, STNumber, bank account, amount/weight scales, metal wallet mode.
## Base URL (PDF)
`http://{host}[:port]{optionalBasePath}/api/{Endpoint}`
PDF example: `http://192.168.1.1/api/Document/Put`
Postman often inserts `/WsServer` or `/WsServer-3.13` before `/api`.
Operator port hint: `2030`. SQL Server name is **not** the HTTP host.
## Request shape
Every call body includes `Config`.
Get calls also include `Domain` (+ `RowStart`/`RowCount` query).
Put calls include `PutObject` array at the **same level** as `Config` (raw HTTP / Postman). PDF C# wrapper is named `Put`.
### Config fields
`Server`, `AllowRowSecurity`, `Level`, `DBUserName`, `DBPassword`, `DataBaseName`, `AuthUser`, `AuthPassword`, `Language`
Auth: Shayegan cloud / Hesabgar / none (empty Auth*).
## Endpoints used
| Op | Method path |
|----|-------------|
| Health (read) | `POST .../api/Account/Get?RowStart=0&RowCount=1` |
| Trade | `POST .../api/Invoice/Put` |
| Rial ledger | `POST .../api/Document/Put` |
Customer account | `POST .../api/Account/Put` — `MoinNumber` (e.g. 12101), `AccountName`, `UpdateKind: 3`; response `Number` = تفصیلی stored as `moshtari_code`.
## Put response (check even on HTTP 200)
```json
{
"Result": [{ "ErrorMessage": "", "Number": "6572", "GuId": "..." }],
"ErrorMessage": "",
"TokenString": ""
}
```
Treat non-empty top-level or per-row `ErrorMessage` as failure.
## InvTyp (company)
1 تولید | 2 فروش | 3 خرید | 4 حواله | 5 رسید انبار | 6 برگشت فروش | 7 برگشت خرید | 8/9 تعدیل | 10 انتقال انبار | 11/12 سفارش | 13 پیش‌فاکتور
Customer **buy** copper → company **فروش** → `InvTyp=2`
Customer **sell** copper → company **خرید** → `InvTyp=3`
## Document body (PDF)
Prefer `AmountBed` / `AmountBes` (also `RialBed` / `RialBes` exist).
Header: `DocDescription`, `DocDate` (`yyyyMMdd`), `DocReference`, `GuId`.
## Invoice required (PDF)
`AccountNumber`, `InvTyp`, `InvDate`; line: item + `STNumber` + `Quan` + `Price`.
Ignore Postman keys with trailing spaces — PDF field names are authoritative.
@@ -44,6 +44,22 @@ class WalletInterface
]);
$this->set_hash();
}
$this->absorbMismatchedOwnerTypeBalances();
}
/** واریزِ مانده روی owner_type قدیمی را به نوع فعلی مشتری برمی‌گرداند. */
private function absorbMismatchedOwnerTypeBalances(): void
{
$ownerType = (int) $this->owner_type;
$ownerId = (int) $this->owner_id;
if ($ownerType <= 0 || $ownerId <= 0 || !$this->wallet) {
return;
}
app(\App\Services\WalletBalanceService::class)
->absorbMismatchedOwnerTypeBalances($ownerId, $ownerType);
$this->wallet->refresh();
}
public function validate(): bool
+26 -1
View File
@@ -2,6 +2,7 @@
use App\Http\Controllers\Admin\ConstController;
use App\Http\Controllers\Admin\OrderController;
use App\Http\Controllers\Admin\CopperConvertRequestController;
use App\Http\Controllers\Admin\PriceController;
use App\Http\Controllers\Admin\UserController;
use App\Http\Controllers\Admin\CustomerController;
@@ -19,9 +20,11 @@ use App\Http\Controllers\Admin\ProductController;
use App\Http\Controllers\Admin\TahesabController;
use App\Http\Controllers\Admin\ZarinController;
use App\Http\Controllers\Admin\PargarController;
use App\Http\Controllers\Admin\ShayeganController;
use App\Http\Controllers\Admin\FileController;
use App\Http\Controllers\Site\OfferCodesController;
use App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Admin\DigipayInstallmentController as AdminDigipayInstallmentController;
use App\Http\Controllers\Admin\GoldCreditController as AdminGoldCreditController;
use \App\Http\Controllers\Admin\GiftCardController;
use App\Http\Controllers\Admin\CategoryController;
@@ -31,7 +34,7 @@ use App\Http\Controllers\Admin\SmsPanelController;
use App\Services\ConfigService;
Route::middleware('auth:user')->group(function (){
Route::middleware(['auth:user', 'admin.page'])->group(function (){
Route::middleware('validation')->group(function (){
Route::get('/p', [PriceController::class, 'methodPrices'])
->withoutMiddleware(['throttle:api']);
@@ -183,6 +186,9 @@ Route::middleware('auth:user')->group(function (){
Route::put('/gold_credit/{id}', [AdminGoldCreditController::class, 'update']);
Route::post('/gold_credit', [AdminGoldCreditController::class, 'store']);
Route::post('/digipay_installment/credit', [AdminDigipayInstallmentController::class, 'setCredit']);
Route::post('/digipay_installment/orders', [AdminDigipayInstallmentController::class, 'orders']);
Route::post('/wallet/charge_wallet',[WalletController::class,'charge_wallet']);
Route::get('/wallet/charge-targets',[WalletController::class,'chargeTargets']);
Route::post('/wallet/table',[WalletController::class,'indexWallet']);
@@ -193,6 +199,8 @@ Route::middleware('auth:user')->group(function (){
Route::put('/wallet/withdraw/{id}',[WalletController::class,'updateWithdraw']);
Route::get('/wallet/withdraw/{id}',[WalletController::class,'getWithdraw']);
Route::post('/wallet/withdraw/complete',[WalletController::class,'completeWithdraw']);
Route::post('/wallet/deposit/approve', [WalletController::class, 'approveDeposit']);
Route::post('/wallet/deposit/reject', [WalletController::class, 'rejectDeposit']);
Route::post('/wallet/withdraw_physical/table',[WalletController::class,'indexPhysicalWithdraw']);
Route::get('/wallet/withdraw_physical/options/{customerId}',[WalletController::class,'physicalWithdrawOptions']);
Route::post('/wallet/withdraw_physical',[WalletController::class,'createPhysicalWithdraw']);
@@ -204,6 +212,9 @@ Route::middleware('auth:user')->group(function (){
Route::post('order/single/table', [OrderController::class, 'singleOrderTable']);
Route::post('order/colleague/table', [OrderController::class, 'colleagueTable']);
Route::post('single/order', [SingleOrderController::class, 'store']);
Route::get('copper-convert-request', [CopperConvertRequestController::class, 'index']);
Route::post('copper-convert-request/{id}/approve', [CopperConvertRequestController::class, 'approve']);
Route::post('copper-convert-request/{id}/reject', [CopperConvertRequestController::class, 'reject']);
//-------------------price
Route::post('price', [PriceController::class, 'store']);
@@ -288,6 +299,17 @@ Route::middleware('auth:user')->group(function (){
Route::post('customer/{id}/zarin/sync-wallet', [ZarinController::class, 'syncCustomerWallet']);
Route::post('customer/{id}/zarin/preview-wallet', [ZarinController::class, 'previewCustomerWallet']);
Route::get('shayegan/health', [ShayeganController::class, 'healthCheck']);
Route::post('shayegan/table', [ShayeganController::class, 'table']);
Route::get('shayegan/{id}', [ShayeganController::class, 'show']);
Route::post('shayegan/{id}/retry', [ShayeganController::class, 'retrySanad']);
Route::post('customer/{id}/shayegan/register', [ShayeganController::class, 'registerCustomer']);
Route::get('shayegan/charges/pending', [ShayeganController::class, 'pendingCharges']);
Route::post('shayegan/charges/table', [ShayeganController::class, 'chargesTable']);
Route::post('shayegan/charges/{id}/approve', [ShayeganController::class, 'approveCharge']);
Route::post('shayegan/charges/{id}/reject', [ShayeganController::class, 'rejectCharge']);
Route::post('shayegan/charges/sync', [ShayeganController::class, 'syncChargesFromShayegan']);
Route::post('pargar/table', [PargarController::class, 'table']);
Route::get('pargar/customer-sync/status', [PargarController::class, 'customerSyncStatus']);
Route::get('pargar/stuck-outbound', [PargarController::class, 'stuckOutbound']);
@@ -323,6 +345,9 @@ Route::middleware('auth:user')->group(function (){
//Giftcard
Route::post('giftcard/generate/', [GiftCardController::class, 'redeem']);
Route::post('giftcard/table/', [GiftCardController::class, 'table']);
Route::post('giftcard/codes-usage-report/', [GiftCardController::class, 'codesUsageReport']);
Route::put('giftcard/{id}', [GiftCardController::class, 'update']);
Route::delete('giftcard/{id}', [GiftCardController::class, 'destroy']);
Route::get('categories', [CategoryController::class, 'index']);
Route::post('categories', [CategoryController::class, 'store']);
+7 -5
View File
@@ -13,6 +13,7 @@ use App\Http\Controllers\Admin\SettingsController;
use App\Http\Controllers\Site\RequestsController;
use App\Services\ConfigService;
use App\Http\Controllers\Customer\CartController;
use App\Http\Controllers\Customer\WalletController;
use App\Http\Controllers\Admin\CategoryController;
use App\Http\Controllers\Chat\SupportChatNotifyController;
use App\Http\Controllers\Super\SuperSettingsController;
@@ -36,14 +37,12 @@ Route::middleware('superadmin.remote')->group(function () {
Route::get('/candle',[ReportController::class, 'candleChart']);
Route::get('/price/up',[ReportController::class, 'upDownPrice']);
Route::match(['get', 'post'],'/price/last',[ReportController::class, 'lastPrice']);
// همان دادهٔ /customer/prices/all — بدون لاگین، برای نمودار مهمان
Route::match(['get', 'post'], '/price/all', [WalletController::class, 'priceData']);
$priceStreamRoute = Route::get('/price/stream', [PriceStreamController::class, 'stream'])
Route::get('/price/stream', [PriceStreamController::class, 'stream'])
->withoutMiddleware(['throttle:api']);
if (! app(ConfigService::class)->isStore()) {
$priceStreamRoute->middleware(['auth:customer', 'customer.active']);
}
Route::get('/price/updatePrise',[ReportController::class, 'updatePrise']);
Route::get('/const/key/{key}',[ConstController::class, 'showValue']);
Route::get('/check',[ReportController::class, 'check']);
@@ -72,3 +71,6 @@ if (app(ConfigService::class)->isStore()) {
Route::post('/cart/remove', [CartController::class, 'removeItem']);
Route::get('categories', [CategoryController::class, 'clientIndex']);
}
// وب‌هوک دریافت شارژ مشتری از شایگان
Route::post('/shayegan/webhook/inbound-charge', [\App\Http\Controllers\Admin\ShayeganController::class, 'inboundWebhook']);
+12
View File
@@ -1,8 +1,10 @@
<?php
use App\Http\Controllers\Customer\CustomerController;
use App\Http\Controllers\Customer\DigipayInstallmentController;
use App\Http\Controllers\Customer\GoldCreditController;
use App\Http\Controllers\Customer\OrderController;
use App\Http\Controllers\Customer\CopperConvertRequestController;
use App\Http\Controllers\Customer\AddressController;
use App\Http\Controllers\Customer\WalletController;
use App\Http\Controllers\Customer\PriceTriggerController;
@@ -117,6 +119,7 @@ Route::middleware(['auth:customer', 'customer.active'])->group(function () use (
Route::post('/wallet/withdraw/table', [WalletController::class, 'indexWithdraw']);
Route::post('/wallet/withdraw_physical/table', [WalletController::class, 'index_withdraw_physical']);
Route::post('wallet/withdraw/otp', [WalletController::class, 'withdrawOtp']);
Route::post('wallet/deposit_request', [WalletController::class, 'depositRequest']);
Route::post('/withdraw/table', [WalletController::class, 'withdrawTable']);
@@ -130,6 +133,10 @@ Route::middleware(['auth:customer', 'customer.active'])->group(function () use (
Route::get('order/pending', [SingleOrderController::class, 'pendingColleague']);
Route::get('order/{id}/status', [SingleOrderController::class, 'colleagueStatus']);
Route::post('order', [OrderController::class, 'store']);
Route::get('copper-convert-request', [CopperConvertRequestController::class, 'index']);
Route::post('copper-convert-request', [CopperConvertRequestController::class, 'store']);
Route::put('copper-convert-request/{id}', [CopperConvertRequestController::class, 'update']);
Route::delete('copper-convert-request/{id}', [CopperConvertRequestController::class, 'destroy']);
//-----------------single order
Route::post('single/order/table', [SingleOrderController::class, 'table']);
@@ -162,6 +169,7 @@ Route::middleware(['auth:customer', 'customer.active'])->group(function () use (
Route::post('account/tahesab/trade', [TahesabController::class, 'storeTrade']);
//--------------------use gift card
Route::get('giftcard/mine', [GiftCardController::class, 'mine']);
Route::post('giftcard/use', [GiftCardController::class, 'useGiftCard']);
//offer code
@@ -172,6 +180,10 @@ Route::middleware(['auth:customer', 'customer.active'])->group(function () use (
Route::post('gold_credit/request', [GoldCreditController::class, 'requestLoan']);
Route::post('gold_credit/installments/pay', [GoldCreditController::class, 'payInstallments']);
Route::get('digipay_installment', [DigipayInstallmentController::class, 'show']);
Route::post('digipay_installment/start', [DigipayInstallmentController::class, 'start']);
Route::post('digipay_installment/buy', [DigipayInstallmentController::class, 'buy']);
if ($isStore) {
Route::post('vc_validate', [havaleController::class, 'virtualCardValidate']);
Route::post('havale', [havaleController::class, 'havale']);
@@ -0,0 +1,57 @@
<?php
namespace Tests\Unit;
use App\Services\ShayeganClient;
use PHPUnit\Framework\TestCase;
use ReflectionMethod;
class ShayeganClientErrorMessageTest extends TestCase
{
public function test_extract_error_message_from_top_level(): void
{
$client = $this->clientWithoutConstruct();
$method = new ReflectionMethod(ShayeganClient::class, 'extractErrorMessage');
$method->setAccessible(true);
$msg = $method->invoke($client, [
'ErrorMessage' => 'missing account',
'Result' => [['ErrorMessage' => '', 'Number' => '1']],
]);
$this->assertSame('missing account', $msg);
}
public function test_extract_error_message_from_result_row(): void
{
$client = $this->clientWithoutConstruct();
$method = new ReflectionMethod(ShayeganClient::class, 'extractErrorMessage');
$method->setAccessible(true);
$msg = $method->invoke($client, [
'ErrorMessage' => '',
'Result' => [['ErrorMessage' => 'row failed', 'Number' => null]],
]);
$this->assertSame('row failed', $msg);
}
public function test_empty_error_message_is_success_signal(): void
{
$client = $this->clientWithoutConstruct();
$method = new ReflectionMethod(ShayeganClient::class, 'extractErrorMessage');
$method->setAccessible(true);
$msg = $method->invoke($client, [
'ErrorMessage' => '',
'Result' => [['ErrorMessage' => '', 'Number' => '12', 'GuId' => 'abc']],
]);
$this->assertSame('', $msg);
}
private function clientWithoutConstruct(): ShayeganClient
{
return (new \ReflectionClass(ShayeganClient::class))->newInstanceWithoutConstructor();
}
}