feat(quick-sales): improve checkout controls and reliability #18

Merged
morrning merged 1 commit from Seyyed/Seyyed_arc:codex/quick-sales-windows-shortcuts into master 2026-10-18 11:45:26 +03:30
37 changed files with 3771 additions and 256 deletions

View file

@ -0,0 +1,35 @@
# اعمال مانده مشتری در فروش سریع
در فروش سریع، پس از انتخاب یک مشتری مشخص، مانده حساب او در ارز فاکتور و تا تاریخ فاکتور زیر فیلد مشتری نمایش داده می‌شود. علامت مانده در API به این صورت است:
- مانده مثبت: مشتری بستانکار است.
- مانده منفی: مشتری بدهکار است.
- مانده صفر: حساب تسویه است.
گزینه «اعمال مانده در مبلغ قابل تسویه» به صورت پیش‌فرض خاموش است. این گزینه برای مشتری ناشناس یا مانده صفر فعال نمی‌شود. مبلغ خود فاکتور با فعال کردن این گزینه تغییر نمی‌کند؛ فقط مبلغی که صندوق‌دار باید تسویه کند تغییر می‌کند.
## محاسبه مبلغ قابل تسویه
اگر مبلغ فاکتور ۵٬۰۰۰٬۰۰۰ ریال باشد:
- مشتری با ۲٬۰۰۰٬۰۰۰ ریال بدهی قبلی باید ۷٬۰۰۰٬۰۰۰ ریال بپردازد.
- مشتری با ۲٬۰۰۰٬۰۰۰ ریال بستانکاری قبلی باید ۳٬۰۰۰٬۰۰۰ ریال بپردازد.
- اگر بستانکاری مشتری ۷٬۰۰۰٬۰۰۰ ریال باشد، مبلغ قابل تسویه صفر است و ۲٬۰۰۰٬۰۰۰ ریال بستانکاری برای او باقی می‌ماند.
در حالت بدهکار، دریافتی ابتدا بدهی قبلی را تسویه می‌کند و سپس به فاکتور جاری تخصیص می‌یابد. در حالت بستانکار، بخشی از اعتبار قبلی تا سقف مبلغ فاکتور به فاکتور جاری تخصیص داده می‌شود.
## کنترل هم‌زمانی و تاریخ
رابط کاربری مانده را از مسیر زیر دریافت می‌کند:
`GET /api/v1/businesses/{business_id}/quick-sales/customer-balance`
پارامترهای درخواست `person_id`، `currency_id` و `as_of_date` هستند. محاسبه فقط اسناد قطعی سال مالی جاری را در همان ارز و تا تاریخ فاکتور در نظر می‌گیرد.
هنگام ثبت فاکتور، بک‌اند مانده را دوباره محاسبه می‌کند. اگر مانده از زمان نمایش تا ثبت تغییر کرده باشد، پاسخ `409` با کد `QUICK_SALE_CUSTOMER_BALANCE_CHANGED` برگردانده می‌شود تا کاربر مانده جدید را ببیند و دوباره تصمیم بگیرد.
## اطلاعات ذخیره‌شده روی فاکتور
نتیجه نهایی در `extra_info.quick_sale_customer_balance` ثبت می‌شود و شامل مانده قبل از فاکتور، بدهی قبلی، اعتبار اعمال‌شده و مبلغ قابل تسویه است. این اطلاعات برای محاسبه مانده همان فاکتور و تشخیص اضافه‌دریافت استفاده می‌شود. سند حسابداری جداگانه‌ای برای «اعمال مانده» ساخته نمی‌شود، چون اثر آن از گردش واقعی حساب شخص به دست می‌آید.
در فروش‌های پارک‌شده فقط انتخاب کاربر برای اعمال مانده نگهداری می‌شود. هنگام بازگشت به فروش، مانده دوباره از سرور خوانده می‌شود و مقدار قدیمی به عنوان مبنای ثبت استفاده نمی‌شود.

View file

@ -12,8 +12,9 @@
- پرداخت‌های ثبت‌شده در یک فهرست مستقل و اسکرول‌دار نمایش داده می‌شوند. مبلغ هر ردیف قابل ویرایش و خود ردیف قابل حذف است.
- هر ردیف پرداخت، آیکون متناسب با نوع مقصد، تاریخ و ساعت ثبت و دکمه حذف قرمز دارد.
- کاربر می‌تواند مرز بین فضای دکمه‌ها و فهرست پرداخت‌ها را با ماوس جابه‌جا کند. عرض انتخاب‌شده برای همان کاربر و کسب‌وکار در مرورگر ذخیره می‌شود. دوبار کلیک روی مرز، عرض پیش‌فرض را برمی‌گرداند و کلیدهای جهت نیز مرز را حرکت می‌دهند.
- خلاصه فاکتور و دکمه‌های «ثبت» و «ثبت و چاپ» در پایین سمت چپ ثابت هستند. پنل سمت راست شامل مبلغ، دکمه‌ها و فهرست پرداخت‌ها با فلش جمع یا باز می‌شود تا در حالت جمع‌شده فضای بیشتری به فهرست کالاها برسد. وضعیت انتخاب‌شده برای همان کاربر و کسب‌وکار در مرورگر ذخیره می‌شود.
- خلاصه فاکتور و دکمه‌های «ثبت» و «ثبت و چاپ» در یک پنل فشرده در پایین سمت چپ ثابت هستند. ارتفاع رزروشده ستون جزئیات فقط به اندازه همین پنل است. پنل سمت راست شامل مبلغ، دکمه‌ها و فهرست پرداخت‌ها با فلش جمع یا باز می‌شود تا در حالت جمع‌شده فضای بیشتری به فهرست کالاها برسد. وضعیت انتخاب‌شده برای همان کاربر و کسب‌وکار در مرورگر ذخیره می‌شود.
- «جزئیات سند» و بخش «شرح سند» در ستون سمت چپ به‌صورت پیش‌فرض باز هستند.
- فیلد «تاریخ فاکتور» در حالت فشرده فضای عمودی کافی برای عنوان شناور دارد تا متن فارسی از بالا بریده نشود.
- جمع پرداخت‌ها اگر از مبلغ فاکتور بیشتر شود، مبلغ اضافه‌دریافت با رنگ خطا نمایش داده می‌شود. با انتخاب آن، پنجره «تعیین تکلیف اضافه‌دریافت» باز می‌شود. خود فیلد مبلغ در این حالت صفر می‌ماند.
- ثبت فاکتور بدون هیچ پرداختی، پس از تأیید کاربر، کل مبلغ را بدهی مشتری ثبت می‌کند.
@ -27,7 +28,7 @@
در مقصد شخص، عنوان دکمه همیشه نام همان شخص است. این حالت برای زمانی است که وجه فاکتور به حساب شخصی صندوقدار یا شخص تعریف‌شده دیگری واریز شده باشد. در سند دریافت، شخص مقصد بدهکار می‌شود؛ یعنی وجه کسب‌وکار نزد او ثبت می‌شود.
دکمه می‌تواند شخصی یا مشترک باشد. دکمه شخصی فقط برای سازنده دیده می‌شود. ایجاد، ویرایش، حذف و تغییر ترتیب دکمه مشترک به دسترسی تنظیمات کسب‌وکار نیاز دارد.
دکمه می‌تواند شخصی یا مشترک باشد. دکمه شخصی فقط برای سازنده دیده می‌شود. کاربر دارای دسترسی تنظیمات کسب‌وکار می‌تواند هنگام ویرایش نیز دکمه را از شخصی به مشترک یا از مشترک به شخصی تبدیل کند. دکمه منتقل‌شده در انتهای چیدمان مقصد قرار می‌گیرد و محدودیت تعداد دکمه‌های همان دامنه دوباره کنترل می‌شود. ایجاد، ویرایش، حذف و تغییر ترتیب دکمه مشترک به دسترسی تنظیمات کسب‌وکار نیاز دارد.
میانبرهای مجاز شامل `F1` تا `F12` به‌جز `F5` و ترکیب‌هایی مانند `Alt+1` یا `Ctrl+Shift+K` هستند. میانبرهای رزروشده فروش سریع و مرورگر پذیرفته نمی‌شوند و یک میانبر مؤثر نمی‌تواند برای دو دکمه تکرار شود.

View file

@ -0,0 +1,151 @@
# میانبرهای دکمه‌های پرداخت فروش سریع
## رفتار
دکمه‌های پرداخت همچنان در بخش پرداخت فروش سریع تعریف می‌شوند. هر دکمه در دو محیط، پروفایل مستقل دارد:
- برنامه ویندوز؛
- رابط وب.
برای هر محیط، ترتیب انتخاب میانبر مؤثر چنین است:
```text
personal override > business default > no shortcut
```
میانبرها هنگام بارگذاری دکمه‌ها یک‌بار از API دریافت و در حافظه نگهداری می‌شوند. فشردن کلید درخواست دیتابیس یا API ایجاد نمی‌کند.
## محل تنظیمات و دسترسی
پیش‌فرض‌های کسب‌وکار در صفحه «تنظیمات فروش سریع»، بخش «میانبرهای پیش‌فرض پرداخت» مدیریت می‌شوند. دکمه مدیریت پیش‌فرض‌ها داخل نوار پرداخت نمایش داده نمی‌شود.
مجوز مستقل زیر در جدول کاربران و دسترسی‌ها قرار دارد:
```text
quick_sales.manage_default_payment_shortcuts
```
مالک و superadmin به‌صورت ضمنی مجازند. کاربری که فقط این مجوز را دارد می‌تواند وارد صفحه تنظیمات فروش سریع شود، ولی سایر تنظیمات آن صفحه برای او نمایش داده نمی‌شود.
تنظیم شخصی از منوی هر دکمه پرداخت و گزینه «میانبرهای شخصی» انجام می‌شود. کاربر برای ویندوز و وب می‌تواند یکی از این سه حالت را انتخاب کند:
- استفاده از پیش‌فرض کسب‌وکار؛
- میانبر شخصی من؛
- بدون میانبر برای من.
## ذخیره‌سازی
پیش‌فرض ویندوز در `quick_sales_payment_buttons.shortcut` و پیش‌فرض وب در `quick_sales_payment_buttons.web_shortcut` نگهداری می‌شود. ستون وب با migration زیر اضافه شده است:
```text
20261015_000001_quick_sales_web_shortcut
```
تنظیم شخصی در JSON جدول `user_ui_preferences` و به تفکیک کسب‌وکار و پلتفرم ذخیره می‌شود:
```json
{
"quick_sales_payment_shortcuts": {
"4952": {
"windows": {
"17": "F12",
"22": "__DISABLED__"
},
"web": {
"17": "ALT+1"
}
}
}
}
```
`__DISABLED__` یعنی میانبر همان دکمه فقط برای آن کاربر و آن محیط غیرفعال است. پیش‌فرض مالک برای کاربران کپی نمی‌شود؛ در نتیجه تغییر بعدی پیش‌فرض برای کاربرانی که override ندارند فوراً اعمال می‌شود.
## API
فهرست دکمه‌ها:
```http
GET /api/v1/businesses/{business_id}/quick-sales/payment-buttons
```
هر دکمه `shortcut_profiles` دارد:
```json
{
"shortcut_profiles": {
"windows": {
"default_shortcut": "F1",
"user_shortcut": "F8",
"effective_shortcut": "F8",
"shortcut_source": "user",
"shortcut_conflict": false,
"user_shortcut_disabled": false
},
"web": {
"default_shortcut": "ALT+1",
"user_shortcut": null,
"effective_shortcut": "ALT+1",
"shortcut_source": "business",
"shortcut_conflict": false,
"user_shortcut_disabled": false
}
}
}
```
فیلدهای سطح اول میانبر برای سازگاری با کلاینت قدیمی، نماینده پروفایل ویندوز هستند.
تنظیم شخصی:
```http
PUT /api/v1/businesses/{business_id}/quick-sales/payment-buttons/{button_key}/shortcut
```
رابط جدید هر دو پروفایل را در یک درخواست و یک تراکنش ذخیره می‌کند:
```json
{
"platforms": {
"windows": {"mode": "inherit", "shortcut": null},
"web": {"mode": "custom", "shortcut": "ALT+1"}
}
}
```
برای سازگاری، ارسال یک `platform` نیز پشتیبانی می‌شود. نام پلتفرم یکی از `windows` و `web` و `mode` یکی از `inherit`، `custom` و `disabled` است.
فهرست و ذخیره یکجای پیش‌فرض‌ها:
```http
GET /api/v1/businesses/{business_id}/quick-sales/payment-buttons/default-shortcuts
PUT /api/v1/businesses/{business_id}/quick-sales/payment-buttons/default-shortcuts
```
```json
{
"shortcuts": [
{
"button_id": 17,
"shortcuts": {"windows": "F1", "web": "ALT+1"}
}
]
}
```
تمام ردیف‌ها پیش از تغییر دیتابیس اعتبارسنجی می‌شوند. تکراری‌بودن میانبر به‌صورت مستقل در هر پلتفرم بررسی می‌شود.
## کلیدهای مجاز
در ویندوز:
- `F1` تا `F12`؛
- ترکیب `CTRL`، `ALT` یا `SHIFT` با حرف، عدد یا کلید تابع.
در وب:
- ترکیبی شامل `CTRL` یا `ALT` و یک حرف یا عدد، مانند `ALT+1` یا `CTRL+ALT+R`؛
- کلیدهای تابع به‌تنهایی پذیرفته نمی‌شوند؛
- ترکیب‌های رزروشده مرورگر مانند `CTRL+L`، `CTRL+R` و `CTRL+P` پذیرفته نمی‌شوند.
هنگامی که فوکوس داخل فیلد متنی است، میانبر وب اجرا نمی‌شود. در هر محیط، نگاشت نهایی فقط از `effective_shortcut` ساخته می‌شود و یک کلید هم‌زمان دو پرداخت را فعال نمی‌کند.

View file

@ -12,7 +12,7 @@ API همهٔ اقلام دارای کسری را در یک پاسخ `409 / INSUF
1. **انصراف**: فاکتور و موجودی تغییری نمی‌کند.
2. **پارک فروش**: فروش جاری در فهرست فروش‌های پارک‌شده نگهداری و یک فروش خالی باز می‌شود.
3. **اصلاح موجودی**: فقط برای موجودی فیزیکیِ مازاد با منشأ نامشخص است. کاربر باید این وضعیت را صریحاً تأیید کند. سامانه سند «کالای درآمدشده» را با تاریخ واقعی روز کشف، مقدار کسری و بهای خرید پایه کالا ثبت و قطعی می‌کند؛ سپس ثبت فاکتور را دوباره انجام می‌دهد.
3. **اصلاح موجودی**: فقط برای موجودی فیزیکیِ مازاد با منشأ نامشخص است. کاربر باید این وضعیت را صریحاً تأیید کند. سامانه سند «کالای درآمدشده» را با همان تاریخ فاکتور، مقدار کسری و بهای خرید پایه کالا ثبت و قطعی می‌کند؛ سپس ثبت فاکتور را دوباره انجام می‌دهد. یک `request_token` پایدار برای هر فروش و مجموعه کسری ارسال می‌شود تا تکرار کلیک، قطع پاسخ شبکه یا تلاش مجدد، سند اصلاح دیگری نسازد.
4. **ثبت با موجودی منفی**: کاربر علت را انتخاب می‌کند و فاکتور فقط برای کالاهای فله ثبت می‌شود. یک پرونده مغایرت باز و به فاکتور و حواله انبار پیوند داده می‌شود.
اگر خرید، انتقال یا موجودی اول دوره از قلم افتاده است، کاربر نباید گزینه «اصلاح موجودی» را انتخاب کند. در آن حالت سند اصلی خرید، انتقال یا افتتاحیه باید با تاریخ واقعی خودش ثبت شود.
@ -81,6 +81,21 @@ APIهای رسیدگی:
- `POST /api/v1/businesses/{business_id}/quick-sales/stock-corrections`
- `POST /api/v1/businesses/{business_id}/quick-sales/stock-discrepancies/{case_id}/resolve`
نمونه درخواست اصلاح پیش از ثبت:
```json
{
"document_date": "2026-10-17",
"request_token": "qs-stock-4952-sale-id-2f3a91c0",
"confirm_unexplained_physical_surplus": true,
"lines": [
{"product_id": 10, "warehouse_id": 3, "quantity": 1}
]
}
```
سرور توکن را در `extra_info` سند نگه می‌دارد و درخواست‌های همزمان را با قفل تراکنشی سری می‌کند. اگر همان توکن و همان تاریخ و ردیف‌ها دوباره ارسال شود، همان سند قبلی با `idempotent_replay: true` برگردانده می‌شود. استفاده از یک توکن برای محتوای متفاوت با خطای `409` رد می‌شود.
## رسیدگی پس از ثبت موجودی منفی
پرونده‌های ایجادشده از مسیر «انبار ← مغایرت‌های موجودی فروش سریع» قابل مشاهده‌اند. فیلتر صفحه پرونده‌های باز، رفع‌شده یا همه موارد را نشان می‌دهد و اطلاعات فاکتور، علت، کالا، انبار و مقدار کسری را نمایش می‌دهد.
@ -97,7 +112,7 @@ APIهای رسیدگی:
## تاریخ و بهای تمام‌شده
تاریخ اصلاح، تاریخ واقعی کشف و ثبت اصلاح است و به روز قبل از فروش جعل نمی‌شود. حوالهٔ ورودی کالای درآمدشده با `unit_cost` وارد جریان تحلیلی FIFO/LIFO می‌شود. در رفع پرونده پس از فروش، مقدار و بهای اصلاح به ردیف فروش تخصیص داده و دفتر بهای تمام‌شده و سود ناخالص همان ردیف بازشناسی می‌شود.
در اصلاح پیش از فروش، تاریخ سند اصلاح دقیقاً با تاریخ فاکتور یکسان است تا رسید ورودی در کنترل موجودی همان فاکتور دیده شود؛ بنابراین تاریخ فاکتور باید تاریخ واقعی فروش باشد. اصلاح به روز قبل از فروش منتقل نمی‌شود. حوالهٔ ورودی کالای درآمدشده با `unit_cost` وارد جریان تحلیلی FIFO/LIFO می‌شود. در رفع پرونده پس از فروش، مقدار و بهای اصلاح به ردیف فروش تخصیص داده و دفتر بهای تمام‌شده و سود ناخالص همان ردیف بازشناسی می‌شود.
این طراحی زنجیره زمانی انبار را حفظ می‌کند: رویداد گذشته فقط وقتی با تاریخ گذشته ثبت می‌شود که واقعاً سند اصلیِ گذشته، مانند خرید یا انتقال، بازیابی و ثبت شده باشد.
@ -119,6 +134,7 @@ cd hesabixAPI
3. مقدار `_stock_override` جعلی در `extra_info` هیچ اثری نداشته باشد.
4. کالای یونیک حتی با مجوز override ثبت نشود.
5. ثبت منفی، فاکتور و حواله قطعی و یک پرونده باز بسازد.
6. اصلاح موجودی، سند کالای درآمدشده را با تاریخ روز ایجاد کند و ثبت فاکتور در تلاش بعدی موفق شود.
7. رفع پرونده، سند اصلاح را پیوند دهد، پرونده را `resolved` کند و بهای تمام‌شده ردیف فروش را بازشناسی کند.
8. انتقال انبار همچنان با کنترل مثبت موجودی اجرا شود.
6. اصلاح موجودی، سند کالای درآمدشده را با تاریخ فاکتور ایجاد کند و ثبت فاکتور در تلاش بعدی موفق شود.
7. ارسال دوباره همان درخواست اصلاح، همان سند را برگرداند و سند دوم نسازد.
8. رفع پرونده، سند اصلاح را پیوند دهد، پرونده را `resolved` کند و بهای تمام‌شده ردیف فروش را بازشناسی کند.
9. انتقال انبار همچنان با کنترل مثبت موجودی اجرا شود.

View file

@ -21,9 +21,14 @@ from app.services.quick_sales_service import (
create_quick_sales_payment_button,
delete_quick_sales_payment_button,
get_or_create_anonymous_customer,
get_quick_sales_customer_balance,
get_quick_sales_settings,
list_quick_sales_payment_default_shortcuts,
list_quick_sales_payment_buttons,
reorder_quick_sales_payment_buttons,
set_quick_sales_payment_default_shortcuts,
set_quick_sales_payment_button_shortcut,
set_quick_sales_payment_button_shortcuts,
update_quick_sales_payment_button,
update_quick_sales_settings,
)
@ -45,6 +50,27 @@ def _body_date(value: Any) -> date:
raise ApiError("INVALID_DATE", "تاریخ اصلاح موجودی نامعتبر است", http_status=400) from exc
@router.get("/customer-balance", summary="مانده مشتری در فروش سریع")
def get_customer_balance_endpoint(
request: Request,
business_id: int,
person_id: int,
currency_id: int,
as_of_date: date,
_: None = Depends(require_business_access_dep),
db: Session = Depends(get_db),
ctx: AuthContext = Depends(get_current_user),
) -> dict:
data = get_quick_sales_customer_balance(
db,
business_id=business_id,
person_id=person_id,
currency_id=currency_id,
as_of_date=as_of_date,
)
return success_response(data, request)
@router.get(
"/settings",
summary="دریافت تنظیمات فروش سریع",
@ -165,6 +191,85 @@ def reorder_payment_buttons_endpoint(
return success_response(data, request, message="QUICK_SALES_PAYMENT_BUTTONS_REORDERED")
@router.put(
"/payment-buttons/{button_key}/shortcut",
summary="تنظیم میانبر دکمه پرداخت برای کاربر جاری",
)
def update_payment_button_shortcut_endpoint(
request: Request,
business_id: int,
button_key: str,
payload: Dict[str, Any] = Body(...),
_: None = Depends(require_business_access_dep),
db: Session = Depends(get_db),
ctx: AuthContext = Depends(get_current_user),
) -> dict:
if "platforms" in payload:
data = set_quick_sales_payment_button_shortcuts(
db,
business_id=business_id,
user_id=ctx.get_user_id(),
button_key=button_key,
platforms=payload.get("platforms"),
)
else:
data = set_quick_sales_payment_button_shortcut(
db,
business_id=business_id,
user_id=ctx.get_user_id(),
button_key=button_key,
shortcut=payload.get("shortcut"),
mode=payload.get("mode"),
platform=str(payload.get("platform") or "windows").strip().lower(),
)
return success_response(data, request, message="QUICK_SALES_PAYMENT_SHORTCUT_UPDATED")
@router.get(
"/payment-buttons/default-shortcuts",
summary="فهرست میانبرهای پیش‌فرض دکمه‌های مشترک فروش سریع",
)
def list_payment_button_default_shortcuts_endpoint(
request: Request,
business_id: int,
_: None = Depends(
require_business_permission_dep(
"quick_sales", "manage_default_payment_shortcuts"
)
),
db: Session = Depends(get_db),
) -> dict:
data = list_quick_sales_payment_default_shortcuts(db, business_id)
return success_response(data, request)
@router.put(
"/payment-buttons/default-shortcuts",
summary="ذخیره یکجای میانبرهای پیش‌فرض دکمه‌های مشترک فروش سریع",
)
def update_payment_button_default_shortcuts_endpoint(
request: Request,
business_id: int,
payload: Dict[str, Any] = Body(...),
_: None = Depends(
require_business_permission_dep(
"quick_sales", "manage_default_payment_shortcuts"
)
),
db: Session = Depends(get_db),
) -> dict:
data = set_quick_sales_payment_default_shortcuts(
db,
business_id=business_id,
items=payload.get("shortcuts"),
)
return success_response(
data,
request,
message="QUICK_SALES_DEFAULT_PAYMENT_SHORTCUTS_UPDATED",
)
@router.put("/payment-buttons/{button_id}", summary="ویرایش دکمه پرداخت فروش سریع")
def update_payment_button_endpoint(
request: Request,
@ -230,6 +335,13 @@ def create_stock_correction_endpoint(
db: Session = Depends(get_db),
ctx: AuthContext = Depends(get_current_user),
) -> dict:
request_token = str(payload.get("request_token") or "").strip()
if not request_token:
raise ApiError(
"STOCK_CORRECTION_REQUEST_TOKEN_REQUIRED",
"شناسه درخواست اصلاح موجودی الزامی است",
http_status=400,
)
if payload.get("confirm_unexplained_physical_surplus") is not True:
raise ApiError(
"PHYSICAL_SURPLUS_CONFIRMATION_REQUIRED",
@ -250,6 +362,7 @@ def create_stock_correction_endpoint(
user_can_allocate=_can(ctx, db, business_id, "goods_expense_income", "allocate"),
user_can_post=_can(ctx, db, business_id, "goods_expense_income", "post"),
user_can_change_unit_cost=_can(ctx, db, business_id, "goods_expense_income", "change_unit_cost"),
request_token=request_token,
)
db.commit()
return success_response(result, request, message="QUICK_SALES_STOCK_CORRECTED")

View file

@ -65,6 +65,7 @@ class QuickSalesPaymentButton(Base):
)
label: Mapped[str | None] = mapped_column(String(120), nullable=True)
shortcut: Mapped[str | None] = mapped_column(String(32), nullable=True)
web_shortcut: Mapped[str | None] = mapped_column(String(32), nullable=True)
position: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
created_by_user_id: Mapped[int | None] = mapped_column(

View file

@ -1,17 +1,13 @@
"""قفل‌های تراکنشی نام‌دار برای سری‌کردن عملیات همزمان حساس."""
from __future__ import annotations
"""
قفل‌های سطح دیتابیس برای جلوگیری از نشت سهمیهٔ ارسال OTP/SMS ناشی از race همزمان.
"""
from sqlalchemy import text
from sqlalchemy.orm import Session
def acquire_sms_rate_lock(db: Session, key: str) -> None:
"""
قفل تراکنشی (PostgreSQL: pg_advisory_xact_lock) تا پایان تراکنش جاری.
مقدار key باید برای هر شناسهٔ ارسال (موبایل، ایمیل، user_id) یکتا باشد.
"""
def acquire_transaction_lock(db: Session, key: str) -> None:
"""قفل تراکنشی نام‌دار را تا پایان تراکنش جاری نگه می‌دارد."""
bind = db.get_bind()
if bind.dialect.name != "postgresql":
return
@ -20,3 +16,8 @@ def acquire_sms_rate_lock(db: Session, key: str) -> None:
text("SELECT pg_advisory_xact_lock((hashtext(CAST(:k AS text)))::bigint)"),
{"k": key[:4000]},
)
def acquire_sms_rate_lock(db: Session, key: str) -> None:
"""سازگاری با فراخوان‌های قدیمی محدودکنندهٔ پیامک."""
acquire_transaction_lock(db, key)

View file

@ -1,5 +1,8 @@
from __future__ import annotations
import hashlib
import json
import re
from datetime import date, datetime
from decimal import Decimal
from typing import Any
@ -8,18 +11,75 @@ from sqlalchemy.orm import Session, selectinload
from sqlalchemy.orm.attributes import flag_modified
from adapters.db.models.document import Document
from adapters.db.models.goods_expense_income import GoodsExpenseIncomeDocument
from adapters.db.models.inventory_discrepancy import (
InventoryDiscrepancyCase,
InventoryDiscrepancyLine,
)
from adapters.db.models.invoice_item_line import InvoiceItemLine
from app.core.responses import ApiError
from app.core.transaction_lock import acquire_transaction_lock
_QUICK_SALES_CORRECTION_TOKEN_RE = re.compile(r"^[A-Za-z0-9._:-]{16,160}$")
def _decimal(value: Any) -> Decimal:
return Decimal(str(value or 0))
def _correction_request_fingerprint(document_date: date, lines: list[dict[str, Any]]) -> str:
try:
normalized_lines = sorted(
(
int(line.get("product_id")),
int(line.get("warehouse_id")),
format(_decimal(line.get("quantity")).normalize(), "f"),
)
for line in lines
)
except (TypeError, ValueError, ArithmeticError) as exc:
raise ApiError(
"INVALID_STOCK_CORRECTION_LINES",
"اطلاعات ردیف‌های اصلاح موجودی نامعتبر است",
http_status=400,
) from exc
raw = json.dumps(
{"document_date": document_date.isoformat(), "lines": normalized_lines},
ensure_ascii=True,
separators=(",", ":"),
)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def _normalize_correction_request_token(value: Any) -> str | None:
token = str(value or "").strip()
if not token:
return None
if not _QUICK_SALES_CORRECTION_TOKEN_RE.fullmatch(token):
raise ApiError(
"INVALID_STOCK_CORRECTION_REQUEST_TOKEN",
"شناسه درخواست اصلاح موجودی نامعتبر است",
http_status=400,
)
return token
def _find_quick_sales_correction_by_token(
db: Session,
*,
business_id: int,
request_token: str,
) -> GoodsExpenseIncomeDocument | None:
return db.query(GoodsExpenseIncomeDocument).filter(
GoodsExpenseIncomeDocument.business_id == int(business_id),
GoodsExpenseIncomeDocument.doc_kind == "goods_income",
GoodsExpenseIncomeDocument.extra_info["source"].as_string()
== "quick_sales_stock_correction",
GoodsExpenseIncomeDocument.extra_info["request_token"].as_string()
== request_token,
).first()
def _correction_lines_by_case_line(lines: list[dict[str, Any]]) -> dict[int, dict[str, Any]]:
indexed: dict[int, dict[str, Any]] = {}
for line in lines:
@ -184,6 +244,7 @@ def create_goods_income_correction(
user_can_post: bool,
user_can_change_unit_cost: bool,
case_id: int | None = None,
request_token: str | None = None,
) -> dict[str, Any]:
"""کسری ناشی از موجودی فیزیکی ثبت‌نشده را با تاریخ واقعی کشف اصلاح می‌کند."""
if not user_can_post:
@ -192,7 +253,35 @@ def create_goods_income_correction(
"برای اصلاح فوری موجودی، مجوز قطعی‌کردن کالای درآمدشده لازم است",
http_status=403,
)
from app.services.goods_expense_income_service import create_document, post_document
from app.services.goods_expense_income_service import (
_document_to_dict,
create_document,
post_document,
)
normalized_token = _normalize_correction_request_token(request_token)
fingerprint = _correction_request_fingerprint(document_date, lines)
if normalized_token:
acquire_transaction_lock(
db,
f"quick_sales_stock_correction:{business_id}:{normalized_token}",
)
existing = _find_quick_sales_correction_by_token(
db,
business_id=business_id,
request_token=normalized_token,
)
if existing is not None:
existing_fingerprint = (existing.extra_info or {}).get("request_fingerprint")
if existing_fingerprint != fingerprint:
raise ApiError(
"STOCK_CORRECTION_REQUEST_TOKEN_REUSED",
"این شناسه درخواست قبلاً برای اصلاح دیگری استفاده شده است",
http_status=409,
)
result = _document_to_dict(existing, db)
result["idempotent_replay"] = True
return result
payload = {
"doc_kind": "goods_income",
@ -202,6 +291,8 @@ def create_goods_income_correction(
"extra_info": {
"source": "quick_sales_stock_correction",
"inventory_discrepancy_case_id": case_id,
"request_token": normalized_token,
"request_fingerprint": fingerprint,
},
"lines": lines,
}
@ -217,6 +308,7 @@ def create_goods_income_correction(
)
if result.get("status") != "posted":
result = post_document(db, business_id, user_id, int(result["id"]), commit=False)
result["idempotent_replay"] = False
return result

View file

@ -2761,9 +2761,141 @@ def _create_receipt_payment_documents_for_invoice_payments(
return payment_docs
def _quick_sale_customer_balance_meta(document: Document) -> Dict[str, Any]:
extra = document.extra_info if isinstance(document.extra_info, dict) else {}
raw = extra.get("quick_sale_customer_balance")
return dict(raw) if isinstance(raw, dict) and raw.get("applied") is True else {}
def _quick_sale_payment_target(document: Document) -> Decimal:
"""Amount to collect after applying the customer's prior balance."""
meta = _quick_sale_customer_balance_meta(document)
if meta.get("payment_target") is not None:
try:
return max(Decimal(0), Decimal(str(meta["payment_target"])))
except Exception:
pass
return Decimal(str(((document.extra_info or {}).get("totals") or {}).get("net", 0) or 0))
def _adjust_quick_sale_invoice_paid(document: Document, total_paid: Decimal) -> Decimal:
"""Allocate receipts to prior debt first and prior credit to this invoice."""
meta = _quick_sale_customer_balance_meta(document)
if not meta:
return total_paid
try:
prior_debt = max(Decimal(0), Decimal(str(meta.get("prior_debt_amount", 0) or 0)))
credit_applied = max(Decimal(0), Decimal(str(meta.get("credit_applied_amount", 0) or 0)))
invoice_total = Decimal(
str(((document.extra_info or {}).get("totals") or {}).get("net", 0) or 0)
)
except Exception:
return total_paid
old_debt_settled = min(max(total_paid, Decimal(0)), prior_debt)
return min(
max(invoice_total, Decimal(0)),
max(Decimal(0), total_paid - old_debt_settled) + credit_applied,
)
def _normalize_quick_sale_customer_balance_application(
db: Session,
*,
business_id: int,
person_id: int,
currency_id: int,
document_date: date,
fiscal_year_id: int,
invoice_total: Decimal,
header_extra: Dict[str, Any],
) -> Dict[str, Any]:
request = header_extra.get("quick_sale_customer_balance")
if not isinstance(request, dict) or request.get("apply") is not True:
header_extra.pop("quick_sale_customer_balance", None)
return header_extra
try:
requested_person_id = int(request.get("person_id"))
requested_currency_id = int(request.get("currency_id"))
expected_balance = Decimal(str(request.get("balance_before")))
except Exception as exc:
raise ApiError(
"QUICK_SALE_CUSTOMER_BALANCE_INVALID",
"اطلاعات مانده مشتری نامعتبر است؛ مانده را دوباره دریافت کنید",
http_status=400,
) from exc
if requested_person_id != int(person_id) or requested_currency_id != int(currency_id):
raise ApiError(
"QUICK_SALE_CUSTOMER_BALANCE_MISMATCH",
"مشتری یا ارز مانده با فاکتور هم‌خوانی ندارد",
http_status=400,
)
from adapters.db.models.quick_sales_settings import QuickSalesSetting
quick_sales_settings = (
db.query(QuickSalesSetting)
.filter(QuickSalesSetting.business_id == int(business_id))
.first()
)
if (
quick_sales_settings is not None
and quick_sales_settings.default_anonymous_customer_id is not None
and int(quick_sales_settings.default_anonymous_customer_id) == int(person_id)
):
raise ApiError(
"QUICK_SALE_ANONYMOUS_BALANCE_NOT_ALLOWED",
"اعمال مانده برای مشتری ناشناس مجاز نیست",
http_status=400,
)
from app.services.quick_sales_service import get_quick_sales_customer_balance
current = get_quick_sales_customer_balance(
db,
business_id=business_id,
person_id=person_id,
currency_id=currency_id,
as_of_date=document_date,
fiscal_year_id=fiscal_year_id,
)
current_balance = Decimal(str(current.get("balance", 0) or 0))
decimal_places = max(0, int(current.get("decimal_places", 2) or 2))
epsilon = Decimal(1).scaleb(-decimal_places) / Decimal(2)
if abs(current_balance - expected_balance) > epsilon:
raise ApiError(
"QUICK_SALE_CUSTOMER_BALANCE_CHANGED",
"مانده حساب مشتری تغییر کرده است؛ مانده را به‌روزرسانی و دوباره ثبت کنید",
http_status=409,
details={
"balance": float(current_balance),
"status": current.get("status"),
"currency_id": int(currency_id),
"as_of_date": document_date.isoformat(),
},
)
normalized_total = max(Decimal(0), invoice_total)
prior_debt = max(Decimal(0), -current_balance)
credit_applied = min(max(Decimal(0), current_balance), normalized_total)
payment_target = max(Decimal(0), normalized_total + prior_debt - credit_applied)
header_extra["quick_sale_customer_balance"] = {
"applied": True,
"person_id": int(person_id),
"currency_id": int(currency_id),
"as_of_date": document_date.isoformat(),
"balance_before": float(current_balance),
"status": current.get("status"),
"prior_debt_amount": float(prior_debt),
"credit_applied_amount": float(credit_applied),
"payment_target": float(payment_target),
}
return header_extra
def _quick_sale_change_amount(document: Document, payments: List[Dict[str, Any]]) -> Decimal:
"""مبلغ اضافه‌دریافت نسبت به خالص فاکتور، به ارز خود فاکتور."""
total = Decimal(str(((document.extra_info or {}).get("totals") or {}).get("net", 0) or 0))
"""مبلغ اضافه‌دریافت نسبت به مبلغ قابل تسویه، به ارز خود فاکتور."""
total = _quick_sale_payment_target(document)
paid = Decimal(0)
for item in payments:
raw = item.get("settles_amount")
@ -5190,6 +5322,24 @@ def create_invoice(
header_extra = dict(data.get("extra_info") or {})
totals = dict(header_extra.get("totals") or {})
if (
invoice_type == INVOICE_SALES
and not bool(data.get("is_proforma", False))
and person_id
and header_extra.get("quick_sale") is True
):
header_extra = _normalize_quick_sale_customer_balance_application(
db,
business_id=business_id,
person_id=int(person_id),
currency_id=int(currency_id),
document_date=document_date,
fiscal_year_id=int(fiscal_year.id),
invoice_total=Decimal(str(totals.get("net", 0) or 0)),
header_extra=header_extra,
)
data["extra_info"] = header_extra
# Inventory posting is decoupled; no stock validation here
post_inventory: bool = _is_inventory_posting_enabled(data)
movement_hint, _ = _movement_from_type(invoice_type)
@ -10913,6 +11063,7 @@ def batch_calculate_invoices_remaining(
processed_doc_ids.add(parsed_change_doc_id)
total_paid -= _quick_sale_change_document_amount(change_doc)
total_paid = _adjust_quick_sale_invoice_paid(doc, total_paid)
remaining = total_amount - total_paid
results[inv_id] = {
"invoice_id": inv_id,
@ -11067,6 +11218,7 @@ def calculate_invoice_remaining(
processed_doc_ids.add(parsed_change_doc_id)
total_paid -= _quick_sale_change_document_amount(change_doc)
total_paid = _adjust_quick_sale_invoice_paid(invoice, total_paid)
remaining = total_amount - total_paid
logger.debug(

View file

@ -1316,6 +1316,7 @@ def calculate_person_balances_by_currency(
db: Session,
person_id: int,
fiscal_year_id: Optional[int] = None,
as_of_date: Optional[date] = None,
) -> Dict[str, Any]:
"""
مانده شخص به تفکیک ارز سند (مبالغ بومی) + معادل ارز پایه.
@ -1356,6 +1357,8 @@ def calculate_person_balances_by_currency(
)
if fiscal_year_id:
line_query = line_query.filter(Document.fiscal_year_id == fiscal_year_id)
if as_of_date is not None:
line_query = line_query.filter(Document.document_date <= as_of_date)
rows = line_query.all()
# currency_id -> {debit, credit, debit_base, credit_base}

View file

@ -3,6 +3,7 @@ from __future__ import annotations
import json
import logging
import re
from datetime import date
from typing import Any, Dict, List
from sqlalchemy import and_, func, or_
@ -12,12 +13,18 @@ from adapters.api.v1.schema_models.person import PersonCreateRequest
from adapters.db.models.bank_account import BankAccount
from adapters.db.models.business import Business
from adapters.db.models.cash_register import CashRegister
from adapters.db.models.currency import BusinessCurrency, Currency
from adapters.db.models.fiscal_year import FiscalYear
from adapters.db.models.person import Person, PersonType
from adapters.db.models.quick_sales_payment_button import QuickSalesPaymentButton
from adapters.db.models.quick_sales_settings import QuickSalesSetting
from app.core.responses import ApiError
from app.services.person_group_service import assert_assignable_person_group
from app.services.person_service import create_person
from app.services.person_service import calculate_person_balances_by_currency, create_person
from app.services.user_ui_preferences_service import (
get_quick_sales_payment_shortcuts,
save_quick_sales_payment_shortcuts,
)
logger = logging.getLogger(__name__)
@ -32,10 +39,116 @@ PAYMENT_BUTTON_SCOPES = frozenset({"business", "user"})
PAYMENT_BUTTON_RESERVED_SHORTCUTS = frozenset(
{"ENTER", "ESCAPE", "DELETE", "BACKSPACE", "F5", "+", "-"}
)
PAYMENT_BUTTON_SHORTCUT_PLATFORMS = frozenset({"windows", "web"})
PAYMENT_BUTTON_WEB_RESERVED_SHORTCUTS = frozenset(
{
"CTRL+D",
"CTRL+F",
"CTRL+H",
"CTRL+J",
"CTRL+L",
"CTRL+N",
"CTRL+P",
"CTRL+R",
"CTRL+S",
"CTRL+T",
"CTRL+U",
"CTRL+W",
"CTRL+SHIFT+N",
"CTRL+SHIFT+T",
}
)
MAX_PAYMENT_BUTTONS_PER_SCOPE = 30
PAYMENT_BUTTON_SHORTCUT_DISABLED = "__DISABLED__"
def _normalize_payment_button_shortcut(value: Any) -> str | None:
def get_quick_sales_customer_balance(
db: Session,
*,
business_id: int,
person_id: int,
currency_id: int,
as_of_date: date,
fiscal_year_id: int | None = None,
) -> Dict[str, Any]:
"""Return the selected customer's native-currency balance for quick sales."""
person = (
db.query(Person)
.filter(Person.id == int(person_id), Person.business_id == int(business_id))
.first()
)
if not person:
raise ApiError("PERSON_NOT_FOUND", "شخص یافت نشد", http_status=404)
currency = (
db.query(Currency)
.join(BusinessCurrency, BusinessCurrency.currency_id == Currency.id)
.filter(
Currency.id == int(currency_id),
BusinessCurrency.business_id == int(business_id),
)
.first()
)
if not currency:
raise ApiError("CURRENCY_NOT_FOUND", "ارز انتخاب‌شده یافت نشد", http_status=404)
if fiscal_year_id is None:
fiscal_year = (
db.query(FiscalYear)
.filter(
FiscalYear.business_id == int(business_id),
FiscalYear.is_last == True, # noqa: E712
)
.first()
)
fiscal_year_id = int(fiscal_year.id) if fiscal_year else None
breakdown = calculate_person_balances_by_currency(
db,
int(person_id),
fiscal_year_id=fiscal_year_id,
as_of_date=as_of_date,
)
selected = next(
(
row
for row in breakdown.get("balances", [])
if int(row.get("currency_id") or 0) == int(currency_id)
),
None,
)
balance = float((selected or {}).get("balance") or 0)
if balance > 0:
status = "بستانکار"
elif balance < 0:
status = "بدهکار"
else:
status = "تسویه"
return {
"person_id": int(person_id),
"currency_id": int(currency_id),
"as_of_date": as_of_date.isoformat(),
"fiscal_year_id": fiscal_year_id,
"balance": balance,
"status": status,
"currency_code": getattr(currency, "code", None),
"currency_title": getattr(currency, "title", None),
"currency_symbol": getattr(currency, "symbol", None),
"decimal_places": int(getattr(currency, "decimal_places", 2) or 2),
}
def _normalize_payment_button_shortcut(
value: Any,
*,
platform: str = "windows",
) -> str | None:
if platform not in PAYMENT_BUTTON_SHORTCUT_PLATFORMS:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_PLATFORM_INVALID",
"پلتفرم میانبر نامعتبر است",
http_status=400,
)
shortcut = str(value or "").strip().upper().replace(" ", "")
if not shortcut:
return None
@ -47,6 +160,25 @@ def _normalize_payment_button_shortcut(value: Any) -> str | None:
"این کلید در فروش سریع یا مرورگر رزرو شده است",
http_status=400,
)
if platform == "web":
if shortcut in PAYMENT_BUTTON_WEB_RESERVED_SHORTCUTS:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_RESERVED",
"این ترکیب توسط مرورگر رزرو شده است",
http_status=400,
)
parts = shortcut.split("+")
modifiers = parts[:-1]
if (
not re.fullmatch(r"(?:(?:CTRL|ALT|SHIFT)\+)+(?:[A-Z0-9])", shortcut)
or not any(modifier in {"CTRL", "ALT"} for modifier in modifiers)
):
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_INVALID",
"میانبر وب باید ترکیبی مانند Alt+1 یا Ctrl+Alt+R باشد",
http_status=400,
)
return shortcut
if not re.fullmatch(
r"(?:F(?:[1-9]|1[0-2])|(?:(?:CTRL|ALT|SHIFT)\+)+(?:[A-Z0-9]|F(?:[1-9]|1[0-2])))",
shortcut,
@ -130,49 +262,136 @@ def _payment_button_to_dict(db: Session, row: QuickSalesPaymentButton) -> Dict[s
"target_id": _payment_button_target_id(row),
"target_name": target_name,
"label": label,
"shortcut": row.shortcut,
# Shared-button defaults are stored by platform on the button row.
# Personal choices live in user_ui_preferences and are resolved below.
"default_shortcuts": {
"windows": (
_normalize_payment_button_shortcut(row.shortcut)
if row.scope == "business"
else None
),
"web": (
_normalize_payment_button_shortcut(
row.web_shortcut,
platform="web",
)
if row.scope == "business"
else None
),
},
"legacy_user_shortcut": (
_normalize_payment_button_shortcut(row.shortcut)
if row.scope == "user"
else None
),
"position": int(row.position),
"is_active": bool(row.is_active),
"is_system": False,
}
def _assert_payment_button_shortcut_available(
db: Session,
def _resolve_user_payment_shortcuts(
buttons: List[Dict[str, Any]],
shortcuts: Dict[str, str],
*,
platform: str = "windows",
prune_stale: bool = True,
) -> tuple[List[Dict[str, Any]], Dict[str, str]]:
"""Resolve personal override > business default > no shortcut.
Personal shortcuts claim keys first. This keeps an existing personal choice
deterministic if a manager later assigns the same key as a business default.
The conflicting inherited default is disabled for that user and is reported
to the UI instead of allowing two buttons to react to one key press.
"""
visible_keys = {str(button["id"]) for button in buttons}
stored = {
str(key): str(value)
for key, value in shortcuts.items()
if not prune_stale or str(key) in visible_keys
}
claimed: Dict[str, str] = {}
for button in buttons:
key = str(button["id"])
assigned = stored.get(key)
if not assigned or assigned == PAYMENT_BUTTON_SHORTCUT_DISABLED:
continue
normalized = _normalize_payment_button_shortcut(
assigned,
platform=platform,
)
if normalized and normalized not in claimed:
claimed[normalized] = key
for button in buttons:
key = str(button["id"])
default_shortcuts = button.get("default_shortcuts") or {}
default_shortcut = _normalize_payment_button_shortcut(
default_shortcuts.get(platform)
if default_shortcuts
else button.get("default_shortcut")
if platform == "windows"
else None,
platform=platform,
)
assigned = stored.get(key)
user_shortcut = None
effective_shortcut = None
source = "none"
conflict = False
if assigned == PAYMENT_BUTTON_SHORTCUT_DISABLED:
source = "disabled"
elif assigned:
user_shortcut = _normalize_payment_button_shortcut(
assigned,
platform=platform,
)
if user_shortcut and claimed.get(user_shortcut) == key:
effective_shortcut = user_shortcut
source = "user"
else:
source = "user"
conflict = True
elif default_shortcut:
if default_shortcut not in claimed:
claimed[default_shortcut] = key
effective_shortcut = default_shortcut
source = "business"
else:
source = "business"
conflict = True
button["default_shortcut"] = default_shortcut
button["user_shortcut"] = user_shortcut
button["user_shortcut_disabled"] = (
assigned == PAYMENT_BUTTON_SHORTCUT_DISABLED
)
button["effective_shortcut"] = effective_shortcut
button["shortcut_source"] = source
button["shortcut_conflict"] = conflict
# Backward-compatible alias consumed by older quick-sales clients.
button["shortcut"] = effective_shortcut
return buttons, stored
def _assert_user_payment_shortcut_available(
buttons: List[Dict[str, Any]],
*,
business_id: int,
scope: str,
owner_user_id: int | None,
shortcut: str | None,
exclude_id: int | None = None,
platform: str = "windows",
exclude_button_key: str | None = None,
) -> None:
if not shortcut:
return
query = db.query(QuickSalesPaymentButton).filter(
QuickSalesPaymentButton.business_id == int(business_id),
QuickSalesPaymentButton.is_active == True, # noqa: E712
func.upper(QuickSalesPaymentButton.shortcut) == shortcut,
)
if exclude_id is not None:
query = query.filter(QuickSalesPaymentButton.id != int(exclude_id))
if scope == "business":
query = query.filter(
or_(
QuickSalesPaymentButton.scope == "business",
QuickSalesPaymentButton.scope == "user",
)
)
else:
query = query.filter(
or_(
QuickSalesPaymentButton.scope == "business",
and_(
QuickSalesPaymentButton.scope == "user",
QuickSalesPaymentButton.owner_user_id == int(owner_user_id),
),
)
)
if query.first():
for button in buttons:
button_key = str(button["id"])
assigned = (
(button.get("shortcut_profiles") or {}).get(platform) or {}
).get("effective_shortcut", button.get("effective_shortcut"))
if button_key != exclude_button_key and assigned == shortcut:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_CONFLICT",
"این میانبر قبلاً برای یک دکمه پرداخت استفاده شده است",
@ -180,6 +399,75 @@ def _assert_payment_button_shortcut_available(
)
def _apply_user_payment_shortcuts(
db: Session,
*,
business_id: int,
user_id: int,
buttons: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
"""Resolve Windows and web shortcuts and discard stale preferences."""
base_buttons = [dict(button) for button in buttons]
legacy_by_key: Dict[str, str] = {}
for button in base_buttons:
legacy = button.pop("legacy_user_shortcut", None)
if legacy:
legacy_by_key[str(button["id"])] = legacy
profiles_by_platform: Dict[str, Dict[str, Dict[str, Any]]] = {}
for platform in ("windows", "web"):
stored = get_quick_sales_payment_shortcuts(
db, user_id, business_id, platform=platform
)
migrated = dict(stored)
if platform == "windows":
for key, legacy in legacy_by_key.items():
if key not in migrated:
migrated[key] = legacy
platform_buttons = [dict(button) for button in base_buttons]
resolved, cleaned = _resolve_user_payment_shortcuts(
platform_buttons,
migrated,
platform=platform,
)
profiles_by_platform[platform] = {
str(button["id"]): {
"default_shortcut": button.get("default_shortcut"),
"user_shortcut": button.get("user_shortcut"),
"user_shortcut_disabled": button.get(
"user_shortcut_disabled", False
),
"effective_shortcut": button.get("effective_shortcut"),
"shortcut_source": button.get("shortcut_source", "none"),
"shortcut_conflict": button.get("shortcut_conflict", False),
}
for button in resolved
}
if cleaned != stored:
save_quick_sales_payment_shortcuts(
db,
user_id,
business_id,
cleaned,
platform=platform,
)
result: List[Dict[str, Any]] = []
for button in base_buttons:
key = str(button["id"])
profiles = {
platform: profiles_by_platform[platform][key]
for platform in ("windows", "web")
}
windows = profiles["windows"]
button["shortcut_profiles"] = profiles
# Backward-compatible Windows aliases for older clients.
button.update(windows)
button["shortcut"] = windows.get("effective_shortcut")
result.append(button)
return result
def list_quick_sales_payment_buttons(
db: Session, business_id: int, user_id: int
) -> List[Dict[str, Any]]:
@ -201,7 +489,12 @@ def list_quick_sales_payment_buttons(
)
result = [_payment_button_to_dict(db, row) for row in rows]
if result:
return result
return _apply_user_payment_shortcuts(
db,
business_id=business_id,
user_id=user_id,
buttons=result,
)
settings = (
db.query(QuickSalesSetting)
@ -215,7 +508,7 @@ def list_quick_sales_payment_buttons(
_, name = _payment_button_target(db, business_id, "cash_register", register_id)
except ApiError:
return []
return [{
return _apply_user_payment_shortcuts(db, business_id=business_id, user_id=user_id, buttons=[{
"id": f"system-cash-{int(register_id)}",
"business_id": int(business_id),
"scope": "system",
@ -224,11 +517,290 @@ def list_quick_sales_payment_buttons(
"target_id": int(register_id),
"target_name": name,
"label": name,
"shortcut": None,
"default_shortcuts": {"windows": None, "web": None},
"position": 0,
"is_active": True,
"is_system": True,
}]
}])
def set_quick_sales_payment_button_shortcut(
db: Session,
*,
business_id: int,
user_id: int,
button_key: str,
shortcut: Any,
mode: str | None = None,
platform: str = "windows",
) -> Dict[str, Any]:
if platform not in PAYMENT_BUTTON_SHORTCUT_PLATFORMS:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_PLATFORM_INVALID",
"پلتفرم میانبر نامعتبر است",
http_status=400,
)
key = str(button_key or "").strip()
visible = list_quick_sales_payment_buttons(db, business_id, user_id)
button = next((row for row in visible if str(row["id"]) == key), None)
if button is None:
raise ApiError(
"PAYMENT_BUTTON_NOT_FOUND",
"دکمه پرداخت یافت نشد یا برای این کاربر قابل مشاهده نیست",
http_status=404,
)
requested_mode = str(mode or "").strip().lower()
if not requested_mode:
# Compatibility with the first shortcut client: null meant disabled.
requested_mode = "custom" if shortcut else "disabled"
if requested_mode not in {"inherit", "custom", "disabled"}:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_MODE_INVALID",
"حالت میانبر شخصی نامعتبر است",
http_status=400,
)
normalized = (
_normalize_payment_button_shortcut(shortcut, platform=platform)
if requested_mode == "custom"
else None
)
if requested_mode == "custom" and not normalized:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_REQUIRED",
"برای حالت شخصی باید میانبر را وارد کنید",
http_status=400,
)
shortcuts = get_quick_sales_payment_shortcuts(
db, user_id, business_id, platform=platform
)
_assert_user_payment_shortcut_available(
visible,
shortcut=normalized,
platform=platform,
exclude_button_key=key,
)
if requested_mode == "custom":
shortcuts[key] = normalized
elif requested_mode == "disabled":
shortcuts[key] = PAYMENT_BUTTON_SHORTCUT_DISABLED
else:
shortcuts.pop(key, None)
save_quick_sales_payment_shortcuts(
db, user_id, business_id, shortcuts, platform=platform
)
refreshed = list_quick_sales_payment_buttons(db, business_id, user_id)
result = next(row for row in refreshed if str(row["id"]) == key)
profile = (result.get("shortcut_profiles") or {}).get(platform) or {}
return {
"button_id": button["id"],
"platform": platform,
"default_shortcut": profile.get("default_shortcut"),
"user_shortcut": profile.get("user_shortcut"),
"effective_shortcut": profile.get("effective_shortcut"),
"shortcut_source": profile.get("shortcut_source"),
"shortcut_conflict": profile.get("shortcut_conflict", False),
"shortcut": profile.get("effective_shortcut"),
}
def set_quick_sales_payment_button_shortcuts(
db: Session,
*,
business_id: int,
user_id: int,
button_key: str,
platforms: Any,
) -> Dict[str, Any]:
"""Save all requested platform overrides in one database transaction."""
if not isinstance(platforms, dict) or not platforms:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUTS_INVALID",
"تنظیمات میانبرها نامعتبر است",
http_status=400,
)
unknown = set(platforms) - PAYMENT_BUTTON_SHORTCUT_PLATFORMS
if unknown:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_PLATFORM_INVALID",
"پلتفرم میانبر نامعتبر است",
http_status=400,
)
profiles: Dict[str, Dict[str, Any]] = {}
for platform in ("windows", "web"):
if platform not in platforms:
continue
config = platforms[platform]
if not isinstance(config, dict):
raise ApiError(
"PAYMENT_BUTTON_SHORTCUTS_INVALID",
"تنظیم میانبر هر پلتفرم باید یک شیء معتبر باشد",
http_status=400,
)
profiles[platform] = set_quick_sales_payment_button_shortcut(
db,
business_id=business_id,
user_id=user_id,
button_key=button_key,
shortcut=config.get("shortcut"),
mode=config.get("mode"),
platform=platform,
)
return {"button_id": button_key, "shortcut_profiles": profiles}
def list_quick_sales_payment_default_shortcuts(
db: Session,
business_id: int,
) -> List[Dict[str, Any]]:
rows = (
db.query(QuickSalesPaymentButton)
.filter(
QuickSalesPaymentButton.business_id == int(business_id),
QuickSalesPaymentButton.scope == "business",
QuickSalesPaymentButton.is_active == True, # noqa: E712
)
.order_by(QuickSalesPaymentButton.position.asc(), QuickSalesPaymentButton.id.asc())
.all()
)
result: List[Dict[str, Any]] = []
for row in rows:
button = _payment_button_to_dict(db, row)
result.append(
{
"button_id": button["id"],
"label": button["label"],
"target_type": button["target_type"],
"target_name": button["target_name"],
"default_shortcuts": button["default_shortcuts"],
"default_shortcut": button["default_shortcuts"]["windows"],
}
)
return result
def set_quick_sales_payment_default_shortcuts(
db: Session,
*,
business_id: int,
items: Any,
) -> List[Dict[str, Any]]:
if not isinstance(items, list):
raise ApiError(
"PAYMENT_BUTTON_DEFAULT_SHORTCUTS_INVALID",
"فهرست میانبرهای پیش‌فرض نامعتبر است",
http_status=400,
)
normalized_by_id: Dict[int, Dict[str, str | None]] = {}
used: Dict[str, Dict[str, int]] = {"windows": {}, "web": {}}
for item in items:
if not isinstance(item, dict):
raise ApiError(
"PAYMENT_BUTTON_DEFAULT_SHORTCUTS_INVALID",
"هر ردیف میانبر باید یک دکمه معتبر باشد",
http_status=400,
)
try:
button_id = int(item.get("button_id"))
except (TypeError, ValueError) as exc:
raise ApiError(
"PAYMENT_BUTTON_DEFAULT_SHORTCUTS_INVALID",
"شناسه دکمه پرداخت نامعتبر است",
http_status=400,
) from exc
if button_id in normalized_by_id:
raise ApiError(
"PAYMENT_BUTTON_DEFAULT_SHORTCUT_DUPLICATE_BUTTON",
"یک دکمه بیش از یک بار در فهرست ارسال شده است",
http_status=400,
)
raw_shortcuts = item.get("shortcuts")
if raw_shortcuts is None:
raw_shortcuts = {"windows": item.get("shortcut")}
if not isinstance(raw_shortcuts, dict):
raise ApiError(
"PAYMENT_BUTTON_DEFAULT_SHORTCUTS_INVALID",
"ساختار میانبرهای دکمه نامعتبر است",
http_status=400,
)
normalized_by_id[button_id] = {}
for platform in ("windows", "web"):
if platform not in raw_shortcuts:
continue
normalized = _normalize_payment_button_shortcut(
raw_shortcuts.get(platform), platform=platform
)
if normalized and normalized in used[platform]:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_CONFLICT",
"یک میانبر برای چند دکمه پرداخت انتخاب شده است",
http_status=409,
)
if normalized:
used[platform][normalized] = button_id
normalized_by_id[button_id][platform] = normalized
if not normalized_by_id:
return list_quick_sales_payment_default_shortcuts(db, business_id)
rows = (
db.query(QuickSalesPaymentButton)
.filter(
QuickSalesPaymentButton.business_id == int(business_id),
QuickSalesPaymentButton.scope == "business",
QuickSalesPaymentButton.is_active == True, # noqa: E712
QuickSalesPaymentButton.id.in_(list(normalized_by_id)),
)
.all()
)
rows_by_id = {int(row.id): row for row in rows}
missing = set(normalized_by_id) - set(rows_by_id)
if missing:
raise ApiError(
"PAYMENT_BUTTON_NOT_FOUND",
"یکی از دکمه‌های مشترک یافت نشد یا متعلق به این کسب‌وکار نیست",
http_status=404,
)
# Include unchanged rows in uniqueness validation so partial API callers
# cannot accidentally duplicate an existing business default.
all_rows = (
db.query(QuickSalesPaymentButton)
.filter(
QuickSalesPaymentButton.business_id == int(business_id),
QuickSalesPaymentButton.scope == "business",
QuickSalesPaymentButton.is_active == True, # noqa: E712
)
.all()
)
all_used: Dict[str, Dict[str, int]] = {"windows": {}, "web": {}}
for row in all_rows:
row_id = int(row.id)
values = {
"windows": _normalize_payment_button_shortcut(row.shortcut),
"web": _normalize_payment_button_shortcut(
row.web_shortcut, platform="web"
),
}
values.update(normalized_by_id.get(row_id) or {})
for platform, value in values.items():
if value and value in all_used[platform]:
raise ApiError(
"PAYMENT_BUTTON_SHORTCUT_CONFLICT",
"یک میانبر برای چند دکمه پرداخت انتخاب شده است",
http_status=409,
)
if value:
all_used[platform][value] = row_id
for button_id, shortcut_values in normalized_by_id.items():
if "windows" in shortcut_values:
rows_by_id[button_id].shortcut = shortcut_values["windows"]
if "web" in shortcut_values:
rows_by_id[button_id].web_shortcut = shortcut_values["web"]
db.flush()
return list_quick_sales_payment_default_shortcuts(db, business_id)
def create_quick_sales_payment_button(
@ -265,13 +837,6 @@ def create_quick_sales_payment_button(
if int(count) >= MAX_PAYMENT_BUTTONS_PER_SCOPE:
raise ApiError("PAYMENT_BUTTON_LIMIT", "حداکثر تعداد دکمه‌های پرداخت ثبت شده است", http_status=400)
shortcut = _normalize_payment_button_shortcut(payload.get("shortcut"))
_assert_payment_button_shortcut_available(
db,
business_id=business_id,
scope=scope,
owner_user_id=owner_user_id,
shortcut=shortcut,
)
max_position = (
db.query(func.max(QuickSalesPaymentButton.position))
.filter(
@ -293,15 +858,28 @@ def create_quick_sales_payment_button(
bank_account_id=int(target.id) if target_type == "bank" else None,
person_id=int(target.id) if target_type == "person" else None,
label=label[:120],
shortcut=shortcut,
shortcut=None,
position=(int(max_position) + 1) if max_position is not None else 0,
is_active=True,
created_by_user_id=int(user_id),
)
db.add(row)
db.flush()
if shortcut:
set_quick_sales_payment_button_shortcut(
db,
business_id=business_id,
user_id=user_id,
button_key=str(row.id),
shortcut=shortcut,
)
db.commit()
db.refresh(row)
return _payment_button_to_dict(db, row)
return next(
button
for button in list_quick_sales_payment_buttons(db, business_id, user_id)
if str(button["id"]) == str(row.id)
)
def update_quick_sales_payment_button(
@ -329,18 +907,56 @@ def update_quick_sales_payment_button(
if row.scope == "user" and int(row.owner_user_id or 0) != int(user_id):
raise ApiError("FORBIDDEN", "این دکمه متعلق به کاربر دیگری است", http_status=403)
requested_scope = str(payload.get("scope") or row.scope).strip().lower()
if requested_scope not in PAYMENT_BUTTON_SCOPES:
raise ApiError(
"PAYMENT_BUTTON_SCOPE_INVALID",
"دامنه دکمه نامعتبر است",
http_status=400,
)
scope_changed = requested_scope != row.scope
if scope_changed:
if not can_manage_business:
raise ApiError(
"FORBIDDEN",
"مجوز تغییر دامنه دکمه پرداخت را ندارید",
http_status=403,
)
target_owner_user_id = int(user_id) if requested_scope == "user" else None
target_count = (
db.query(func.count(QuickSalesPaymentButton.id))
.filter(
QuickSalesPaymentButton.business_id == int(business_id),
QuickSalesPaymentButton.scope == requested_scope,
QuickSalesPaymentButton.owner_user_id == target_owner_user_id,
QuickSalesPaymentButton.is_active == True, # noqa: E712
)
.scalar()
or 0
)
if int(target_count) >= MAX_PAYMENT_BUTTONS_PER_SCOPE:
raise ApiError(
"PAYMENT_BUTTON_LIMIT",
"حداکثر تعداد دکمه‌های پرداخت ثبت شده است",
http_status=400,
)
max_position = (
db.query(func.max(QuickSalesPaymentButton.position))
.filter(
QuickSalesPaymentButton.business_id == int(business_id),
QuickSalesPaymentButton.scope == requested_scope,
QuickSalesPaymentButton.owner_user_id == target_owner_user_id,
QuickSalesPaymentButton.is_active == True, # noqa: E712
)
.scalar()
)
row.scope = requested_scope
row.owner_user_id = target_owner_user_id
row.position = (int(max_position) + 1) if max_position is not None else 0
target_type = str(payload.get("target_type") or row.target_type).strip().lower()
target_id = payload.get("target_id", _payment_button_target_id(row))
target, target_name = _payment_button_target(db, business_id, target_type, target_id)
shortcut = _normalize_payment_button_shortcut(payload.get("shortcut", row.shortcut))
_assert_payment_button_shortcut_available(
db,
business_id=business_id,
scope=row.scope,
owner_user_id=row.owner_user_id,
shortcut=shortcut,
exclude_id=row.id,
)
row.target_type = target_type
row.cash_register_id = int(target.id) if target_type == "cash_register" else None
row.bank_account_id = int(target.id) if target_type == "bank" else None
@ -350,12 +966,24 @@ def update_quick_sales_payment_button(
if target_type == "person"
else (str(payload.get("label") or row.label or target_name).strip() or target_name)[:120]
)
row.shortcut = shortcut
if "position" in payload:
if "position" in payload and not scope_changed:
row.position = max(0, int(payload.get("position") or 0))
db.flush()
if "shortcut" in payload:
set_quick_sales_payment_button_shortcut(
db,
business_id=business_id,
user_id=user_id,
button_key=str(row.id),
shortcut=payload.get("shortcut"),
)
db.commit()
db.refresh(row)
return _payment_button_to_dict(db, row)
return next(
button
for button in list_quick_sales_payment_buttons(db, business_id, user_id)
if str(button["id"]) == str(row.id)
)
def delete_quick_sales_payment_button(
@ -382,6 +1010,9 @@ def delete_quick_sales_payment_button(
if row.scope == "user" and int(row.owner_user_id or 0) != int(user_id):
raise ApiError("FORBIDDEN", "این دکمه متعلق به کاربر دیگری است", http_status=403)
row.is_active = False
shortcuts = get_quick_sales_payment_shortcuts(db, user_id, business_id)
if shortcuts.pop(str(row.id), None) is not None:
save_quick_sales_payment_shortcuts(db, user_id, business_id, shortcuts)
db.commit()

View file

@ -10,6 +10,9 @@ from adapters.db.models.user_ui_preferences import UserUiPreferences
_BUSINESS_PATH_RE = re.compile(r"^/business/(\d+)(/.*)?$")
_MAX_TABS_PER_BUSINESS = 24
_MAX_QUICK_SALES_SHORTCUT_BUSINESSES = 100
_MAX_QUICK_SALES_SHORTCUTS_PER_BUSINESS = 100
_QUICK_SALES_SHORTCUT_PLATFORMS = frozenset({"windows", "web"})
def _default_preferences() -> Dict[str, Any]:
@ -101,6 +104,37 @@ def _normalize_tabs_payload(raw: Any) -> Dict[str, Any]:
return out
def _normalize_quick_sales_payment_shortcuts(raw: Any) -> Dict[str, Any]:
"""Keep per-user quick-sales shortcuts small and safe inside the JSON preferences row."""
if not isinstance(raw, dict):
return {}
out: Dict[str, Any] = {}
for business_key, platform_payload in list(raw.items())[:_MAX_QUICK_SALES_SHORTCUT_BUSINESSES]:
try:
business_id = int(str(business_key))
except (TypeError, ValueError):
continue
if business_id <= 0 or not isinstance(platform_payload, dict):
continue
platforms: Dict[str, Dict[str, str]] = {}
for platform in _QUICK_SALES_SHORTCUT_PLATFORMS:
button_payload = platform_payload.get(platform)
if not isinstance(button_payload, dict):
continue
buttons: Dict[str, str] = {}
for button_key, shortcut in list(button_payload.items())[:_MAX_QUICK_SALES_SHORTCUTS_PER_BUSINESS]:
key = str(button_key or "").strip()
value = str(shortcut or "").strip().upper().replace(" ", "")
if not key or len(key) > 64 or not value or len(value) > 32:
continue
buttons[key] = value
if buttons:
platforms[platform] = buttons
if platforms:
out[str(business_id)] = platforms
return out
def _parse_business_path(path: str) -> Tuple[bool, int, str]:
m = _BUSINESS_PATH_RE.match(path.split("?")[0])
if not m:
@ -125,6 +159,9 @@ def get_user_ui_preferences(db: Session, user_id: int) -> Dict[str, Any]:
data["business_panel_sidebar_tab_behavior"] = base["business_panel_sidebar_tab_behavior"]
tabs = _normalize_tabs_payload(stored.get("business_panel_tabs"))
data["business_panel_tabs"] = tabs
data["quick_sales_payment_shortcuts"] = _normalize_quick_sales_payment_shortcuts(
stored.get("quick_sales_payment_shortcuts")
)
# فقط اگر کاربر قبلاً تم را صریحاً ذخیره کرده باشد برگردان
if "theme_id" in stored:
tid = _normalize_theme_id(stored.get("theme_id"))
@ -168,6 +205,17 @@ def save_user_ui_preferences(db: Session, user_id: int, payload: Dict[str, Any])
"business_panel_tabs": tabs,
}
if "quick_sales_payment_shortcuts" in payload:
quick_sales_shortcuts = _normalize_quick_sales_payment_shortcuts(
payload.get("quick_sales_payment_shortcuts")
)
else:
quick_sales_shortcuts = _normalize_quick_sales_payment_shortcuts(
stored_raw.get("quick_sales_payment_shortcuts")
)
if quick_sales_shortcuts:
next_prefs["quick_sales_payment_shortcuts"] = quick_sales_shortcuts
# تم فقط وقتی در payload باشد یا قبلاً توسط کاربر ذخیره شده باشد حفظ می‌شود
if "theme_id" in payload:
tid = _normalize_theme_id(payload.get("theme_id"), "classic_blue")
@ -195,3 +243,56 @@ def save_user_ui_preferences(db: Session, user_id: int, payload: Dict[str, Any])
row.updated_at = now
db.flush()
return get_user_ui_preferences(db, user_id)
def get_quick_sales_payment_shortcuts(
db: Session,
user_id: int,
business_id: int,
*,
platform: str = "windows",
) -> Dict[str, str]:
preferences = get_user_ui_preferences(db, user_id)
all_shortcuts = preferences.get("quick_sales_payment_shortcuts") or {}
business_shortcuts = all_shortcuts.get(str(int(business_id))) or {}
platform_shortcuts = business_shortcuts.get(platform) or {}
return dict(platform_shortcuts) if isinstance(platform_shortcuts, dict) else {}
def save_quick_sales_payment_shortcuts(
db: Session,
user_id: int,
business_id: int,
shortcuts: Dict[str, str],
*,
platform: str = "windows",
) -> Dict[str, str]:
if platform not in _QUICK_SALES_SHORTCUT_PLATFORMS:
raise ValueError("Unsupported quick-sales shortcut platform")
preferences = get_user_ui_preferences(db, user_id)
all_shortcuts = dict(preferences.get("quick_sales_payment_shortcuts") or {})
business_key = str(int(business_id))
business_shortcuts = dict(all_shortcuts.get(business_key) or {})
clean_shortcuts = {
str(key): str(value)
for key, value in shortcuts.items()
if str(key).strip() and str(value).strip()
}
if clean_shortcuts:
business_shortcuts[platform] = clean_shortcuts
all_shortcuts[business_key] = business_shortcuts
else:
business_shortcuts.pop(platform, None)
if business_shortcuts:
all_shortcuts[business_key] = business_shortcuts
else:
all_shortcuts.pop(business_key, None)
result = save_user_ui_preferences(
db,
user_id,
{"quick_sales_payment_shortcuts": all_shortcuts},
)
return dict(
((result.get("quick_sales_payment_shortcuts") or {}).get(business_key) or {}).get(platform)
or {}
)

View file

@ -0,0 +1,30 @@
"""Add web shortcuts to quick-sales payment buttons.
Revision ID: 20261015_000001_quick_sales_web_shortcut
Revises: 20261014_000002_quick_sales_customer_group
"""
import sqlalchemy as sa
from alembic import op
revision = "20261015_000001_quick_sales_web_shortcut"
down_revision = "20261014_000002_quick_sales_customer_group"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column(
"quick_sales_payment_buttons",
sa.Column(
"web_shortcut",
sa.String(length=32),
nullable=True,
comment="میانبر پیش‌فرض دکمه پرداخت در رابط وب",
),
)
def downgrade() -> None:
op.drop_column("quick_sales_payment_buttons", "web_shortcut")

View file

@ -1,8 +1,14 @@
from datetime import date
from types import SimpleNamespace
import pytest
from app.core.responses import ApiError
from app.services.inventory_discrepancy_service import (
_correction_lines_by_case_line,
_correction_request_fingerprint,
_serialize,
create_goods_income_correction,
)
@ -72,3 +78,118 @@ def test_correction_lines_are_matched_by_case_line_not_only_product():
assert indexed[7]["warehouse_id"] == 1
assert indexed[8]["warehouse_id"] == 2
def test_stock_correction_reuses_document_for_same_request_token(monkeypatch):
from app.services import goods_expense_income_service
from app.services import inventory_discrepancy_service as service
document_date = date(2026, 10, 17)
lines = [{"product_id": 11, "warehouse_id": 3, "quantity": 2}]
existing = SimpleNamespace(
id=91,
extra_info={
"request_fingerprint": _correction_request_fingerprint(
document_date,
lines,
)
},
)
monkeypatch.setattr(service, "acquire_transaction_lock", lambda *_args: None)
monkeypatch.setattr(
service,
"_find_quick_sales_correction_by_token",
lambda *_args, **_kwargs: existing,
)
monkeypatch.setattr(
goods_expense_income_service,
"_document_to_dict",
lambda *_args: {"id": 91, "status": "posted"},
)
monkeypatch.setattr(
goods_expense_income_service,
"create_document",
lambda *_args, **_kwargs: pytest.fail("نباید سند دوم ساخته شود"),
)
result = create_goods_income_correction(
SimpleNamespace(),
business_id=5,
user_id=7,
document_date=document_date,
lines=lines,
description="اصلاح فروش سریع",
user_can_allocate=True,
user_can_post=True,
user_can_change_unit_cost=False,
request_token="qs-stock-5-sale-1-12345678",
)
assert result == {"id": 91, "status": "posted", "idempotent_replay": True}
def test_stock_correction_rejects_reused_token_for_different_request(monkeypatch):
from app.services import inventory_discrepancy_service as service
existing = SimpleNamespace(
id=91,
extra_info={"request_fingerprint": "another-request"},
)
monkeypatch.setattr(service, "acquire_transaction_lock", lambda *_args: None)
monkeypatch.setattr(
service,
"_find_quick_sales_correction_by_token",
lambda *_args, **_kwargs: existing,
)
with pytest.raises(ApiError) as exc_info:
create_goods_income_correction(
SimpleNamespace(),
business_id=5,
user_id=7,
document_date=date(2026, 10, 17),
lines=[{"product_id": 11, "warehouse_id": 3, "quantity": 2}],
description="اصلاح فروش سریع",
user_can_allocate=True,
user_can_post=True,
user_can_change_unit_cost=False,
request_token="qs-stock-5-sale-1-12345678",
)
assert exc_info.value.code == "STOCK_CORRECTION_REQUEST_TOKEN_REUSED"
def test_stock_correction_stores_token_and_fingerprint(monkeypatch):
from app.services import goods_expense_income_service
from app.services import inventory_discrepancy_service as service
captured = {}
monkeypatch.setattr(service, "acquire_transaction_lock", lambda *_args: None)
monkeypatch.setattr(
service,
"_find_quick_sales_correction_by_token",
lambda *_args, **_kwargs: None,
)
def create_document(_db, _business_id, _user_id, payload, **_kwargs):
captured.update(payload)
return {"id": 92, "status": "posted"}
monkeypatch.setattr(goods_expense_income_service, "create_document", create_document)
result = create_goods_income_correction(
SimpleNamespace(),
business_id=5,
user_id=7,
document_date=date(2026, 10, 17),
lines=[{"product_id": 11, "warehouse_id": 3, "quantity": 2}],
description="اصلاح فروش سریع",
user_can_allocate=True,
user_can_post=True,
user_can_change_unit_cost=False,
request_token="qs-stock-5-sale-1-12345678",
)
assert result["idempotent_replay"] is False
assert captured["extra_info"]["request_token"] == "qs-stock-5-sale-1-12345678"
assert len(captured["extra_info"]["request_fingerprint"]) == 64

View file

@ -0,0 +1,146 @@
from __future__ import annotations
from datetime import date
from decimal import Decimal
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
from app.core.responses import ApiError
from app.services import quick_sales_service
from app.services.invoice_service import (
_adjust_quick_sale_invoice_paid,
_normalize_quick_sale_customer_balance_application,
_quick_sale_change_amount,
_quick_sale_payment_target,
)
def _document(*, total: float, meta: dict | None = None) -> SimpleNamespace:
extra = {"totals": {"net": total}}
if meta is not None:
extra["quick_sale_customer_balance"] = {"applied": True, **meta}
return SimpleNamespace(extra_info=extra)
def test_prior_debt_increases_payment_target_and_is_allocated_first() -> None:
document = _document(
total=5_000_000,
meta={
"prior_debt_amount": 2_000_000,
"credit_applied_amount": 0,
"payment_target": 7_000_000,
},
)
assert _quick_sale_payment_target(document) == Decimal("7000000")
assert _adjust_quick_sale_invoice_paid(document, Decimal("7000000")) == Decimal(
"5000000"
)
assert _adjust_quick_sale_invoice_paid(document, Decimal("4000000")) == Decimal(
"2000000"
)
def test_prior_credit_reduces_target_and_settles_invoice() -> None:
document = _document(
total=5_000_000,
meta={
"prior_debt_amount": 0,
"credit_applied_amount": 2_000_000,
"payment_target": 3_000_000,
},
)
assert _quick_sale_payment_target(document) == Decimal("3000000")
assert _adjust_quick_sale_invoice_paid(document, Decimal("3000000")) == Decimal(
"5000000"
)
assert _quick_sale_change_amount(
document,
[{"amount": 3_500_000}],
) == Decimal("500000")
def test_credit_larger_than_invoice_caps_applied_credit() -> None:
document = _document(
total=5_000_000,
meta={
"prior_debt_amount": 0,
"credit_applied_amount": 5_000_000,
"payment_target": 0,
},
)
assert _adjust_quick_sale_invoice_paid(document, Decimal(0)) == Decimal("5000000")
def test_server_normalizes_customer_balance_application(monkeypatch) -> None:
monkeypatch.setattr(
quick_sales_service,
"get_quick_sales_customer_balance",
lambda *_args, **_kwargs: {
"balance": -2_000_000,
"status": "بدهکار",
"decimal_places": 0,
},
)
extra = {
"quick_sale_customer_balance": {
"apply": True,
"person_id": 10,
"currency_id": 1,
"balance_before": -2_000_000,
}
}
result = _normalize_quick_sale_customer_balance_application(
MagicMock(),
business_id=1,
person_id=10,
currency_id=1,
document_date=date(2026, 10, 16),
fiscal_year_id=2,
invoice_total=Decimal("5000000"),
header_extra=extra,
)
normalized = result["quick_sale_customer_balance"]
assert normalized["prior_debt_amount"] == 2_000_000
assert normalized["credit_applied_amount"] == 0
assert normalized["payment_target"] == 7_000_000
def test_server_rejects_stale_customer_balance(monkeypatch) -> None:
monkeypatch.setattr(
quick_sales_service,
"get_quick_sales_customer_balance",
lambda *_args, **_kwargs: {
"balance": -2_500_000,
"status": "بدهکار",
"decimal_places": 0,
},
)
with pytest.raises(ApiError) as exc_info:
_normalize_quick_sale_customer_balance_application(
MagicMock(),
business_id=1,
person_id=10,
currency_id=1,
document_date=date(2026, 10, 16),
fiscal_year_id=2,
invoice_total=Decimal("5000000"),
header_extra={
"quick_sale_customer_balance": {
"apply": True,
"person_id": 10,
"currency_id": 1,
"balance_before": -2_000_000,
}
},
)
assert exc_info.value.code == "QUICK_SALE_CUSTOMER_BALANCE_CHANGED"
assert exc_info.value.status_code == 409

View file

@ -2,7 +2,8 @@
from __future__ import annotations
from unittest.mock import MagicMock
from types import SimpleNamespace
from unittest.mock import ANY, MagicMock
import pytest
@ -14,11 +15,16 @@ from app.core.responses import ApiError
from app.services.quick_sales_service import (
DEFAULT_SHARE_CHANNELS,
DEFAULT_SHARE_EXPIRY_HOURS,
PAYMENT_BUTTON_SHORTCUT_DISABLED,
_apply_user_payment_shortcuts,
_assert_user_payment_shortcut_available,
_normalize_payment_button_shortcut,
_resolve_user_payment_shortcuts,
_share_settings_from_obj,
get_quick_sales_settings,
normalize_default_share_channels,
normalize_share_expiry_hours,
set_quick_sales_payment_default_shortcuts,
)
@ -145,6 +151,129 @@ def test_update_quick_sales_settings_can_clear_customer_group(monkeypatch) -> No
assert result["quick_customer_group_id"] is None
def _payment_button_row(*, scope: str, owner_user_id: int | None):
return SimpleNamespace(
id=11,
business_id=5,
scope=scope,
owner_user_id=owner_user_id,
target_type="cash_register",
cash_register_id=7,
bank_account_id=None,
person_id=None,
label="صندوق اصلی",
shortcut=None,
web_shortcut=None,
position=2,
is_active=True,
)
def _query_with_scalar(value):
query = MagicMock()
query.filter.return_value.scalar.return_value = value
return query
def test_update_payment_button_can_move_personal_button_to_business(monkeypatch) -> None:
from app.services import quick_sales_service as service
row = _payment_button_row(scope="user", owner_user_id=9)
row_query = MagicMock()
row_query.filter.return_value.first.return_value = row
db = MagicMock()
db.query.side_effect = [
row_query,
_query_with_scalar(3),
_query_with_scalar(6),
]
monkeypatch.setattr(
service,
"_payment_button_target",
lambda *_args: (SimpleNamespace(id=7), "صندوق اصلی"),
)
monkeypatch.setattr(
service,
"list_quick_sales_payment_buttons",
lambda *_args: [{"id": 11, "scope": row.scope}],
)
result = service.update_quick_sales_payment_button(
db,
business_id=5,
button_id=11,
user_id=9,
payload={"scope": "business"},
can_manage_business=True,
)
assert row.scope == "business"
assert row.owner_user_id is None
assert row.position == 7
assert result["scope"] == "business"
db.commit.assert_called_once()
def test_update_payment_button_can_move_shared_button_to_current_user(monkeypatch) -> None:
from app.services import quick_sales_service as service
row = _payment_button_row(scope="business", owner_user_id=None)
row_query = MagicMock()
row_query.filter.return_value.first.return_value = row
db = MagicMock()
db.query.side_effect = [
row_query,
_query_with_scalar(0),
_query_with_scalar(None),
]
monkeypatch.setattr(
service,
"_payment_button_target",
lambda *_args: (SimpleNamespace(id=7), "صندوق اصلی"),
)
monkeypatch.setattr(
service,
"list_quick_sales_payment_buttons",
lambda *_args: [{"id": 11, "scope": row.scope}],
)
service.update_quick_sales_payment_button(
db,
business_id=5,
button_id=11,
user_id=9,
payload={"scope": "user"},
can_manage_business=True,
)
assert row.scope == "user"
assert row.owner_user_id == 9
assert row.position == 0
def test_update_payment_button_scope_requires_business_permission() -> None:
from app.services import quick_sales_service as service
row = _payment_button_row(scope="user", owner_user_id=9)
row_query = MagicMock()
row_query.filter.return_value.first.return_value = row
db = MagicMock()
db.query.return_value = row_query
with pytest.raises(ApiError) as exc:
service.update_quick_sales_payment_button(
db,
business_id=5,
button_id=11,
user_id=9,
payload={"scope": "business"},
can_manage_business=False,
)
assert exc.value.detail["error"]["code"] == "FORBIDDEN"
db.commit.assert_not_called()
def test_invoice_share_link_event_type_in_seed_catalog() -> None:
codes = {row["code"] for row in NOTIFICATION_EVENT_TYPES_ROWS}
assert INVOICE_SHARE_LINK_EVENT_CODES <= codes
@ -168,7 +297,12 @@ def test_validate_share_gateway_id_rejects_unknown_gateway() -> None:
@pytest.mark.parametrize(
("raw", "expected"),
[("alt + 1", "ALT+1"), ("F3", "F3"), ("ctrl+shift+k", "CTRL+SHIFT+K")],
[
("alt + 1", "ALT+1"),
("F3", "F3"),
("F12", "F12"),
("ctrl+shift+k", "CTRL+SHIFT+K"),
],
)
def test_normalize_payment_button_shortcut(raw: str, expected: str) -> None:
assert _normalize_payment_button_shortcut(raw) == expected
@ -178,3 +312,265 @@ def test_normalize_payment_button_shortcut(raw: str, expected: str) -> None:
def test_normalize_payment_button_shortcut_rejects_invalid_or_reserved(raw: str) -> None:
with pytest.raises(ApiError):
_normalize_payment_button_shortcut(raw)
@pytest.mark.parametrize(
("raw", "expected"),
[("alt + 1", "ALT+1"), ("ctrl+alt+r", "CTRL+ALT+R")],
)
def test_normalize_web_payment_button_shortcut(raw: str, expected: str) -> None:
assert _normalize_payment_button_shortcut(raw, platform="web") == expected
@pytest.mark.parametrize("raw", ["F12", "SHIFT+A", "CTRL+L"])
def test_normalize_web_payment_button_shortcut_rejects_invalid_or_reserved(
raw: str,
) -> None:
with pytest.raises(ApiError):
_normalize_payment_button_shortcut(raw, platform="web")
def test_user_payment_shortcut_conflict_is_scoped_to_current_mapping() -> None:
with pytest.raises(ApiError) as exc:
_assert_user_payment_shortcut_available(
[
{"id": 11, "effective_shortcut": "F12"},
{"id": 12, "effective_shortcut": "ALT+R"},
],
shortcut="F12",
exclude_button_key="12",
)
assert exc.value.detail["error"]["code"] == "PAYMENT_BUTTON_SHORTCUT_CONFLICT"
def test_user_payment_shortcut_can_keep_its_own_value() -> None:
_assert_user_payment_shortcut_available(
[{"id": 11, "effective_shortcut": "F12"}],
shortcut="F12",
exclude_button_key="11",
)
def test_resolve_shortcuts_inherits_business_default() -> None:
result, stored = _resolve_user_payment_shortcuts(
[{"id": 11, "default_shortcut": "F12"}],
{},
)
assert stored == {}
assert result[0]["effective_shortcut"] == "F12"
assert result[0]["shortcut_source"] == "business"
assert result[0]["user_shortcut"] is None
def test_resolve_shortcuts_personal_override_wins() -> None:
result, _ = _resolve_user_payment_shortcuts(
[{"id": 11, "default_shortcut": "F12"}],
{"11": "ALT+R"},
)
assert result[0]["effective_shortcut"] == "ALT+R"
assert result[0]["shortcut_source"] == "user"
def test_resolve_shortcuts_can_disable_inherited_default() -> None:
result, _ = _resolve_user_payment_shortcuts(
[{"id": 11, "default_shortcut": "F12"}],
{"11": PAYMENT_BUTTON_SHORTCUT_DISABLED},
)
assert result[0]["effective_shortcut"] is None
assert result[0]["shortcut_source"] == "disabled"
assert result[0]["user_shortcut_disabled"] is True
def test_resolve_shortcuts_personal_choice_suppresses_later_conflicting_default() -> None:
result, _ = _resolve_user_payment_shortcuts(
[
{"id": 11, "default_shortcut": "F12"},
{"id": 12, "default_shortcut": "ALT+R"},
],
{"12": "F12"},
)
assert result[0]["effective_shortcut"] is None
assert result[0]["shortcut_conflict"] is True
assert result[1]["effective_shortcut"] == "F12"
assert result[1]["shortcut_source"] == "user"
def test_apply_user_shortcuts_prunes_stale_values_without_copying_defaults(
monkeypatch,
) -> None:
from app.services import quick_sales_service as service
saved = MagicMock()
monkeypatch.setattr(
service,
"get_quick_sales_payment_shortcuts",
lambda _db, _user_id, _business_id, platform="windows": (
{"stale": "F9"} if platform == "windows" else {}
),
)
monkeypatch.setattr(service, "save_quick_sales_payment_shortcuts", saved)
buttons = [
{"id": 11, "default_shortcut": "F12"},
{"id": 12, "default_shortcut": "ALT+R"},
]
result = _apply_user_payment_shortcuts(
MagicMock(),
business_id=5,
user_id=7,
buttons=buttons,
)
assert [row["shortcut"] for row in result] == ["F12", "ALT+R"]
saved.assert_called_once_with(
ANY,
7,
5,
{},
platform="windows",
)
def test_apply_user_shortcuts_migrates_only_legacy_personal_button(
monkeypatch,
) -> None:
from app.services import quick_sales_service as service
saved = MagicMock()
monkeypatch.setattr(
service,
"get_quick_sales_payment_shortcuts",
lambda _db, _user_id, _business_id, platform="windows": {},
)
monkeypatch.setattr(service, "save_quick_sales_payment_shortcuts", saved)
result = _apply_user_payment_shortcuts(
MagicMock(),
business_id=5,
user_id=7,
buttons=[
{
"id": 11,
"default_shortcut": None,
"legacy_user_shortcut": "ALT+R",
}
],
)
assert result[0]["shortcut"] == "ALT+R"
assert result[0]["shortcut_source"] == "user"
saved.assert_called_once_with(
ANY, 7, 5, {"11": "ALT+R"}, platform="windows"
)
def test_apply_user_shortcuts_respects_explicitly_disabled_default(
monkeypatch,
) -> None:
from app.services import quick_sales_service as service
saved = MagicMock()
monkeypatch.setattr(
service,
"get_quick_sales_payment_shortcuts",
lambda _db, _user_id, _business_id, platform="windows": (
{"11": PAYMENT_BUTTON_SHORTCUT_DISABLED}
if platform == "windows"
else {}
),
)
monkeypatch.setattr(service, "save_quick_sales_payment_shortcuts", saved)
result = _apply_user_payment_shortcuts(
MagicMock(),
business_id=5,
user_id=7,
buttons=[{"id": 11, "default_shortcut": "F12"}],
)
assert result[0]["shortcut"] is None
saved.assert_not_called()
def test_bulk_default_shortcuts_rejects_duplicate_keys_before_writing() -> None:
db = MagicMock()
with pytest.raises(ApiError) as exc:
set_quick_sales_payment_default_shortcuts(
db,
business_id=5,
items=[
{"button_id": 11, "shortcut": "F1"},
{"button_id": 12, "shortcut": "F1"},
],
)
assert exc.value.detail["error"]["code"] == "PAYMENT_BUTTON_SHORTCUT_CONFLICT"
db.query.assert_not_called()
def test_bulk_default_shortcuts_rejects_duplicate_web_keys_before_writing() -> None:
db = MagicMock()
with pytest.raises(ApiError) as exc:
set_quick_sales_payment_default_shortcuts(
db,
business_id=5,
items=[
{
"button_id": 11,
"shortcuts": {"windows": "F1", "web": "ALT+1"},
},
{
"button_id": 12,
"shortcuts": {"windows": "F2", "web": "ALT+1"},
},
],
)
assert exc.value.detail["error"]["code"] == "PAYMENT_BUTTON_SHORTCUT_CONFLICT"
db.query.assert_not_called()
def test_bulk_default_shortcuts_updates_all_rows_after_validation(
monkeypatch,
) -> None:
from app.services import quick_sales_service as service
first = SimpleNamespace(id=11, shortcut="F1", web_shortcut="ALT+1")
second = SimpleNamespace(id=12, shortcut=None, web_shortcut="ALT+2")
query = MagicMock()
query.filter.return_value.all.side_effect = [
[first, second],
[first, second],
]
db = MagicMock()
db.query.return_value = query
monkeypatch.setattr(
service,
"list_quick_sales_payment_default_shortcuts",
lambda _db, _business_id: [
{"button_id": 11, "default_shortcut": first.shortcut},
{"button_id": 12, "default_shortcut": second.shortcut},
],
)
result = set_quick_sales_payment_default_shortcuts(
db,
business_id=5,
items=[
{"button_id": 11, "shortcut": "F2"},
{"button_id": 12, "shortcut": "ALT+R"},
],
)
assert first.shortcut == "F2"
assert second.shortcut == "ALT+R"
assert first.web_shortcut == "ALT+1"
assert second.web_shortcut == "ALT+2"
assert result[1]["default_shortcut"] == "ALT+R"
db.flush.assert_called_once_with()

View file

@ -0,0 +1,68 @@
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import MagicMock
from app.services.user_ui_preferences_service import (
_normalize_quick_sales_payment_shortcuts,
get_user_ui_preferences,
save_user_ui_preferences,
)
def test_normalize_quick_sales_shortcuts_keeps_platform_values() -> None:
result = _normalize_quick_sales_payment_shortcuts(
{
"4952": {
"windows": {"17": " f12 ", "21": "alt + r"},
"web": {"17": "CTRL+1"},
},
"invalid": {"windows": {"1": "F2"}},
}
)
assert result == {
"4952": {
"windows": {"17": "F12", "21": "ALT+R"},
"web": {"17": "CTRL+1"},
}
}
def test_generic_preference_update_preserves_quick_sales_shortcuts() -> None:
row = SimpleNamespace(
preferences={
"business_panel_navigation": "single",
"business_panel_sidebar_tab_behavior": "reuse_across_tabs",
"business_panel_tabs": {},
"quick_sales_payment_shortcuts": {
"4952": {"windows": {"17": "F12"}}
},
},
updated_at=None,
)
db = MagicMock()
db.query.return_value.filter.return_value.first.return_value = row
result = save_user_ui_preferences(
db,
user_id=7,
payload={"business_panel_navigation": "tabs"},
)
assert result["business_panel_navigation"] == "tabs"
assert result["quick_sales_payment_shortcuts"] == {
"4952": {"windows": {"17": "F12"}}
}
assert row.preferences["quick_sales_payment_shortcuts"] == {
"4952": {"windows": {"17": "F12"}}
}
def test_get_preferences_returns_empty_shortcut_map_by_default() -> None:
db = MagicMock()
db.query.return_value.filter.return_value.first.return_value = None
result = get_user_ui_preferences(db, user_id=7)
assert result.get("quick_sales_payment_shortcuts", {}) == {}

View file

@ -4322,11 +4322,15 @@ class _MyAppState extends State<MyApp> {
final businessId = int.parse(
state.pathParameters['business_id']!,
);
// گارد دسترسی: فقط کاربرانی که دسترسی join دارند
if (!_authStore!.hasBusinessPermission(
'settings',
'join',
)) {
final canJoinSettings = _authStore!
.hasBusinessPermission('settings', 'join');
final canManageDefaultShortcuts = _authStore!
.hasBusinessPermission(
'quick_sales',
'manage_default_payment_shortcuts',
);
if (!canJoinSettings &&
!canManageDefaultShortcuts) {
return hesabixNoTransitionPage(
state,
PermissionGuard.buildAccessDeniedPage(),
@ -4645,10 +4649,18 @@ class _MyAppState extends State<MyApp> {
final businessId = int.parse(
state.pathParameters['business_id']!,
);
if (!_authStore!.hasBusinessPermission(
final canManageSettings = _authStore!
.hasBusinessPermission(
'settings',
'business',
)) {
);
final canManageDefaultShortcuts = _authStore!
.hasBusinessPermission(
'quick_sales',
'manage_default_payment_shortcuts',
);
if (!canManageSettings &&
!canManageDefaultShortcuts) {
return hesabixNoTransitionPage(
state,
PermissionGuard.buildAccessDeniedPage(),

View file

@ -20,6 +20,7 @@ class QuickSalesParkedSale {
final List<InvoiceLineItem> cartItems;
final List<InvoiceTransaction> payments;
final bool cashFollowsTotal;
final bool applyCustomerBalance;
final String? cashRegisterId;
final int? warehouseId;
final DateTime documentDate;
@ -45,6 +46,7 @@ class QuickSalesParkedSale {
this.cartItems = const [],
this.payments = const [],
this.cashFollowsTotal = true,
this.applyCustomerBalance = false,
this.cashRegisterId,
this.warehouseId,
required this.documentDate,
@ -92,6 +94,7 @@ class QuickSalesParkedSale {
List<InvoiceLineItem>? cartItems,
List<InvoiceTransaction>? payments,
bool? cashFollowsTotal,
bool? applyCustomerBalance,
String? cashRegisterId,
int? warehouseId,
DateTime? documentDate,
@ -118,6 +121,7 @@ class QuickSalesParkedSale {
cartItems: cartItems ?? this.cartItems,
payments: payments ?? this.payments,
cashFollowsTotal: cashFollowsTotal ?? this.cashFollowsTotal,
applyCustomerBalance: applyCustomerBalance ?? this.applyCustomerBalance,
cashRegisterId: cashRegisterId ?? this.cashRegisterId,
warehouseId: warehouseId ?? this.warehouseId,
documentDate: documentDate ?? this.documentDate,
@ -150,6 +154,7 @@ class QuickSalesParkedSale {
'cart_items': cartItems.map(encodeLine).toList(),
'payments': payments.map((p) => p.toJson()).toList(),
'cash_follows_total': cashFollowsTotal,
'apply_customer_balance': applyCustomerBalance,
'cash_register_id': cashRegisterId,
'warehouse_id': warehouseId,
'document_date': documentDate.toIso8601String(),
@ -217,6 +222,7 @@ class QuickSalesParkedSale {
payments: payments,
cashFollowsTotal:
json['cash_follows_total'] != false && (payments.length <= 1),
applyCustomerBalance: json['apply_customer_balance'] == true,
cashRegisterId: json['cash_register_id']?.toString(),
warehouseId: _asInt(json['warehouse_id']),
documentDate:

View file

@ -1,5 +1,34 @@
enum QuickSalesPaymentTargetType { cashRegister, bank, person }
class QuickSalesShortcutProfile {
final String? defaultShortcut;
final String? userShortcut;
final String? effectiveShortcut;
final String source;
final bool conflict;
final bool userShortcutDisabled;
const QuickSalesShortcutProfile({
this.defaultShortcut,
this.userShortcut,
this.effectiveShortcut,
this.source = 'none',
this.conflict = false,
this.userShortcutDisabled = false,
});
factory QuickSalesShortcutProfile.fromJson(Map<String, dynamic> json) =>
QuickSalesShortcutProfile(
defaultShortcut: json['default_shortcut']?.toString(),
userShortcut: json['user_shortcut']?.toString(),
effectiveShortcut: (json['effective_shortcut'] ?? json['shortcut'])
?.toString(),
source: (json['shortcut_source'] ?? 'none').toString(),
conflict: json['shortcut_conflict'] == true,
userShortcutDisabled: json['user_shortcut_disabled'] == true,
);
}
class QuickSalesPaymentButtonModel {
final Object id;
final int businessId;
@ -9,7 +38,13 @@ class QuickSalesPaymentButtonModel {
final int targetId;
final String targetName;
final String label;
final String? defaultShortcut;
final String? userShortcut;
final String? shortcut;
final String shortcutSource;
final bool shortcutConflict;
final bool userShortcutDisabled;
final Map<String, QuickSalesShortcutProfile> shortcutProfiles;
final int position;
final bool isSystem;
@ -22,13 +57,25 @@ class QuickSalesPaymentButtonModel {
required this.targetId,
required this.targetName,
required this.label,
required this.defaultShortcut,
required this.userShortcut,
required this.shortcut,
required this.shortcutSource,
required this.shortcutConflict,
required this.userShortcutDisabled,
required this.shortcutProfiles,
required this.position,
required this.isSystem,
});
bool get isPersonal => scope == 'user';
QuickSalesShortcutProfile shortcutProfile(String platform) =>
shortcutProfiles[platform] ?? const QuickSalesShortcutProfile();
String? shortcutForPlatform(String platform) =>
shortcutProfile(platform).effectiveShortcut;
factory QuickSalesPaymentButtonModel.fromJson(Map<String, dynamic> json) {
final target = switch ((json['target_type'] ?? '').toString()) {
'cash_register' => QuickSalesPaymentTargetType.cashRegister,
@ -38,6 +85,21 @@ class QuickSalesPaymentButtonModel {
'Unsupported quick-sales payment target',
),
};
final rawProfiles = json['shortcut_profiles'];
final profiles = <String, QuickSalesShortcutProfile>{};
if (rawProfiles is Map) {
for (final entry in rawProfiles.entries) {
if (entry.value is Map) {
profiles[entry.key.toString()] = QuickSalesShortcutProfile.fromJson(
Map<String, dynamic>.from(entry.value as Map),
);
}
}
}
profiles.putIfAbsent(
'windows',
() => QuickSalesShortcutProfile.fromJson(json),
);
return QuickSalesPaymentButtonModel(
id: json['id'] ?? '',
businessId: (json['business_id'] as num).toInt(),
@ -47,7 +109,13 @@ class QuickSalesPaymentButtonModel {
targetId: (json['target_id'] as num).toInt(),
targetName: (json['target_name'] ?? '').toString(),
label: (json['label'] ?? json['target_name'] ?? '').toString(),
shortcut: json['shortcut']?.toString(),
defaultShortcut: json['default_shortcut']?.toString(),
userShortcut: json['user_shortcut']?.toString(),
shortcut: (json['effective_shortcut'] ?? json['shortcut'])?.toString(),
shortcutSource: (json['shortcut_source'] ?? 'none').toString(),
shortcutConflict: json['shortcut_conflict'] == true,
userShortcutDisabled: json['user_shortcut_disabled'] == true,
shortcutProfiles: Map.unmodifiable(profiles),
position: (json['position'] as num?)?.toInt() ?? 0,
isSystem: json['is_system'] == true,
);

View file

@ -3805,7 +3805,11 @@ class _BusinessShellState extends State<BusinessShell> {
// تنظیمات: نیازمند دسترسی join
if (section == 'settings' && item.label == AppLocalizations.of(context).settings) {
final hasJoin = widget.authStore.hasBusinessPermission('settings', 'join');
return hasJoin;
final canManageDefaultShortcuts = widget.authStore.hasBusinessPermission(
'quick_sales',
'manage_default_payment_shortcuts',
);
return hasJoin || canManageDefaultShortcuts;
}
// استعلامات: نیازمند دسترسی read برای settings

View file

@ -24,6 +24,8 @@ import '../../utils/number_normalizer.dart' as number_utils;
import '../../utils/number_formatters.dart';
import '../../utils/product_search_overlay_policy.dart';
import '../../utils/invoice_global_discount_calculator.dart';
import '../../utils/quick_sales_customer_balance.dart';
import '../../utils/quick_sales_stock_correction.dart';
import '../../l10n/app_localizations.dart';
import '../../services/business_api_service.dart';
import '../../services/currency_service.dart';
@ -156,6 +158,12 @@ class _QuickSalesPageState extends State<QuickSalesPage>
// مشتری
Customer? _selectedCustomer;
num? _customerBalance;
String? _customerBalanceStatus;
bool _customerBalanceLoading = false;
String? _customerBalanceError;
bool _applyCustomerBalance = false;
int _customerBalanceRequestGeneration = 0;
// پرداخت
List<InvoiceTransaction> _payments = [];
@ -529,6 +537,8 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_parkedHydrated = true;
});
unawaited(_refreshCustomerBalance(preserveApply: _applyCustomerBalance));
unawaited(_loadShareGatewaysAndDefaults());
unawaited(_loadBusinessMetadata());
@ -646,6 +656,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
cartItems: _cartItems.map(QuickSalesParkedSale.cloneLine).toList(),
payments: List<InvoiceTransaction>.from(_payments),
cashFollowsTotal: _cashFollowsTotal,
applyCustomerBalance: _applyCustomerBalance,
cashRegisterId: _selectedCashRegisterId,
warehouseId: _defaultWarehouseId,
documentDate: _documentDate,
@ -678,6 +689,11 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_payments = List<InvoiceTransaction>.from(sale.payments);
_changeResolution = sale.changeResolution;
_cashFollowsTotal = sale.cashFollowsTotal;
_applyCustomerBalance = sale.applyCustomerBalance;
_customerBalance = null;
_customerBalanceStatus = null;
_customerBalanceError = null;
_customerBalanceLoading = false;
_shareRemainingEnabled = false;
_checkoutDiscountExpanded = false;
_selectedCashRegisterId =
@ -706,6 +722,11 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_payments = [];
_changeResolution = null;
_cashFollowsTotal = false;
_applyCustomerBalance = false;
_customerBalance = null;
_customerBalanceStatus = null;
_customerBalanceError = null;
_customerBalanceLoading = false;
_shareRemainingEnabled = false;
_checkoutDiscountExpanded = false;
_selectedCashRegisterId = _settingsDefaultCashRegisterId;
@ -757,6 +778,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
if (_showInventory && _cartItems.isNotEmpty) {
_refreshAllStocks();
}
unawaited(_refreshCustomerBalance(preserveApply: _applyCustomerBalance));
}
void _startNewSale() {
@ -1057,9 +1079,103 @@ class _QuickSalesPageState extends State<QuickSalesPage>
});
}
void _onCustomerChanged(Customer? customer) {
setState(() {
_selectedCustomer = customer ?? _anonymousCustomer;
_applyCustomerBalance = false;
_customerBalance = null;
_customerBalanceStatus = null;
_customerBalanceError = null;
_changeResolution = null;
_syncShareChannelDefaults();
});
unawaited(_refreshCustomerBalance());
}
void _onDocumentDateChanged(DateTime value) {
setState(() {
_documentDate = value;
_applyCustomerBalance = false;
_changeResolution = null;
});
unawaited(_refreshCustomerBalance());
}
Future<void> _refreshCustomerBalance({bool preserveApply = false}) async {
final customer = _selectedCustomer;
final currencyId = _defaultCurrencyId;
final requestGeneration = ++_customerBalanceRequestGeneration;
if (customer == null || currencyId == null || _isAnonymousSelected) {
if (!mounted) return;
setState(() {
_customerBalance = null;
_customerBalanceStatus = null;
_customerBalanceError = null;
_customerBalanceLoading = false;
_applyCustomerBalance = false;
});
return;
}
final requestedPersonId = customer.id;
final requestedDate = _documentDate;
final keepApply = preserveApply && _applyCustomerBalance;
setState(() {
_customerBalanceLoading = true;
_customerBalanceError = null;
if (!preserveApply) _applyCustomerBalance = false;
});
try {
final result = await _quickSalesService.getCustomerBalance(
businessId: widget.businessId,
personId: requestedPersonId,
currencyId: currencyId,
asOfDate: requestedDate,
);
if (!mounted || requestGeneration != _customerBalanceRequestGeneration) {
return;
}
if (_selectedCustomer?.id != requestedPersonId ||
_defaultCurrencyId != currencyId ||
_documentDate.year != requestedDate.year ||
_documentDate.month != requestedDate.month ||
_documentDate.day != requestedDate.day) {
return;
}
final balance = (result['balance'] as num?) ?? 0;
setState(() {
_customerBalance = balance;
_customerBalanceStatus =
result['status']?.toString() ??
quickSalesCustomerBalanceStatus(balance);
_customerBalanceLoading = false;
_customerBalanceError = null;
_applyCustomerBalance = keepApply && balance.abs() > _paymentEpsilon;
_changeResolution = null;
});
} catch (error) {
if (!mounted || requestGeneration != _customerBalanceRequestGeneration) {
return;
}
setState(() {
_customerBalance = null;
_customerBalanceStatus = null;
_customerBalanceLoading = false;
_customerBalanceError = ErrorExtractor.forContext(error, context);
_applyCustomerBalance = false;
});
}
}
num get _paidAmount =>
_payments.fold<num>(0, (sum, p) => sum + p.settlesAgainstInvoice);
num get _paymentTargetAmount => quickSalesPaymentTarget(
invoiceTotal: _totalAmount,
customerBalance: _customerBalance ?? 0,
applyBalance: _applyCustomerBalance,
);
num get _paymentEpsilon {
if (_invoiceCurrencyDecimalPlaces <= 0) return 0.5;
var e = 1.0;
@ -1070,17 +1186,17 @@ class _QuickSalesPageState extends State<QuickSalesPage>
}
num get _remainingAmount {
if (!_autoCreatePaymentDocument) return _totalAmount;
final raw = _totalAmount - _paidAmount;
if (!_autoCreatePaymentDocument) return _paymentTargetAmount;
final raw = _paymentTargetAmount - _paidAmount;
if (raw.abs() <= _paymentEpsilon) return 0;
return raw;
}
bool get _isOverpaid =>
_autoCreatePaymentDocument &&
_paidAmount > _totalAmount + _paymentEpsilon;
_paidAmount > _paymentTargetAmount + _paymentEpsilon;
num get _changeAmount => _isOverpaid ? _paidAmount - _totalAmount : 0;
num get _changeAmount => _isOverpaid ? _paidAmount - _paymentTargetAmount : 0;
QuickSalesChangeResolution? get _validChangeResolution {
final value = _changeResolution;
@ -1409,12 +1525,6 @@ class _QuickSalesPageState extends State<QuickSalesPage>
);
await _addToCart(fullProduct, skipHydrate: true);
await _saveRecentProduct(fullProduct);
if (mounted) {
SnackBarHelper.show(
context,
message: '${product['name'] ?? 'محصول'} به سبد اضافه شد',
);
}
} catch (e) {
if (mounted) {
SnackBarHelper.show(
@ -1515,12 +1625,6 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_lastFailedSearchQuery = null;
});
}
if (mounted) {
SnackBarHelper.show(
context,
message: '${product['name'] ?? 'محصول'} به سبد اضافه شد',
);
}
return;
}
}
@ -1564,13 +1668,6 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_lastFailedSearchQuery = null;
});
}
// فیدبک بصری
if (mounted) {
SnackBarHelper.show(
context,
message: '${product['name'] ?? 'محصول'} به سبد اضافه شد',
);
}
return;
}
} catch (e) {
@ -1624,13 +1721,6 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_lastFailedSearchQuery = null;
});
}
// فیدبک بصری
if (mounted) {
SnackBarHelper.show(
context,
message: '${selected['name'] ?? 'محصول'} به سبد اضافه شد',
);
}
} else {
// اگر دیالوگ انتخاب بسته شد بدون انتخاب، جستجوی ناموفق را ثبت کن
if (mounted) {
@ -1653,13 +1743,6 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_lastFailedSearchQuery = null;
});
}
// فیدبک بصری
if (mounted) {
SnackBarHelper.show(
context,
message: '${product['name'] ?? 'محصول'} به سبد اضافه شد',
);
}
} catch (e) {
if (mounted) {
SnackBarHelper.show(
@ -1733,12 +1816,6 @@ class _QuickSalesPageState extends State<QuickSalesPage>
});
_barcodeController.clear();
_barcodeFocus.requestFocus();
SnackBarHelper.show(
context,
message:
'${product['name'] ?? 'محصول'} با موفقیت اضافه شد و به سبد خرید اضافه گردید',
);
} catch (e) {
SnackBarHelper.show(
context,
@ -2472,7 +2549,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
return result;
}
Future<bool> _correctShortagesBeforeSale(
Future<String?> _correctShortagesBeforeSale(
List<Map<String, dynamic>> shortages,
) async {
final confirmed = await showDialog<bool>(
@ -2480,7 +2557,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
builder: (dialogContext) => AlertDialog(
title: const Text('اصلاح موجودی'),
content: const Text(
'این گزینه «کالای درآمدشده» را با تاریخ امروز ثبت می‌کند. فقط وقتی ادامه دهید که کالا واقعاً در انبار موجود است و خرید، انتقال یا موجودی اول دوره‌ای از قلم نیفتاده باشد.',
'این گزینه «کالای درآمدشده» را با همان تاریخ فاکتور ثبت می‌کند. فقط وقتی ادامه دهید که کالا واقعاً در انبار موجود است و خرید، انتقال یا موجودی اول دوره‌ای از قلم نیفتاده باشد.',
),
actions: [
TextButton(
@ -2494,12 +2571,19 @@ class _QuickSalesPageState extends State<QuickSalesPage>
],
),
);
if (confirmed != true) return false;
final today = DateTime.now().toIso8601String().split('T').first;
if (confirmed != true) return null;
final documentDate = _documentDate.toIso8601String().split('T').first;
final requestToken = quickSalesStockCorrectionToken(
businessId: widget.businessId,
saleId: _activeSaleId,
documentDate: _documentDate,
shortages: shortages,
);
await _quickSalesService.createStockCorrection(
businessId: widget.businessId,
payload: {
'document_date': today,
'document_date': documentDate,
'request_token': requestToken,
'confirm_unexplained_physical_surplus': true,
'description': 'اصلاح کسری کشف‌شده هنگام فروش سریع',
'lines': shortages
@ -2513,13 +2597,14 @@ class _QuickSalesPageState extends State<QuickSalesPage>
.toList(),
},
);
return true;
return requestToken;
}
Future<void> _saveInvoice({
bool print = false,
Map<String, dynamic>? stockOverride,
bool debtConfirmed = false,
String? appliedStockCorrectionToken,
}) async {
// اعتبارسنجی سبد خرید
if (_cartItems.isEmpty) {
@ -2559,14 +2644,14 @@ class _QuickSalesPageState extends State<QuickSalesPage>
}
if (_autoCreatePaymentDocument &&
_payments.isEmpty &&
_totalAmount > 0 &&
_paymentTargetAmount > 0 &&
!debtConfirmed) {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('ثبت بدون دریافت'),
content: const Text(
'هیچ پرداختی ثبت نشده است و کل مبلغ فاکتور به حساب مشتری بدهکار می‌شود. ادامه می‌دهید؟',
content: Text(
'هیچ پرداختی ثبت نشده است و مبلغ ${_formatNumber(_paymentTargetAmount)} $_paymentCurrencyUnit در حساب مشتری تسویه‌نشده می‌ماند. ادامه می‌دهید؟',
),
actions: [
TextButton(
@ -2639,9 +2724,9 @@ class _QuickSalesPageState extends State<QuickSalesPage>
final shouldShare = _shouldShareAfterSave;
final savedShareAmount = _remainingAmount > 0
? _remainingAmount
: _totalAmount;
: _paymentTargetAmount;
Map<String, dynamic>? retryOverride;
var retryAfterCorrection = false;
String? retryCorrectionToken;
var parkAfterFailure = false;
try {
@ -2724,6 +2809,14 @@ class _QuickSalesPageState extends State<QuickSalesPage>
'tax': _totalTax,
'net': _totalAmount,
},
if (_applyCustomerBalance && _customerBalance != null)
'quick_sale_customer_balance': {
'apply': true,
'person_id': personId,
'currency_id': _defaultCurrencyId,
'as_of_date': _documentDate.toIso8601String().split('T')[0],
'balance_before': _customerBalance,
},
if (_isOverpaid) 'quick_sale_change': changeResolution!.toJson(),
};
@ -2767,6 +2860,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
_payments = [];
_changeResolution = null;
_cashFollowsTotal = false;
_applyCustomerBalance = false;
_shareRemainingEnabled = false;
_checkoutDiscountExpanded = false;
_productStocks.clear();
@ -2778,6 +2872,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
});
_barcodeFocus.requestFocus();
unawaited(_refreshCustomerBalance());
final successMsg = StringBuffer('فاکتور با موفقیت ثبت شد');
if (invoiceCode != null) successMsg.write(' ($invoiceCode)');
@ -2804,7 +2899,14 @@ class _QuickSalesPageState extends State<QuickSalesPage>
} catch (e) {
if (mounted) {
final shortages = _stockShortagesFromError(e);
if (shortages.isNotEmpty && stockOverride == null) {
if (shortages.isNotEmpty && appliedStockCorrectionToken != null) {
SnackBarHelper.show(
context,
message:
'اصلاح موجودی ثبت شد، اما فاکتور هنوز به علت کسری موجودی ثبت نشد. تاریخ فاکتور و گردش انبار را بررسی کنید؛ با تکرار ثبت، سند اصلاح جدید ساخته نمی‌شود.',
isError: true,
);
} else if (shortages.isNotEmpty && stockOverride == null) {
final action = await _showStockShortageDialog(shortages);
if (!mounted) return;
if (action == _StockShortageAction.override) {
@ -2812,7 +2914,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
if (!mounted) return;
} else if (action == _StockShortageAction.correct) {
try {
retryAfterCorrection = await _correctShortagesBeforeSale(
retryCorrectionToken = await _correctShortagesBeforeSale(
shortages,
);
} catch (correctionError) {
@ -2836,6 +2938,12 @@ class _QuickSalesPageState extends State<QuickSalesPage>
String errorMessage = 'خطا در ثبت فاکتور';
if (e.toString().contains('INSUFFICIENT_STOCK')) {
errorMessage = 'موجودی کافی برای برخی محصولات وجود ندارد';
} else if (e.toString().contains(
'QUICK_SALE_CUSTOMER_BALANCE_CHANGED',
)) {
errorMessage =
'مانده حساب مشتری تغییر کرده است؛ مانده جدید را بررسی کنید';
unawaited(_refreshCustomerBalance());
} else if (e.toString().contains('CURRENCY')) {
errorMessage = 'خطا در تنظیمات ارز';
} else {
@ -2855,11 +2963,12 @@ class _QuickSalesPageState extends State<QuickSalesPage>
if (!mounted) return;
if (parkAfterFailure) {
_startNewSale();
} else if (retryAfterCorrection || retryOverride != null) {
} else if (retryCorrectionToken != null || retryOverride != null) {
await _saveInvoice(
print: print,
stockOverride: retryOverride,
debtConfirmed: debtConfirmed,
appliedStockCorrectionToken: retryCorrectionToken,
);
}
}
@ -3406,10 +3515,6 @@ class _QuickSalesPageState extends State<QuickSalesPage>
setState(() {
_lastFailedSearchQuery = null;
});
SnackBarHelper.show(
context,
message: '${product['name'] ?? 'محصول'} به سبد اضافه شد',
);
}
bool _handleKeyEvent(KeyEvent event) {
@ -3518,6 +3623,138 @@ class _QuickSalesPageState extends State<QuickSalesPage>
return false;
}
Widget _buildCustomerSelector({bool dense = false}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CustomerComboboxWidget(
selectedCustomer: _selectedCustomer,
onCustomerChanged: _onCustomerChanged,
businessId: widget.businessId,
authStore: widget.authStore,
isRequired: false,
enableQuickCreateOnSubmit: true,
dense: dense,
label: 'مشتری',
hintText: 'مشتری ناشناس',
),
if (!_isAnonymousSelected) ...[
const SizedBox(height: 6),
_buildCustomerBalancePanel(),
],
],
);
}
Widget _buildCustomerBalancePanel() {
final cs = Theme.of(context).colorScheme;
if (_customerBalanceLoading) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
color: cs.surfaceContainerLow,
borderRadius: BorderRadius.circular(8),
),
child: const Row(
children: [
SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2),
),
SizedBox(width: 8),
Expanded(child: Text('در حال دریافت مانده حساب…')),
],
),
);
}
if (_customerBalanceError != null) {
return Container(
padding: const EdgeInsetsDirectional.only(start: 10),
decoration: BoxDecoration(
color: cs.errorContainer,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Expanded(
child: Text(
'مانده حساب دریافت نشد',
style: TextStyle(color: cs.onErrorContainer),
),
),
IconButton(
tooltip: 'تلاش دوباره',
onPressed: () => unawaited(_refreshCustomerBalance()),
icon: const Icon(Icons.refresh),
),
],
),
);
}
final balance = _customerBalance;
if (balance == null) return const SizedBox.shrink();
final isSettled = balance.abs() <= _paymentEpsilon;
final status =
_customerBalanceStatus ?? quickSalesCustomerBalanceStatus(balance);
final statusColor = isSettled
? cs.onSurfaceVariant
: balance < 0
? cs.error
: Colors.green.shade700;
final remainingCredit = balance > _totalAmount ? balance - _totalAmount : 0;
return Container(
decoration: BoxDecoration(
color: cs.surfaceContainerLow,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: cs.outlineVariant),
),
child: SwitchListTile.adaptive(
dense: true,
contentPadding: const EdgeInsetsDirectional.only(start: 10, end: 4),
secondary: Icon(
balance < 0
? Icons.account_balance_wallet_outlined
: Icons.savings_outlined,
color: statusColor,
),
title: Text.rich(
TextSpan(
text: 'مانده حساب: ',
children: [
TextSpan(
text: isSettled
? 'تسویه'
: '${_formatNumber(balance.abs())} $_paymentCurrencyUnit — $status',
style: TextStyle(
color: statusColor,
fontWeight: FontWeight.w700,
),
),
],
),
),
subtitle: Text(
_applyCustomerBalance
? remainingCredit > _paymentEpsilon
? 'قابل تسویه: ${_formatNumber(_paymentTargetAmount)} $_paymentCurrencyUnit • اعتبار باقی‌مانده: ${_formatNumber(remainingCredit)}'
: 'مبلغ قابل تسویه: ${_formatNumber(_paymentTargetAmount)} $_paymentCurrencyUnit'
: 'اعمال مانده در مبلغ قابل تسویه این فروش',
),
value: _applyCustomerBalance,
onChanged: isSettled || _isSaving
? null
: (value) {
setState(() {
_applyCustomerBalance = value;
_changeResolution = null;
_shareRemainingEnabled = false;
});
},
),
);
}
/// تاریخ فاکتور (شمسی/میلادی طبق تنظیم کاربر) و شرح سند — چیدمان فشرده
Widget _buildDocumentDateAndDescription({
required bool isMobile,
@ -3529,9 +3766,15 @@ class _QuickSalesPageState extends State<QuickSalesPage>
hintText: 'انتخاب تاریخ',
calendarController: widget.calendarController,
isDense: true,
contentPadding: const EdgeInsetsDirectional.only(
start: 12,
top: 14,
bottom: 12,
end: 12,
),
onChanged: (d) {
if (d != null) {
setState(() => _documentDate = d);
_onDocumentDateChanged(d);
}
},
);
@ -3569,7 +3812,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
dateWidget,
Padding(padding: const EdgeInsets.only(top: 4), child: dateWidget),
Theme(
data: Theme.of(
context,
@ -3922,23 +4165,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
],
),
SizedBox(height: isCompact ? 6 : 8),
CustomerComboboxWidget(
selectedCustomer: _selectedCustomer,
onCustomerChanged: (customer) {
setState(() {
_selectedCustomer =
customer ?? _anonymousCustomer;
_changeResolution = null;
_syncShareChannelDefaults();
});
},
businessId: widget.businessId,
authStore: widget.authStore,
isRequired: false,
enableQuickCreateOnSubmit: true,
label: 'مشتری',
hintText: 'مشتری ناشناس',
),
_buildCustomerSelector(),
SizedBox(height: isCompact ? 6 : 8),
_buildDocumentDateAndDescription(
isMobile: true,
@ -4389,6 +4616,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
payments: _payments,
onChanged: _onPaymentsChanged,
invoiceTotal: _totalAmount,
paymentTarget: _paymentTargetAmount,
changeResolution: _validChangeResolution,
onConfigureChange: _openChangeResolutionDialog,
defaultCashRegisterId: _selectedCashRegisterId,
@ -4845,22 +5073,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CustomerComboboxWidget(
selectedCustomer: _selectedCustomer,
onCustomerChanged: (customer) {
setState(() {
_selectedCustomer = customer ?? _anonymousCustomer;
_changeResolution = null;
_syncShareChannelDefaults();
});
},
businessId: widget.businessId,
authStore: widget.authStore,
isRequired: false,
enableQuickCreateOnSubmit: true,
label: 'مشتری',
hintText: 'مشتری ناشناس',
),
_buildCustomerSelector(),
const SizedBox(height: 12),
_buildDocumentDateAndDescription(isMobile: true, compact: isCompact),
],
@ -5222,7 +5435,9 @@ class _QuickSalesPageState extends State<QuickSalesPage>
12,
12,
12,
_autoCreatePaymentDocument ? 232 : 8,
_autoCreatePaymentDocument
? QuickSalesPaymentDock.desktopSummaryHeight + 8
: 8,
),
child: _buildCheckoutScrollBody(
cs,
@ -5247,23 +5462,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (includeCustomer) ...[
CustomerComboboxWidget(
selectedCustomer: _selectedCustomer,
onCustomerChanged: (customer) {
setState(() {
_selectedCustomer = customer ?? _anonymousCustomer;
_changeResolution = null;
_syncShareChannelDefaults();
});
},
businessId: widget.businessId,
authStore: widget.authStore,
isRequired: false,
enableQuickCreateOnSubmit: true,
dense: true,
label: 'مشتری',
hintText: 'مشتری ناشناس',
),
_buildCustomerSelector(dense: true),
const SizedBox(height: 10),
],
if (includeTotal) ...[
@ -5588,7 +5787,7 @@ class _QuickSalesPageState extends State<QuickSalesPage>
if (v == _cashFollowsTotal) return;
setState(() => _cashFollowsTotal = v);
},
invoiceTotal: _totalAmount,
invoiceTotal: _paymentTargetAmount,
defaultCashRegisterId: _selectedCashRegisterId,
enabled: !_isSaving,
currencyId: _defaultCurrencyId,

View file

@ -15,6 +15,7 @@ import '../../widgets/banking/currency_picker_widget.dart';
import '../../models/customer_model.dart';
import '../../models/person_group_model.dart';
import '../../widgets/business_subpage_back_leading.dart';
import '../../widgets/quick_sales/quick_sales_default_shortcuts_dialog.dart';
import '../../constants/invoice_print_paper.dart';
import '../../services/report_template_service.dart';
@ -81,6 +82,11 @@ class _QuickSalesSettingsPageState extends State<QuickSalesSettingsPage> {
final _gatewayService = PaymentGatewayService(ApiClient());
final _personGroupService = PersonGroupService();
bool get _canManageGeneralSettings =>
widget.authStore.hasBusinessPermission('settings', 'business');
bool get _canManageDefaultShortcuts => widget.authStore
.hasBusinessPermission('quick_sales', 'manage_default_payment_shortcuts');
@override
void initState() {
super.initState();
@ -98,6 +104,10 @@ class _QuickSalesSettingsPageState extends State<QuickSalesSettingsPage> {
_loading = true;
_error = null;
});
if (!_canManageGeneralSettings) {
setState(() => _loading = false);
return;
}
try {
final settings = await _service.getSettings(businessId: widget.businessId);
setState(() {
@ -150,6 +160,16 @@ class _QuickSalesSettingsPageState extends State<QuickSalesSettingsPage> {
}
}
Future<void> _openDefaultShortcuts() async {
await showDialog<bool>(
context: context,
builder: (context) => QuickSalesDefaultShortcutsDialog(
businessId: widget.businessId,
service: _service,
),
);
}
Future<void> _loadQuickCustomerGroups() async {
setState(() {
_loadingQuickCustomerGroups = true;
@ -343,6 +363,16 @@ class _QuickSalesSettingsPageState extends State<QuickSalesSettingsPage> {
? const Center(child: CircularProgressIndicator())
: _error != null
? Center(child: Text(_error!))
: !_canManageGeneralSettings
? SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 900),
child: _buildDefaultShortcutsSection(),
),
),
)
: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Center(
@ -351,6 +381,10 @@ class _QuickSalesSettingsPageState extends State<QuickSalesSettingsPage> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (_canManageDefaultShortcuts) ...[
_buildDefaultShortcutsSection(),
const SizedBox(height: 24),
],
// بخش مشتری ناشناس
_buildSection(
title: 'مشتری ناشناس',
@ -744,6 +778,29 @@ class _QuickSalesSettingsPageState extends State<QuickSalesSettingsPage> {
);
}
Widget _buildDefaultShortcutsSection() {
return _buildSection(
title: 'میانبرهای پیش‌فرض پرداخت',
icon: Icons.keyboard_outlined,
children: [
const Text(
'میانبرهای دکمه‌های پرداخت مشترک را برای ویندوز و وب یکجا تعیین کنید. هر کاربر می‌تواند میانبر شخصی خودش را روی همان دکمه تنظیم کند.',
),
const SizedBox(height: 12),
Align(
alignment: AlignmentDirectional.centerStart,
child: FilledButton.tonalIcon(
onPressed: _canManageDefaultShortcuts
? _openDefaultShortcuts
: null,
icon: const Icon(Icons.tune_outlined),
label: const Text('مدیریت میانبرهای پیش‌فرض'),
),
),
],
);
}
Widget _buildShareDefaultsSection(AppLocalizations t, ColorScheme cs) {
final gatewayIds = _shareGateways
.map((g) => (g['id'] as num?)?.toInt())

View file

@ -205,7 +205,7 @@ class BusinessSettingsCategorizationService {
static SettingsCategory _salesDocuments(BusinessSettingsContext ctx) {
final items = <SettingsItem>[
if (ctx.canManageBusiness)
if (ctx.canManageBusiness || ctx.canManageDefaultPaymentShortcuts)
_item(
id: 'quick_sales',
title: 'businessSettingsQuickSales',

View file

@ -62,6 +62,13 @@ class BusinessSettingsContext {
bool get canManageBusiness =>
isOwner || authStore.hasBusinessPermission('settings', 'business');
bool get canManageDefaultPaymentShortcuts =>
isOwner ||
authStore.hasBusinessPermission(
'quick_sales',
'manage_default_payment_shortcuts',
);
bool get canEditFiscalYear =>
isOwner || authStore.hasBusinessPermission('fiscal_years', 'edit');

View file

@ -1161,6 +1161,10 @@ class _PermissionsDialogState extends State<_PermissionsDialog> {
'export': '${t.export} ${t.invoices}',
'change_unit_price': t.permissionInvoiceChangeUnitPrice,
},
'quick_sales': {
'manage_default_payment_shortcuts':
'مدیریت میانبرهای پیش‌فرض پرداخت در فروش سریع',
},
'invoice_types': {
'sales': t.invoiceTypeSales,
'sales_return': t.invoiceTypeSalesReturn,
@ -1857,7 +1861,13 @@ class _PermissionsDialogState extends State<_PermissionsDialog> {
{
'title': t.permissionsCategoryInvoicesAndExpenses,
'icon': Icons.receipt,
'sections': ['invoices', 'invoice_types', 'pricing', 'expenses_income'],
'sections': [
'invoices',
'quick_sales',
'invoice_types',
'pricing',
'expenses_income',
],
},
{
'title': t.accounting,
@ -2033,6 +2043,8 @@ class _PermissionsDialogState extends State<_PermissionsDialog> {
return t.transfers;
case 'invoices':
return t.invoices;
case 'quick_sales':
return 'فروش سریع';
case 'invoice_types':
return t.permissionSectionInvoiceTypes;
case 'pricing':
@ -2161,6 +2173,8 @@ class _PermissionsDialogState extends State<_PermissionsDialog> {
return t.settingsPermissionManageFtp;
case 'manage_ai_provider':
return 'مدیریت ارائه‌دهنده هوش مصنوعی';
case 'manage_default_payment_shortcuts':
return 'مدیریت میانبرهای پیش‌فرض پرداخت در فروش سریع';
case 'collect':
return t.collect;
case 'transfer':

View file

@ -36,6 +36,24 @@ class QuickSalesService {
return Map<String, dynamic>.from(res.data?['data'] ?? const {});
}
Future<Map<String, dynamic>> getCustomerBalance({
required int businessId,
required int personId,
required int currencyId,
required DateTime asOfDate,
}) async {
final date = asOfDate.toIso8601String().split('T').first;
final res = await _api.get<Map<String, dynamic>>(
'/api/v1/businesses/$businessId/quick-sales/customer-balance',
query: {
'person_id': personId,
'currency_id': currencyId,
'as_of_date': date,
},
);
return Map<String, dynamic>.from(res.data?['data'] ?? const {});
}
Future<List<QuickSalesPaymentButtonModel>> listPaymentButtons({
required int businessId,
}) async {
@ -81,6 +99,64 @@ class QuickSalesService {
);
}
Future<Map<String, dynamic>> updatePaymentButtonShortcut({
required int businessId,
required Object buttonId,
required String platform,
required String mode,
required String? shortcut,
}) async {
final buttonKey = Uri.encodeComponent(buttonId.toString());
final res = await _api.put<Map<String, dynamic>>(
'/api/v1/businesses/$businessId/quick-sales/payment-buttons/$buttonKey/shortcut',
data: {'platform': platform, 'mode': mode, 'shortcut': shortcut},
);
return Map<String, dynamic>.from(res.data?['data'] ?? const {});
}
Future<Map<String, dynamic>> updatePaymentButtonShortcuts({
required int businessId,
required Object buttonId,
required Map<String, Map<String, dynamic>> platforms,
}) async {
final buttonKey = Uri.encodeComponent(buttonId.toString());
final res = await _api.put<Map<String, dynamic>>(
'/api/v1/businesses/$businessId/quick-sales/payment-buttons/$buttonKey/shortcut',
data: {'platforms': platforms},
);
return Map<String, dynamic>.from(res.data?['data'] ?? const {});
}
Future<List<Map<String, dynamic>>> listDefaultPaymentShortcuts({
required int businessId,
}) async {
final res = await _api.get<Map<String, dynamic>>(
'/api/v1/businesses/$businessId/quick-sales/payment-buttons/default-shortcuts',
);
final raw = res.data?['data'];
if (raw is! List) return const [];
return raw
.whereType<Map>()
.map((row) => Map<String, dynamic>.from(row))
.toList();
}
Future<List<Map<String, dynamic>>> updateDefaultPaymentShortcuts({
required int businessId,
required List<Map<String, dynamic>> shortcuts,
}) async {
final res = await _api.put<Map<String, dynamic>>(
'/api/v1/businesses/$businessId/quick-sales/payment-buttons/default-shortcuts',
data: {'shortcuts': shortcuts},
);
final raw = res.data?['data'];
if (raw is! List) return const [];
return raw
.whereType<Map>()
.map((row) => Map<String, dynamic>.from(row))
.toList();
}
Future<void> deletePaymentButton({
required int businessId,
required int buttonId,

View file

@ -0,0 +1,16 @@
num quickSalesPaymentTarget({
required num invoiceTotal,
required num customerBalance,
required bool applyBalance,
}) {
if (!applyBalance) return invoiceTotal;
if (customerBalance < 0) return invoiceTotal + customerBalance.abs();
final target = invoiceTotal - customerBalance;
return target > 0 ? target : 0;
}
String quickSalesCustomerBalanceStatus(num balance) {
if (balance > 0) return 'بستانکار';
if (balance < 0) return 'بدهکار';
return 'تسویه';
}

View file

@ -0,0 +1,37 @@
String _canonicalStockQuantity(Object? value) {
final number = value is num ? value : num.tryParse(value?.toString() ?? '');
if (number == null) return value?.toString().trim() ?? '';
if (number == number.truncateToDouble()) return number.toInt().toString();
return number
.toStringAsFixed(6)
.replaceFirst(RegExp(r'0+$'), '')
.replaceFirst(RegExp(r'\.$'), '');
}
/// شناسه‌ای پایدار برای اینکه تکرار درخواست اصلاح یک فروش، سند تازه نسازد.
String quickSalesStockCorrectionToken({
required int businessId,
required String saleId,
required DateTime documentDate,
required List<Map<String, dynamic>> shortages,
}) {
final rows =
shortages
.map(
(row) =>
'${row['product_id']}:${row['warehouse_id']}:'
'${_canonicalStockQuantity(row['shortage_quantity'])}',
)
.toList()
..sort();
final date = documentDate.toIso8601String().split('T').first;
final input = '$businessId|$saleId|$date|${rows.join(';')}';
var hash = 0x811c9dc5;
for (final byte in input.codeUnits) {
hash ^= byte;
hash = (hash * 0x01000193) & 0xffffffff;
}
final digest = hash.toRadixString(16).padLeft(8, '0');
return 'qs-stock-$businessId-$saleId-$digest';
}

View file

@ -19,6 +19,7 @@ class DateInputField extends StatefulWidget {
final bool enabled;
final CalendarController calendarController;
final bool isDense;
final EdgeInsetsGeometry? contentPadding;
final String? Function(String?)? validator;
const DateInputField({
@ -33,6 +34,7 @@ class DateInputField extends StatefulWidget {
this.enabled = true,
required this.calendarController,
this.isDense = false,
this.contentPadding,
this.validator,
});
@ -82,7 +84,8 @@ class _DateInputFieldState extends State<DateInputField> {
@override
void didUpdateWidget(DateInputField oldWidget) {
super.didUpdateWidget(oldWidget);
final calChanged = (oldWidget.calendarController.isJalali == true) !=
final calChanged =
(oldWidget.calendarController.isJalali == true) !=
(widget.calendarController.isJalali == true);
if (!_sameDateOnly(oldWidget.value, widget.value) || calChanged) {
_updateDisplayValue();
@ -259,7 +262,12 @@ class _DateInputFieldState extends State<DateInputField> {
suffixIcon: IconButton(
padding: EdgeInsets.zero,
constraints: widget.isDense
? const BoxConstraints(minWidth: 40, minHeight: 40, maxWidth: 44, maxHeight: 44)
? const BoxConstraints(
minWidth: 40,
minHeight: 40,
maxWidth: 44,
maxHeight: 44,
)
: null,
icon: Icon(Icons.calendar_today, size: widget.isDense ? 20 : 24),
tooltip: t.dateInputOpenCalendar,
@ -270,9 +278,16 @@ class _DateInputFieldState extends State<DateInputField> {
: null,
border: const OutlineInputBorder(),
isDense: widget.isDense,
contentPadding: widget.isDense
? const EdgeInsetsDirectional.only(start: 12, top: 10, bottom: 10, end: 12)
: null,
contentPadding:
widget.contentPadding ??
(widget.isDense
? const EdgeInsetsDirectional.only(
start: 12,
top: 10,
bottom: 10,
end: 12,
)
: null),
),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9/]')),

View file

@ -0,0 +1,406 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../services/quick_sales_service.dart';
import '../../utils/error_extractor.dart';
import '../../utils/snackbar_helper.dart';
class QuickSalesDefaultShortcutsDialog extends StatefulWidget {
final int businessId;
final QuickSalesService service;
const QuickSalesDefaultShortcutsDialog({
super.key,
required this.businessId,
required this.service,
});
@override
State<QuickSalesDefaultShortcutsDialog> createState() =>
_QuickSalesDefaultShortcutsDialogState();
}
class _QuickSalesDefaultShortcutsDialogState
extends State<QuickSalesDefaultShortcutsDialog> {
List<Map<String, dynamic>> _rows = const [];
final Map<String, TextEditingController> _controllers = {};
String _platform = 'windows';
bool _loading = true;
bool _saving = false;
String _key(int id, String platform) => '$id:$platform';
@override
void initState() {
super.initState();
unawaited(_load());
}
@override
void dispose() {
for (final controller in _controllers.values) {
controller.dispose();
}
super.dispose();
}
Future<void> _load() async {
try {
final rows = await widget.service.listDefaultPaymentShortcuts(
businessId: widget.businessId,
);
if (!mounted) return;
for (final controller in _controllers.values) {
controller.dispose();
}
_controllers.clear();
for (final row in rows) {
final id = (row['button_id'] as num).toInt();
final raw = row['default_shortcuts'];
final shortcuts = raw is Map
? Map<String, dynamic>.from(raw)
: const {};
_controllers[_key(id, 'windows')] = TextEditingController(
text: (shortcuts['windows'] ?? row['default_shortcut'] ?? '')
.toString(),
);
_controllers[_key(id, 'web')] = TextEditingController(
text: (shortcuts['web'] ?? '').toString(),
);
}
setState(() {
_rows = rows;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() => _loading = false);
SnackBarHelper.show(
context,
message: ErrorExtractor.forContext(e, context),
isError: true,
);
}
}
Future<void> _save() async {
for (final platform in const ['windows', 'web']) {
final seen = <String>{};
for (final row in _rows) {
final id = (row['button_id'] as num).toInt();
final value = _controllers[_key(id, platform)]!.text
.trim()
.replaceAll(' ', '')
.toUpperCase();
if (value.isNotEmpty && !seen.add(value)) {
SnackBarHelper.show(
context,
message:
'در بخش ${platform == 'web' ? 'وب' : 'ویندوز'} یک میانبر برای چند دکمه انتخاب شده است.',
isError: true,
);
return;
}
}
}
setState(() => _saving = true);
try {
await widget.service.updateDefaultPaymentShortcuts(
businessId: widget.businessId,
shortcuts: [
for (final row in _rows)
{
'button_id': row['button_id'],
'shortcuts': {
for (final platform in const ['windows', 'web'])
platform:
_controllers[_key(
(row['button_id'] as num).toInt(),
platform,
)]!
.text
.trim(),
},
},
],
);
if (mounted) Navigator.pop(context, true);
} catch (e) {
if (!mounted) return;
setState(() => _saving = false);
SnackBarHelper.show(
context,
message: ErrorExtractor.forContext(e, context),
isError: true,
);
}
}
IconData _targetIcon(String type) => switch (type) {
'cash_register' => Icons.payments_outlined,
'bank' => Icons.account_balance_outlined,
'person' => Icons.person_outline,
_ => Icons.payment_outlined,
};
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('میانبرهای پیش‌فرض کسب‌وکار'),
content: SizedBox(
width: 650,
height: 500,
child: _loading
? const Center(child: CircularProgressIndicator())
: _rows.isEmpty
? const Center(
child: Text(
'هنوز دکمه مشترکی تعریف نشده است. ابتدا در فروش سریع یک دکمه با گزینه «نمایش برای همه کاربران» بسازید.',
textAlign: TextAlign.center,
),
)
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
'این میانبرها برای همه کاربران پیش‌فرض هستند. تنظیم شخصی هر کاربر اولویت دارد.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
SegmentedButton<String>(
segments: const [
ButtonSegment(
value: 'windows',
icon: Icon(Icons.desktop_windows_outlined),
label: Text('ویندوز'),
),
ButtonSegment(
value: 'web',
icon: Icon(Icons.language_outlined),
label: Text('وب'),
),
],
selected: {_platform},
onSelectionChanged: _saving
? null
: (value) => setState(() => _platform = value.first),
),
const SizedBox(height: 8),
Text(
_platform == 'web'
? 'در وب از ترکیب Ctrl یا Alt با یک حرف یا عدد استفاده کنید؛ میانبرهای مرورگر پذیرفته نمی‌شوند.'
: 'در ویندوز کلیدهای F1 تا F12 و ترکیب‌هایی مانند Alt+R قابل استفاده‌اند.',
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: 12),
Expanded(
child: ListView.separated(
itemCount: _rows.length,
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, index) {
final row = _rows[index];
final id = (row['button_id'] as num).toInt();
return Row(
children: [
Icon(
_targetIcon(row['target_type']?.toString() ?? ''),
),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
row['label']?.toString() ?? '',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
),
),
Text(
row['target_name']?.toString() ?? '',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(
context,
).textTheme.bodySmall,
),
],
),
),
const SizedBox(width: 12),
SizedBox(
width: 280,
child: QuickSalesShortcutRecorderField(
controller: _controllers[_key(id, _platform)]!,
enabled: !_saving,
platform: _platform,
compact: true,
),
),
],
);
},
),
),
],
),
),
actions: [
TextButton(
onPressed: _saving ? null : () => Navigator.pop(context, false),
child: const Text('انصراف'),
),
FilledButton.icon(
onPressed: _saving || _loading || _rows.isEmpty ? null : _save,
icon: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Icon(Icons.save_outlined),
label: const Text('ذخیره همه'),
),
],
);
}
}
class QuickSalesShortcutRecorderField extends StatefulWidget {
final TextEditingController controller;
final bool enabled;
final String platform;
final bool compact;
const QuickSalesShortcutRecorderField({
super.key,
required this.controller,
required this.enabled,
required this.platform,
this.compact = false,
});
@override
State<QuickSalesShortcutRecorderField> createState() =>
_QuickSalesShortcutRecorderFieldState();
}
class _QuickSalesShortcutRecorderFieldState
extends State<QuickSalesShortcutRecorderField> {
final FocusNode _focusNode = FocusNode();
bool _manualEntry = false;
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
bool _isModifier(LogicalKeyboardKey key) =>
key == LogicalKeyboardKey.controlLeft ||
key == LogicalKeyboardKey.controlRight ||
key == LogicalKeyboardKey.metaLeft ||
key == LogicalKeyboardKey.metaRight ||
key == LogicalKeyboardKey.altLeft ||
key == LogicalKeyboardKey.altRight ||
key == LogicalKeyboardKey.shiftLeft ||
key == LogicalKeyboardKey.shiftRight;
KeyEventResult _record(KeyEvent event) {
if (_manualEntry || !widget.enabled || event is! KeyDownEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
if (_isModifier(key)) return KeyEventResult.handled;
if (key == LogicalKeyboardKey.escape) {
_focusNode.unfocus();
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.backspace ||
key == LogicalKeyboardKey.delete) {
setState(widget.controller.clear);
return KeyEventResult.handled;
}
final keyLabel = key.keyLabel.trim().toUpperCase();
if (keyLabel.isEmpty) return KeyEventResult.ignored;
final keyboard = HardwareKeyboard.instance;
final value = <String>[
if (keyboard.isControlPressed || keyboard.isMetaPressed) 'CTRL',
if (keyboard.isAltPressed) 'ALT',
if (keyboard.isShiftPressed) 'SHIFT',
keyLabel,
].join('+');
setState(() {
widget.controller.value = TextEditingValue(
text: value,
selection: TextSelection.collapsed(offset: value.length),
);
});
return KeyEventResult.handled;
}
@override
Widget build(BuildContext context) {
final isWeb = widget.platform == 'web';
return Focus(
onKeyEvent: (_, event) => _record(event),
child: TextField(
controller: widget.controller,
focusNode: _focusNode,
enabled: widget.enabled,
readOnly: !_manualEntry,
textDirection: TextDirection.ltr,
textCapitalization: TextCapitalization.characters,
decoration: InputDecoration(
labelText: widget.compact
? 'میانبر'
: 'کلید میانبر ${isWeb ? 'وب' : 'ویندوز'}',
hintText: _manualEntry
? (isWeb ? 'مثلاً Alt+1' : 'مثلاً F12 یا Alt+R')
: 'اینجا کلیک کنید و کلیدها را فشار دهید',
border: const OutlineInputBorder(),
prefixIcon: Icon(
isWeb ? Icons.language_outlined : Icons.keyboard_outlined,
),
suffixIcon: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (widget.controller.text.isNotEmpty)
IconButton(
tooltip: 'پاک‌کردن میانبر',
onPressed: widget.enabled
? () => setState(widget.controller.clear)
: null,
icon: const Icon(Icons.clear),
),
TextButton(
onPressed: widget.enabled
? () {
setState(() => _manualEntry = !_manualEntry);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _focusNode.requestFocus();
});
}
: null,
child: Text(_manualEntry ? 'ضبط کلید' : 'ورود دستی'),
),
],
),
),
onChanged: (_) => setState(() {}),
onTap: () {
if (!_manualEntry) {
widget.controller.selection = TextSelection(
baseOffset: 0,
extentOffset: widget.controller.text.length,
);
}
},
),
);
}
}

View file

@ -1,5 +1,6 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
@ -22,11 +23,14 @@ import '../invoice/cash_register_combobox_widget.dart';
import '../invoice/person_combobox_widget.dart';
class QuickSalesPaymentDock extends StatefulWidget {
static const double desktopSummaryHeight = 128;
final int businessId;
final AuthStore authStore;
final List<InvoiceTransaction> payments;
final ValueChanged<List<InvoiceTransaction>> onChanged;
final num invoiceTotal;
final num paymentTarget;
final QuickSalesChangeResolution? changeResolution;
final Future<QuickSalesChangeResolution?> Function() onConfigureChange;
final String? defaultCashRegisterId;
@ -44,6 +48,7 @@ class QuickSalesPaymentDock extends StatefulWidget {
required this.payments,
required this.onChanged,
required this.invoiceTotal,
required this.paymentTarget,
required this.changeResolution,
required this.onConfigureChange,
required this.defaultCashRegisterId,
@ -77,10 +82,18 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
final ScrollController _paymentScroll = ScrollController();
final ScrollController _buttonScroll = ScrollController();
List<QuickSalesPaymentButtonModel> _buttons = const [];
Map<String, QuickSalesPaymentButtonModel> _buttonsByShortcut = const {};
bool _loadingButtons = true;
double _buttonWidth = _defaultButtonWidth;
bool _expanded = false;
String? get _activeShortcutPlatform => kIsWeb
? 'web'
: defaultTargetPlatform == TargetPlatform.windows
? 'windows'
: null;
bool get _shortcutsEnabled => _activeShortcutPlatform != null;
num get _epsilon {
if (widget.decimalPlaces <= 0) return 0.5;
var value = 1.0;
@ -92,11 +105,11 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
num get _paid =>
widget.payments.fold<num>(0, (sum, p) => sum + p.settlesAgainstInvoice);
num get _remaining => (widget.invoiceTotal - _paid) > _epsilon
? widget.invoiceTotal - _paid
num get _remaining => (widget.paymentTarget - _paid) > _epsilon
? widget.paymentTarget - _paid
: 0;
num get _change => (_paid - widget.invoiceTotal) > _epsilon
? _paid - widget.invoiceTotal
num get _change => (_paid - widget.paymentTarget) > _epsilon
? _paid - widget.paymentTarget
: 0;
String get _preferenceKey =>
@ -108,7 +121,9 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
void initState() {
super.initState();
_service = widget.service ?? QuickSalesService();
if (_shortcutsEnabled) {
HardwareKeyboard.instance.addHandler(_handleShortcutKeyEvent);
}
_amountFocus.addListener(() {
if (_amountFocus.hasFocus) {
_amountController.selection = TextSelection(
@ -126,7 +141,7 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
@override
void didUpdateWidget(covariant QuickSalesPaymentDock oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.invoiceTotal != widget.invoiceTotal ||
if (oldWidget.paymentTarget != widget.paymentTarget ||
oldWidget.payments != widget.payments) {
_syncAmount();
}
@ -134,7 +149,9 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
@override
void dispose() {
if (_shortcutsEnabled) {
HardwareKeyboard.instance.removeHandler(_handleShortcutKeyEvent);
}
_amountController.dispose();
_amountFocus.dispose();
_paymentScroll.dispose();
@ -160,6 +177,7 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
}
final route = ModalRoute.of(context);
if (route != null && !route.isCurrent) return false;
if (kIsWeb && _hasEditableTextFocus()) return false;
final key = event.logicalKey.keyLabel.trim().toUpperCase();
if (key.isEmpty) return false;
final keyboard = HardwareKeyboard.instance;
@ -170,14 +188,32 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
key,
];
final shortcut = parts.join('+');
for (final button in _buttons) {
if ((button.shortcut ?? '').replaceAll(' ', '').toUpperCase() ==
shortcut) {
final button = _buttonsByShortcut[shortcut];
if (button == null) return false;
_addPayment(button);
return true;
}
bool _hasEditableTextFocus() {
final focusContext = FocusManager.instance.primaryFocus?.context;
if (focusContext == null) return false;
if (focusContext.widget is EditableText) return true;
return focusContext.findAncestorWidgetOfExactType<EditableText>() != null;
}
return false;
void _replaceButtons(List<QuickSalesPaymentButtonModel> rows) {
_buttons = rows;
final platform = _activeShortcutPlatform;
_buttonsByShortcut = {
for (final button in rows)
if (platform != null &&
(button.shortcutForPlatform(platform) ?? '').trim().isNotEmpty)
button
.shortcutForPlatform(platform)!
.replaceAll(' ', '')
.toUpperCase():
button,
};
}
Future<void> _loadButtons() async {
@ -187,7 +223,7 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
);
if (!mounted) return;
setState(() {
_buttons = rows;
_replaceButtons(rows);
_loadingButtons = false;
});
} catch (e) {
@ -356,8 +392,9 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
left: 0,
bottom: 0,
width: _summaryWidth,
height: _expandedHeight,
height: QuickSalesPaymentDock.desktopSummaryHeight,
child: Material(
key: const ValueKey('quick-sales-payment-summary'),
elevation: 6,
color: cs.surfaceContainerLow,
shape: Border(
@ -551,12 +588,12 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
);
}
return Padding(
padding: const EdgeInsets.all(12),
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
...figures,
const Spacer(),
const SizedBox(height: 4),
Row(
children: [
Expanded(child: actions.first),
@ -823,6 +860,7 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
onEdit: button.isSystem
? null
: () => _openEditor(existing: button),
onShortcut: () => _openShortcutEditor(button),
onDelete: button.isSystem
? null
: () => _deleteButton(button),
@ -901,13 +939,13 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
if (id == null) return;
ids.add(id);
}
setState(() => _buttons = next);
setState(() => _replaceButtons(next));
try {
final saved = await _service.reorderPaymentButtons(
businessId: widget.businessId,
buttonIds: ids,
);
if (mounted) setState(() => _buttons = saved);
if (mounted) setState(() => _replaceButtons(saved));
} catch (e) {
if (!mounted) return;
await _loadButtons();
@ -936,7 +974,7 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
service: _service,
existing: existing,
initialPerson: selectedPerson,
canCreateShared: widget.authStore.hasBusinessPermission(
canManageShared: widget.authStore.hasBusinessPermission(
'settings',
'business',
),
@ -944,6 +982,18 @@ class _QuickSalesPaymentDockState extends State<QuickSalesPaymentDock> {
);
if (changed == true) await _loadButtons();
}
Future<void> _openShortcutEditor(QuickSalesPaymentButtonModel button) async {
final changed = await showDialog<bool>(
context: context,
builder: (context) => _PaymentShortcutDialog(
businessId: widget.businessId,
service: _service,
button: button,
),
);
if (changed == true) await _loadButtons();
}
}
class _DockExpansionHandle extends StatelessWidget {
@ -1072,6 +1122,7 @@ class _PaymentTargetTile extends StatelessWidget {
final bool enabled;
final VoidCallback onPressed;
final VoidCallback? onEdit;
final VoidCallback? onShortcut;
final VoidCallback? onDelete;
final VoidCallback? onMoveBefore;
final VoidCallback? onMoveAfter;
@ -1082,6 +1133,7 @@ class _PaymentTargetTile extends StatelessWidget {
required this.enabled,
required this.onPressed,
this.onEdit,
this.onShortcut,
this.onDelete,
this.onMoveBefore,
this.onMoveAfter,
@ -1104,16 +1156,25 @@ class _PaymentTargetTile extends StatelessWidget {
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if (button.shortcut != null)
if (button.shortcutForPlatform(kIsWeb ? 'web' : 'windows') !=
null)
Text(
button.shortcut!,
'${kIsWeb ? 'وب' : 'ویندوز'}: ${button.shortcutForPlatform(kIsWeb ? 'web' : 'windows')!}',
style: Theme.of(context).textTheme.labelSmall,
),
if (button.shortcutProfile(kIsWeb ? 'web' : 'windows').conflict)
Text(
'تداخل میانبر',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
],
),
),
),
if (onEdit != null ||
onShortcut != null ||
onDelete != null ||
onMoveBefore != null ||
onMoveAfter != null)
@ -1129,6 +1190,9 @@ class _PaymentTargetTile extends StatelessWidget {
case 'edit':
onEdit?.call();
break;
case 'shortcut':
onShortcut?.call();
break;
case 'delete':
onDelete?.call();
break;
@ -1143,6 +1207,11 @@ class _PaymentTargetTile extends StatelessWidget {
itemBuilder: (_) => [
if (onEdit != null)
const PopupMenuItem(value: 'edit', child: Text('ویرایش')),
if (onShortcut != null)
const PopupMenuItem(
value: 'shortcut',
child: Text('میانبرهای شخصی'),
),
if (onMoveBefore != null)
const PopupMenuItem(
value: 'before',
@ -1168,14 +1237,14 @@ class _PaymentButtonEditorDialog extends StatefulWidget {
final QuickSalesService service;
final QuickSalesPaymentButtonModel? existing;
final Person? initialPerson;
final bool canCreateShared;
final bool canManageShared;
const _PaymentButtonEditorDialog({
required this.businessId,
required this.service,
required this.existing,
required this.initialPerson,
required this.canCreateShared,
required this.canManageShared,
});
@override
@ -1187,7 +1256,6 @@ class _PaymentButtonEditorDialogState
extends State<_PaymentButtonEditorDialog> {
late QuickSalesPaymentTargetType _type;
late final TextEditingController _labelController;
late final TextEditingController _shortcutController;
String? _cashId;
String? _bankId;
Person? _person;
@ -1204,7 +1272,6 @@ class _PaymentButtonEditorDialogState
? ''
: existing?.label ?? '',
);
_shortcutController = TextEditingController(text: existing?.shortcut ?? '');
_shared = existing?.scope == 'business';
if (existing?.targetType == QuickSalesPaymentTargetType.cashRegister) {
_cashId = existing!.targetId.toString();
@ -1218,7 +1285,6 @@ class _PaymentButtonEditorDialogState
@override
void dispose() {
_labelController.dispose();
_shortcutController.dispose();
super.dispose();
}
@ -1244,7 +1310,6 @@ class _PaymentButtonEditorDialogState
'target_id': _targetId,
if (_type != QuickSalesPaymentTargetType.person)
'label': _labelController.text.trim(),
'shortcut': _shortcutController.text.trim(),
};
try {
final existingId = widget.existing?.id;
@ -1346,22 +1411,18 @@ class _PaymentButtonEditorDialogState
),
),
],
const SizedBox(height: 12),
TextField(
controller: _shortcutController,
textDirection: TextDirection.ltr,
decoration: const InputDecoration(
labelText: 'کلید میانبر (اختیاری)',
hintText: 'مثلاً Alt+1',
border: OutlineInputBorder(),
),
),
if (widget.canCreateShared)
if (widget.canManageShared)
SwitchListTile.adaptive(
key: const ValueKey('quick-sales-payment-shared-switch'),
contentPadding: EdgeInsets.zero,
title: const Text('نمایش برای همه کاربران'),
subtitle: Text(
_shared
? 'این دکمه برای همه کاربران کسب‌وکار نمایش داده می‌شود.'
: 'این دکمه فقط برای شما نمایش داده می‌شود.',
),
value: _shared,
onChanged: _saving || widget.existing != null
onChanged: _saving
? null
: (value) => setState(() => _shared = value),
),
@ -1388,3 +1449,321 @@ class _PaymentButtonEditorDialogState
);
}
}
class _PaymentShortcutDialog extends StatefulWidget {
final int businessId;
final QuickSalesService service;
final QuickSalesPaymentButtonModel button;
const _PaymentShortcutDialog({
required this.businessId,
required this.service,
required this.button,
});
@override
State<_PaymentShortcutDialog> createState() => _PaymentShortcutDialogState();
}
class _PaymentShortcutDialogState extends State<_PaymentShortcutDialog> {
late final Map<String, TextEditingController> _controllers;
late final Map<String, String> _modes;
String _platform = kIsWeb ? 'web' : 'windows';
bool _saving = false;
@override
void initState() {
super.initState();
_controllers = {
for (final platform in const ['windows', 'web'])
platform: TextEditingController(
text: widget.button.shortcutProfile(platform).userShortcut ?? '',
),
};
_modes = {
for (final platform in const ['windows', 'web'])
platform: _initialMode(widget.button.shortcutProfile(platform)),
};
}
String _initialMode(QuickSalesShortcutProfile profile) =>
profile.userShortcutDisabled
? 'disabled'
: profile.userShortcut != null
? 'custom'
: 'inherit';
@override
void dispose() {
for (final controller in _controllers.values) {
controller.dispose();
}
super.dispose();
}
Future<void> _save() async {
setState(() => _saving = true);
try {
await widget.service.updatePaymentButtonShortcuts(
businessId: widget.businessId,
buttonId: widget.button.id,
platforms: {
for (final platform in const ['windows', 'web'])
platform: {
'mode': _modes[platform]!,
'shortcut': _modes[platform] == 'custom'
? _controllers[platform]!.text.trim()
: null,
},
},
);
if (mounted) Navigator.pop(context, true);
} catch (e) {
if (!mounted) return;
setState(() => _saving = false);
SnackBarHelper.show(
context,
message: ErrorExtractor.forContext(e, context),
isError: true,
);
}
}
@override
Widget build(BuildContext context) {
final profile = widget.button.shortcutProfile(_platform);
final mode = _modes[_platform]!;
return AlertDialog(
title: Text('میانبرهای شخصی «${widget.button.label}»'),
content: SizedBox(
width: 470,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SegmentedButton<String>(
segments: const [
ButtonSegment(
value: 'windows',
icon: Icon(Icons.desktop_windows_outlined),
label: Text('ویندوز'),
),
ButtonSegment(
value: 'web',
icon: Icon(Icons.language_outlined),
label: Text('وب'),
),
],
selected: {_platform},
onSelectionChanged: _saving
? null
: (value) => setState(() => _platform = value.first),
),
const SizedBox(height: 12),
if (profile.defaultShortcut != null)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Text(
'پیش‌فرض کسب‌وکار: ${profile.defaultShortcut}',
style: Theme.of(context).textTheme.bodySmall,
),
),
RadioGroup<String>(
groupValue: mode,
onChanged: (value) {
if (!_saving) {
setState(() => _modes[_platform] = value ?? 'inherit');
}
},
child: Column(
children: [
RadioListTile<String>(
value: 'inherit',
title: Text(
profile.defaultShortcut == null
? 'استفاده از پیش‌فرض کسب‌وکار (فعلاً بدون میانبر)'
: 'استفاده از پیش‌فرض کسب‌وکار',
),
contentPadding: EdgeInsets.zero,
),
const RadioListTile<String>(
value: 'custom',
title: Text('میانبر شخصی من'),
contentPadding: EdgeInsets.zero,
),
const RadioListTile<String>(
value: 'disabled',
title: Text('بدون میانبر برای من'),
contentPadding: EdgeInsets.zero,
),
],
),
),
if (mode == 'custom') ...[
const SizedBox(height: 8),
_ShortcutRecorderField(
controller: _controllers[_platform]!,
enabled: !_saving,
platform: _platform,
),
],
if (_platform == 'web') ...[
const SizedBox(height: 8),
Text(
'میانبر وب باید شامل Ctrl یا Alt و یک حرف یا عدد باشد. ترکیب‌های رزروشده مرورگر قابل ذخیره نیستند.',
style: Theme.of(context).textTheme.bodySmall,
),
],
],
),
),
actions: [
TextButton(
onPressed: _saving ? null : () => Navigator.pop(context, false),
child: const Text('انصراف'),
),
FilledButton(
onPressed: _saving ? null : _save,
child: _saving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('ذخیره'),
),
],
);
}
}
class _ShortcutRecorderField extends StatefulWidget {
final TextEditingController controller;
final bool enabled;
final String platform;
const _ShortcutRecorderField({
required this.controller,
required this.enabled,
this.platform = 'windows',
});
@override
State<_ShortcutRecorderField> createState() => _ShortcutRecorderFieldState();
}
class _ShortcutRecorderFieldState extends State<_ShortcutRecorderField> {
final FocusNode _focusNode = FocusNode();
bool _manualEntry = false;
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
bool _isModifier(LogicalKeyboardKey key) =>
key == LogicalKeyboardKey.controlLeft ||
key == LogicalKeyboardKey.controlRight ||
key == LogicalKeyboardKey.metaLeft ||
key == LogicalKeyboardKey.metaRight ||
key == LogicalKeyboardKey.altLeft ||
key == LogicalKeyboardKey.altRight ||
key == LogicalKeyboardKey.shiftLeft ||
key == LogicalKeyboardKey.shiftRight;
KeyEventResult _record(KeyEvent event) {
if (_manualEntry || !widget.enabled || event is! KeyDownEvent) {
return KeyEventResult.ignored;
}
final key = event.logicalKey;
if (_isModifier(key)) return KeyEventResult.handled;
if (key == LogicalKeyboardKey.escape) {
_focusNode.unfocus();
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.backspace ||
key == LogicalKeyboardKey.delete) {
setState(widget.controller.clear);
return KeyEventResult.handled;
}
final keyLabel = key.keyLabel.trim().toUpperCase();
if (keyLabel.isEmpty) return KeyEventResult.ignored;
final keyboard = HardwareKeyboard.instance;
final parts = <String>[
if (keyboard.isControlPressed || keyboard.isMetaPressed) 'CTRL',
if (keyboard.isAltPressed) 'ALT',
if (keyboard.isShiftPressed) 'SHIFT',
keyLabel,
];
final value = parts.join('+');
setState(() {
widget.controller.value = TextEditingValue(
text: value,
selection: TextSelection.collapsed(offset: value.length),
);
});
return KeyEventResult.handled;
}
void _toggleMode() {
setState(() => _manualEntry = !_manualEntry);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && widget.enabled) _focusNode.requestFocus();
});
}
@override
Widget build(BuildContext context) {
final isWeb = widget.platform == 'web';
return Focus(
onKeyEvent: (_, event) => _record(event),
child: TextField(
controller: widget.controller,
focusNode: _focusNode,
enabled: widget.enabled,
readOnly: !_manualEntry,
textDirection: TextDirection.ltr,
textCapitalization: TextCapitalization.characters,
decoration: InputDecoration(
labelText: 'کلید میانبر ${isWeb ? 'وب' : 'ویندوز'} (اختیاری)',
hintText: _manualEntry
? (isWeb ? 'مثلاً Alt+1' : 'مثلاً F12 یا Alt+R')
: 'اینجا کلیک کنید و کلیدها را فشار دهید',
helperText: _manualEntry
? 'ورود دستی فعال است.'
: 'برای پاک‌کردن Backspace بزنید.',
helperMaxLines: 2,
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.keyboard_outlined),
suffixIcon: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (widget.controller.text.isNotEmpty)
IconButton(
tooltip: 'پاک‌کردن میانبر',
onPressed: widget.enabled
? () => setState(widget.controller.clear)
: null,
icon: const Icon(Icons.clear),
),
TextButton(
onPressed: widget.enabled ? _toggleMode : null,
child: Text(_manualEntry ? 'ضبط کلید' : 'ورود دستی'),
),
],
),
),
onChanged: (_) => setState(() {}),
onTap: () {
if (!_manualEntry) {
widget.controller.selection = TextSelection(
baseOffset: 0,
extentOffset: widget.controller.text.length,
);
}
},
),
);
}
}

View file

@ -0,0 +1,57 @@
#!/usr/bin/env python3
"""Serve a Flutter web release with SPA route fallback for local testing."""
from __future__ import annotations
import argparse
import os
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import urlsplit
DEFAULT_ROOT = Path(__file__).resolve().parent.parent / "build" / "web"
class SpaRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802 - stdlib handler API
path = urlsplit(self.path).path
requested = (Path.cwd() / path.lstrip("/")).resolve()
root = Path.cwd().resolve()
try:
requested.relative_to(root)
except ValueError:
self.send_error(403)
return
if not requested.exists() or requested.is_dir():
self.path = "/index.html"
super().do_GET()
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--host", default="0.0.0.0")
parser.add_argument("--port", type=int, default=8080)
parser.add_argument("--root", type=Path, default=DEFAULT_ROOT)
args = parser.parse_args()
root = args.root.expanduser().resolve()
index = root / "index.html"
if not index.is_file():
raise SystemExit(
f"Flutter build not found at {root}. Run 'flutter build web' first."
)
os.chdir(root)
server = ThreadingHTTPServer((args.host, args.port), SpaRequestHandler)
print(f"Serving {root} at http://{args.host}:{args.port}")
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()

View file

@ -0,0 +1,50 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:hesabix_ui/utils/quick_sales_customer_balance.dart';
void main() {
group('quickSalesPaymentTarget', () {
test('keeps invoice total when balance is not applied', () {
expect(
quickSalesPaymentTarget(
invoiceTotal: 5000000,
customerBalance: -2000000,
applyBalance: false,
),
5000000,
);
});
test('adds prior debt to the amount to collect', () {
expect(
quickSalesPaymentTarget(
invoiceTotal: 5000000,
customerBalance: -2000000,
applyBalance: true,
),
7000000,
);
});
test('uses prior credit against the invoice', () {
expect(
quickSalesPaymentTarget(
invoiceTotal: 5000000,
customerBalance: 2000000,
applyBalance: true,
),
3000000,
);
});
test('never produces a negative payment target', () {
expect(
quickSalesPaymentTarget(
invoiceTotal: 5000000,
customerBalance: 7000000,
applyBalance: true,
),
0,
);
});
});
}

View file

@ -30,6 +30,7 @@ void main() {
documentDescription: 'فروش صندوق',
globalDiscountType: 'percent',
globalDiscountValue: '5',
applyCustomerBalance: true,
itemCount: 1,
totalAmount: 33000,
);
@ -44,6 +45,7 @@ void main() {
expect(parsed.cartItems.first.warehouseId, 3);
expect(parsed.cartItems.first.extraInfo?['unit_price_source'], 'base');
expect(parsed.globalDiscountValue, '5');
expect(parsed.applyCustomerBalance, isTrue);
expect(parsed.totalAmount, 33000);
expect(parsed.isBlank(anonymousCustomerId: 1), isFalse);
});

View file

@ -45,6 +45,7 @@ void main() {
payments: [payment],
onChanged: (value) => changedPayments = value,
invoiceTotal: 2800000,
paymentTarget: 2800000,
changeResolution: null,
onConfigureChange: () async => null,
defaultCashRegisterId: '7',
@ -66,6 +67,12 @@ void main() {
expect(find.text('پرداخت‌شده'), findsOneWidget);
expect(find.text('ثبت'), findsOneWidget);
expect(find.text('ثبت و چاپ'), findsOneWidget);
expect(
tester
.getSize(find.byKey(const ValueKey('quick-sales-payment-summary')))
.height,
QuickSalesPaymentDock.desktopSummaryHeight,
);
expect(find.text('پرداخت‌ها (1)'), findsOneWidget);
expect(find.text('دریافت در صندوق اصلی'), findsNothing);

View file

@ -0,0 +1,45 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:hesabix_ui/utils/quick_sales_stock_correction.dart';
void main() {
test('correction token is independent from shortage row order', () {
final date = DateTime(2026, 10, 17);
final first = quickSalesStockCorrectionToken(
businessId: 4952,
saleId: 'sale-1',
documentDate: date,
shortages: const [
{'product_id': 2, 'warehouse_id': 1, 'shortage_quantity': 1.0},
{'product_id': 1, 'warehouse_id': 1, 'shortage_quantity': 2},
],
);
final second = quickSalesStockCorrectionToken(
businessId: 4952,
saleId: 'sale-1',
documentDate: date,
shortages: const [
{'product_id': 1, 'warehouse_id': 1, 'shortage_quantity': 2.0},
{'product_id': 2, 'warehouse_id': 1, 'shortage_quantity': 1},
],
);
expect(second, first);
});
test('correction token changes for another sale, date, or quantity', () {
String token(String sale, DateTime date, num quantity) =>
quickSalesStockCorrectionToken(
businessId: 4952,
saleId: sale,
documentDate: date,
shortages: [
{'product_id': 1, 'warehouse_id': 1, 'shortage_quantity': quantity},
],
);
final base = token('sale-1', DateTime(2026, 10, 17), 1);
expect(token('sale-2', DateTime(2026, 10, 17), 1), isNot(base));
expect(token('sale-1', DateTime(2026, 10, 18), 1), isNot(base));
expect(token('sale-1', DateTime(2026, 10, 17), 2), isNot(base));
});
}