codex/international-customer-mobile-identity #21
18 changed files with 821 additions and 92 deletions
47
docs/person-phone-identity.md
Normal file
47
docs/person-phone-identity.md
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
# هویت شماره تلفن اشخاص
|
||||||
|
|
||||||
|
این سند قرارداد فنی شماره تلفن اشخاص را برای جستوجو و ثبت سریع تعریف میکند.
|
||||||
|
|
||||||
|
## مدل داده
|
||||||
|
|
||||||
|
مقادیر `mobile`، `mobile_2`، `mobile_3` و `phone` فیلدهای نمایشی و قابل ویرایش فعلی باقی میمانند و migration یا تغییر منطقه آنها را بازنویسی نمیکند. ثبت سریع مشتری جدید، شماره استانداردشده را در `mobile` ذخیره میکند. برای هر فیلد یک ستون متناظر با پسوند `_normalized` وجود دارد که فقط در صورت معتبر بودن شماره، مقدار E.164 را نگه میدارد.
|
||||||
|
|
||||||
|
هر ستون استاندارد همراه `business_id` ایندکس شده است. تطبیق یک شماره در فروش سریع با query مستقیم روی این چهار ایندکس انجام میشود و به تعداد اشخاص کسبوکار یا سقف نتایج جستوجوی نام وابسته نیست.
|
||||||
|
|
||||||
|
## منطقه پیشفرض
|
||||||
|
|
||||||
|
`businesses.default_phone_region` یک کد دوحرفی ISO-3166 است. مقدار پیشفرض برای کسبوکارهای فعلی `IR` است.
|
||||||
|
|
||||||
|
- شمارههای دارای `+` یا پیششماره `00` مستقل از این تنظیم تفسیر میشوند.
|
||||||
|
- شمارههای محلی با منطقه کسبوکار تفسیر میشوند.
|
||||||
|
- نمونهها: `IR`، `AE`، `TR` و `US`.
|
||||||
|
- تغییر منطقه، ستونهای استاندارد اشخاص همان کسبوکار را در batchهای محدود بازسازی میکند؛ مقدار خام شماره تغییر نمیکند.
|
||||||
|
|
||||||
|
برای کسبوکار فعلی خارج از ایران باید ابتدا منطقه درست در «تنظیمات کسبوکار ← اطلاعات کسبوکار» ثبت شود. پس از ذخیره، شمارههای محلی موجود دوباره بررسی و استاندارد میشوند.
|
||||||
|
|
||||||
|
## Migration و دادههای قبلی
|
||||||
|
|
||||||
|
Migration `20261018_000001_person_phone_identity` ستون منطقه، چهار ستون استاندارد و چهار ایندکس مرکب را اضافه میکند. سپس شمارههای قبلی را بهصورت دستهای backfill میکند. چون کسبوکارهای قدیمی هنوز منطقهای نداشتهاند، اولین backfill با مقدار پیشفرض `IR` انجام میشود.
|
||||||
|
|
||||||
|
شماره نامعتبر یا مبهم بدون کلید استاندارد باقی میماند و مقدار اصلی آن حذف نمیشود. رکوردهای تکراری موجود نیز خودکار حذف یا ادغام نمیشوند، زیرا انتخاب رکورد مرجع یک تصمیم حسابداری است. فروش سریع تطبیقهای یک شماره را مستقل از جایگاه شخص در فهرست پیدا میکند و تا سقف پاسخ endpoint برای انتخاب کاربر برمیگرداند.
|
||||||
|
|
||||||
|
## مسیرهای نوشتن
|
||||||
|
|
||||||
|
رویدادهای SQLAlchemy مدل `Person` قبل از insert و update کلیدهای استاندارد را با منطقه کسبوکار همگام میکنند. در نتیجه ثبت سریع، فرم اشخاص، ورود فایل و سایر مسیرهای ORM از یک تابع مرکزی استفاده میکنند.
|
||||||
|
|
||||||
|
منطقه کسبوکار در سطح Session پایگاه داده cache میشود تا ورود گروهی اشخاص برای هر ردیف یک query جداگانه ایجاد نکند. تغییر منطقه این cache را پیش از بازسازی کلیدها باطل میکند.
|
||||||
|
|
||||||
|
بازیابی بکاپ اشخاص را با SQL خام وارد میکند و رویدادهای ORM در آن اجرا نمیشوند؛ به همین دلیل هر دو مسیر restore پس از ورود جدولها، کلیدهای استاندارد اشخاص کسبوکار بازیابیشده را صریحاً بازسازی میکنند. بکاپ قدیمی که فیلد منطقه را ندارد، برای کسبوکار جدید `IR` میگیرد و در حالت جایگزینی، منطقه فعلی کسبوکار را حفظ میکند.
|
||||||
|
|
||||||
|
ثبت سریع در PostgreSQL پیش از query و create یک advisory transaction lock مخصوص همان کسبوکار میگیرد. دو درخواست همزمان فروش سریع نمیتوانند هر دو مرحله «پیدا نشد» را رد کنند و یک شماره را همزمان بسازند.
|
||||||
|
|
||||||
|
این ساختار عمداً unique constraint سراسری روی موبایل ایجاد نمیکند تا دادههای تکراری قبلی migration را متوقف نکنند و کاربردهای فعلی سایر ماژولها شکسته نشوند. جلوگیری از ایجاد تکراری در مسیر ثبت سریع از query مستقیم و قفل تراکنشی حاصل میشود.
|
||||||
|
|
||||||
|
## آزمونهای لازم
|
||||||
|
|
||||||
|
- ورودی محلی ایران، امارات و آمریکا و ورودی بینالمللی با `+` یا `00` باید به E.164 مورد انتظار برسند.
|
||||||
|
- ارقام فارسی و عربی باید همان کلید ارقام لاتین را تولید کنند.
|
||||||
|
- شماره نامعتبر نباید هویت استاندارد بگیرد.
|
||||||
|
- query موبایل باید بدون `LIMIT 500` اجرا شود.
|
||||||
|
- ثبت همزمان PostgreSQL باید advisory lock را پیش از create بگیرد.
|
||||||
|
- Alembic باید پس از افزودن migration فقط یک head داشته باشد.
|
||||||
|
|
@ -32,27 +32,36 @@ Enter هنگام ثبت سریع فوکوس فیلد را تا دریافت پا
|
||||||
| `علی رضایی` | `علی رضایی` | خالی |
|
| `علی رضایی` | `علی رضایی` | خالی |
|
||||||
| `09121234567` | `09121234567` | `09121234567` |
|
| `09121234567` | `09121234567` | `09121234567` |
|
||||||
| `09121234567 سید محمد مهدی رضوی` | `سید محمد مهدی رضوی` | `09121234567` |
|
| `09121234567 سید محمد مهدی رضوی` | `سید محمد مهدی رضوی` | `09121234567` |
|
||||||
| `زهرا سادات موسوی +989121234567` | `زهرا سادات موسوی` | `09121234567` |
|
| `زهرا سادات موسوی +989121234567` | `زهرا سادات موسوی` | `+989121234567` |
|
||||||
| `۰۹۱۲۱۲۳۴۵۶۷ کاظمی` | `کاظمی` | `09121234567` |
|
| `۰۹۱۲۱۲۳۴۵۶۷ کاظمی` | `کاظمی` | `09121234567` |
|
||||||
|
| `John Smith +1 (415) 555-2671` | `John Smith` | `+14155552671` |
|
||||||
|
| `050 123 4567 Al Noor` با منطقه `AE` | `Al Noor` | `0501234567` |
|
||||||
|
|
||||||
اعداد فارسی و عربی به انگلیسی تبدیل میشوند. قالبهای `09xxxxxxxxx`، `9xxxxxxxxx`، `+989xxxxxxxxx`، `989xxxxxxxxx` و `00989xxxxxxxxx` پشتیبانی میشوند. فاصله و خط تیره داخل شماره نیز پذیرفته میشود. وجود بیش از یک موبایل معتبر، ورودی را مبهم میکند و ثبت خودکار انجام نمیشود.
|
اعداد فارسی و عربی به انگلیسی تبدیل میشوند. شمارهای که با `+` یا `00` شروع شود کد کشور خود را دارد. شمارهٔ محلی با «منطقه پیشفرض شماره تلفن» کسبوکار تفسیر میشود؛ این تنظیم در «تنظیمات کسبوکار ← اطلاعات کسبوکار»، کنار اطلاعات جغرافیایی و با کد دوحرفی ISO مانند `IR`، `AE`، `TR` یا `US` قرار دارد. فاصله، خط تیره و پرانتز داخل شماره پذیرفته میشوند. وجود بیش از یک شماره معتبر، ورودی را مبهم میکند و ثبت خودکار انجام نمیشود.
|
||||||
|
|
||||||
|
Migration و تغییر منطقه، مقدار اصلی شماره را برای نمایش و ویرایش بازنویسی نمیکنند. بکاند در ستون جداگانه یک کلید استاندارد E.164 مانند `+989121234567` یا `+14155552671` میسازد. بنابراین شکلهای محلی، بینالمللی و ارقام فارسی یک شماره به یک هویت واحد میرسند. مشتری تازهای که از ثبت سریع ساخته میشود، شماره استانداردشده را در فیلد موبایل نیز میگیرد. اگر شماره بر اساس منطقه کسبوکار معتبر نباشد، ثبت سریع با خطای شماره نامعتبر متوقف میشود و کلید ساختگی تولید نمیشود.
|
||||||
|
|
||||||
در ورودی فقط موبایل، بهدلیل الزامیبودن نام مستعار شخص، موبایل استانداردشده بهعنوان نام مستعار نیز ذخیره میشود.
|
در ورودی فقط موبایل، بهدلیل الزامیبودن نام مستعار شخص، موبایل استانداردشده بهعنوان نام مستعار نیز ذخیره میشود.
|
||||||
|
|
||||||
## جلوگیری از ثبت تکراری
|
## جلوگیری از ثبت تکراری
|
||||||
|
|
||||||
API پیش از ایجاد شخص، کاندیداهای همان کسبوکار را با فیلتر موبایل/نام (با درنظرگرفتن حروف عربی/فارسی) از دیتابیس میگیرد و سپس دقیق تطبیق میدهد:
|
API پیش از ایجاد شخص، تطبیق را در همان کسبوکار انجام میدهد:
|
||||||
|
|
||||||
- موبایل پس از استانداردسازی با فیلدهای موبایل، موبایل دوم، موبایل سوم و تلفن مقایسه میشود.
|
- موبایل پس از استانداردسازی با ستونهای ایندکسشدهٔ موبایل، موبایل دوم، موبایل سوم و تلفن مقایسه میشود. این query مستقیم است و سقف ۵۰۰ نتیجه ندارد.
|
||||||
- نام با یکسانسازی فاصلهها، نیمفاصله و حروف عربی/فارسی مقایسه میشود.
|
- نام با یکسانسازی فاصلهها، نیمفاصله و حروف عربی/فارسی مقایسه میشود.
|
||||||
- نام مستعار، نام، نام خانوادگی، نام شرکت و ترکیب نام و نام خانوادگی در بررسی تشابه شرکت دارند.
|
- نام مستعار، نام، نام خانوادگی، نام شرکت و ترکیب نام و نام خانوادگی در بررسی تشابه شرکت دارند.
|
||||||
- اگر ورودی موبایل داشته باشد، فقط همان موبایل استانداردشده معیار تکراریبودن است؛ نام یکسان یا مشابه بررسی نمیشود.
|
- اگر ورودی موبایل داشته باشد، فقط همان موبایل استانداردشده معیار تکراریبودن است؛ نام یکسان یا مشابه بررسی نمیشود.
|
||||||
- اگر همان موبایل در هیچیک از فیلدهای موبایل، موبایل دوم، موبایل سوم یا تلفن پیدا نشود، مشتری جدید حتی با نام کاملاً یکسان بدون هشدار ساخته میشود.
|
- اگر همان موبایل در هیچیک از فیلدهای موبایل، موبایل دوم، موبایل سوم یا تلفن پیدا نشود، مشتری جدید حتی با نام کاملاً یکسان بدون هشدار ساخته میشود.
|
||||||
- اگر یک رکورد با همان موبایل پیدا شود، همان مشتری انتخاب میشود. چند رکورد با موبایل یکسان در فهرست میمانند تا کاربر انتخاب کند.
|
- اگر یک رکورد با همان موبایل پیدا شود، همان مشتری انتخاب میشود. چند رکورد با موبایل یکسان در فهرست میمانند تا کاربر انتخاب کند.
|
||||||
- در ورودی فقط نام، نام یکسان یا مشابه میتواند شخص موجود را برگرداند یا چند گزینه برای انتخاب نمایش دهد.
|
- در ورودی فقط نام، نام یکسان یا مشابه میتواند شخص موجود را برگرداند یا چند گزینه برای انتخاب نمایش دهد.
|
||||||
|
- سقف ۵۰۰ کاندیدا فقط برای جستوجوی تقریبی نام باقی مانده است؛ تطبیق دقیق نام و هویت موبایل به آن وابسته نیستند.
|
||||||
- در PostgreSQL، بررسی و ایجاد سریع برای هر کسبوکار با قفل تراکنشی سریالی میشود تا دو درخواست همزمان رکورد تکراری نسازند.
|
- در PostgreSQL، بررسی و ایجاد سریع برای هر کسبوکار با قفل تراکنشی سریالی میشود تا دو درخواست همزمان رکورد تکراری نسازند.
|
||||||
- endpoint فقط برای اعضای همان کسبوکار مجاز است (`can_access_business`).
|
- endpoint فقط برای اعضای همان کسبوکار مجاز است (`can_access_business`).
|
||||||
|
|
||||||
|
Migration مقادیر قبلی را برای هر کسبوکار backfill میکند و چهار ایندکس مرکب `(business_id, *_normalized)` میسازد. رکوردهای تکراری قبلی حذف یا ادغام نمیشوند؛ اگر چند شخص از قبل یک شماره داشته باشند، برای انتخاب صریح کاربر برگردانده میشوند. تغییر منطقه پیشفرض، کلیدهای استاندارد تمام اشخاص همان کسبوکار را دستهای بازسازی میکند و مقدار خام شماره را تغییر نمیدهد.
|
||||||
|
|
||||||
|
مسیرهای ایجاد و ویرایش معمول شخص نیز هنگام ذخیره همین کلیدها را بهروز میکنند؛ بنابراین دادههای ساختهشده خارج از فروش سریع از ایندکس جستوجو خارج نمیمانند.
|
||||||
|
|
||||||
شخصی که واقعاً جدید باشد با نوع «مشتری» ساخته میشود و بدون بازشدن فرم شخص، برای فاکتور جاری انتخاب میشود.
|
شخصی که واقعاً جدید باشد با نوع «مشتری» ساخته میشود و بدون بازشدن فرم شخص، برای فاکتور جاری انتخاب میشود.
|
||||||
|
|
||||||
در پیشنمایش وب محلی، اگر `API_BASE_URL` صریحاً تنظیم نشده باشد، درخواستها به پورت `8000` همان میزبان ارسال میشوند؛ برای نمونه، رابط `192.168.50.101:8080` از API آدرس `192.168.50.101:8000` استفاده میکند. این fallback مانع ارسال اشتباه درخواستها به وبسرور Flutter روی پورت ۸۰۸۰ و دریافت خطای `405 Method Not Allowed` میشود. در محیطهای غیرمحلی، همان origin و reverse proxy برنامه استفاده میشود.
|
در پیشنمایش وب محلی، اگر `API_BASE_URL` صریحاً تنظیم نشده باشد، درخواستها به پورت `8000` همان میزبان ارسال میشوند؛ برای نمونه، رابط `192.168.50.101:8080` از API آدرس `192.168.50.101:8000` استفاده میکند. این fallback مانع ارسال اشتباه درخواستها به وبسرور Flutter روی پورت ۸۰۸۰ و دریافت خطای `405 Method Not Allowed` میشود. در محیطهای غیرمحلی، همان origin و reverse proxy برنامه استفاده میشود.
|
||||||
|
|
@ -64,6 +73,9 @@ API پیش از ایجاد شخص، کاندیداهای همان کسبوک
|
||||||
- فراخوانی API: `hesabixUI/hesabix_ui/lib/services/customer_service.dart`
|
- فراخوانی API: `hesabixUI/hesabix_ui/lib/services/customer_service.dart`
|
||||||
- endpoint: `POST /api/v1/customers/quick-resolve`
|
- endpoint: `POST /api/v1/customers/quick-resolve`
|
||||||
- منطق تطبیق و ایجاد: `hesabixAPI/app/services/customer_quick_entry_service.py`
|
- منطق تطبیق و ایجاد: `hesabixAPI/app/services/customer_quick_entry_service.py`
|
||||||
|
- نرمالسازی مرکزی و بازسازی کلیدها: `hesabixAPI/app/services/person_phone_normalization.py`
|
||||||
|
- مدل و همگامسازی create/update: `hesabixAPI/adapters/db/models/person.py`
|
||||||
|
- Migration: `hesabixAPI/migrations/versions/20261018_000001_person_phone_identity.py`
|
||||||
|
|
||||||
## گروه پیشفرض مشتری جدید
|
## گروه پیشفرض مشتری جدید
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1123,6 +1123,7 @@ async def restore_backup(
|
||||||
registration_number=original_business.get('registration_number'),
|
registration_number=original_business.get('registration_number'),
|
||||||
economic_id=original_business.get('economic_id'),
|
economic_id=original_business.get('economic_id'),
|
||||||
country=original_business.get('country'),
|
country=original_business.get('country'),
|
||||||
|
default_phone_region=original_business.get('default_phone_region') or 'IR',
|
||||||
province=original_business.get('province'),
|
province=original_business.get('province'),
|
||||||
city=original_business.get('city'),
|
city=original_business.get('city'),
|
||||||
postal_code=original_business.get('postal_code'),
|
postal_code=original_business.get('postal_code'),
|
||||||
|
|
@ -1185,6 +1186,16 @@ async def restore_backup(
|
||||||
cols = [c for c in tables_info["businesses"]["columns"] if c not in ("id", "created_at", "updated_at", "owner_id")]
|
cols = [c for c in tables_info["businesses"]["columns"] if c not in ("id", "created_at", "updated_at", "owner_id")]
|
||||||
assignments = ", ".join([f"{c} = :{c}" for c in cols])
|
assignments = ", ".join([f"{c} = :{c}" for c in cols])
|
||||||
params = {c: row.get(c) for c in cols}
|
params = {c: row.get(c) for c in cols}
|
||||||
|
if "default_phone_region" in cols and not params.get("default_phone_region"):
|
||||||
|
params["default_phone_region"] = (
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT default_phone_region FROM businesses WHERE id = :id"
|
||||||
|
),
|
||||||
|
{"id": new_business_id},
|
||||||
|
).scalar()
|
||||||
|
or "IR"
|
||||||
|
)
|
||||||
params["id"] = new_business_id
|
params["id"] = new_business_id
|
||||||
conn.execute(text(f"UPDATE businesses SET {assignments} WHERE id = :id"), params)
|
conn.execute(text(f"UPDATE businesses SET {assignments} WHERE id = :id"), params)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
|
|
@ -1228,6 +1239,25 @@ async def restore_backup(
|
||||||
|
|
||||||
_reset_session_replication_role(conn, replica_role_ok)
|
_reset_session_replication_role(conn, replica_role_ok)
|
||||||
|
|
||||||
|
from app.services.person_phone_normalization import (
|
||||||
|
renormalize_business_person_phones,
|
||||||
|
)
|
||||||
|
|
||||||
|
restored_phone_region = (
|
||||||
|
conn.execute(
|
||||||
|
text(
|
||||||
|
"SELECT default_phone_region FROM businesses WHERE id = :id"
|
||||||
|
),
|
||||||
|
{"id": new_business_id},
|
||||||
|
).scalar()
|
||||||
|
or "IR"
|
||||||
|
)
|
||||||
|
renormalize_business_person_phones(
|
||||||
|
db,
|
||||||
|
business_id=int(new_business_id),
|
||||||
|
default_region=restored_phone_region,
|
||||||
|
)
|
||||||
|
|
||||||
jm.update(job_id, 85, "Resetting financial state")
|
jm.update(job_id, 85, "Resetting financial state")
|
||||||
finalize_financial_state_after_restore(db, new_business_id)
|
finalize_financial_state_after_restore(db, new_business_id)
|
||||||
if mode == "new_business":
|
if mode == "new_business":
|
||||||
|
|
@ -1297,5 +1327,3 @@ async def restore_backup(
|
||||||
# مسیر همزمان قبلی (همان منطق، بدون job)
|
# مسیر همزمان قبلی (همان منطق، بدون job)
|
||||||
# برای اختصار، از مسیر async استفاده کنید؛ این شاخه برای سازگاری باقی میماند
|
# برای اختصار، از مسیر async استفاده کنید؛ این شاخه برای سازگاری باقی میماند
|
||||||
raise ApiError("SYNC_DISABLED", "Use async_mode=true for restore")
|
raise ApiError("SYNC_DISABLED", "Use async_mode=true for restore")
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -326,6 +326,7 @@ async def import_business_from_backup(
|
||||||
registration_number=original_business.get('registration_number'),
|
registration_number=original_business.get('registration_number'),
|
||||||
economic_id=original_business.get('economic_id'),
|
economic_id=original_business.get('economic_id'),
|
||||||
country=original_business.get('country'),
|
country=original_business.get('country'),
|
||||||
|
default_phone_region=original_business.get('default_phone_region') or 'IR',
|
||||||
province=original_business.get('province'),
|
province=original_business.get('province'),
|
||||||
city=original_business.get('city'),
|
city=original_business.get('city'),
|
||||||
postal_code=original_business.get('postal_code'),
|
postal_code=original_business.get('postal_code'),
|
||||||
|
|
@ -403,6 +404,18 @@ async def import_business_from_backup(
|
||||||
|
|
||||||
_reset_session_replication_role(conn, replica_role_ok)
|
_reset_session_replication_role(conn, replica_role_ok)
|
||||||
|
|
||||||
|
from app.services.person_phone_normalization import (
|
||||||
|
renormalize_business_person_phones,
|
||||||
|
)
|
||||||
|
|
||||||
|
renormalize_business_person_phones(
|
||||||
|
db,
|
||||||
|
business_id=int(new_business_id),
|
||||||
|
default_region=(
|
||||||
|
original_business.get("default_phone_region") or "IR"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
jm.update(job_id, 90, "Resetting financial state")
|
jm.update(job_id, 90, "Resetting financial state")
|
||||||
finalize_financial_state_after_restore(db, new_business_id)
|
finalize_financial_state_after_restore(db, new_business_id)
|
||||||
register_backup_import(
|
register_backup_import(
|
||||||
|
|
|
||||||
|
|
@ -760,6 +760,12 @@ class BusinessCreateRequest(BaseModel):
|
||||||
registration_number: Optional[str] = Field(default=None, max_length=50, description="شماره ثبت")
|
registration_number: Optional[str] = Field(default=None, max_length=50, description="شماره ثبت")
|
||||||
economic_id: Optional[str] = Field(default=None, max_length=50, description="شناسه اقتصادی")
|
economic_id: Optional[str] = Field(default=None, max_length=50, description="شناسه اقتصادی")
|
||||||
country: Optional[str] = Field(default=None, max_length=100, description="کشور")
|
country: Optional[str] = Field(default=None, max_length=100, description="کشور")
|
||||||
|
default_phone_region: str = Field(
|
||||||
|
default="IR",
|
||||||
|
min_length=2,
|
||||||
|
max_length=2,
|
||||||
|
description="کد ISO دوحرفی کشور پیشفرض شمارههای محلی",
|
||||||
|
)
|
||||||
province: Optional[str] = Field(default=None, max_length=100, description="استان")
|
province: Optional[str] = Field(default=None, max_length=100, description="استان")
|
||||||
city: Optional[str] = Field(default=None, max_length=100, description="شهر")
|
city: Optional[str] = Field(default=None, max_length=100, description="شهر")
|
||||||
postal_code: Optional[str] = Field(default=None, max_length=20, description="کد پستی")
|
postal_code: Optional[str] = Field(default=None, max_length=20, description="کد پستی")
|
||||||
|
|
@ -786,6 +792,12 @@ class BusinessUpdateRequest(BaseModel):
|
||||||
registration_number: Optional[str] = Field(default=None, max_length=50, description="شماره ثبت")
|
registration_number: Optional[str] = Field(default=None, max_length=50, description="شماره ثبت")
|
||||||
economic_id: Optional[str] = Field(default=None, max_length=50, description="شناسه اقتصادی")
|
economic_id: Optional[str] = Field(default=None, max_length=50, description="شناسه اقتصادی")
|
||||||
country: Optional[str] = Field(default=None, max_length=100, description="کشور")
|
country: Optional[str] = Field(default=None, max_length=100, description="کشور")
|
||||||
|
default_phone_region: Optional[str] = Field(
|
||||||
|
default=None,
|
||||||
|
min_length=2,
|
||||||
|
max_length=2,
|
||||||
|
description="کد ISO دوحرفی کشور پیشفرض شمارههای محلی",
|
||||||
|
)
|
||||||
province: Optional[str] = Field(default=None, max_length=100, description="استان")
|
province: Optional[str] = Field(default=None, max_length=100, description="استان")
|
||||||
city: Optional[str] = Field(default=None, max_length=100, description="شهر")
|
city: Optional[str] = Field(default=None, max_length=100, description="شهر")
|
||||||
postal_code: Optional[str] = Field(default=None, max_length=20, description="کد پستی")
|
postal_code: Optional[str] = Field(default=None, max_length=20, description="کد پستی")
|
||||||
|
|
@ -1147,6 +1159,10 @@ class BusinessResponse(BaseModel):
|
||||||
registration_number: Optional[str] = Field(default=None, description="شماره ثبت")
|
registration_number: Optional[str] = Field(default=None, description="شماره ثبت")
|
||||||
economic_id: Optional[str] = Field(default=None, description="شناسه اقتصادی")
|
economic_id: Optional[str] = Field(default=None, description="شناسه اقتصادی")
|
||||||
country: Optional[str] = Field(default=None, description="کشور")
|
country: Optional[str] = Field(default=None, description="کشور")
|
||||||
|
default_phone_region: str = Field(
|
||||||
|
default="IR",
|
||||||
|
description="کد ISO دوحرفی کشور پیشفرض شمارههای محلی",
|
||||||
|
)
|
||||||
province: Optional[str] = Field(default=None, description="استان")
|
province: Optional[str] = Field(default=None, description="استان")
|
||||||
city: Optional[str] = Field(default=None, description="شهر")
|
city: Optional[str] = Field(default=None, description="شهر")
|
||||||
postal_code: Optional[str] = Field(default=None, description="کد پستی")
|
postal_code: Optional[str] = Field(default=None, description="کد پستی")
|
||||||
|
|
@ -1462,4 +1478,3 @@ class DocumentCodeReservationResponse(BaseModel):
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -52,6 +52,13 @@ class Business(Base):
|
||||||
|
|
||||||
# فیلدهای جغرافیایی
|
# فیلدهای جغرافیایی
|
||||||
country: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
country: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
||||||
|
default_phone_region: Mapped[str] = mapped_column(
|
||||||
|
String(2),
|
||||||
|
nullable=False,
|
||||||
|
default="IR",
|
||||||
|
server_default="IR",
|
||||||
|
comment="ISO-3166 alpha-2 region used to parse local phone numbers",
|
||||||
|
)
|
||||||
province: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
province: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
||||||
city: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
city: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
||||||
postal_code: Mapped[str | None] = mapped_column(String(20), nullable=True)
|
postal_code: Mapped[str | None] = mapped_column(String(20), nullable=True)
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,8 @@ from __future__ import annotations
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
|
||||||
from sqlalchemy import String, DateTime, Integer, ForeignKey, Enum as SQLEnum, Text, UniqueConstraint, Numeric, Boolean
|
from sqlalchemy import String, DateTime, Integer, ForeignKey, Enum as SQLEnum, Text, UniqueConstraint, Numeric, Boolean, event, inspect as sa_inspect, select
|
||||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
from sqlalchemy.orm import Mapped, mapped_column, object_session, relationship
|
||||||
|
|
||||||
from adapters.db.session import Base
|
from adapters.db.session import Base
|
||||||
|
|
||||||
|
|
@ -83,6 +83,10 @@ class Person(Base):
|
||||||
mobile: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="موبایل")
|
mobile: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="موبایل")
|
||||||
mobile_2: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="موبایل ۲")
|
mobile_2: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="موبایل ۲")
|
||||||
mobile_3: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="موبایل ۳")
|
mobile_3: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="موبایل ۳")
|
||||||
|
phone_normalized: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||||
|
mobile_normalized: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||||
|
mobile_2_normalized: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||||
|
mobile_3_normalized: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||||
fax: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="فکس")
|
fax: Mapped[str | None] = mapped_column(String(20), nullable=True, comment="فکس")
|
||||||
email: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="پست الکترونیکی")
|
email: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="پست الکترونیکی")
|
||||||
website: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="وبسایت")
|
website: Mapped[str | None] = mapped_column(String(255), nullable=True, comment="وبسایت")
|
||||||
|
|
@ -104,6 +108,47 @@ class Person(Base):
|
||||||
crm_activities: Mapped[list["CrmActivity"]] = relationship("CrmActivity", back_populates="person", cascade="all, delete-orphan")
|
crm_activities: Mapped[list["CrmActivity"]] = relationship("CrmActivity", back_populates="person", cascade="all, delete-orphan")
|
||||||
|
|
||||||
|
|
||||||
|
@event.listens_for(Person, "before_insert")
|
||||||
|
@event.listens_for(Person, "before_update")
|
||||||
|
def _sync_person_normalized_phones(_mapper, connection, target: Person) -> None:
|
||||||
|
"""Keep indexed identities in sync for every ORM create/update path."""
|
||||||
|
from adapters.db.models.business import Business
|
||||||
|
from app.services.person_phone_normalization import (
|
||||||
|
PHONE_REGION_SESSION_CACHE_KEY,
|
||||||
|
normalized_person_phone_values,
|
||||||
|
)
|
||||||
|
|
||||||
|
state = sa_inspect(target)
|
||||||
|
phone_fields = ("mobile", "mobile_2", "mobile_3", "phone")
|
||||||
|
if target.id is not None and not any(
|
||||||
|
state.attrs[field].history.has_changes() for field in phone_fields
|
||||||
|
):
|
||||||
|
return
|
||||||
|
|
||||||
|
business_id = int(target.business_id)
|
||||||
|
session = object_session(target)
|
||||||
|
region_cache = (
|
||||||
|
session.info.setdefault(PHONE_REGION_SESSION_CACHE_KEY, {})
|
||||||
|
if session is not None
|
||||||
|
else {}
|
||||||
|
)
|
||||||
|
region = region_cache.get(business_id)
|
||||||
|
if region is None:
|
||||||
|
region = connection.execute(
|
||||||
|
select(Business.default_phone_region).where(Business.id == business_id)
|
||||||
|
).scalar_one_or_none() or "IR"
|
||||||
|
region_cache[business_id] = region
|
||||||
|
values = normalized_person_phone_values(
|
||||||
|
default_region=region,
|
||||||
|
mobile=target.mobile,
|
||||||
|
mobile_2=target.mobile_2,
|
||||||
|
mobile_3=target.mobile_3,
|
||||||
|
phone=target.phone,
|
||||||
|
)
|
||||||
|
for field, value in values.items():
|
||||||
|
setattr(target, field, value)
|
||||||
|
|
||||||
|
|
||||||
class PersonBankAccount(Base):
|
class PersonBankAccount(Base):
|
||||||
__tablename__ = "person_bank_accounts"
|
__tablename__ = "person_bank_accounts"
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -86,6 +86,7 @@ class BusinessRepository(BaseRepository[Business]):
|
||||||
registration_number: str | None = None,
|
registration_number: str | None = None,
|
||||||
economic_id: str | None = None,
|
economic_id: str | None = None,
|
||||||
country: str | None = None,
|
country: str | None = None,
|
||||||
|
default_phone_region: str = "IR",
|
||||||
province: str | None = None,
|
province: str | None = None,
|
||||||
city: str | None = None,
|
city: str | None = None,
|
||||||
postal_code: str | None = None,
|
postal_code: str | None = None,
|
||||||
|
|
@ -105,6 +106,7 @@ class BusinessRepository(BaseRepository[Business]):
|
||||||
registration_number=registration_number,
|
registration_number=registration_number,
|
||||||
economic_id=economic_id,
|
economic_id=economic_id,
|
||||||
country=country,
|
country=country,
|
||||||
|
default_phone_region=default_phone_region,
|
||||||
province=province,
|
province=province,
|
||||||
city=city,
|
city=city,
|
||||||
postal_code=postal_code
|
postal_code=postal_code
|
||||||
|
|
|
||||||
|
|
@ -259,6 +259,15 @@ def create_business(
|
||||||
http_status=403
|
http_status=403
|
||||||
)
|
)
|
||||||
|
|
||||||
|
from app.services.person_phone_normalization import validate_phone_region
|
||||||
|
|
||||||
|
try:
|
||||||
|
default_phone_region = validate_phone_region(
|
||||||
|
getattr(business_data, "default_phone_region", "IR")
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ApiError("INVALID_PHONE_REGION", str(exc), http_status=400) from exc
|
||||||
|
|
||||||
business_repo = BusinessRepository(db)
|
business_repo = BusinessRepository(db)
|
||||||
fiscal_repo = FiscalYearRepository(db)
|
fiscal_repo = FiscalYearRepository(db)
|
||||||
|
|
||||||
|
|
@ -281,6 +290,7 @@ def create_business(
|
||||||
registration_number=business_data.registration_number,
|
registration_number=business_data.registration_number,
|
||||||
economic_id=business_data.economic_id,
|
economic_id=business_data.economic_id,
|
||||||
country=business_data.country,
|
country=business_data.country,
|
||||||
|
default_phone_region=default_phone_region,
|
||||||
province=business_data.province,
|
province=business_data.province,
|
||||||
city=business_data.city,
|
city=business_data.city,
|
||||||
postal_code=business_data.postal_code,
|
postal_code=business_data.postal_code,
|
||||||
|
|
@ -634,6 +644,27 @@ def update_business(db: Session, business_id: int, business_data, owner_id: int)
|
||||||
db.flush()
|
db.flush()
|
||||||
|
|
||||||
# بهروزرسانی سایر فیلدها
|
# بهروزرسانی سایر فیلدها
|
||||||
|
phone_region_changed = False
|
||||||
|
if "default_phone_region" in update_data:
|
||||||
|
from app.services.person_phone_normalization import (
|
||||||
|
invalidate_business_phone_region_cache,
|
||||||
|
normalize_phone_region,
|
||||||
|
validate_phone_region,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
update_data["default_phone_region"] = validate_phone_region(
|
||||||
|
update_data.get("default_phone_region")
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise ApiError("INVALID_PHONE_REGION", str(exc), http_status=400) from exc
|
||||||
|
phone_region_changed = (
|
||||||
|
normalize_phone_region(business.default_phone_region)
|
||||||
|
!= update_data["default_phone_region"]
|
||||||
|
)
|
||||||
|
if phone_region_changed:
|
||||||
|
invalidate_business_phone_region_cache(db, int(business_id))
|
||||||
|
|
||||||
if "display_timezone" in update_data:
|
if "display_timezone" in update_data:
|
||||||
from app.services.business_timezone_service import (
|
from app.services.business_timezone_service import (
|
||||||
invalidate_business_display_timezone_cache,
|
invalidate_business_display_timezone_cache,
|
||||||
|
|
@ -647,6 +678,18 @@ def update_business(db: Session, business_id: int, business_data, owner_id: int)
|
||||||
for field, value in update_data.items():
|
for field, value in update_data.items():
|
||||||
setattr(business, field, value)
|
setattr(business, field, value)
|
||||||
|
|
||||||
|
if phone_region_changed:
|
||||||
|
from app.services.person_phone_normalization import (
|
||||||
|
renormalize_business_person_phones,
|
||||||
|
)
|
||||||
|
|
||||||
|
db.flush()
|
||||||
|
renormalize_business_person_phones(
|
||||||
|
db,
|
||||||
|
business_id=int(business_id),
|
||||||
|
default_region=update_data["default_phone_region"],
|
||||||
|
)
|
||||||
|
|
||||||
# ذخیره تغییرات
|
# ذخیره تغییرات
|
||||||
updated_business = business_repo.update(business)
|
updated_business = business_repo.update(business)
|
||||||
|
|
||||||
|
|
@ -1620,6 +1663,7 @@ def _business_to_dict(business: Business) -> Dict[str, Any]:
|
||||||
"registration_number": business.registration_number,
|
"registration_number": business.registration_number,
|
||||||
"economic_id": business.economic_id,
|
"economic_id": business.economic_id,
|
||||||
"country": business.country,
|
"country": business.country,
|
||||||
|
"default_phone_region": getattr(business, "default_phone_region", "IR") or "IR",
|
||||||
"province": business.province,
|
"province": business.province,
|
||||||
"city": business.city,
|
"city": business.city,
|
||||||
"postal_code": business.postal_code,
|
"postal_code": business.postal_code,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
import re
|
|
||||||
from typing import Iterable
|
from typing import Iterable
|
||||||
|
|
||||||
from sqlalchemy import and_, func, literal, or_, text
|
from sqlalchemy import and_, func, literal, or_, text
|
||||||
|
|
@ -10,17 +9,23 @@ from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from adapters.api.v1.schema_models.person import (
|
from adapters.api.v1.schema_models.person import (
|
||||||
PersonCreateRequest,
|
PersonCreateRequest,
|
||||||
|
)
|
||||||
|
from adapters.api.v1.schema_models.person import (
|
||||||
PersonType as PersonRequestType,
|
PersonType as PersonRequestType,
|
||||||
)
|
)
|
||||||
|
from adapters.db.models.business import Business
|
||||||
from adapters.db.models.person import Person
|
from adapters.db.models.person import Person
|
||||||
from adapters.db.models.quick_sales_settings import QuickSalesSetting
|
from adapters.db.models.quick_sales_settings import QuickSalesSetting
|
||||||
from app.core.responses import ApiError
|
from app.core.responses import ApiError
|
||||||
|
from app.services.person_phone_normalization import (
|
||||||
|
DEFAULT_PHONE_REGION,
|
||||||
|
normalize_phone_e164,
|
||||||
|
normalize_phone_region,
|
||||||
|
)
|
||||||
from app.services.person_service import create_person
|
from app.services.person_service import create_person
|
||||||
from app.services.telephony.phone_normalizer import normalize_iran_phone, numbers_match
|
|
||||||
|
|
||||||
|
|
||||||
_NAME_TRANSLATION = str.maketrans({"ي": "ی", "ى": "ی", "ك": "ک", "ۀ": "ه"})
|
_NAME_TRANSLATION = str.maketrans({"ي": "ی", "ى": "ی", "ك": "ک", "ۀ": "ه"})
|
||||||
_CANDIDATE_FETCH_LIMIT = 500
|
_NAME_CANDIDATE_FETCH_LIMIT = 500
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|
@ -41,13 +46,12 @@ def normalize_customer_alias(value: str | None) -> str:
|
||||||
return (clean_customer_alias(value) or "").casefold()
|
return (clean_customer_alias(value) or "").casefold()
|
||||||
|
|
||||||
|
|
||||||
def normalize_customer_mobile(value: str | None) -> str | None:
|
def normalize_customer_mobile(
|
||||||
if value is None or not str(value).strip():
|
value: str | None,
|
||||||
return None
|
*,
|
||||||
canonical = normalize_iran_phone(str(value)).get("canonical")
|
default_region: str = DEFAULT_PHONE_REGION,
|
||||||
if canonical and re.fullmatch(r"09\d{9}", canonical):
|
) -> str | None:
|
||||||
return canonical
|
return normalize_phone_e164(value, default_region=default_region)
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def alias_search_variants(alias: str) -> set[str]:
|
def alias_search_variants(alias: str) -> set[str]:
|
||||||
|
|
@ -60,24 +64,6 @@ def alias_search_variants(alias: str) -> set[str]:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def mobile_search_needles(mobile: str) -> set[str]:
|
|
||||||
"""Digit fragments useful for SQL prefiltering of stored phone fields."""
|
|
||||||
digits = re.sub(r"\D", "", mobile)
|
|
||||||
needles = {digits}
|
|
||||||
if digits.startswith("0") and len(digits) >= 11:
|
|
||||||
without_zero = digits[1:]
|
|
||||||
needles.add(without_zero)
|
|
||||||
needles.add(f"98{without_zero}")
|
|
||||||
elif digits.startswith("98") and len(digits) >= 12:
|
|
||||||
local = digits[2:]
|
|
||||||
needles.add(local)
|
|
||||||
needles.add(f"0{local}")
|
|
||||||
elif len(digits) == 10 and digits.startswith("9"):
|
|
||||||
needles.add(f"0{digits}")
|
|
||||||
needles.add(f"98{digits}")
|
|
||||||
return {needle for needle in needles if len(needle) >= 10}
|
|
||||||
|
|
||||||
|
|
||||||
def _person_alias_candidates(person: Person) -> set[str]:
|
def _person_alias_candidates(person: Person) -> set[str]:
|
||||||
raw_values = {
|
raw_values = {
|
||||||
person.alias_name,
|
person.alias_name,
|
||||||
|
|
@ -107,17 +93,12 @@ def person_matches_quick_customer_entry(
|
||||||
mobile: str | None,
|
mobile: str | None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
if mobile:
|
if mobile:
|
||||||
stored_numbers = (
|
stored_numbers = (person.mobile, person.mobile_2, person.mobile_3, person.phone)
|
||||||
person.mobile,
|
|
||||||
person.mobile_2,
|
|
||||||
person.mobile_3,
|
|
||||||
person.phone,
|
|
||||||
)
|
|
||||||
# When a mobile is supplied it is the customer identity. A matching
|
# When a mobile is supplied it is the customer identity. A matching
|
||||||
# name with another mobile must remain eligible for a new record.
|
# name with another mobile must remain eligible for a new record.
|
||||||
return any(
|
canonical = normalize_customer_mobile(mobile)
|
||||||
numbers_match(mobile, stored, min_len=10)
|
return canonical is not None and any(
|
||||||
for stored in stored_numbers
|
normalize_customer_mobile(stored) == canonical for stored in stored_numbers
|
||||||
)
|
)
|
||||||
|
|
||||||
normalized_alias = normalize_customer_alias(alias_name)
|
normalized_alias = normalize_customer_alias(alias_name)
|
||||||
|
|
@ -129,14 +110,33 @@ def person_matches_quick_customer_entry(
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _person_matches_mobile(person: Person, mobile: str) -> bool:
|
def _person_matches_mobile(
|
||||||
|
person: Person,
|
||||||
|
mobile: str,
|
||||||
|
*,
|
||||||
|
default_region: str = DEFAULT_PHONE_REGION,
|
||||||
|
) -> bool:
|
||||||
|
canonical = normalize_customer_mobile(mobile, default_region=default_region)
|
||||||
|
if canonical is None:
|
||||||
|
return False
|
||||||
|
normalized_values = (
|
||||||
|
getattr(person, "mobile_normalized", None),
|
||||||
|
getattr(person, "mobile_2_normalized", None),
|
||||||
|
getattr(person, "mobile_3_normalized", None),
|
||||||
|
getattr(person, "phone_normalized", None),
|
||||||
|
)
|
||||||
|
if canonical in normalized_values:
|
||||||
|
return True
|
||||||
stored_numbers = (
|
stored_numbers = (
|
||||||
person.mobile,
|
person.mobile,
|
||||||
person.mobile_2,
|
person.mobile_2,
|
||||||
person.mobile_3,
|
person.mobile_3,
|
||||||
person.phone,
|
person.phone,
|
||||||
)
|
)
|
||||||
return any(numbers_match(mobile, stored, min_len=10) for stored in stored_numbers)
|
return any(
|
||||||
|
normalize_customer_mobile(stored, default_region=default_region) == canonical
|
||||||
|
for stored in stored_numbers
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def find_quick_customer_matches(
|
def find_quick_customer_matches(
|
||||||
|
|
@ -145,6 +145,7 @@ def find_quick_customer_matches(
|
||||||
alias_name: str | None,
|
alias_name: str | None,
|
||||||
mobile: str | None,
|
mobile: str | None,
|
||||||
limit: int = 20,
|
limit: int = 20,
|
||||||
|
default_region: str = DEFAULT_PHONE_REGION,
|
||||||
) -> list[Person]:
|
) -> list[Person]:
|
||||||
candidates = list(persons)
|
candidates = list(persons)
|
||||||
|
|
||||||
|
|
@ -152,7 +153,9 @@ def find_quick_customer_matches(
|
||||||
# دو مشتری همنام با موبایلهای متفاوت بدون هشدار ثبت شوند.
|
# دو مشتری همنام با موبایلهای متفاوت بدون هشدار ثبت شوند.
|
||||||
if mobile:
|
if mobile:
|
||||||
return [
|
return [
|
||||||
person for person in candidates if _person_matches_mobile(person, mobile)
|
person
|
||||||
|
for person in candidates
|
||||||
|
if _person_matches_mobile(person, mobile, default_region=default_region)
|
||||||
][:limit]
|
][:limit]
|
||||||
|
|
||||||
normalized_alias = normalize_customer_alias(alias_name)
|
normalized_alias = normalize_customer_alias(alias_name)
|
||||||
|
|
@ -197,21 +200,11 @@ def load_quick_customer_candidates(
|
||||||
*,
|
*,
|
||||||
business_id: int,
|
business_id: int,
|
||||||
alias_name: str | None,
|
alias_name: str | None,
|
||||||
mobile: str | None,
|
limit: int = _NAME_CANDIDATE_FETCH_LIMIT,
|
||||||
limit: int = _CANDIDATE_FETCH_LIMIT,
|
|
||||||
) -> list[Person]:
|
) -> list[Person]:
|
||||||
"""Load a bounded candidate set instead of every person in the business."""
|
"""Load bounded fuzzy-name suggestions; phone identity uses an exact index."""
|
||||||
filters = []
|
filters = []
|
||||||
if mobile:
|
if alias_name:
|
||||||
phone_columns = (Person.mobile, Person.mobile_2, Person.mobile_3, Person.phone)
|
|
||||||
for needle in mobile_search_needles(mobile):
|
|
||||||
like = f"%{needle}%"
|
|
||||||
for column in phone_columns:
|
|
||||||
filters.append(and_(column.isnot(None), column.ilike(like)))
|
|
||||||
|
|
||||||
# If a mobile is present, only load phone candidates. Mixing common-name
|
|
||||||
# candidates into this bounded query could hide the actual mobile match.
|
|
||||||
if alias_name and not mobile:
|
|
||||||
variants = alias_search_variants(alias_name)
|
variants = alias_search_variants(alias_name)
|
||||||
name_columns = (
|
name_columns = (
|
||||||
Person.alias_name,
|
Person.alias_name,
|
||||||
|
|
@ -251,6 +244,38 @@ def load_quick_customer_candidates(
|
||||||
return query.limit(int(limit)).all()
|
return query.limit(int(limit)).all()
|
||||||
|
|
||||||
|
|
||||||
|
def get_business_default_phone_region(db: Session, business_id: int) -> str:
|
||||||
|
value = (
|
||||||
|
db.query(Business.default_phone_region)
|
||||||
|
.filter(Business.id == int(business_id))
|
||||||
|
.scalar()
|
||||||
|
)
|
||||||
|
return normalize_phone_region(value if isinstance(value, str) else None)
|
||||||
|
|
||||||
|
|
||||||
|
def load_quick_customer_mobile_matches(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
business_id: int,
|
||||||
|
normalized_mobile: str,
|
||||||
|
) -> list[Person]:
|
||||||
|
"""Find every matching person through indexed E.164 identity columns."""
|
||||||
|
return (
|
||||||
|
db.query(Person)
|
||||||
|
.filter(
|
||||||
|
Person.business_id == int(business_id),
|
||||||
|
or_(
|
||||||
|
Person.mobile_normalized == normalized_mobile,
|
||||||
|
Person.mobile_2_normalized == normalized_mobile,
|
||||||
|
Person.mobile_3_normalized == normalized_mobile,
|
||||||
|
Person.phone_normalized == normalized_mobile,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.order_by(Person.id)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def load_exact_quick_customer_candidates(
|
def load_exact_quick_customer_candidates(
|
||||||
db: Session,
|
db: Session,
|
||||||
*,
|
*,
|
||||||
|
|
@ -301,7 +326,8 @@ def resolve_or_create_quick_customer(
|
||||||
mobile: str | None,
|
mobile: str | None,
|
||||||
) -> QuickCustomerResolution:
|
) -> QuickCustomerResolution:
|
||||||
cleaned_alias = clean_customer_alias(alias_name)
|
cleaned_alias = clean_customer_alias(alias_name)
|
||||||
normalized_mobile = normalize_customer_mobile(mobile)
|
phone_region = get_business_default_phone_region(db, int(business_id))
|
||||||
|
normalized_mobile = normalize_customer_mobile(mobile, default_region=phone_region)
|
||||||
if mobile and not normalized_mobile:
|
if mobile and not normalized_mobile:
|
||||||
raise ApiError("INVALID_CUSTOMER_MOBILE", "شماره موبایل معتبر نیست")
|
raise ApiError("INVALID_CUSTOMER_MOBILE", "شماره موبایل معتبر نیست")
|
||||||
if not cleaned_alias and not normalized_mobile:
|
if not cleaned_alias and not normalized_mobile:
|
||||||
|
|
@ -327,11 +353,18 @@ def resolve_or_create_quick_customer(
|
||||||
if not normalized_mobile
|
if not normalized_mobile
|
||||||
else []
|
else []
|
||||||
)
|
)
|
||||||
persons = load_quick_customer_candidates(
|
persons = (
|
||||||
db,
|
load_quick_customer_mobile_matches(
|
||||||
business_id=int(business_id),
|
db,
|
||||||
alias_name=cleaned_alias,
|
business_id=int(business_id),
|
||||||
mobile=normalized_mobile,
|
normalized_mobile=normalized_mobile,
|
||||||
|
)
|
||||||
|
if normalized_mobile
|
||||||
|
else load_quick_customer_candidates(
|
||||||
|
db,
|
||||||
|
business_id=int(business_id),
|
||||||
|
alias_name=cleaned_alias,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
if exact_persons:
|
if exact_persons:
|
||||||
seen_ids = {int(person.id) for person in exact_persons}
|
seen_ids = {int(person.id) for person in exact_persons}
|
||||||
|
|
@ -342,6 +375,7 @@ def resolve_or_create_quick_customer(
|
||||||
persons,
|
persons,
|
||||||
alias_name=cleaned_alias,
|
alias_name=cleaned_alias,
|
||||||
mobile=normalized_mobile,
|
mobile=normalized_mobile,
|
||||||
|
default_region=phone_region,
|
||||||
)
|
)
|
||||||
if matches:
|
if matches:
|
||||||
return QuickCustomerResolution(persons=matches, created=False)
|
return QuickCustomerResolution(persons=matches, created=False)
|
||||||
|
|
|
||||||
152
hesabixAPI/app/services/person_phone_normalization.py
Normal file
152
hesabixAPI/app/services/person_phone_normalization.py
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
"""Canonical, business-aware phone normalization for person identity lookups."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import phonenumbers
|
||||||
|
from phonenumbers import NumberParseException, PhoneNumberFormat
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_PHONE_REGION = "IR"
|
||||||
|
PHONE_REGION_SESSION_CACHE_KEY = "person_phone_regions"
|
||||||
|
PHONE_FIELDS = ("mobile", "mobile_2", "mobile_3", "phone")
|
||||||
|
NORMALIZED_PHONE_FIELDS = tuple(f"{field}_normalized" for field in PHONE_FIELDS)
|
||||||
|
_DIGIT_TRANSLATION = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "0123456789" * 2)
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_phone_region(value: str | None, *, fallback: str = DEFAULT_PHONE_REGION) -> str:
|
||||||
|
"""Return an ISO-3166 alpha-2 region understood by libphonenumber."""
|
||||||
|
candidate = str(value or "").strip().upper()
|
||||||
|
if candidate in phonenumbers.SUPPORTED_REGIONS:
|
||||||
|
return candidate
|
||||||
|
fallback_value = str(fallback or DEFAULT_PHONE_REGION).strip().upper()
|
||||||
|
if fallback_value in phonenumbers.SUPPORTED_REGIONS:
|
||||||
|
return fallback_value
|
||||||
|
return DEFAULT_PHONE_REGION
|
||||||
|
|
||||||
|
|
||||||
|
def validate_phone_region(value: str | None) -> str:
|
||||||
|
"""Validate a user supplied default region without silently changing it."""
|
||||||
|
candidate = str(value or "").strip().upper()
|
||||||
|
if candidate not in phonenumbers.SUPPORTED_REGIONS:
|
||||||
|
raise ValueError("کد کشور شماره تلفن معتبر نیست؛ مانند IR، AE، TR یا US")
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_phone_e164(
|
||||||
|
value: str | None, *, default_region: str = DEFAULT_PHONE_REGION
|
||||||
|
) -> str | None:
|
||||||
|
"""Normalize a valid local or international number to E.164.
|
||||||
|
|
||||||
|
Numbers that start with ``+`` or ``00`` carry their own country code. Local
|
||||||
|
numbers use the business' default region. Invalid or ambiguous values are
|
||||||
|
deliberately left unresolved instead of manufacturing an identity key.
|
||||||
|
"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
raw = str(value).translate(_DIGIT_TRANSLATION).strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
compact = "".join(char for char in raw if char.isdigit() or char == "+")
|
||||||
|
if compact.startswith("00"):
|
||||||
|
compact = f"+{compact[2:]}"
|
||||||
|
if not compact:
|
||||||
|
return None
|
||||||
|
region = None if compact.startswith("+") else normalize_phone_region(default_region)
|
||||||
|
try:
|
||||||
|
parsed = phonenumbers.parse(compact, region)
|
||||||
|
except NumberParseException:
|
||||||
|
return None
|
||||||
|
if not phonenumbers.is_valid_number(parsed):
|
||||||
|
return None
|
||||||
|
return phonenumbers.format_number(parsed, PhoneNumberFormat.E164)
|
||||||
|
|
||||||
|
|
||||||
|
def normalized_person_phone_values(
|
||||||
|
*,
|
||||||
|
default_region: str,
|
||||||
|
mobile: str | None = None,
|
||||||
|
mobile_2: str | None = None,
|
||||||
|
mobile_3: str | None = None,
|
||||||
|
phone: str | None = None,
|
||||||
|
) -> dict[str, str | None]:
|
||||||
|
raw_values = {
|
||||||
|
"mobile": mobile,
|
||||||
|
"mobile_2": mobile_2,
|
||||||
|
"mobile_3": mobile_3,
|
||||||
|
"phone": phone,
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
f"{field}_normalized": normalize_phone_e164(value, default_region=default_region)
|
||||||
|
for field, value in raw_values.items()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def invalidate_business_phone_region_cache(db: "Session", business_id: int) -> None:
|
||||||
|
"""Discard one business region cached for ORM person hooks."""
|
||||||
|
cache = db.info.get(PHONE_REGION_SESSION_CACHE_KEY)
|
||||||
|
if isinstance(cache, dict):
|
||||||
|
cache.pop(int(business_id), None)
|
||||||
|
|
||||||
|
|
||||||
|
def renormalize_business_person_phones(
|
||||||
|
db: "Session",
|
||||||
|
*,
|
||||||
|
business_id: int,
|
||||||
|
default_region: str,
|
||||||
|
batch_size: int = 1000,
|
||||||
|
) -> int:
|
||||||
|
"""Rebuild indexed phone identities after a business region changes.
|
||||||
|
|
||||||
|
Raw phone values remain unchanged. Rows are read and updated in bounded
|
||||||
|
batches so a business with many persons does not have to load them all into
|
||||||
|
the ORM identity map at once.
|
||||||
|
"""
|
||||||
|
from adapters.db.models.person import Person
|
||||||
|
|
||||||
|
region = validate_phone_region(default_region)
|
||||||
|
updated_count = 0
|
||||||
|
last_id = 0
|
||||||
|
while True:
|
||||||
|
rows = (
|
||||||
|
db.query(
|
||||||
|
Person.id,
|
||||||
|
Person.mobile,
|
||||||
|
Person.mobile_2,
|
||||||
|
Person.mobile_3,
|
||||||
|
Person.phone,
|
||||||
|
)
|
||||||
|
.filter(
|
||||||
|
Person.business_id == int(business_id),
|
||||||
|
Person.id > int(last_id),
|
||||||
|
)
|
||||||
|
.order_by(Person.id)
|
||||||
|
.limit(int(batch_size))
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
if not rows:
|
||||||
|
break
|
||||||
|
|
||||||
|
mappings = []
|
||||||
|
for row in rows:
|
||||||
|
mappings.append(
|
||||||
|
{
|
||||||
|
"id": int(row.id),
|
||||||
|
**normalized_person_phone_values(
|
||||||
|
default_region=region,
|
||||||
|
mobile=row.mobile,
|
||||||
|
mobile_2=row.mobile_2,
|
||||||
|
mobile_3=row.mobile_3,
|
||||||
|
phone=row.phone,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
db.bulk_update_mappings(Person, mappings)
|
||||||
|
updated_count += len(mappings)
|
||||||
|
last_id = int(rows[-1].id)
|
||||||
|
|
||||||
|
return updated_count
|
||||||
|
|
@ -0,0 +1,123 @@
|
||||||
|
"""Add indexed international phone identities for persons.
|
||||||
|
|
||||||
|
Revision ID: 20261018_000001_person_phone_identity
|
||||||
|
Revises: 20261017_000001_quick_sales_audit_permissions
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import phonenumbers
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
from phonenumbers import NumberParseException, PhoneNumberFormat
|
||||||
|
|
||||||
|
revision = "20261018_000001_person_phone_identity"
|
||||||
|
down_revision = "20261017_000001_quick_sales_audit_permissions"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
_DIGIT_TRANSLATION = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "0123456789" * 2)
|
||||||
|
_PHONE_COLUMNS = ("mobile", "mobile_2", "mobile_3", "phone")
|
||||||
|
|
||||||
|
|
||||||
|
def _normalize(value: str | None, region: str) -> str | None:
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
raw = str(value).translate(_DIGIT_TRANSLATION).strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
compact = "".join(char for char in raw if char.isdigit() or char == "+")
|
||||||
|
if compact.startswith("00"):
|
||||||
|
compact = f"+{compact[2:]}"
|
||||||
|
parse_region = None if compact.startswith("+") else region
|
||||||
|
try:
|
||||||
|
parsed = phonenumbers.parse(compact, parse_region)
|
||||||
|
except NumberParseException:
|
||||||
|
return None
|
||||||
|
if not phonenumbers.is_valid_number(parsed):
|
||||||
|
return None
|
||||||
|
return phonenumbers.format_number(parsed, PhoneNumberFormat.E164)
|
||||||
|
|
||||||
|
|
||||||
|
def _backfill() -> None:
|
||||||
|
connection = op.get_bind()
|
||||||
|
region_rows = connection.execute(
|
||||||
|
sa.text("SELECT id, default_phone_region FROM businesses")
|
||||||
|
).mappings()
|
||||||
|
regions = {
|
||||||
|
int(row["id"]): str(row["default_phone_region"] or "IR").upper() for row in region_rows
|
||||||
|
}
|
||||||
|
result = connection.execute(
|
||||||
|
sa.text(
|
||||||
|
"""
|
||||||
|
SELECT id, business_id, mobile, mobile_2, mobile_3, phone
|
||||||
|
FROM persons
|
||||||
|
ORDER BY id
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
).mappings()
|
||||||
|
update_sql = sa.text(
|
||||||
|
"""
|
||||||
|
UPDATE persons
|
||||||
|
SET mobile_normalized = :mobile_normalized,
|
||||||
|
mobile_2_normalized = :mobile_2_normalized,
|
||||||
|
mobile_3_normalized = :mobile_3_normalized,
|
||||||
|
phone_normalized = :phone_normalized
|
||||||
|
WHERE id = :id
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
while True:
|
||||||
|
rows = result.fetchmany(1000)
|
||||||
|
if not rows:
|
||||||
|
break
|
||||||
|
updates = []
|
||||||
|
for row in rows:
|
||||||
|
region = regions.get(int(row["business_id"]), "IR")
|
||||||
|
if region not in phonenumbers.SUPPORTED_REGIONS:
|
||||||
|
region = "IR"
|
||||||
|
updates.append(
|
||||||
|
{
|
||||||
|
"id": int(row["id"]),
|
||||||
|
**{
|
||||||
|
f"{field}_normalized": _normalize(row[field], region)
|
||||||
|
for field in _PHONE_COLUMNS
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if updates:
|
||||||
|
connection.execute(update_sql, updates)
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
op.add_column(
|
||||||
|
"businesses",
|
||||||
|
sa.Column(
|
||||||
|
"default_phone_region",
|
||||||
|
sa.String(length=2),
|
||||||
|
nullable=False,
|
||||||
|
server_default="IR",
|
||||||
|
comment="ISO-3166 alpha-2 region used to parse local phone numbers",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
for field in _PHONE_COLUMNS:
|
||||||
|
op.add_column(
|
||||||
|
"persons",
|
||||||
|
sa.Column(f"{field}_normalized", sa.String(length=32), nullable=True),
|
||||||
|
)
|
||||||
|
|
||||||
|
_backfill()
|
||||||
|
|
||||||
|
for field in _PHONE_COLUMNS:
|
||||||
|
op.create_index(
|
||||||
|
f"ix_persons_business_{field}_normalized",
|
||||||
|
"persons",
|
||||||
|
["business_id", f"{field}_normalized"],
|
||||||
|
unique=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
for field in reversed(_PHONE_COLUMNS):
|
||||||
|
op.drop_index(f"ix_persons_business_{field}_normalized", table_name="persons")
|
||||||
|
op.drop_column("persons", f"{field}_normalized")
|
||||||
|
op.drop_column("businesses", "default_phone_region")
|
||||||
|
|
@ -9,7 +9,7 @@ from app.services.customer_quick_entry_service import (
|
||||||
alias_search_variants,
|
alias_search_variants,
|
||||||
clean_customer_alias,
|
clean_customer_alias,
|
||||||
find_quick_customer_matches,
|
find_quick_customer_matches,
|
||||||
mobile_search_needles,
|
load_quick_customer_mobile_matches,
|
||||||
normalize_customer_alias,
|
normalize_customer_alias,
|
||||||
normalize_customer_mobile,
|
normalize_customer_mobile,
|
||||||
resolve_or_create_quick_customer,
|
resolve_or_create_quick_customer,
|
||||||
|
|
@ -38,23 +38,46 @@ def _person(
|
||||||
mobile_2=None,
|
mobile_2=None,
|
||||||
mobile_3=None,
|
mobile_3=None,
|
||||||
phone=None,
|
phone=None,
|
||||||
|
mobile_normalized=None,
|
||||||
|
mobile_2_normalized=None,
|
||||||
|
mobile_3_normalized=None,
|
||||||
|
phone_normalized=None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def test_normalizes_customer_alias_and_mobile_variants():
|
def test_normalizes_customer_alias_and_mobile_variants():
|
||||||
assert clean_customer_alias(" علي رضايي ") == "علی رضایی"
|
assert clean_customer_alias(" علي رضايي ") == "علی رضایی"
|
||||||
assert normalize_customer_alias("علي رضايي") == "علی رضایی"
|
assert normalize_customer_alias("علي رضايي") == "علی رضایی"
|
||||||
assert normalize_customer_mobile("+98 912 123 4567") == "09121234567"
|
assert normalize_customer_mobile("+98 912 123 4567") == "+989121234567"
|
||||||
assert normalize_customer_mobile("۰۹۱۲۱۲۳۴۵۶۷") == "09121234567"
|
assert normalize_customer_mobile("۰۹۱۲۱۲۳۴۵۶۷") == "+989121234567"
|
||||||
|
|
||||||
|
|
||||||
def test_alias_and_mobile_search_helpers_cover_common_variants():
|
def test_alias_search_helpers_cover_common_variants():
|
||||||
assert "علی" in alias_search_variants("علي")
|
assert "علی" in alias_search_variants("علي")
|
||||||
assert "علي" in alias_search_variants("علی")
|
assert "علي" in alias_search_variants("علی")
|
||||||
needles = mobile_search_needles("09121234567")
|
|
||||||
assert "09121234567" in needles
|
|
||||||
assert "9121234567" in needles
|
def test_normalizes_foreign_local_mobile_with_business_region():
|
||||||
assert "989121234567" in needles
|
assert normalize_customer_mobile("050 123 4567", default_region="AE") == "+971501234567"
|
||||||
|
assert normalize_customer_mobile("(415) 555-2671", default_region="US") == "+14155552671"
|
||||||
|
|
||||||
|
|
||||||
|
def test_mobile_identity_query_is_not_limited_to_500_candidates():
|
||||||
|
db = MagicMock()
|
||||||
|
rows = [_person(i, f"مشتری {i}", mobile="09121234567") for i in range(1, 602)]
|
||||||
|
query = db.query.return_value
|
||||||
|
ordered = query.filter.return_value.order_by.return_value
|
||||||
|
ordered.all.return_value = rows
|
||||||
|
|
||||||
|
result = load_quick_customer_mobile_matches(
|
||||||
|
db,
|
||||||
|
business_id=8,
|
||||||
|
normalized_mobile="+989121234567",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert len(result) == 601
|
||||||
|
query.limit.assert_not_called()
|
||||||
|
ordered.limit.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
def test_finds_existing_person_by_mobile_before_creation():
|
def test_finds_existing_person_by_mobile_before_creation():
|
||||||
|
|
@ -194,6 +217,8 @@ def test_new_quick_customer_uses_group_from_quick_sales_settings(
|
||||||
|
|
||||||
db.query.side_effect = query_for
|
db.query.side_effect = query_for
|
||||||
monkeypatch.setattr(service, "load_quick_customer_candidates", lambda *args, **kwargs: [])
|
monkeypatch.setattr(service, "load_quick_customer_candidates", lambda *args, **kwargs: [])
|
||||||
|
monkeypatch.setattr(service, "get_business_default_phone_region", lambda *_args: "IR")
|
||||||
|
monkeypatch.setattr(service, "load_quick_customer_mobile_matches", lambda *args, **kwargs: [])
|
||||||
captured_request = {}
|
captured_request = {}
|
||||||
|
|
||||||
def fake_create_person(_db, _business_id, request):
|
def fake_create_person(_db, _business_id, request):
|
||||||
|
|
@ -223,9 +248,10 @@ def test_existing_quick_customer_keeps_its_current_group(monkeypatch):
|
||||||
existing.person_group_id = 4
|
existing.person_group_id = 4
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(
|
||||||
service,
|
service,
|
||||||
"load_quick_customer_candidates",
|
"load_quick_customer_mobile_matches",
|
||||||
lambda *args, **kwargs: [existing],
|
lambda *args, **kwargs: [existing],
|
||||||
)
|
)
|
||||||
|
monkeypatch.setattr(service, "get_business_default_phone_region", lambda *_args: "IR")
|
||||||
create_person = MagicMock()
|
create_person = MagicMock()
|
||||||
monkeypatch.setattr(service, "create_person", create_person)
|
monkeypatch.setattr(service, "create_person", create_person)
|
||||||
|
|
||||||
|
|
@ -243,6 +269,34 @@ def test_existing_quick_customer_keeps_its_current_group(monkeypatch):
|
||||||
db.query.assert_not_called()
|
db.query.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_postgresql_quick_customer_resolution_takes_transaction_lock(monkeypatch):
|
||||||
|
from app.services import customer_quick_entry_service as service
|
||||||
|
|
||||||
|
db = MagicMock()
|
||||||
|
db.get_bind.return_value = SimpleNamespace(
|
||||||
|
dialect=SimpleNamespace(name="postgresql")
|
||||||
|
)
|
||||||
|
existing = _person(9, "مشتری موجود", mobile="+989121234567")
|
||||||
|
monkeypatch.setattr(service, "get_business_default_phone_region", lambda *_args: "IR")
|
||||||
|
monkeypatch.setattr(
|
||||||
|
service,
|
||||||
|
"load_quick_customer_mobile_matches",
|
||||||
|
lambda *args, **kwargs: [existing],
|
||||||
|
)
|
||||||
|
|
||||||
|
result = resolve_or_create_quick_customer(
|
||||||
|
db,
|
||||||
|
business_id=8,
|
||||||
|
alias_name="مشتری موجود",
|
||||||
|
mobile="09121234567",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result.created is False
|
||||||
|
assert result.persons == [existing]
|
||||||
|
db.execute.assert_called_once()
|
||||||
|
assert "pg_advisory_xact_lock" in str(db.execute.call_args.args[0])
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_quick_resolve_requires_business_access(monkeypatch):
|
async def test_quick_resolve_requires_business_access(monkeypatch):
|
||||||
from adapters.api.v1.customers import (
|
from adapters.api.v1.customers import (
|
||||||
|
|
|
||||||
108
hesabixAPI/tests/test_person_phone_normalization.py
Normal file
108
hesabixAPI/tests/test_person_phone_normalization.py
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.services.person_phone_normalization import (
|
||||||
|
normalize_phone_e164,
|
||||||
|
normalize_phone_region,
|
||||||
|
normalized_person_phone_values,
|
||||||
|
renormalize_business_person_phones,
|
||||||
|
validate_phone_region,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("raw", "region", "expected"),
|
||||||
|
[
|
||||||
|
("0917 100 6219", "IR", "+989171006219"),
|
||||||
|
("۰۹۱۷۱۰۰۶۲۱۹", "IR", "+989171006219"),
|
||||||
|
("0098 917 100 6219", "US", "+989171006219"),
|
||||||
|
("+98 917 100 6219", "AE", "+989171006219"),
|
||||||
|
("050 123 4567", "AE", "+971501234567"),
|
||||||
|
("(415) 555-2671", "US", "+14155552671"),
|
||||||
|
("+49 151 23456789", "IR", "+4915123456789"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_normalizes_local_and_international_numbers(raw, region, expected):
|
||||||
|
assert normalize_phone_e164(raw, default_region=region) == expected
|
||||||
|
|
||||||
|
|
||||||
|
def test_invalid_number_is_not_assigned_an_identity():
|
||||||
|
assert normalize_phone_e164("123", default_region="IR") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_validates_supported_business_region():
|
||||||
|
assert normalize_phone_region("ae") == "AE"
|
||||||
|
assert validate_phone_region("us") == "US"
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
validate_phone_region("XX")
|
||||||
|
|
||||||
|
|
||||||
|
def test_normalizes_all_person_phone_slots():
|
||||||
|
values = normalized_person_phone_values(
|
||||||
|
default_region="AE",
|
||||||
|
mobile="050 123 4567",
|
||||||
|
mobile_2="+1 415 555 2671",
|
||||||
|
mobile_3=None,
|
||||||
|
phone="04 234 5678",
|
||||||
|
)
|
||||||
|
assert values["mobile_normalized"] == "+971501234567"
|
||||||
|
assert values["mobile_2_normalized"] == "+14155552671"
|
||||||
|
assert values["mobile_3_normalized"] is None
|
||||||
|
assert values["phone_normalized"] == "+97142345678"
|
||||||
|
|
||||||
|
|
||||||
|
def test_renormalizes_existing_persons_in_bounded_batches():
|
||||||
|
db = MagicMock()
|
||||||
|
rows = [
|
||||||
|
SimpleNamespace(
|
||||||
|
id=1,
|
||||||
|
mobile="050 123 4567",
|
||||||
|
mobile_2=None,
|
||||||
|
mobile_3=None,
|
||||||
|
phone="04 234 5678",
|
||||||
|
),
|
||||||
|
SimpleNamespace(
|
||||||
|
id=2,
|
||||||
|
mobile="+1 415 555 2671",
|
||||||
|
mobile_2=None,
|
||||||
|
mobile_3=None,
|
||||||
|
phone=None,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
all_rows = (
|
||||||
|
db.query.return_value.filter.return_value.order_by.return_value.limit.return_value.all
|
||||||
|
)
|
||||||
|
all_rows.side_effect = [rows, []]
|
||||||
|
|
||||||
|
count = renormalize_business_person_phones(
|
||||||
|
db,
|
||||||
|
business_id=8,
|
||||||
|
default_region="AE",
|
||||||
|
batch_size=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert count == 2
|
||||||
|
mappings = db.bulk_update_mappings.call_args.args[1]
|
||||||
|
assert mappings[0]["mobile_normalized"] == "+971501234567"
|
||||||
|
assert mappings[0]["phone_normalized"] == "+97142345678"
|
||||||
|
assert mappings[1]["mobile_normalized"] == "+14155552671"
|
||||||
|
|
||||||
|
|
||||||
|
def test_person_orm_hook_populates_indexed_phone_identity():
|
||||||
|
from adapters.db.models.person import Person, _sync_person_normalized_phones
|
||||||
|
|
||||||
|
person = Person(
|
||||||
|
business_id=8,
|
||||||
|
alias_name="مشتری",
|
||||||
|
person_types='["مشتری"]',
|
||||||
|
mobile="۰۹۱۷۱۰۰۶۲۱۹",
|
||||||
|
)
|
||||||
|
connection = MagicMock()
|
||||||
|
connection.execute.return_value.scalar_one_or_none.return_value = "IR"
|
||||||
|
|
||||||
|
_sync_person_normalized_phones(None, connection, person)
|
||||||
|
|
||||||
|
assert person.mobile_normalized == "+989171006219"
|
||||||
|
connection.execute.assert_called_once()
|
||||||
|
|
@ -351,6 +351,7 @@ class BusinessResponse {
|
||||||
final String? registrationNumber;
|
final String? registrationNumber;
|
||||||
final String? economicId;
|
final String? economicId;
|
||||||
final String? country;
|
final String? country;
|
||||||
|
final String defaultPhoneRegion;
|
||||||
final String? province;
|
final String? province;
|
||||||
final String? city;
|
final String? city;
|
||||||
final String? postalCode;
|
final String? postalCode;
|
||||||
|
|
@ -434,6 +435,7 @@ class BusinessResponse {
|
||||||
this.registrationNumber,
|
this.registrationNumber,
|
||||||
this.economicId,
|
this.economicId,
|
||||||
this.country,
|
this.country,
|
||||||
|
this.defaultPhoneRegion = 'IR',
|
||||||
this.province,
|
this.province,
|
||||||
this.city,
|
this.city,
|
||||||
this.postalCode,
|
this.postalCode,
|
||||||
|
|
@ -524,6 +526,8 @@ class BusinessResponse {
|
||||||
registrationNumber: json['registration_number'],
|
registrationNumber: json['registration_number'],
|
||||||
economicId: json['economic_id'],
|
economicId: json['economic_id'],
|
||||||
country: json['country'],
|
country: json['country'],
|
||||||
|
defaultPhoneRegion:
|
||||||
|
(json['default_phone_region'] as String?)?.toUpperCase() ?? 'IR',
|
||||||
province: json['province'],
|
province: json['province'],
|
||||||
city: json['city'],
|
city: json['city'],
|
||||||
postalCode: json['postal_code'],
|
postalCode: json['postal_code'],
|
||||||
|
|
|
||||||
|
|
@ -27,7 +27,6 @@ class BusinessInfoSettingsPage extends StatefulWidget {
|
||||||
@override
|
@override
|
||||||
State<BusinessInfoSettingsPage> createState() => _BusinessInfoSettingsPageState();
|
State<BusinessInfoSettingsPage> createState() => _BusinessInfoSettingsPageState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
final _formKey = GlobalKey<FormState>();
|
final _formKey = GlobalKey<FormState>();
|
||||||
|
|
||||||
|
|
@ -46,6 +45,7 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
final _registrationNumberController = TextEditingController();
|
final _registrationNumberController = TextEditingController();
|
||||||
final _economicIdController = TextEditingController();
|
final _economicIdController = TextEditingController();
|
||||||
final _countryController = TextEditingController();
|
final _countryController = TextEditingController();
|
||||||
|
final _defaultPhoneRegionController = TextEditingController(text: 'IR');
|
||||||
final _provinceController = TextEditingController();
|
final _provinceController = TextEditingController();
|
||||||
final _cityController = TextEditingController();
|
final _cityController = TextEditingController();
|
||||||
final _displayTimezoneController = TextEditingController();
|
final _displayTimezoneController = TextEditingController();
|
||||||
|
|
@ -141,6 +141,7 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
_registrationNumberController.dispose();
|
_registrationNumberController.dispose();
|
||||||
_economicIdController.dispose();
|
_economicIdController.dispose();
|
||||||
_countryController.dispose();
|
_countryController.dispose();
|
||||||
|
_defaultPhoneRegionController.dispose();
|
||||||
_provinceController.dispose();
|
_provinceController.dispose();
|
||||||
_cityController.dispose();
|
_cityController.dispose();
|
||||||
_displayTimezoneController.dispose();
|
_displayTimezoneController.dispose();
|
||||||
|
|
@ -189,6 +190,7 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
_registrationNumberController.text = resp.registrationNumber ?? '';
|
_registrationNumberController.text = resp.registrationNumber ?? '';
|
||||||
_economicIdController.text = resp.economicId ?? '';
|
_economicIdController.text = resp.economicId ?? '';
|
||||||
_countryController.text = resp.country ?? '';
|
_countryController.text = resp.country ?? '';
|
||||||
|
_defaultPhoneRegionController.text = resp.defaultPhoneRegion;
|
||||||
_provinceController.text = resp.province ?? '';
|
_provinceController.text = resp.province ?? '';
|
||||||
_cityController.text = resp.city ?? '';
|
_cityController.text = resp.city ?? '';
|
||||||
_displayTimezoneController.text = resp.displayTimezone ?? '';
|
_displayTimezoneController.text = resp.displayTimezone ?? '';
|
||||||
|
|
@ -325,6 +327,10 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
if ((orig.economicId ?? '') != eco) payload['economic_id'] = eco.isEmpty ? null : eco;
|
if ((orig.economicId ?? '') != eco) payload['economic_id'] = eco.isEmpty ? null : eco;
|
||||||
final country = _countryController.text.trim();
|
final country = _countryController.text.trim();
|
||||||
if ((orig.country ?? '') != country) payload['country'] = country.isEmpty ? null : country;
|
if ((orig.country ?? '') != country) payload['country'] = country.isEmpty ? null : country;
|
||||||
|
final phoneRegion = _defaultPhoneRegionController.text.trim().toUpperCase();
|
||||||
|
if (orig.defaultPhoneRegion != phoneRegion) {
|
||||||
|
payload['default_phone_region'] = phoneRegion;
|
||||||
|
}
|
||||||
final province = _provinceController.text.trim();
|
final province = _provinceController.text.trim();
|
||||||
if ((orig.province ?? '') != province) payload['province'] = province.isEmpty ? null : province;
|
if ((orig.province ?? '') != province) payload['province'] = province.isEmpty ? null : province;
|
||||||
final city = _cityController.text.trim();
|
final city = _cityController.text.trim();
|
||||||
|
|
@ -1131,6 +1137,25 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
|
TextFormField(
|
||||||
|
controller: _defaultPhoneRegionController,
|
||||||
|
textCapitalization: TextCapitalization.characters,
|
||||||
|
maxLength: 2,
|
||||||
|
decoration: const InputDecoration(
|
||||||
|
labelText: 'منطقه پیشفرض شمارههای محلی',
|
||||||
|
hintText: 'IR',
|
||||||
|
helperText: 'کد دوحرفی کشور مانند IR، AE، TR یا US؛ شمارههای دارای + مستقل از این تنظیم هستند.',
|
||||||
|
counterText: '',
|
||||||
|
),
|
||||||
|
validator: (value) {
|
||||||
|
final region = (value ?? '').trim();
|
||||||
|
if (!RegExp(r'^[A-Za-z]{2}$').hasMatch(region)) {
|
||||||
|
return 'کد دوحرفی معتبر کشور را وارد کنید';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
_buildTextField(controller: _cityController, label: t.city),
|
_buildTextField(controller: _cityController, label: t.city),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
_buildTextField(
|
_buildTextField(
|
||||||
|
|
@ -2307,5 +2332,3 @@ class _BusinessInfoSettingsPageState extends State<BusinessInfoSettingsPage> {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,19 +24,27 @@ String _collapseCustomerName(String value) => value
|
||||||
.where((part) => part.isNotEmpty)
|
.where((part) => part.isNotEmpty)
|
||||||
.join(' ');
|
.join(' ');
|
||||||
|
|
||||||
String? _canonicalIranianMobile(String value) {
|
String? _canonicalPhoneCandidate(String value) {
|
||||||
|
final normalized = toEnglishDigits(value).trim();
|
||||||
final digits = toEnglishDigits(value).replaceAll(RegExp(r'\D'), '');
|
final digits = toEnglishDigits(value).replaceAll(RegExp(r'\D'), '');
|
||||||
|
if (normalized.startsWith('+')) {
|
||||||
|
return digits.length >= 8 && digits.length <= 15 ? '+$digits' : null;
|
||||||
|
}
|
||||||
|
if (normalized.startsWith('00')) {
|
||||||
|
final international = digits.substring(2);
|
||||||
|
return international.length >= 8 && international.length <= 15
|
||||||
|
? '+$international'
|
||||||
|
: null;
|
||||||
|
}
|
||||||
late final String canonical;
|
late final String canonical;
|
||||||
if (digits.startsWith('0098') && digits.length == 14) {
|
if (digits.startsWith('98') && digits.length == 12) {
|
||||||
canonical = '0${digits.substring(4)}';
|
|
||||||
} else if (digits.startsWith('98') && digits.length == 12) {
|
|
||||||
canonical = '0${digits.substring(2)}';
|
canonical = '0${digits.substring(2)}';
|
||||||
} else if (digits.startsWith('09') && digits.length == 11) {
|
} else if (digits.startsWith('09') && digits.length == 11) {
|
||||||
canonical = digits;
|
canonical = digits;
|
||||||
} else if (digits.startsWith('9') && digits.length == 10) {
|
} else if (digits.startsWith('9') && digits.length == 10) {
|
||||||
canonical = '0$digits';
|
canonical = '0$digits';
|
||||||
} else {
|
} else {
|
||||||
return null;
|
return digits.length >= 7 && digits.length <= 15 ? digits : null;
|
||||||
}
|
}
|
||||||
return RegExp(r'^09\d{9}$').hasMatch(canonical) ? canonical : null;
|
return RegExp(r'^09\d{9}$').hasMatch(canonical) ? canonical : null;
|
||||||
}
|
}
|
||||||
|
|
@ -45,9 +53,7 @@ CustomerQuickEntry? parseCustomerQuickEntry(String rawInput) {
|
||||||
final input = toEnglishDigits(rawInput).trim();
|
final input = toEnglishDigits(rawInput).trim();
|
||||||
if (input.isEmpty) return null;
|
if (input.isEmpty) return null;
|
||||||
|
|
||||||
final mobilePattern = RegExp(
|
final mobilePattern = RegExp(r'(?:(?:\+|00)?\d)(?:[\s\-\(\)]*\d){6,14}');
|
||||||
r'(?:(?:\+98|0098|98)9|0?9)(?:[\s\-\(\)]?\d){9}',
|
|
||||||
);
|
|
||||||
final matches = mobilePattern.allMatches(input).where((match) {
|
final matches = mobilePattern.allMatches(input).where((match) {
|
||||||
final before = match.start > 0 ? input[match.start - 1] : '';
|
final before = match.start > 0 ? input[match.start - 1] : '';
|
||||||
final after = match.end < input.length ? input[match.end] : '';
|
final after = match.end < input.length ? input[match.end] : '';
|
||||||
|
|
@ -63,7 +69,7 @@ CustomerQuickEntry? parseCustomerQuickEntry(String rawInput) {
|
||||||
}
|
}
|
||||||
|
|
||||||
final rawMobile = matches.single.group(0)!;
|
final rawMobile = matches.single.group(0)!;
|
||||||
final mobile = _canonicalIranianMobile(rawMobile);
|
final mobile = _canonicalPhoneCandidate(rawMobile);
|
||||||
if (mobile == null) return null;
|
if (mobile == null) return null;
|
||||||
final alias = _collapseCustomerName(
|
final alias = _collapseCustomerName(
|
||||||
input.replaceRange(matches.single.start, matches.single.end, ' '),
|
input.replaceRange(matches.single.start, matches.single.end, ' '),
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ void main() {
|
||||||
|
|
||||||
test('extracts a trailing international mobile', () {
|
test('extracts a trailing international mobile', () {
|
||||||
final entry = parseCustomerQuickEntry('زهرا سادات موسوی +989121234567');
|
final entry = parseCustomerQuickEntry('زهرا سادات موسوی +989121234567');
|
||||||
expect(entry?.mobile, '09121234567');
|
expect(entry?.mobile, '+989121234567');
|
||||||
expect(entry?.aliasName, 'زهرا سادات موسوی');
|
expect(entry?.aliasName, 'زهرا سادات موسوی');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -21,6 +21,18 @@ void main() {
|
||||||
expect(entry?.aliasName, isNull);
|
expect(entry?.aliasName, isNull);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('keeps an international E164 mobile for server resolution', () {
|
||||||
|
final entry = parseCustomerQuickEntry('John Smith +1 (415) 555-2671');
|
||||||
|
expect(entry?.mobile, '+14155552671');
|
||||||
|
expect(entry?.aliasName, 'John Smith');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('passes a local foreign mobile for business-region resolution', () {
|
||||||
|
final entry = parseCustomerQuickEntry('050 123 4567 Al Zahra');
|
||||||
|
expect(entry?.mobile, '0501234567');
|
||||||
|
expect(entry?.aliasName, 'Al Zahra');
|
||||||
|
});
|
||||||
|
|
||||||
test('accepts a name-only entry and normalizes Persian letters', () {
|
test('accepts a name-only entry and normalizes Persian letters', () {
|
||||||
final entry = parseCustomerQuickEntry(' علي رضايي ');
|
final entry = parseCustomerQuickEntry(' علي رضايي ');
|
||||||
expect(entry?.mobile, isNull);
|
expect(entry?.mobile, isNull);
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue