Plugin Directory

Changeset 3757421


Ignore:
Timestamp:
10/20/2026 08:19:38 PM (5 weeks ago)
Author:
nabzbusiness
Message:

Release Nabz Lite 1.5.17; source 3ab033f3eb196d93b37d69c3cb5c5d7e65af781f; ZIP SHA-256 3bdd4b473f1fd64a469666463afb001bbea85237895e3d44045b0305c4261ec1

Location:
nabz-lite
Files:
18 added
60 edited
1 copied

Legend:

Unmodified
Added
Removed
  • nabz-lite/tags/1.5.17/CHANGELOG.md

    r3750712 r3757421  
    44[Semantic Versioning](https://semver.org/) شماره‌گذاری شده‌اند.
    55
     6## [1.5.17] - 2026-10-20
     7
     8- همگام‌سازی آمار ارسال موفق، کلیک و زمان آخرین کلیک با API و دیتابیس مرکزی موجود نبض برای سایت‌های متصل، در لایت و پریمیوم؛ شامل سوابق قبلی و ارسال‌های پنل شخصی در سایت دارای حساب نبض.
     9- اجرای دسته‌ای در زمان‌بند اختصاصی، checkpoint پایدار، replay یکسان پس از پاسخ نامطمئن و حذف درخواست‌های بدون تغییر؛ بدون انتقال شماره، IP، مرورگر، متن یا مقصد پیام.
     10- تجمیع چند لینک یک پیام برای حفظ شمارش یکتا و CTR، و اسکن دوره‌ای برای کلیک‌های تازه روی پیام‌های قدیمی؛ تست SQL واقعی و HTTP با شبیه‌ساز Postman.
     11
     12## [1.5.16] - 2026-10-20
     13
     14- پایان نشست مدیریتی حساب، توکن مستقل فروشگاه، موجودی کیف پول و صف پیام‌ها را پاک نمی‌کند؛ وضعیت ارسال با API و همان توکن قبلی بررسی می‌شود.
     15- شارژ کیف پول همچنان نشست معتبر می‌خواهد؛ ورود دوباره برای شارژ، اتصال ارسال را قطع نمی‌کند. خروج عمدی، تعویض حساب و لغو واقعی توکن همچنان ارسال حساب قبلی را متوقف می‌کنند.
     16- آزمون HTTP واقعی با شبیه‌ساز محلی برای نشست منقضی، لغو توکن و خطای موقت، و رگرسیون فرم ورود و شارژ اضافه شد.
     17
     18## [1.5.15] - 2026-10-20
     19
     20- رفع توقف محاسبات روی نصب‌های دارای جدول MyISAM/Aria: تبدیل جدول مشتق‌شدهٔ RFM به InnoDB زیر قفل محاسبه و پیش از خواندن سفارش‌ها؛ تمام رکوردهای قبلی حفظ می‌شوند.
     21- جدول تازهٔ RFM صریحاً با InnoDB ساخته می‌شود؛ شکست تبدیل، snapshot قبلی را حفظ و علت قابل‌اقدام را در گزارش زمان‌بند ثبت می‌کند.
     22- آزمون واقعی تبدیل موتور، حفظ داده، شکست ALTER، بازیابی و انتشار تراکنشی در محیط محلی اضافه شد.
     23
     24## [1.5.14] - 2026-10-20
     25
     26- اجرای صف و محاسبات با زمان‌بند اختصاصی روی init و ادامهٔ غیرهم‌زمان، مستقل از فعال‌بودن WP-Cron.
     27- انتقال رویدادهای قبلی نبض به صف پایدار، قفل اجرای هم‌زمان و تلاش مجدد مستقل برای هر کار.
     28- اجرای محاسبهٔ دستی از همان صف و اعلام خطای واقعی در صورت ناموفق‌بودن ثبت کار.
     29
     30## [1.5.13] - 2026-10-18
     31
     32- افزودن کاوه‌نگار، SMS.ir و قاصدک برای ارسال متن و الگوی تأییدشده و OTP از پنل شخصی.
     33- اعتبارسنجی نام و مقدار متغیرهای کاوه‌نگار، رسید هر پنل و حفظ صف مستقل هنگام خروج از حساب نبض.
     34
     35## [1.5.12] - 2026-10-18
     36
     37- پشتیبانی از پنل شخصی ملی‌پیامک و فراز (ارسال متن، الگو و کد ورود) بدون حساب یا کیف پول نبض.
     38- نگهداری رمزگذاری‌شدهٔ کلید پنل و جلوگیری از ارسال دوباره پس از پاسخ نامطمئن.
     39- اصلاح ساختار بستهٔ راست‌چین، کاور شیشه‌ای و مسیر ثابت اینفوگرافی.
     40
    641## [Unreleased]
     42
     43## [1.5.11] - 2026-10-17
     44
     45- موجودی کیف پول کش‌بک درست پیش از ثبت checkout کلاسیک و به‌روزرسانی draft در Checkout Blocks دوباره خوانده می‌شود؛ اگر موجودی هم‌زمان تغییر کند، تخفیف و مبلغ سفارش با موجودی واقعی هماهنگ می‌مانند.
     46- در صورت شکست رزرو کش‌بک، کد خطا، مبلغ درخواستی، موجودی موجود، کاربر و سفارش در لاگ ووکامرس ثبت می‌شوند تا بررسی اختلاف‌های checkout قابل اتکا باشد.
     47- تست یکپارچهٔ checkout هم‌زمان به بستهٔ منبع اضافه شد.
    748
    849## [1.5.10] - 2026-10-16
  • nabz-lite/tags/1.5.17/assets/css/admin.css

    r3737690 r3757421  
    59485948.nbz-account-logout-modal__actions { display: flex; align-items: center; justify-content: flex-start; gap: 10px; margin-top: 18px; }
    59495949.nbz-account-logout-modal__actions .button-primary { display: inline-flex; align-items: center; }
     5950
     5951/* Customer-owned SMS gateway settings. */
     5952.nabz-gateway-profile { border:1px solid var(--ss-border,#dce5df); border-radius:12px; padding:16px; margin-top:16px; }
     5953.nabz-gateway-profile summary { cursor:pointer; padding:6px 0; }
     5954.nabz-gateway-fields { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr)); gap:16px; margin-block:16px; }
     5955.nabz-gateway-fields label { display:flex; flex-direction:column; gap:8px; }
     5956.nabz-gateway-fields input { width:100%; max-width:100%; }
     5957.nabz-gateway-pattern { padding:10px 0; border-top:1px solid var(--ss-border,#dce5df); }
     5958.nabz-gateway-copy { line-height:1.9; padding:12px; background:#f4f8f5; border-radius:8px; overflow-wrap:anywhere; }
  • nabz-lite/tags/1.5.17/assets/js/account-auth.js

    r3737123 r3757421  
    178178        var authenticated = !!state.authenticated;
    179179        card.setAttribute('data-authenticated', authenticated ? '1' : '0');
    180         if (login) login.hidden = authenticated;
     180        if (login) login.hidden = authenticated && !state.reauth_required;
     181        var reauthHint = card.querySelector('[data-nbz-account-reauth]');
     182        if (reauthHint) reauthHint.hidden = !state.reauth_required;
    181183        if (summary) summary.hidden = !authenticated;
    182184        if (details) details.hidden = !authenticated;
    … …  
    291293                    }
    292294                } else {
     295                    if (result && result.data && result.data.state) applyState(result.data.state);
    293296                    setMessage(summaryStatus, responseMessage(result, 'به‌روزرسانی وضعیت ناموفق بود.'), 'error');
    294297                }
    … …  
    304307    });
    305308
     309    document.addEventListener('nbz:account-state', function (event) {
     310        applyState(event.detail);
     311        if (event.detail && event.detail.reauth_required && mobileInput) mobileInput.focus();
     312    });
     313
    306314    if (card.getAttribute('data-authenticated') === '1') {
    307315        request('nbz_account_context', {}).then(function (result) {
    308             if (result && result.success) applyState(result.data && result.data.state);
     316            if (result && result.data && result.data.state) applyState(result.data.state);
    309317        });
    310318    }
    … …  
    315323        if (event.persisted && card.getAttribute('data-authenticated') === '1') {
    316324            request('nbz_account_context', {}).then(function (result) {
    317                 if (result && result.success) applyState(result.data && result.data.state);
     325                if (result && result.data && result.data.state) applyState(result.data.state);
    318326            });
    319327        }
  • nabz-lite/tags/1.5.17/assets/js/wallet-topup.js

    r3737123 r3757421  
    7878        opener.focus();
    7979    }
     80    function renewSession(result) {
     81        if (!result || !result.data || result.data.code !== 'account_reauth_required') return false;
     82        busy(false);
     83        close();
     84        document.dispatchEvent(new CustomEvent('nbz:account-state', { detail: result.data.state }));
     85        return true;
     86    }
    8087    opener.addEventListener('click', function () {
    8188        modal.hidden = false;
    … …  
    9299        request('nbz_account_checkout_options', {}).then(function (result) {
    93100            if (current !== revision) return;
     101            if (renewSession(result)) return;
    94102            if (!result.success) throw new Error((result.data && result.data.msg) || 'دریافت اطلاعات شارژ ممکن نشد.');
    95103            var options = result.data || {};
    … …  
    134142        message('در حال ساخت فاکتور…');
    135143        request('nbz_account_create_invoice', { kind: 'sms_credit', amount_irr: amount * 10, request_id: requestId }).then(function (result) {
     144            if (renewSession(result)) return;
    136145            if (!result.success || !result.data || !result.data.invoice_url) {
    137146                throw new Error((result.data && result.data.msg) || 'ساخت فاکتور ممکن نشد.');
  • nabz-lite/tags/1.5.17/build-meta/manifest.json

    r3750712 r3757421  
    22    "schema": 1,
    33    "product": "nabz",
    4     "version": "1.5.10",
     4    "version": "1.5.17",
    55    "flavor": "source",
    6     "source_date_epoch": 1792165464,
     6    "source_date_epoch": 1792526641,
    77    "requires": {
    88        "php": ">=7.4",
    … …  
    1414    "files": {
    1515        "CHANGELOG.md": {
    16             "sha256": "11e73183b59824d959be742e23d8f9c74d33bde6e6594f11774b79b721ed35de",
    17             "bytes": 44033
     16            "sha256": "a6c1ec5671a7aad323f7e48b70a68a6e5b39554fc717f7f63876a04672c7b522",
     17            "bytes": 48455
    1818        },
    1919        "LICENSE": {
    … …  
    3030        },
    3131        "assets/css/admin.css": {
    32             "sha256": "6b3a98e3f82b059256417d06affd886b3cdf02774588357def7bae965bbd619b",
    33             "bytes": 147275
     32            "sha256": "dd2fe2601f75a910bfd555218aaa07113e25c2929b97c453148fad1e83a44e0e",
     33            "bytes": 147982
    3434        },
    3535        "assets/css/cashback.css": {
    … …  
    178178        },
    179179        "assets/js/account-auth.js": {
    180             "sha256": "dd7a2783c591df9a8909bf4718d6fb41fee51d74ce34a8848780c0db771e7695",
    181             "bytes": 19908
     180            "sha256": "7e846cd3641b17b99a60cae3da5ee4275bc35817177487685716ec3ce84d8087",
     181            "bytes": 20388
    182182        },
    183183        "assets/js/admin-lite.js": {
    … …  
    250250        },
    251251        "assets/js/wallet-topup.js": {
    252             "sha256": "2903be9ec4595823f27ce1bc28e5bd4efeb77f2c539ec7e1c42d1894947f4712",
    253             "bytes": 7992
     252            "sha256": "4d5d0aa12018eb83fc8257bb6fde6d7f02ce6b7f6f4195e3b3ad2f9e6b15a79f",
     253            "bytes": 8387
    254254        },
    255255        "build-meta/sbom.spdx.json": {
    256             "sha256": "f8832246eae88d35880de89bb20bc8adbaf4e88081b9e228e2873b0a8106b490",
     256            "sha256": "fe232fe419ee9adcd82afb88ba1c539fcb08aa0e6854d0754cdc7689a1605227",
    257257            "bytes": 2092
    258258        },
    … …  
    262262        },
    263263        "nabz.php": {
    264             "sha256": "67264f59f16fb7154de3d5d5b4a8e82d2628476ba9fb7f937e64d18b12574b9c",
     264            "sha256": "63ac5b9f015bf508d98290f0bc114e94985a9b79f69d343f0bedb1cc6858539b",
    265265            "bytes": 2921
    266266        },
    267267        "readme.txt": {
    268             "sha256": "8b4c53a6e9b7c0bf6c7f03d9dd4768cfcd6b0e21b3ae27924516ab42dbdc77f6",
    269             "bytes": 18537
     268            "sha256": "bac6d910428e6db2a0e01444f777d37d26b2478ade6fda259d508c8c4a2a45b3",
     269            "bytes": 20533
    270270        },
    271271        "src/Admin/AccountGate.php": {
    272             "sha256": "0142b3044be9015970915ed64715ef2b600b94ddd95f1a78fbb9bda386565298",
    273             "bytes": 4344
     272            "sha256": "0bb1f0157532d669a2daefc8e2804438db10aa16ed8c9098d312d2073f8eb5c3",
     273            "bytes": 4681
    274274        },
    275275        "src/Admin/AdminRecipients.php": {
    … …  
    278278        },
    279279        "src/Admin/Menu.php": {
    280             "sha256": "7f359143c42539bfd39bbae71428fb63cb8185960325227aac92d15c8edde7c3",
    281             "bytes": 18744
     280            "sha256": "95cf7c57c293e632fdaad2538985a31c9dba1512b043ba7a4e3f0eeca34f5bb5",
     281            "bytes": 18787
    282282        },
    283283        "src/Admin/Onboarding.php": {
    … …  
    294294        },
    295295        "src/Admin/Pages/CashbackPage.php": {
    296             "sha256": "be332ab7dff5594046ab5b8e3e8641fa5c5b1183602400d7a66ad35d6a7c0f77",
    297             "bytes": 42278
     296            "sha256": "792305264d3e57c27826d70a968bf10d8b9437595d547a2576de74beb7159d56",
     297            "bytes": 42318
    298298        },
    299299        "src/Admin/Pages/CustomersPage.php": {
    300             "sha256": "eb5f1c1df867fc6f4d8b166a84f76098ecdb0e445ff37f6651209b2bdbe9f4cf",
    301             "bytes": 30772
     300            "sha256": "2787adf5e117d014d7fd55849fe7de94471189974e7209adbb6c40f358b4604f",
     301            "bytes": 30747
    302302        },
    303303        "src/Admin/Pages/FreeMessagesPage.php": {
    304             "sha256": "05968081a38f835c072ddaebf901562693d0a20c79c0c2c1f20ac2fad81700dc",
    305             "bytes": 17037
     304            "sha256": "376949e30ab3082c7374ca22d757b6afbb1d0942aa24cc6721a94a21cd876400",
     305            "bytes": 17049
    306306        },
    307307        "src/Admin/Pages/LicensePage.php": {
    308             "sha256": "6f50dd6df56fa92988787e47b3a0c3a818adb51d3debc4141358cad6201ba75e",
    309             "bytes": 32546
     308            "sha256": "f81f403de1f363c3e5783ad09d8e4cd2c94361650af7335d3a71372f4f317bf8",
     309            "bytes": 33029
    310310        },
    311311        "src/Admin/Pages/LogsPage.php": {
    … …  
    337337            "bytes": 5637
    338338        },
     339        "src/Admin/SmsGatewayForm.php": {
     340            "sha256": "1fcb1426c8984c460931ef60b2e2f1efee37ad124dcfa9c5c3574866a5bfd52c",
     341            "bytes": 9356
     342        },
    339343        "src/Admin/Views/AnalyticsView.php": {
    340344            "sha256": "1ff8692dbdc69d5699a71f6d7c69f50ef3baabee67aa93a3c68cef964805a5c7",
    … …  
    358362        },
    359363        "src/Admin/Views/MessengersView.php": {
    360             "sha256": "3f19d0ef1c351570351b0a965f241ec9f983f83411d5c27f0ef95678f8ade1a9",
    361             "bytes": 33646
     364            "sha256": "72aac06b011c976fac56de892b541a67cc4016e185abca1db10766b1255ae8f5",
     365            "bytes": 33791
    362366        },
    363367        "src/Admin/Views/SmsLoginView.php": {
    … …  
    389393            "bytes": 2779
    390394        },
     395        "src/Analytics/Sync.php": {
     396            "sha256": "d4972ee8b016b3b5fc560b770ef99c35295f3a345596403f31b4301608e2afac",
     397            "bytes": 7562
     398        },
    391399        "src/Api/CircuitBreaker.php": {
    392400            "sha256": "fda9f9a55680c2e8a9ced0edae533fb42f3c9cd346723808d7c01ce839e267f4",
    … …  
    394402        },
    395403        "src/Api/Client.php": {
    396             "sha256": "9e3d4ccb1bf4b22276bcf464c56f28e5da235157f87e84757c24c7046262ae29",
    397             "bytes": 34052
     404            "sha256": "79129f198e0f4c6c825236cd9dbafe53dd5e68a90ad28d36d2873edc7d50a275",
     405            "bytes": 35478
    398406        },
    399407        "src/Auth/BusinessAccount.php": {
    400             "sha256": "74b77bfc07947797774b54279c4e977e44282688d0dbbc884bf00a1f6c1fdcdb",
    401             "bytes": 18414
     408            "sha256": "a14947aa6550139f280cb1021f90bf7964da91e48c984332621529595dc21f6f",
     409            "bytes": 20388
    402410        },
    403411        "src/Auth/CheckoutOtp.php": {
    … …  
    422430        },
    423431        "src/Cashback/Cart.php": {
    424             "sha256": "a66350f4964c894dde737075b205ccc7185884663f1f4204e1f996c6b226a60b",
    425             "bytes": 11352
     432            "sha256": "0e2e24260aa8d77da1b2d870b329f8715b735c9ee7bd4921636647fc63c5c038",
     433            "bytes": 14047
    426434        },
    427435        "src/Cashback/CashbackWidget.php": {
    … …  
    430438        },
    431439        "src/Cashback/Expiry.php": {
    432             "sha256": "7de7101676626b0d93a200139e91990175ef9709ee7f3fed05790d455d9c506f",
    433             "bytes": 3593
     440            "sha256": "ba828b54eb4818b4af3b57faab02eccb92f99cba72024819c4905e01fc9ff3cc",
     441            "bytes": 3846
    434442        },
    435443        "src/Cashback/Frontend.php": {
    … …  
    442450        },
    443451        "src/Cashback/Lifecycle.php": {
    444             "sha256": "de1b23515a88e6ff8611ca24ed613df637f61764c0046315c9c429d17331a803",
    445             "bytes": 25289
     452            "sha256": "b5f0585bc612fbdbf89d86105b1bfb0ab856f29971f541482bc1bcbdf026b39f",
     453            "bytes": 26036
    446454        },
    447455        "src/Cashback/Schema.php": {
    … …  
    474482        },
    475483        "src/Crm/RfmCalculator.php": {
    476             "sha256": "e0827e438269e85d39012c8009c1bfe0c7febd1bcc72bbe7e3359dcec7b33383",
    477             "bytes": 18186
     484            "sha256": "a496d3bfc202c07704934d488c1d2d163fde83eb93405f817b01c240bb4317c9",
     485            "bytes": 17813
    478486        },
    479487        "src/Crm/RfmRepository.php": {
    … …  
    486494        },
    487495        "src/Crm/Schema.php": {
    488             "sha256": "501e50914102ef028837018510aeb7100b7dd0244a29fe15b46f7a6881d1f1ff",
    489             "bytes": 2249
     496            "sha256": "798a4282b329f87393840a270a681270de1877583a622756167e871b69ddddda",
     497            "bytes": 3317
    490498        },
    491499        "src/Crm/Segments.php": {
    … …  
    530538        },
    531539        "src/Jobs/Dispatcher.php": {
    532             "sha256": "01c5a1306cfa140a7aa951f00bd2372235fd704ef1fe856d211160eb694391f8",
    533             "bytes": 12154
     540            "sha256": "4872191ccd834d83ced6e4c5af9c22be916ab6074db91c19486f1d778ff9921d",
     541            "bytes": 12494
    534542        },
    535543        "src/Jobs/JobManager.php": {
    536             "sha256": "929d75066aae036067f6ab0a2a3f12a572dbca0a5476d850d073688a66971b54",
    537             "bytes": 29362
     544            "sha256": "e10ba07e47061d30702dfda88357f486a447e8d8651ba2c897e7bcf361d5ee0c",
     545            "bytes": 34210
     546        },
     547        "src/Jobs/Scheduler.php": {
     548            "sha256": "d9cbdc38e706c0602c382fa1d813e2cb52e1a009a2fe6fe643486fe098c8ce64",
     549            "bytes": 10320
    538550        },
    539551        "src/Jobs/Schema.php": {
    … …  
    542554        },
    543555        "src/Jobs/Worker.php": {
    544             "sha256": "9db2c781cb3ea33b26d0900b223399dfa2def2d6306800ae3cb5133202bd3927",
    545             "bytes": 6827
     556            "sha256": "19aaf282917bad345bb509a57adb3ca83568a20936fe068ff582b9672a79ecef",
     557            "bytes": 6798
    546558        },
    547559        "src/Orders/DeliveryEstimate.php": {
    … …  
    558570        },
    559571        "src/Plugin.php": {
    560             "sha256": "1fdb58f60ddf3d9350d4b88ba98df276ad0784a8d7e923fd06d9846a5f825969",
    561             "bytes": 28750
     572            "sha256": "9126d87a30c6cd4d1029a549c8427caaf2bb5a4998b0368e8abf0b125453aebf",
     573            "bytes": 23100
    562574        },
    563575        "src/Privacy.php": {
    564             "sha256": "af5384ca545065905db4d49e01cbc31c68c5839c7c08fa4fd0aada35a25c67ad",
    565             "bytes": 14599
     576            "sha256": "cb419fa4772e8b50531599c2974bffb0fd8c911aac1cadaa690e3c1390133faf",
     577            "bytes": 15332
    566578        },
    567579        "src/Product/Features.php": {
    … …  
    574586        },
    575587        "src/Settings/Options.php": {
    576             "sha256": "17b4547c038be9f5ec22f27d37de6118bdc2efd7821e7637ad34c3e96a6443fc",
    577             "bytes": 23952
     588            "sha256": "ad50ae08ecefb19213a041d7ec2ac37a800a6309852105f1c846cb5c9c2df6a3",
     589            "bytes": 24274
     590        },
     591        "src/Sms/ExternalGateway.php": {
     592            "sha256": "080334d5187a144388a34c563dd79313ef3a85a06d428280161593bc34a4d985",
     593            "bytes": 7557
     594        },
     595        "src/Sms/ExternalOtp.php": {
     596            "sha256": "719a9934aa54c22f5265b749d06e93a4dba725e5aff0b55c719f1fa392c3399e",
     597            "bytes": 5361
     598        },
     599        "src/Sms/GatewayAdapters.php": {
     600            "sha256": "7922fe394905997e09bb5feaf32cd58a35b442f8f87e53f678cf08879b184690",
     601            "bytes": 8458
     602        },
     603        "src/Sms/GatewaySettings.php": {
     604            "sha256": "5f2304b0afc715c131bfe6f0e19b4522575f2aadd4b60b0d6973355c6790f916",
     605            "bytes": 8647
     606        },
     607        "src/Sms/LocalTemplates.php": {
     608            "sha256": "fd2c7302ff541b448db45b67911424f858d74239b0b9897259475dac1e647c28",
     609            "bytes": 2857
    578610        },
    579611        "src/Sms/MessageGroups.php": {
    … …  
    582614        },
    583615        "src/Sms/Sender.php": {
    584             "sha256": "75c6e7362786978e38b1358c03652b35c0ff92f9d1e690fbe969f3222353b0e6",
    585             "bytes": 7794
     616            "sha256": "5557ccdfadc4cab18df989d59ff965eb5dea4831e8c48c6afc99ff5cdc3dd1ec",
     617            "bytes": 8445
     618        },
     619        "src/Sms/templates.json": {
     620            "sha256": "d42471824a08cb6b11dbe90ad07e7690d2f4efa064bab3b29b1190affd947708",
     621            "bytes": 17247
    586622        },
    587623        "src/Support/CouponCodes.php": {
    … …  
    602638        },
    603639        "src/Support/LogFormatter.php": {
    604             "sha256": "71aefed3bc776bddadfa5e98162a7bc67f6c8135d47fe60ab0009b9500902f1f",
    605             "bytes": 25923
     640            "sha256": "9648497f25fe2353c39e711fc103defbe7521f6cb81ba7741582ebb41a9377a8",
     641            "bytes": 26845
    606642        },
    607643        "src/Support/Logger.php": {
  • nabz-lite/tags/1.5.17/build-meta/sbom.spdx.json

    r3750712 r3757421  
    33    "dataLicense": "CC0-1.0",
    44    "SPDXID": "SPDXRef-DOCUMENT",
    5     "name": "nabz-1.5.10-source",
    6     "documentNamespace": "https://nabz.business/spdx/nabz/1.5.10/source",
     5    "name": "nabz-1.5.17-source",
     6    "documentNamespace": "https://nabz.business/spdx/nabz/1.5.17/source",
    77    "creationInfo": {
    8         "created": "2026-10-16T15:44:24Z",
     8        "created": "2026-10-20T20:04:01Z",
    99        "creators": [
    1010            "Organization: Nabz",
    … …  
    1616            "name": "nabz",
    1717            "SPDXID": "SPDXRef-Package-Nabz",
    18             "versionInfo": "1.5.10",
     18            "versionInfo": "1.5.17",
    1919            "downloadLocation": "NOASSERTION",
    2020            "filesAnalyzed": false,
  • nabz-lite/tags/1.5.17/nabz.php

    r3750712 r3757421  
    44 * Plugin URI:  https://nabz.business/
    55 * Description: ابزار رایگان افزایش فروش ووکامرس با مدیریت مشتریان، تحلیل فروش، کش‌بک، بازیابی سبد رهاشده و ورود پیامکی.
    6  * Version:     1.5.10
     6 * Version:     1.5.17
    77 * Author:      Ali Beheshti
    88 * Text Domain: nabz-lite
    … …  
    1616defined( 'ABSPATH' ) || exit;
    1717
    18 define( 'NABZ_VERSION', '1.5.10' );
     18define( 'NABZ_VERSION', '1.5.17' );
    1919define( 'NABZ_EDITION', 'lite' );
    2020define( 'NABZ_FILE', __FILE__ );
  • nabz-lite/tags/1.5.17/readme.txt

    r3750712 r3757421  
    66Requires PHP: 7.4
    77Requires Plugins: woocommerce
    8 Stable tag: 1.5.10
     8Stable tag: 1.5.17
    99License: GPLv2 or later
    1010License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    5151حساب متصل برای همگام‌سازی وضعیت و موجودی، دریافت پیش‌نمایش پیام، ساخت فاکتور شارژ و دریافت گزارش ارسال با نبض ارتباط دارد. ارسال پیام شامل کانال، رویداد، شمارهٔ گیرنده، شناسهٔ جلوگیری از ارسال تکراری و حداقل اطلاعات لازم است؛ مانند نام مشتری یا فروشگاه، شماره و مبلغ سفارش، وضعیت پرداخت یا مرسوله، کد رهگیری و لینک مرتبط. نبض متن نهایی و اطلاعات لازم گیرنده را به ارائه‌دهندهٔ ارسال می‌دهد.
    5252
     53پس از اتصال حساب، آمار ارسال موفق و کلیک به تفکیک نوع پیام نیز خودکار با نبض همگام می‌شود: شناسهٔ هش‌شدهٔ پیام، نوع پیام، تعداد کلیک و زمان ارسال و اولین/آخرین کلیک. این همگام‌سازی شماره موبایل، نام مشتری، IP، مرورگر، متن پیام یا نشانی مقصد را ارسال نمی‌کند.
     54
    5355شارژ کیف پول با لینک یک‌بارمصرف به پرداخت حساب نبض منتقل می‌شود و به همان فروشگاه و حساب متقاضی مقید است. افزونه ممکن است برای اجرای صف، به همان نصب وردپرس درخواست داخلی بفرستد.
    5456
    … …  
    111113== Changelog ==
    112114
     115= 1.5.17 =
     116- همگام‌سازی خودکار و قابل‌بازیابی آمار ارسال و کلیک با دیتابیس مرکزی نبض، مستقل از WP-Cron و با انتقال سوابق موجود.
     117
     118= 1.5.16 =
     119- حفظ اتصال مستقل فروشگاه، موجودی و صف پیام‌ها هنگام پایان نشست مدیریتی حساب.
     120
     121= 1.5.15 =
     122- تبدیل داده‌محور جدول قدیمی RFM از MyISAM/Aria به InnoDB پیش از محاسبه، با حفظ رکوردهای قبلی و توقف امن در صورت نداشتن دسترسی.
     123- نمایش علت شکست و زمان تلاش مجدد کارهای زمان‌بند در گزارش‌ها.
     124
     125= 1.5.14 =
     126- اجرای صف و محاسبات با زمان‌بند اختصاصی روی init و ادامهٔ غیرهم‌زمان، مستقل از فعال‌بودن WP-Cron.
     127- انتقال رویدادهای قبلی نبض به صف پایدار، قفل اجرای هم‌زمان و تلاش مجدد مستقل برای هر کار.
     128- اجرای محاسبهٔ دستی از همان صف و اعلام خطای واقعی در صورت ناموفق‌بودن ثبت کار.
     129
     130= 1.5.13 =
     131- افزودن کاوه‌نگار، SMS.ir و قاصدک برای ارسال متن و الگوی تأییدشده و OTP از پنل شخصی.
     132- اعتبارسنجی نام و مقدار متغیرهای کاوه‌نگار، رسید هر پنل و حفظ صف مستقل هنگام خروج از حساب نبض.
     133
     134
    113135= 1.5.10 =
    114136* گزینه و ارسال اعلان سبد رهاشده برای مدیر حذف شد؛ پیام‌های قدیمی این اعلان در صف نیز ارسال نمی‌شوند.
  • nabz-lite/tags/1.5.17/src/Admin/AccountGate.php

    r3737123 r3757421  
    4949
    5050    /** Check account access before rendering forms or making API requests. */
    51     public static function page( string $title, string $icon, callable $renderer ): callable {
    52         return static function () use ( $title, $icon, $renderer ): void {
     51    public static function page( string $title, string $icon, callable $renderer, bool $allow_external_sms = true ): callable {
     52        return static function () use ( $title, $icon, $renderer, $allow_external_sms ): void {
    5353            if ( ! current_user_can( 'manage_options' ) ) {
    5454                return;
    5555            }
    56             if ( BusinessAccount::is_authenticated() ) {
     56            if ( BusinessAccount::is_authenticated() || ( $allow_external_sms && \Nabz\Sms\GatewaySettings::ready() ) ) {
    5757                $renderer();
    5858                return;
    … …  
    7777            <span class="nbz-account-gate__icon"><?php echo Icons::get( 'lock' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
    7878            <h2>لطفاً ابتدا وارد شوید</h2>
    79             <p>برای استفاده از این بخش، وارد حساب نبض شوید.</p>
     79            <p>برای استفاده از پیامک، در صفحهٔ اتصال و اعتبار پنل خود را تنظیم کنید یا وارد حساب نبض شوید.</p>
    8080            <a class="button button-primary" href="<?php echo esc_url( self::login_url() ); ?>">ورود به حساب نبض</a>
    8181        </section>
    … …  
    8686    public static function require_login(): void {
    8787        $can_manage = current_user_can( 'manage_options' );
    88         if ( $can_manage && BusinessAccount::is_authenticated() ) {
     88        $local_sms = strpos( current_filter(), 'nabz_messenger_' ) === false && \Nabz\Sms\GatewaySettings::ready();
     89        if ( $can_manage && ( BusinessAccount::is_authenticated() || $local_sms ) ) {
    8990            return;
    9091        }
  • nabz-lite/tags/1.5.17/src/Admin/Menu.php

    r3743205 r3757421  
    6060        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
    6161        ( new PetReporter() )->register();
     62        SmsGatewayForm::register();
    6263
    6364        if ( defined( 'NABZ_DEV' ) && NABZ_DEV ) {
    … …  
    169170            AccountGate::page( 'پیام‌رسان‌ها', 'chat', static function () use ( $messengers ): void {
    170171                PremiumPreview::render_page( Features::MESSENGERS, $messengers ? [ $messengers, 'render' ] : null );
    171             } )
     172            }, false )
    172173        );
    173174        add_submenu_page(
  • nabz-lite/tags/1.5.17/src/Admin/Pages/CashbackPage.php

    r3743205 r3757421  
    239239
    240240    private function render_sms( bool $cashback_enabled ): void {
    241         if ( ! \Nabz\Auth\BusinessAccount::is_authenticated() ) {
     241        if ( ! \Nabz\Auth\BusinessAccount::is_authenticated() && ! \Nabz\Sms\GatewaySettings::ready() ) {
    242242            \Nabz\Admin\AccountGate::render( true );
    243243            return;
  • nabz-lite/tags/1.5.17/src/Admin/Pages/CustomersPage.php

    r3750451 r3757421  
    3232        }
    3333        check_admin_referer( 'nabz_rfm_recompute' );
    34         if ( ! wp_next_scheduled( 'nabz_rfm_recompute' ) ) {
    35             $now = time();
    36             wp_schedule_single_event( $now, 'nabz_rfm_recompute' );
    37             if ( function_exists( 'spawn_cron' ) ) {
    38                 spawn_cron( $now );
    39             }
     34        if ( ! \Nabz\Plugin::schedule_rfm_refresh( 0 ) ) {
     35            wp_die( 'ثبت محاسبه در صف انجام نشد؛ دوباره تلاش کنید.', 'خطای صف نبض', [ 'response' => 503, 'back_link' => true ] );
    4036        }
    4137        wp_safe_redirect( add_query_arg( [
  • nabz-lite/tags/1.5.17/src/Admin/Pages/FreeMessagesPage.php

    r3750712 r3757421  
    3333
    3434        $previews = [];
    35         if ( (string) Options::get( 'installation_token', '' ) !== '' ) {
     35        if ( Options::delivery_connected() ) {
    3636            $response = $this->container->get( Client::class )->message_previews();
    3737            if ( ! empty( $response['ok'] ) && is_array( $response['body']['previews'] ?? null ) ) {
    … …  
    5050                            <?php echo wp_kses( HelpLink::get( 'message-types', 'مدیریت پیام‌ها' ), HelpLink::allowed_html() ); ?>
    5151                        </h1>
    52                         <p class="ss-header__subtitle">همهٔ رویدادهای پیام را ببینید و پیام‌های رایگان را مدیریت کنید. رویدادهای قفل‌شده با نبض پریمیوم فعال می‌شوند. هزینهٔ ارسال از کیف پول سرویس نبض کسر می‌شود.</p>
     52                        <p class="ss-header__subtitle">همهٔ رویدادهای پیام را ببینید و پیام‌های رایگان را مدیریت کنید. رویدادهای قفل‌شده با نبض پریمیوم فعال می‌شوند. هزینهٔ ارسال از پنل پیامکی انتخاب‌شده کسر می‌شود.</p>
    5353                    </div>
    5454                    <span class="ss-header__badge"><?php echo esc_html( number_format_i18n( count( $free_types ) ) ); ?> نوع پیام رایگان</span>
    … …  
    8282                            <?php $first = true; foreach ( $groups as $key => $group ) : ?>
    8383                                <div id="nbz-message-panel-<?php echo esc_attr( $key ); ?>" class="ss-tab-panel<?php echo $first ? ' is-active' : ''; ?>" data-tab-panel="<?php echo esc_attr( $key ); ?>" role="tabpanel" aria-labelledby="nbz-message-tab-<?php echo esc_attr( $key ); ?>">
    84                                     <?php if ( $key === 'cashback' ) : ?><p class="ss-field__hint">کش‌بک، کیف پول و پیامک‌های خودکار این بخش در لایت فعال‌اند؛ هزینهٔ ارسال از اعتبار حساب نبض کسر می‌شود.</p><?php endif; ?>
     84                                    <?php if ( $key === 'cashback' ) : ?><p class="ss-field__hint">کش‌بک، کیف پول و پیامک‌های خودکار این بخش در لایت فعال‌اند؛ هزینهٔ ارسال از اعتبار پنل انتخاب‌شده کسر می‌شود.</p><?php endif; ?>
    8585                                    <div class="ss-msg-grid">
    8686                                        <?php foreach ( $group['types'] as $type ) : ?>
    … …  
    154154            'order_tracking_auto_send' => ! empty( $_POST['order_tracking_auto_send'] ),
    155155        ], \Nabz\Settings\CartRecovery::posted_settings( $_POST, $enabled ) ) );
    156         if ( (string) Options::get( 'installation_token', '' ) !== '' ) {
     156        if ( ! \Nabz\Sms\GatewaySettings::external() && Options::delivery_connected() ) {
    157157            Options::set( 'last_heartbeat_attempt', 0 );
    158158            $this->container->get( Client::class )->announce();
  • nabz-lite/tags/1.5.17/src/Admin/Pages/LicensePage.php

    r3750451 r3757421  
    7272                        <?php echo wp_kses( \Nabz\Support\HelpLink::get( 'activate-license', 'اتصال و اعتبار' ), \Nabz\Support\HelpLink::allowed_html() ); ?>
    7373                    </h1>
    74                     <p class="ss-header__subtitle" data-nbz-page-subtitle><?php echo $account_authenticated ? 'در این صفحه وضعیت اتصال سرویس‌ها و کیف پول را می‌بینید.' : 'برای اتصال به حساب نبض با کد تأیید پیامکی وارد شوید.'; ?></p>
     74                    <p class="ss-header__subtitle" data-nbz-page-subtitle><?php echo $account_authenticated ? 'در این صفحه وضعیت اتصال سرویس‌ها و کیف پول را می‌بینید.' : 'پنل پیامکی خود را انتخاب کنید؛ برای استفاده از سرویس نبض، با کد تأیید وارد شوید.'; ?></p>
    7575                </div>
    7676            </div>
    … …  
    9797            <?php // phpcs:enable WordPress.Security.NonceVerification.Recommended ?>
    9898
     99            <?php \Nabz\Admin\SmsGatewayForm::render(); ?>
    99100            <div class="ss-card nbz-account-card nbz-account-status-card" data-nbz-account-card data-authenticated="<?php echo $account_authenticated ? '1' : '0'; ?>">
    100101                <div class="ss-card__header">
    … …  
    105106                            <?php echo wp_kses( \Nabz\Support\HelpLink::get( 'activate-license', 'شماره موبایل حساب نبض' ), \Nabz\Support\HelpLink::allowed_html() ); ?>
    106107                        </h2>
    107                         <p class="ss-card__desc" data-nbz-account-description><?php echo $account_authenticated ? 'وضعیت حساب و اتصال همین دامنه را اینجا ببینید.' : 'برای اتصال به حساب نبض با کد تأیید پیامکی وارد شوید.'; ?></p>
     108                        <p class="ss-card__desc" data-nbz-account-description><?php echo $account_authenticated ? 'وضعیت حساب و اتصال همین دامنه را اینجا ببینید.' : 'پنل پیامکی خود را انتخاب کنید؛ برای استفاده از سرویس نبض، با کد تأیید وارد شوید.'; ?></p>
    108109                    </div>
    109110                    <span class="ss-badge ss-badge--success" data-nbz-account-badge<?php echo $account_authenticated ? '' : ' hidden'; ?>><span class="ss-dot"></span> واردشده</span>
    … …  
    380381        $error_message = (string) ( ( $account['last_error'] ?? '' ) );
    381382        ?>
    382                 <div class="nbz-account-login" data-nbz-account-login<?php echo $authenticated ? ' hidden' : ''; ?>>
     383                <div class="nbz-account-login" data-nbz-account-login<?php echo $authenticated && empty( $account['reauth_required'] ) ? ' hidden' : ''; ?>>
     384                    <p class="ss-field__hint" data-nbz-account-reauth<?php echo empty( $account['reauth_required'] ) ? ' hidden' : ''; ?>>اتصال ارسال پیام برقرار است. برای شارژ کیف پول، ورود با کد تأیید را تازه کنید.</p>
    383385                    <form data-nbz-account-mobile-form novalidate>
    384386                        <div class="ss-field">
  • nabz-lite/tags/1.5.17/src/Admin/Views/MessengersView.php

    r3744674 r3757421  
    117117                                        <div class="nbz-msgr-account__track nbz-msgr-account__track--empty" aria-hidden="true"><i style="width:0%"></i></div>
    118118                                    </div>
     119                                    <?php if ( ! $sms_enabled || ! empty( $accounts ) ) : ?>
    119120                                    <div class="nbz-msgr-account__actions">
    120121                                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
    … …  
    128129                                        </form>
    129130                                    </div>
     131                                    <?php endif; ?>
    130132                                </article>
    131133                            <?php endif; ?>
  • nabz-lite/tags/1.5.17/src/Api/Client.php

    r3750451 r3757421  
    410410    }
    411411
    412     /** Customer login OTP uses the connected wallet in both editions. */
     412    /** Customer OTP uses the selected SMS service in both editions; Nabz account OTP stays central. */
    413413    public function otp_send( string $mobile, string $idempotency_key = '' ): array {
     414        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::request( $mobile ); }
    414415        $idempotency_key = $idempotency_key !== '' ? $idempotency_key : wp_generate_uuid4();
    415416        return $this->post( '/api/v1/plugin/otp/send',
    … …  
    419420
    420421    public function otp_retry( string $challenge_id, string $idempotency_key = '' ): array {
     422        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::retry( $challenge_id ); }
    421423        $idempotency_key = $idempotency_key !== '' ? $idempotency_key : wp_generate_uuid4();
    422424        return $this->post( '/api/v1/plugin/otp/retry',
    … …  
    427429    /** One storefront request: renew an expired challenge, never retry an uncertain send. */
    428430    public function otp_request( string $mobile, string $challenge_id = '' ): array {
     431        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::request( $mobile, $challenge_id ); }
    429432        if ( $challenge_id === '' ) {
    430433            return $this->otp_send( $mobile );
    … …  
    439442
    440443    public function otp_verify( string $challenge_id, string $code, string $mobile ): array {
     444        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::verify( $challenge_id, $code, $mobile ); }
    441445        return $this->post( '/api/v1/plugin/otp/verify',
    442446            array_merge( $this->connection_payload(), [
    … …  
    560564     */
    561565    public function send_event( string $message_type, string $customer_number, array $parameters, string $channel = 'sms', string $idempotency_key = '' ): array {
     566        if ( $channel === 'sms' && \Nabz\Sms\GatewaySettings::external() ) {
     567            return \Nabz\Sms\ExternalGateway::send( $message_type, $customer_number, $parameters, $idempotency_key );
     568        }
    562569        if ( ! $this->is_v1() ) {
    563570            return self::unsupported( 'ارسال متمرکز پیامک؛ بک‌اند قدیمی باید به نسخه v1 ارتقا پیدا کند' );
    … …  
    608615    }
    609616
     617    /** Send only non-personal analytics records; the token never enters the checkpoint. */
     618    public function analytics_sync( array $payload, string $idempotency_key ): array {
     619        return $this->post( '/api/v1/plugin/analytics/sync', array_merge( $payload, $this->connection_payload() ), 8.0,
     620            [ 'Idempotency-Key' => $idempotency_key ] );
     621    }
     622
     623    public function analytics_scope(): string {
     624        return hash( 'sha256', self::configured_api_base() . '|' . self::current_domain() . '|' . (int) Options::get( 'installation_account_id', 0 ) . '|' . (int) Options::get( 'account_user_id', 0 ) );
     625    }
     626
    610627    /**
    611628     * Pull the backend-side send log (message_logs) for this site. The backend
    … …  
    648665     */
    649666    public function message_previews(): array {
     667        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\LocalTemplates::previews(); }
    650668        if ( ! $this->is_v1() ) {
    651669            return self::unsupported( 'پیش‌نمایش متن متمرکز پیامک' );
  • nabz-lite/tags/1.5.17/src/Auth/BusinessAccount.php

    r3750451 r3757421  
    3838        $last_error = (string) ( Options::get( 'account_last_error', '' ) ?: Options::get( 'last_sync_error', '' ) );
    3939        return [
    40             'authenticated' => $phone !== '' && trim( (string) Options::get( 'account_session_cookie', '' ) ) !== '',
     40            'authenticated' => self::portal_authenticated() || Options::account_connected(),
     41            'reauth_required' => Options::account_connected() && ! self::portal_authenticated(),
    4142            'phone'         => $phone,
    4243            'phone_display' => $display_phone,
    … …  
    6061        $state = self::state();
    6162        return ! empty( $state['authenticated'] );
     63    }
     64
     65    private static function portal_authenticated(): bool {
     66        return trim( (string) Options::get( 'account_phone', '' ) ) !== ''
     67            && trim( (string) Options::get( 'account_session_cookie', '' ) ) !== ''
     68            && trim( (string) Options::get( 'account_csrf_token', '' ) ) !== '';
     69    }
     70
     71    /** A portal 401 is not revocation of the separately authenticated site credential. */
     72    private static function expire_portal_session(): void {
     73        Options::update( [ 'account_session_cookie' => '', 'account_csrf_token' => '' ] );
     74    }
     75
     76    private static function require_portal_login(): void {
     77        wp_send_json_error( [
     78            'code' => 'account_reauth_required',
     79            'msg' => Options::account_connected()
     80                ? 'برای شارژ کیف پول دوباره کد تأیید را وارد کنید. اتصال ارسال پیام تغییری نکرده است.'
     81                : 'ابتدا با کد تأیید وارد حساب نبض شوید.',
     82            'state' => self::state(),
     83        ], 401 );
    6284    }
    6385
    … …  
    161183                'msg'  => $this->provider_error( $response, 'خواندن وضعیت حساب از nabz.business ناموفق بود.' ),
    162184                'code' => 'context_failed',
     185                'state' => self::state(),
    163186            ], $this->http_status( $response ) );
    164187        }
    … …  
    168191    public function ajax_checkout_options(): void {
    169192        $this->authorize_ajax();
    170         if ( ! self::is_authenticated() ) {
    171             wp_send_json_error( [ 'msg' => 'ابتدا وارد حساب نبض شوید.' ], 401 );
     193        if ( ! self::portal_authenticated() ) {
     194            self::require_portal_login();
    172195        }
    173196        $response = $this->client->account_checkout_options(
    … …  
    177200        if ( ! $response['ok'] || ! is_array( $response['body'] ?? null ) ) {
    178201            if ( (int) ( $response['status'] ?? 0 ) === 401 ) {
    179                 self::clear();
     202                self::expire_portal_session();
     203                self::require_portal_login();
    180204            }
    181205            wp_send_json_error( [ 'msg' => $this->provider_error( $response, 'دریافت گزینه‌های خرید ممکن نشد.' ) ], $this->http_status( $response ) );
    … …  
    186210    public function ajax_create_invoice(): void {
    187211        $this->authorize_ajax();
    188         if ( ! self::is_authenticated() ) {
    189             wp_send_json_error( [ 'msg' => 'ابتدا وارد حساب نبض شوید.' ], 401 );
     212        if ( ! self::portal_authenticated() ) {
     213            self::require_portal_login();
    190214        }
    191215        $kind = isset( $_POST['kind'] ) ? sanitize_key( (string) wp_unslash( $_POST['kind'] ) ) : '';
    … …  
    214238        if ( ! $response['ok'] || ! is_array( $response['body'] ?? null ) ) {
    215239            if ( (int) ( $response['status'] ?? 0 ) === 401 ) {
    216                 self::clear();
     240                self::expire_portal_session();
     241                self::require_portal_login();
    217242            }
    218243            wp_send_json_error( [ 'msg' => $this->provider_error( $response, 'ساخت فاکتور ممکن نشد.' ) ], $this->http_status( $response ) );
    … …  
    267292        $csrf    = trim( (string) Options::get( 'account_csrf_token', '' ) );
    268293        if ( $session === '' || $csrf === '' ) {
     294            if ( Options::account_connected() ) {
     295                return $this->sync_connection();
     296            }
    269297            return [ 'ok' => false, 'status' => 401, 'body' => null, 'error' => 'not_authenticated' ];
    270298        }
    … …  
    272300        if ( ! $response['ok'] || ! is_array( $response['body'] ?? null ) ) {
    273301            if ( (int) ( $response['status'] ?? 0 ) === 401 ) {
    274                 self::clear();
     302                self::expire_portal_session();
     303                if ( Options::account_connected() ) {
     304                    return $this->sync_connection();
     305                }
    275306            }
    276307            Options::set( 'account_last_error', (string) ( $response['error'] ?? 'context_failed' ) );
    … …  
    320351    }
    321352
     353    /** Check the existing site token with the API; never create or renew a portal session. */
     354    private function sync_connection(): array {
     355        $response = array_merge( [ 'status' => 0, 'body' => null, 'error' => '' ], $this->client->announce() );
     356        Options::set( 'account_last_error', empty( $response['ok'] ) ? (string) ( $response['error'] ?? 'context_failed' ) : '' );
     357        if ( ! empty( $response['ok'] ) ) {
     358            Options::set( 'account_last_sync', time() );
     359        }
     360        return $response;
     361    }
     362
    322363    private function authorize_ajax(): void {
    323364        if ( ! current_user_can( 'manage_options' ) ) {
  • nabz-lite/tags/1.5.17/src/Cashback/Cart.php

    r3688753 r3757421  
    3131        add_filter( 'nabz_cashback_applied_amount', [ $this, 'applied_amount_irr' ], 10, 2 );
    3232        add_action( 'woocommerce_before_calculate_totals', [ $this, 'sync_coupon' ], 5, 1 );
     33        // A wallet can change while a customer keeps checkout open (for
     34        // example, after another tab finishes an order). Refresh the virtual
     35        // coupon immediately before classic checkout creates its order and
     36        // during Store API draft updates so the order total and ledger debit
     37        // use the same current balance.
     38        add_action( 'woocommerce_before_checkout_process', [ $this, 'refresh_checkout_coupon' ], 1 );
     39        add_action( 'woocommerce_store_api_checkout_update_draft', [ $this, 'refresh_checkout_coupon' ], 1 );
    3340        add_action( 'wp_ajax_nabz_cashback_toggle_wallet', [ $this, 'ajax_toggle' ] );
    3441        add_action( 'wp_ajax_nopriv_nabz_cashback_toggle_wallet', [ $this, 'ajax_guest' ] );
    … …  
    137144    }
    138145
     146    /**
     147     * Rebuild the wallet coupon from the authoritative balance before checkout.
     148     *
     149     * WooCommerce may keep the same applied coupon code in the session while
     150     * its virtual amount was calculated earlier. Removing and applying the
     151     * account-bound code again makes `virtual_coupon_data()` read the latest
     152     * ledger balance before WooCommerce copies cart totals into an order.
     153     */
     154    public function refresh_checkout_coupon( ...$ignored ): void {
     155        if ( function_exists( 'wc_load_cart' ) && ( ! function_exists( 'WC' ) || ! WC()->cart ) ) {
     156            wc_load_cart();
     157        }
     158        if ( ! function_exists( 'WC' ) || ! WC()->cart || ! is_object( WC()->cart ) ) {
     159            return;
     160        }
     161
     162        $cart = WC()->cart;
     163        if ( $this->syncing || ! method_exists( $cart, 'has_discount' ) ) {
     164            return;
     165        }
     166
     167        $user_id = get_current_user_id();
     168        $this->remove_foreign_wallet_coupons( $cart, $user_id );
     169        if ( $user_id <= 0 ) {
     170            return;
     171        }
     172        $code = self::coupon_code( $user_id );
     173        if ( $code === '' ) {
     174            return;
     175        }
     176
     177        $this->syncing = true;
     178        try {
     179            // Re-creating the virtual coupon is intentional. The current
     180            // balance may be lower or higher than the amount held by the
     181            // checkout page since its last totals calculation.
     182            if ( $cart->has_discount( $code ) && method_exists( $cart, 'remove_coupon' ) ) {
     183                $cart->remove_coupon( $code );
     184            }
     185
     186            $should_use = $this->should_use_wallet()
     187                && $this->service->enabled()
     188                && $this->service->balance_irr( $user_id ) > 0;
     189            if ( $should_use && method_exists( $cart, 'apply_coupon' ) ) {
     190                $cart->apply_coupon( $code );
     191            }
     192        } finally {
     193            $this->syncing = false;
     194        }
     195
     196        if ( method_exists( $cart, 'calculate_totals' ) ) {
     197            $cart->calculate_totals();
     198        }
     199        if ( method_exists( $cart, 'set_session' ) ) {
     200            $cart->set_session();
     201        }
     202    }
     203
    139204    public function ajax_guest(): void {
    140205        wp_send_json_error( [
  • nabz-lite/tags/1.5.17/src/Cashback/Expiry.php

    r3688753 r3757421  
    1616    public function register(): void {
    1717        add_action( 'nabz_daily_refresh', [ $this, 'run' ], 30 );
     18        add_action( 'nabz_register_tasks', function ( \Nabz\Jobs\Scheduler $scheduler ): void {
     19            $scheduler->register( 'cashback_expiry', [ $this, 'run' ], DAY_IN_SECONDS, 30 );
     20        } );
    1821    }
    1922
    … …  
    2528            $result = $this->service->expire_all_due( null, 100 );
    2629            if ( is_wp_error( $result ) ) {
    27                 break;
     30                throw new \RuntimeException( $result->get_error_code() );
    2831            }
    2932            $count = is_array( $result ) ? (int) ( $result['processed'] ?? 0 ) : 0;
  • nabz-lite/tags/1.5.17/src/Cashback/Lifecycle.php

    r3737123 r3757421  
    127127        ] );
    128128        if ( is_wp_error( $result ) ) {
     129            $error_data = $result->get_error_data();
     130            if ( ! is_array( $error_data ) ) {
     131                $error_data = [];
     132            }
     133            if ( function_exists( 'wc_get_logger' ) ) {
     134                wc_get_logger()->error( 'Cashback wallet reservation failed.', [
     135                    'source'        => 'nabz-cashback',
     136                    'error_code'    => $result->get_error_code(),
     137                    'user_id'       => $user_id,
     138                    'order_id'      => $order_id,
     139                    'requested_irr' => $amount,
     140                    'available_irr'  => isset( $error_data['available_irr'] ) ? (int) $error_data['available_irr'] : $this->service->balance_irr( $user_id ),
     141                ] );
     142            }
    129143            // Never let checkout continue with a discount that could not be
    130144            // reserved. WooCommerce turns this exception into a checkout notice.
  • nabz-lite/tags/1.5.17/src/Crm/RfmCalculator.php

    r3750451 r3757421  
    5858    /** Perform the rebuild after the cross-request lock has been acquired. */
    5959    private function recompute_locked(): array {
     60
     61        if ( ! Schema::ensure_transactional_storage() ) {
     62            return [ 'customers' => 0, 'orders' => 0, 'failed' => 'storage_engine' ];
     63        }
    6064
    6165        $now_utc = time();
    … …  
    117121        // ── persist ──
    118122        global $wpdb;
    119         $engine = $wpdb->get_var( $wpdb->prepare(
    120             'SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s',
    121             Schema::rfm_table()
    122         ) );
    123         if ( strtoupper( (string) $engine ) !== 'INNODB' ) {
    124             // Legacy nontransactional tables must keep their previous snapshot
    125             // rather than silently losing it on an interrupted publication.
    126             return [ 'customers' => 0, 'orders' => $orders_seen, 'failed' => 'storage_engine' ];
    127         }
    128123        if ( false === $wpdb->query( 'START TRANSACTION' ) ) {
    129124            return [ 'customers' => 0, 'orders' => $orders_seen, 'failed' => 'transaction' ];
  • nabz-lite/tags/1.5.17/src/Crm/Schema.php

    r3688753 r3757421  
    2121        global $wpdb;
    2222        return $wpdb->prefix . 'nabz_automation_runs';
     23    }
     24
     25    /** Upgrade only the derived snapshot; ALTER preserves all existing rows. */
     26    public static function ensure_transactional_storage(): bool {
     27        global $wpdb;
     28        $table = self::rfm_table();
     29        $read_engine = static function () use ( $wpdb, $table ): string {
     30            return strtoupper( (string) $wpdb->get_var( $wpdb->prepare(
     31                'SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s',
     32                $table
     33            ) ) );
     34        };
     35        $engine = $read_engine();
     36        if ( $engine === 'INNODB' ) {
     37            return true;
     38        }
     39        if ( ! in_array( $engine, [ 'MYISAM', 'ARIA' ], true ) ) {
     40            return false;
     41        }
     42        // Called under the RFM rebuild lock, before scanning or deleting rows.
     43        // If InnoDB/ALTER is unavailable, leave the previous snapshot in place.
     44        if ( false === $wpdb->query( "ALTER TABLE {$table} ENGINE=InnoDB" ) ) {
     45            return false;
     46        }
     47        return $read_engine() === 'INNODB';
    2348    }
    2449
    … …  
    5883            KEY idx_frequency (frequency),
    5984            KEY idx_last_order_at (last_order_at)
    60         ) {$charset};";
     85        ) ENGINE=InnoDB {$charset};";
    6186
    6287        dbDelta( $sql );
  • nabz-lite/tags/1.5.17/src/Jobs/Dispatcher.php

    r3750712 r3757421  
    2929    private function route_for( string $message_type ): string {
    3030        try {
     31            if ( \Nabz\Sms\GatewaySettings::external() ) { return ''; }
    3132            return sanitize_key( (string) apply_filters( 'nabz_delivery_route', '', $message_type ) );
    3233        } catch ( \Throwable $e ) {
    … …  
    3839    private function sms_enabled(): bool {
    3940        try {
     41            if ( \Nabz\Sms\GatewaySettings::external() ) { return true; }
    4042            return (bool) apply_filters( 'nabz_sms_delivery_enabled', true );
    4143        } catch ( \Throwable $e ) {
    … …  
    4648    /** Explicit overrides must never degrade to another transport. */
    4749    private function channel_available( string $channel ): bool {
     50        if ( \Nabz\Sms\GatewaySettings::external() ) { return $channel === 'sms' && \Nabz\Sms\GatewaySettings::ready(); }
    4851        try {
    4952            return (bool) apply_filters(
    … …  
    240243            'parameters'      => $parameters,
    241244            'channel'         => 'sms',
     245            'sms_provider'    => \Nabz\Sms\GatewaySettings::provider(),
    242246            // Version the local tracking contract at enqueue time. Previously
    243247            // attempted jobs must keep their original backend fingerprint.
  • nabz-lite/tags/1.5.17/src/Jobs/JobManager.php

    r3737123 r3757421  
    1818    }
    1919
    20     /** Prevent overlapping queue drains from Cron, admin heartbeat and watchdog. */
     20    /** Prevent overlapping native queue drains, admin heartbeats and watchdogs. */
    2121    public function acquire_worker_lock(): bool {
    2222        global $wpdb;
    … …  
    3939    private function worker_lock_name(): string {
    4040        return 'nabz_worker_' . sha1( $this->table() );
     41    }
     42
     43    /** One async batch, including its wait and successor reservation, per site. */
     44    public function acquire_runner_lock(): bool {
     45        global $wpdb;
     46        return (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', 'nabz_runner_' . sha1( $this->table() ) ) ) === '1';
     47    }
     48
     49    public function release_runner_lock(): void {
     50        global $wpdb;
     51        $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', 'nabz_runner_' . sha1( $this->table() ) ) );
    4152    }
    4253
    … …  
    251262    }
    252263
     264    /** Serialize coalescing so concurrent requests cannot insert duplicate maintenance. */
     265    public function enqueue_maintenance( string $type, int $delay = 0, bool $include_running = false, bool $expedite = true ): ?int {
     266        global $wpdb;
     267        if ( strpos( $type, 'maintenance_' ) !== 0 ) {
     268            return null;
     269        }
     270        $lock = 'nabz_schedule_' . sha1( $this->table() . $type );
     271        if ( (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $lock ) ) !== '1' ) {
     272            return null;
     273        }
     274        try {
     275            $states = $include_running ? "'queued','running'" : "'queued'";
     276            $row = $wpdb->get_row( $wpdb->prepare(
     277                "SELECT id, status FROM {$this->table()} WHERE job_type=%s AND status IN ({$states}) ORDER BY id ASC LIMIT 1",
     278                $type
     279            ), ARRAY_A );
     280            if ( $row ) {
     281                if ( $expedite && $row['status'] === 'queued' ) {
     282                    $updated = $wpdb->query( $wpdb->prepare(
     283                        "UPDATE {$this->table()} SET available_at=LEAST(available_at, %s) WHERE id=%d AND status='queued'",
     284                        gmdate( 'Y-m-d H:i:s', time() + max( 0, $delay ) ), (int) $row['id']
     285                    ) );
     286                    if ( $updated === false ) {
     287                        return null;
     288                    }
     289                }
     290                return (int) $row['id'];
     291            }
     292            return $this->enqueue( $type, [], sha1( wp_generate_uuid4() ), $delay, 2147483647 );
     293        } finally {
     294            $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) );
     295        }
     296    }
     297
     298    /** Next eligible task, including recovery of an interrupted worker. */
     299    public function next_available_at( array $maintenance_types, bool $delivery ): ?int {
     300        global $wpdb;
     301        $where = $this->type_condition( $maintenance_types, $delivery );
     302        $value = $wpdb->get_var(
     303            "SELECT MIN(CASE WHEN status='running' THEN DATE_ADD(locked_at, INTERVAL 30 MINUTE) ELSE available_at END)
     304             FROM {$this->table()} WHERE status IN ('queued','running') AND ({$where})"
     305        );
     306        return $value ? (int) strtotime( $value . ' UTC' ) : null;
     307    }
     308
     309    /** An explicit type list isolates local maintenance from the delivery worker. */
     310    private function type_condition( array $types, bool $delivery ): string {
     311        global $wpdb;
     312        $conditions = [];
     313        if ( $delivery ) {
     314            $conditions[] = $wpdb->prepare( 'job_type NOT LIKE %s', $wpdb->esc_like( 'maintenance_' ) . '%' );
     315        }
     316        if ( $types ) {
     317            $placeholders = implode( ',', array_fill( 0, count( $types ), '%s' ) );
     318            $conditions[] = $wpdb->prepare( "job_type IN ({$placeholders})", array_values( $types ) );
     319        }
     320        return $conditions ? implode( ' OR ', $conditions ) : '1=0';
     321    }
     322
    253323    /**
    254324     * Atomically claim the next runnable job. Returns the row array or null if none.
    … …  
    256326     * same UPDATE between the SELECT and our UPDATE will get affected_rows==0.
    257327     */
    258     public function claim_next(): ?array {
     328    public function claim_next( ?array $types = null ): ?array {
    259329        global $wpdb;
    260330        $table = $this->table();
    261331        $now   = current_time( 'mysql', true );
     332
     333        $where = $this->type_condition( $types ?? [], $types === null );
    262334
    263335        // Find a candidate.
    264336        $row = $wpdb->get_row( $wpdb->prepare(
    265337            "SELECT * FROM {$table}
    266              WHERE status='queued' AND available_at <= %s AND lock_key IS NULL
     338             WHERE status='queued' AND available_at <= %s AND lock_key IS NULL AND ({$where})
    267339             ORDER BY available_at ASC, id ASC
    268340             LIMIT 1",
    … …  
    272344            return null;
    273345        }
    274         $lock = wp_generate_uuid4();
    275         $affected = $wpdb->query( $wpdb->prepare(
    276             "UPDATE {$table}
    277              SET status='running', lock_key=%s, locked_at=%s,
    278                  first_attempted_at=COALESCE(first_attempted_at, %s),
    279                  attempts=attempts+1, updated_at=%s
    280              WHERE id=%d AND lock_key IS NULL AND status='queued'",
    281             $lock,
    282             $now,
    283             $now,
    284             $now,
    285             (int) $row['id']
    286         ) );
    287         if ( $affected !== 1 ) {
    288             return null; // another worker won the race
    289         }
    290         $row['lock_key']  = $lock;
    291         $row['locked_at'] = $now;
    292         $row['first_attempted_at'] = ! empty( $row['first_attempted_at'] )
    293             ? $row['first_attempted_at']
    294             : $now;
    295         $row['attempts']  = (int) $row['attempts'] + 1;
    296         $row['status']    = 'running';
    297         return $row;
     346        // Serialize a maintenance claim with coalescing. Otherwise a purchase
     347        // can observe a queued row just as the worker starts its snapshot,
     348        // then incorrectly attach itself to work that is already running.
     349        $schedule_lock = strpos( (string) $row['job_type'], 'maintenance_' ) === 0
     350            ? 'nabz_schedule_' . sha1( $this->table() . $row['job_type'] )
     351            : '';
     352        if ( $schedule_lock !== '' && (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $schedule_lock ) ) !== '1' ) {
     353            return null;
     354        }
     355        try {
     356            $lock = wp_generate_uuid4();
     357            $affected = $wpdb->query( $wpdb->prepare(
     358                "UPDATE {$table}
     359                 SET status='running', lock_key=%s, locked_at=%s,
     360                     first_attempted_at=COALESCE(first_attempted_at, %s),
     361                     attempts=attempts+1, updated_at=%s
     362                 WHERE id=%d AND lock_key IS NULL AND status='queued'",
     363                $lock,
     364                $now,
     365                $now,
     366                $now,
     367                (int) $row['id']
     368            ) );
     369            if ( $affected !== 1 ) {
     370                return null; // another worker won the race
     371            }
     372            $row['lock_key']  = $lock;
     373            $row['locked_at'] = $now;
     374            $row['first_attempted_at'] = ! empty( $row['first_attempted_at'] )
     375                ? $row['first_attempted_at']
     376                : $now;
     377            $row['attempts']  = (int) $row['attempts'] + 1;
     378            $row['status']    = 'running';
     379            return $row;
     380        } finally {
     381            if ( $schedule_lock !== '' ) {
     382                $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $schedule_lock ) );
     383            }
     384        }
    298385    }
    299386
    … …  
    441528    public function last_run_unix(): int {
    442529        global $wpdb;
    443         $row = $wpdb->get_var( "SELECT MAX(locked_at) FROM {$this->table()} WHERE locked_at IS NOT NULL" );
     530        $where = $this->type_condition( [], true );
     531        $row = $wpdb->get_var( "SELECT MAX(locked_at) FROM {$this->table()} WHERE locked_at IS NOT NULL AND ({$where})" );
    444532        return $row ? strtotime( $row . ' UTC' ) : 0;
    445533    }
    … …  
    479567        $table = $this->table();
    480568        $error = 'لغو شد: اتصال حساب نبض قطع شد. ' . LogFormatter::error( $reason );
     569        $preserve = [];
     570        $arguments = [ mb_substr( $error, 0, 1000 ) ];
     571        foreach ( \Nabz\Sms\GatewaySettings::providers() as $provider => $label ) {
     572            $preserve[] = 'payload NOT LIKE %s';
     573            $arguments[] = '%' . $wpdb->esc_like( '"sms_provider":"' . $provider . '"' ) . '%';
     574        }
     575        $central_sms = implode( ' AND ', $preserve );
    481576        return (int) $wpdb->query( $wpdb->prepare(
    482577            "UPDATE {$table}
    483578             SET status='dead', lock_key=NULL, locked_at=NULL,
    484579                 last_error=%s, updated_at=UTC_TIMESTAMP()
    485              WHERE job_type IN ('sms_send','messenger_send') AND status IN ('queued','running')",
    486             mb_substr( $error, 0, 1000 )
     580             WHERE job_type IN ('sms_send','messenger_send') AND status IN ('queued','running')
     581               AND (job_type <> 'sms_send' OR ({$central_sms}))",
     582            ...$arguments
    487583        ) );
    488584    }
  • nabz-lite/tags/1.5.17/src/Jobs/Worker.php

    r3737123 r3757421  
    2929
    3030    public function run( int $max_jobs = 25, int $time_budget_seconds = 25 ): void {
    31         if ( ! Options::delivery_connected() || (string) Options::get( 'installation_token', '' ) === '' ) {
     31        if ( ! Options::delivery_connected() ) {
    3232            return;
    3333        }
    … …  
    4444
    4545            for ( $i = 0; $i < $max_jobs; $i++ ) {
    46                 if ( ! Options::delivery_connected() || (string) Options::get( 'installation_token', '' ) === '' ) {
     46                if ( ! Options::delivery_connected() ) {
    4747                    break;
    4848                }
    … …  
    8484
    8585        // Breaker open → don't burn an attempt; reschedule after cooldown.
    86         if ( $this->breaker->is_open() ) {
     86        if ( ! ( (string) $job['job_type'] === 'sms_send' && \Nabz\Sms\GatewaySettings::external() ) && $this->breaker->is_open() ) {
    8787            $this->jobs->reschedule_without_attempt(
    8888                $id,
  • nabz-lite/tags/1.5.17/src/Plugin.php

    r3750451 r3757421  
    3232use Nabz\Jobs\JobManager;
    3333use Nabz\Jobs\Schema;
     34use Nabz\Jobs\Scheduler;
    3435use Nabz\Jobs\Worker;
    3536use Nabz\Settings\Options;
    … …  
    4142    private Container $container;
    4243    private bool $booted = false;
    43     private ?string $daily_refresh_lock_token = null;
    4444
    4545    public static function instance(): self {
    … …  
    6060
    6161    public static function on_activate(): void {
    62         // The custom schedule must be registered before wp_schedule_event().
    63         // Activation runs before the normal boot hook, so registering this only
    64         // inside boot can silently leave low-traffic sites without a tick.
    65         add_filter( 'cron_schedules', [ self::class, 'cron_schedules' ] );
    6662        Privacy::register();
    6763        // Rename legacy SMART SMS tables/options before installing schemas,
    … …  
    7369        CrmSchema::install();
    7470        CashbackSchema::install();
    75         if ( ! wp_next_scheduled( 'nabz_tick' ) ) {
    76             wp_schedule_event( time() + 60, 'nabz_minute', 'nabz_tick' );
    77         }
    78         // Customer/RFM refreshes are scheduled as one-shot jobs by the init
    79         // watchdog below. A recurring event here made low-traffic stores depend
    80         // on an unreliable WP-Cron cadence and could overlap a manual rebuild.
    8171        // Lite owns short links, customer login and cart recovery.
    8272        add_rewrite_rule( '^ss/([a-zA-Z0-9]{4,12})/?$', 'index.php?nabz_track=$matches[1]', 'top' );
    … …  
    9484    }
    9585
    96     /** Register Nabz's one-minute queue tick for activation and normal boot. */
    97     public static function cron_schedules( array $schedules ): array {
    98         $schedules['nabz_minute'] = [
    99             'interval' => 60,
    100             'display'  => __( 'Every minute (Nabz)', 'nabz-lite' ),
    101         ];
    102         return $schedules;
    103     }
    104 
    10586    public static function on_deactivate(): void {
    10687        wp_clear_scheduled_hook( 'nabz_tick' );
    10788        wp_clear_scheduled_hook( 'nabz_daily_refresh' );
    10889        wp_clear_scheduled_hook( 'nabz_rfm_recompute' );
     90        wp_clear_scheduled_hook( 'nabz_rfm_currency_rebuild' );
     91        delete_option( 'nabz_runner_dispatch' );
    10992        flush_rewrite_rules( false );
    11093    }
    … …  
    142125        } );
    143126
    144         add_filter( 'cron_schedules', [ self::class, 'cron_schedules' ] );
    145         // Self-heal installs upgraded before the custom schedule was registered,
    146         // or sites where WP-Cron was cleared. The central watchdog can then wake
    147         // the standard wp-cron endpoint even when the storefront has no traffic.
    148         if ( ! wp_next_scheduled( 'nabz_tick' ) ) {
    149             wp_schedule_event( time() + 60, 'nabz_minute', 'nabz_tick' );
    150         }
    151 
    152         // Cron tick → kick a non-blocking loopback to admin-ajax to actually run the worker.
     127        // Old external tick callers remain compatible; init owns scheduling.
    153128        add_action( 'nabz_tick', [ $this, 'fire_tick_loopback' ] );
    154129
    … …  
    161136        add_action( 'nabz_rfm_recompute', [ self::class, 'run_rfm_recompute' ] );
    162137        add_action( 'woocommerce_order_status_changed', [ self::class, 'schedule_rfm_after_order' ], 90, 3 );
    163         add_action( 'user_register', [ self::class, 'schedule_rfm_refresh' ], 90 );
     138        add_action( 'user_register', [ self::class, 'schedule_rfm_refresh' ], 90, 0 );
    164139
    165140        // Optional server-cron endpoint. It uses the same per-install secret as
    … …  
    232207        add_action( 'nabz_daily_refresh', [ $this, 'run_daily_refresh' ], 10 );
    233208
    234         // The refresh watchdog runs from init and only schedules a one-shot
    235         // WP-Cron event when the last completed daily pipeline is older than
    236         // 24 hours.
    237         // The heavy scan therefore never runs inside a storefront/admin request.
    238         add_action( 'init', [ $this, 'maybe_schedule_daily_refresh' ], 20 );
    239 
    240209        // The paid add-on attaches its hooks here. The base plugin never boots paid
    241210        // execution paths, even though it renders their read-only previews.
    242211        do_action( 'nabz_premium_runtime', $this->container );
     212
     213        $scheduler = $this->container->get( Scheduler::class );
     214        $scheduler->register( 'rfm', [ self::class, 'run_rfm_recompute' ], DAY_IN_SECONDS, 10, 'last_customer_refresh' );
     215        $scheduler->register( 'currency_rebuild', [ self::class, 'repair_rfm_currency_units' ] );
     216        $scheduler->register( 'inventory', [ $this, 'refresh_inventory' ], DAY_IN_SECONDS, 90 );
     217        $analytics_sync = new \Nabz\Analytics\Sync( $this->container->get( Client::class ) );
     218        $scheduler->register( 'analytics_sync', [ $analytics_sync, 'run' ], MINUTE_IN_SECONDS, 95 );
     219        $scheduler->register( 'pulse', function (): void {
     220            $this->maybe_heartbeat();
     221            do_action( 'nabz_worker_tick' );
     222        }, MINUTE_IN_SECONDS, 100 );
     223        do_action( 'nabz_register_tasks', $scheduler );
     224        add_action( 'init', [ $scheduler, 'on_init' ], 100 );
     225        add_action( 'shutdown', [ $scheduler, 'on_shutdown' ], 2 );
    243226    }
    244227
    … …  
    256239        $c->set( Client::class,         fn ( $c ) => new Client( $c->get( CircuitBreaker::class ) ) );
    257240        $c->set( JobManager::class,     fn () => new JobManager() );
     241        $c->set( Scheduler::class, fn ( $c ) => new Scheduler(
     242            $c->get( JobManager::class ),
     243            $c->get( Worker::class ),
     244            [ $this, 'fire_tick_loopback' ]
     245        ) );
    258246        $c->set( Sender::class,         fn ( $c ) => new Sender( $c->get( Client::class ) ) );
    259247        $c->set( Dispatcher::class,     fn ( $c ) => new Dispatcher( $c->get( JobManager::class ) ) );
    … …  
    268256    }
    269257
    270     /** Fired by WP-Cron each minute. Sends a non-blocking loopback so the worker runs in its own request. */
    271     public function fire_tick_loopback(): void {
    272         $url = admin_url( 'admin-ajax.php?action=nabz_tick&token=' . $this->tick_token() );
    273         wp_remote_post( $url, [
     258    /** Signed non-blocking handoff to the native queue runner. */
     259    public function fire_tick_loopback() {
     260        $url = admin_url( 'admin-ajax.php?action=nabz_tick' );
     261        return wp_remote_post( $url, [
    274262            'timeout'   => 0.1,
    275263            'blocking'  => false,
    276264            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- `https_local_ssl_verify` is a WordPress core filter, not a plugin-defined hook.
    277265            'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
    278             'body'      => [],
     266            'body'      => [ 'token' => $this->tick_token() ],
    279267        ] );
    280268    }
    … …  
    290278            wp_die();
    291279        }
    292         // Backend heartbeat — keeps the site marked "online" and refreshes cached
    293         // connection settings. Throttled to ~10 min so the per-minute tick stays cheap.
    294         $this->maybe_heartbeat();
    295 
    296         if ( ! Options::delivery_connected() ) {
    297             if ( wp_doing_ajax() ) {
    298                 wp_send_json_success( [ 'ok' => true, 'delivery_connected' => false ] );
    299             }
    300             return;
    301         }
    302 
    303         /** @var Worker $worker */
    304         $worker = $this->container->get( Worker::class );
    305         $worker->run( 25 ); // up to 25 jobs per tick or until budget elapses
    306 
    307         // Periodic maintenance that must run in the same (loopback/heartbeat) request
    308         // as the worker — e.g. the abandoned-cart sweep. Runs more reliably here than
    309         // on the raw WP-Cron `nabz_tick` event, which low-traffic sites rarely fire.
    310         do_action( 'nabz_worker_tick' );
     280        $this->container->get( Scheduler::class )->run();
    311281
    312282        if ( wp_doing_ajax() ) {
    … …  
    369339
    370340        // v12: rebuild the derived RFM cache once so historical IRR and IRT
    371         // orders are stored in one unit. Use cron to keep plugin boot fast on
     341        // orders are stored in one unit. Use the native queue to keep boot fast on
    372342        // large stores; the version is advanced only after a successful run.
    373343        if ( $current < 12 ) {
    374             if ( ! wp_next_scheduled( 'nabz_rfm_currency_rebuild' ) ) {
    375                 wp_schedule_single_event( time() + 30, 'nabz_rfm_currency_rebuild' );
    376             }
     344            $this->container->get( Scheduler::class )->enqueue( 'currency_rebuild', 30, true, false );
    377345            return;
    378346        }
    … …  
    432400
    433401    public static function repair_rfm_currency_units(): void {
     402        self::run_rfm_recompute();
     403        if ( (int) Options::get( 'db_version', 0 ) < 12 ) {
     404            Options::set( 'db_version', 12 );
     405        }
     406    }
     407
     408    /** Compatibility entry point for integrations using the former daily hook. */
     409    public function run_daily_refresh(): void {
     410        $this->maybe_schedule_daily_refresh();
     411    }
     412
     413    public function maybe_schedule_daily_refresh(): void {
     414        $this->container->get( Scheduler::class )->schedule_due();
     415    }
     416
     417    /** Queue retries own failures; never publish a successful timestamp early. */
     418    public static function run_rfm_recompute(): void {
    434419        if ( ! function_exists( 'wc_get_orders' ) ) {
    435             return;
     420            throw new \RuntimeException( 'woocommerce_unavailable' );
    436421        }
    437422        $result = ( new RfmCalculator() )->recompute();
    438         if ( empty( $result['skipped'] ) && empty( $result['failed'] ) && (int) Options::get( 'db_version', 0 ) < 12 ) {
    439             Options::set( 'db_version', 12 );
    440         }
    441     }
    442 
    443     /**
    444      * Schedule the customer refresh at most once per 24 hours from init.
    445      *
    446      * This is deliberately a one-shot WP-Cron event rather than a recurring
    447      * event. The cheap staleness check runs on normal requests, while the full
    448      * WooCommerce order scan runs in a separate cron request and never blocks a
    449      * storefront or the customers admin page.
    450      */
    451     public function maybe_schedule_daily_refresh(): void {
    452         if ( ! function_exists( 'wc_get_orders' ) || ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) ) {
    453             return;
    454         }
    455         // Let older one-shot migrations (notably the currency rebuild) finish
    456         // before the new customer scheduler starts another full scan.
    457         if ( (int) Options::get( 'db_version', 0 ) < 15 ) {
    458             return;
    459         }
    460 
    461         $last = (int) Options::get( 'last_daily_refresh', 0 );
    462         if ( $last > 0 && ( time() - $last ) < DAY_IN_SECONDS ) {
    463             return;
    464         }
    465         $scheduled = function_exists( 'wp_get_scheduled_event' )
    466             ? wp_get_scheduled_event( 'nabz_daily_refresh' )
    467             : null;
    468         if ( $scheduled && ! empty( $scheduled->schedule ) ) {
    469             // Remove a recurring event left by <=1.1.10 upgrades. New events
    470             // are intentionally one-shot and must remain scheduled.
    471             wp_clear_scheduled_hook( 'nabz_daily_refresh' );
    472             $scheduled = null;
    473         }
    474         if ( $scheduled || wp_next_scheduled( 'nabz_daily_refresh' ) ) {
    475             // Retry the non-blocking loopback on later traffic when a hosting
    476             // firewall dropped the first spawn attempt.
    477             $due_at = $scheduled && isset( $scheduled->timestamp )
    478                 ? (int) $scheduled->timestamp
    479                 : (int) wp_next_scheduled( 'nabz_daily_refresh' );
    480             if ( $due_at > 0 && $due_at <= time() && function_exists( 'spawn_cron' ) ) {
    481                 spawn_cron( time() );
    482             }
    483             return;
    484         }
    485 
    486         // Run the job in a separate, non-blocking cron request immediately.
    487         // If loopback is unavailable, the due single event is still picked up
    488         // by the next normal WordPress cron opportunity.
    489         $now = time();
    490         wp_schedule_single_event( $now, 'nabz_daily_refresh' );
    491         if ( function_exists( 'spawn_cron' ) ) {
    492             spawn_cron( $now );
    493         }
    494     }
    495 
    496     /** Run the expensive daily pipeline behind a cross-request lock. */
    497     public function run_daily_refresh(): void {
    498         $last = (int) Options::get( 'last_daily_refresh', 0 );
    499         if ( $last > 0 && ( time() - $last ) < DAY_IN_SECONDS ) {
    500             // A previous one-shot event (or an overlapping cron runner) has
    501             // already completed today's maintenance pipeline.
    502             return;
    503         }
    504         if ( ! $this->acquire_daily_refresh_lock() ) {
    505             return;
    506         }
    507 
    508         try {
    509             $customer_last = (int) Options::get( 'last_customer_refresh', 0 );
    510             if ( $customer_last <= 0 || ( time() - $customer_last ) >= DAY_IN_SECONDS ) {
    511                 $result = ( new RfmCalculator() )->recompute();
    512                 if ( ! empty( $result['skipped'] ) || ! empty( $result['failed'] ) ) {
    513                     return;
    514                 }
    515                 Options::set( 'last_customer_refresh', time() );
    516             }
    517             Options::set( 'last_daily_refresh', time() );
    518         } finally {
    519             $this->release_daily_refresh_lock();
    520         }
    521     }
    522 
    523     /** Async handler used by the admin «recompute now» button. */
    524     public static function run_rfm_recompute(): void {
    525         $result = ( new RfmCalculator() )->recompute();
    526         if ( empty( $result['skipped'] ) && empty( $result['failed'] ) ) {
    527             Options::set( 'last_customer_refresh', time() );
    528         } elseif ( ( $result['failed'] ?? '' ) !== 'storage_engine' ) {
    529             self::schedule_rfm_refresh();
    530         }
     423        if ( ! empty( $result['skipped'] ) || ! empty( $result['failed'] ) ) {
     424            throw new \RuntimeException( 'rfm_' . (string) ( $result['skipped'] ?? $result['failed'] ) );
     425        }
     426        Options::set( 'last_customer_refresh', time() );
    531427    }
    532428
    … …  
    538434    }
    539435
    540     /** Debounce new purchases/registrations into one background rebuild. */
    541     public static function schedule_rfm_refresh(): void {
    542         if ( ! wp_next_scheduled( 'nabz_rfm_recompute' ) ) {
    543             wp_schedule_single_event( time() + 60, 'nabz_rfm_recompute' );
    544         }
    545     }
    546 
    547     private function acquire_daily_refresh_lock(): bool {
    548         $now      = time();
    549         $existing = get_option( 'nabz_daily_refresh_lock', false );
    550         if ( is_array( $existing ) && (int) ( $existing['expires'] ?? 0 ) > $now ) {
    551             return false;
    552         }
    553         if ( false !== $existing ) {
    554             delete_option( 'nabz_daily_refresh_lock' );
    555         }
    556         $token = function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'nabz_daily_', true );
    557         if ( ! add_option( 'nabz_daily_refresh_lock', [ 'token' => $token, 'expires' => $now + 1800 ], '', 'no' ) ) {
    558             return false;
    559         }
    560         $this->daily_refresh_lock_token = $token;
    561         return true;
    562     }
    563 
    564     private function release_daily_refresh_lock(): void {
    565         if ( $this->daily_refresh_lock_token === null ) {
    566             return;
    567         }
    568         $current = get_option( 'nabz_daily_refresh_lock', false );
    569         if ( is_array( $current ) && (string) ( $current['token'] ?? '' ) === $this->daily_refresh_lock_token ) {
    570             delete_option( 'nabz_daily_refresh_lock' );
    571         }
    572         $this->daily_refresh_lock_token = null;
    573     }
    574 
    575     public function refresh_inventory(): void {
     436    /** Coalesce untouched purchases; an order during a scan gets a successor. */
     437    public static function schedule_rfm_refresh( int $delay = 60 ): ?int {
     438        $id = self::instance()->container()->get( Scheduler::class )->enqueue( 'rfm', $delay );
     439        if ( ! $id ) {
     440            \Nabz\Support\Logger::error( 'maintenance_enqueue_failed', 'Could not queue the customer refresh.' );
     441        }
     442        return $id;
     443    }
     444
     445    public function refresh_inventory(): bool {
     446        if ( (string) Options::get( 'installation_token', '' ) === '' ) {
     447            return true;
     448        }
    576449        /** @var Client $client */
    577450        $client = $this->container->get( Client::class );
    578451        // Report liveness and package inventory; refresh delivery and wallet settings.
    579         $client->announce();
     452        $result = $client->announce();
     453        return ! empty( $result['ok'] );
    580454    }
    581455
    … …  
    617491    }
    618492
    619     /** Catch up a missed daily cron on the first request after 24 hours. */
     493    /** Catch up inventory on the first request after 24 hours. */
    620494    private function maybe_daily_inventory_sync(): void {
    621495        if ( (string) Options::get( 'installation_token', '' ) === '' ) {
  • nabz-lite/tags/1.5.17/src/Privacy.php

    r3688753 r3757421  
    2121        add_filter( 'wp_privacy_personal_data_erasers', [ self::class, 'erasers' ] );
    2222        add_action( 'nabz_daily_refresh', [ self::class, 'cleanup' ], 100 );
     23        add_action( 'nabz_register_tasks', function ( \Nabz\Jobs\Scheduler $scheduler ): void {
     24            $scheduler->register( 'privacy_cleanup', [ self::class, 'cleanup' ], DAY_IN_SECONDS, 100 );
     25        } );
    2326    }
    2427
    … …  
    3134            . '</p><p>'
    3235            . esc_html__( 'تا پیش از اقدام مدیر برای اتصال سرویس، نبض اطلاعات فروشگاه را به سرویس بیرونی ارسال نمی‌کند. پس از اتصال، افزونه برای اعتبارسنجی و ارسال پیام با nabz.business ارتباط می‌گیرد. داده‌های ارسالی می‌توانند شامل دامنه، نسخه‌های وردپرس/ووکامرس/افزونه، شناسه و کلید عمومی نصب، توکن نصب، نوع رویداد، شماره موبایل گیرنده و پارامترهای لازم پیام مانند نام مشتری، شماره سفارش، مبلغ و لینک مرتبط باشند. متن نهایی پیام و وضعیت تحویل روی سرویس نبض پردازش می‌شوند. سیاست کامل حریم خصوصی و شرایط سرویس در https://nabz.business/legal.html در دسترس است.', 'nabz-lite' )
     36            . '</p><p>'
     37            . esc_html__( 'پس از اتصال حساب نبض، آمار ارسال موفق و کلیک شامل شناسهٔ هش‌شدهٔ پیام، نوع پیام، تعداد کلیک و زمان ارسال و اولین/آخرین کلیک نیز با سرویس نبض همگام می‌شود. همگام‌سازی آمار، شماره موبایل، نام مشتری، IP، مرورگر، متن پیام یا نشانی مقصد را ارسال نمی‌کند.', 'nabz-lite' )
    3338            . '</p><p>'
    3439            . esc_html__( 'نبض برای احراز درخواست‌ها یک کلید خصوصی Ed25519 را فقط در پایگاه داده همین وردپرس ذخیره می‌کند و کلید خصوصی را به سرویس ارسال نمی‌کند. حذف افزونه، داده‌های محلی اختصاصی نبض را پاک می‌کند؛ حذف داده‌های ذخیره‌شده روی سرویس بیرونی باید از حساب یا پشتیبانی نبض درخواست شود.', 'nabz-lite' )
  • nabz-lite/tags/1.5.17/src/Settings/Options.php

    r3750451 r3757421  
    407407    }
    408408
    409     /** API access is tied to the signed-in wallet account, not a product license. */
     409    /** The revocable site credential survives expiry of the owner's portal session. */
     410    public static function account_connected(): bool {
     411        return strlen( trim( (string) self::get( 'installation_token', '' ) ) ) >= 8
     412            && (int) self::get( 'account_user_id', 0 ) > 0;
     413    }
     414
     415    /** Delivery uses the configured personal panel or the connected Nabz account. */
    410416    public static function delivery_connected(): bool {
    411         return strlen( trim( (string) self::get( 'installation_token', '' ) ) ) >= 8
    412             && trim( (string) self::get( 'account_session_cookie', '' ) ) !== ''
    413             && (int) self::get( 'account_user_id', 0 ) > 0;
     417        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\GatewaySettings::ready(); }
     418        return self::account_connected();
    414419    }
    415420
    … …  
    419424
    420425    public static function active_message_types(): array {
     426        if ( \Nabz\Sms\GatewaySettings::external() ) { return array_keys( \Nabz\Sms\LocalTemplates::all() ); }
    421427        $types = self::get( 'active_message_types', [] );
    422428        return is_array( $types ) ? $types : [];
  • nabz-lite/tags/1.5.17/src/Sms/Sender.php

    r3750712 r3757421  
    3131            ];
    3232        }
     33        if ( $job_type === 'messenger_send' && GatewaySettings::external() ) {
     34            return ExternalGateway::failure( 'پنل ارسال پس از ایجاد صف تغییر کرده است؛ صف پیام‌رسان قبلی را بررسی کنید.', 409 );
     35        }
    3336        if ( $job_type !== 'sms_send' ) {
    3437            $extension_response = apply_filters( 'nabz_dispatch_extension_job', null, $job_type, $payload );
    … …  
    3740            }
    3841            return [ 'ok' => false, 'status' => 0, 'body' => null, 'error' => 'unknown_job_type' ];
     42        }
     43        $queued_provider = (string) ( $payload['sms_provider'] ?? 'nabz' );
     44        if ( $queued_provider !== GatewaySettings::provider() ) {
     45            return ExternalGateway::failure( 'پنل پیامکی پس از ایجاد صف تغییر کرده است؛ پیام قبلی برای جلوگیری از ارسال ناخواسته متوقف شد.', 409 );
    3946        }
    4047        $message_type   = (string) ( $payload['message_type'] ?? '' );
  • nabz-lite/tags/1.5.17/src/Support/LogFormatter.php

    r3750451 r3757421  
    5757            'winback'                   => 'بازگشت مشتری',
    5858            'rfm_recompute'             => 'به‌روزرسانی دسته‌بندی مشتریان',
     59            'maintenance_retry'         => 'تلاش مجدد محاسبات و نگهداری',
    5960        ][ $event ] ?? 'رویداد سامانه';
    6061    }
    … …  
    8889    public static function error_code_message( string $code ): string {
    8990        $exact = [
     91            'rfm_storage_engine'               => 'جدول محاسبات مشتریان به InnoDB نیاز دارد؛ تبدیل خودکار جدول انجام نشد. دسترسی ALTER و پشتیبانی InnoDB پایگاه‌داده را بررسی کنید.',
     92            'rfm_busy'                         => 'محاسبهٔ دیگری در حال اجراست؛ پس از آزادشدن قفل دوباره تلاش می‌شود.',
    9093            'connection_invalid'               => 'اعتبار اتصال حساب نامعتبر است؛ دوباره وارد حساب نبض شوید.',
    9194            'account_connection_required'       => 'اتصال حساب نبض برقرار نیست؛ در پیشخوان نبض دوباره وارد حساب شوید یا وضعیت اتصال را همگام کنید.',
    … …  
    187190            return 'کار' . $job_number . ' ناموفق بود و برای تلاش مجدد در صف قرار گرفت: ' . self::error( (string) $raw );
    188191        }
     192        if ( $event === 'maintenance_retry' ) {
     193            return 'اجرای محاسبات یا نگهداری ناموفق بود و دوباره تلاش می‌شود: ' . self::error( (string) ( $context['error'] ?? $message ) );
     194        }
    189195        if ( $event === 'job_dead' ) {
    190196            $raw = preg_replace( '/^.*?dropped:\s*/is', '', $message );
    … …  
    272278            'retry'             => 'ارسال مجدد',
    273279            'error'             => 'خطا',
     280            'task'              => 'نام کار',
     281            'retry_after'       => 'تلاش مجدد پس از (ثانیه)',
    274282            'response'          => 'پاسخ سرور',
    275283            'backend'           => 'نتیجه سرور',
  • nabz-lite/trunk/CHANGELOG.md

    r3750712 r3757421  
    44[Semantic Versioning](https://semver.org/) شماره‌گذاری شده‌اند.
    55
     6## [1.5.17] - 2026-10-20
     7
     8- همگام‌سازی آمار ارسال موفق، کلیک و زمان آخرین کلیک با API و دیتابیس مرکزی موجود نبض برای سایت‌های متصل، در لایت و پریمیوم؛ شامل سوابق قبلی و ارسال‌های پنل شخصی در سایت دارای حساب نبض.
     9- اجرای دسته‌ای در زمان‌بند اختصاصی، checkpoint پایدار، replay یکسان پس از پاسخ نامطمئن و حذف درخواست‌های بدون تغییر؛ بدون انتقال شماره، IP، مرورگر، متن یا مقصد پیام.
     10- تجمیع چند لینک یک پیام برای حفظ شمارش یکتا و CTR، و اسکن دوره‌ای برای کلیک‌های تازه روی پیام‌های قدیمی؛ تست SQL واقعی و HTTP با شبیه‌ساز Postman.
     11
     12## [1.5.16] - 2026-10-20
     13
     14- پایان نشست مدیریتی حساب، توکن مستقل فروشگاه، موجودی کیف پول و صف پیام‌ها را پاک نمی‌کند؛ وضعیت ارسال با API و همان توکن قبلی بررسی می‌شود.
     15- شارژ کیف پول همچنان نشست معتبر می‌خواهد؛ ورود دوباره برای شارژ، اتصال ارسال را قطع نمی‌کند. خروج عمدی، تعویض حساب و لغو واقعی توکن همچنان ارسال حساب قبلی را متوقف می‌کنند.
     16- آزمون HTTP واقعی با شبیه‌ساز محلی برای نشست منقضی، لغو توکن و خطای موقت، و رگرسیون فرم ورود و شارژ اضافه شد.
     17
     18## [1.5.15] - 2026-10-20
     19
     20- رفع توقف محاسبات روی نصب‌های دارای جدول MyISAM/Aria: تبدیل جدول مشتق‌شدهٔ RFM به InnoDB زیر قفل محاسبه و پیش از خواندن سفارش‌ها؛ تمام رکوردهای قبلی حفظ می‌شوند.
     21- جدول تازهٔ RFM صریحاً با InnoDB ساخته می‌شود؛ شکست تبدیل، snapshot قبلی را حفظ و علت قابل‌اقدام را در گزارش زمان‌بند ثبت می‌کند.
     22- آزمون واقعی تبدیل موتور، حفظ داده، شکست ALTER، بازیابی و انتشار تراکنشی در محیط محلی اضافه شد.
     23
     24## [1.5.14] - 2026-10-20
     25
     26- اجرای صف و محاسبات با زمان‌بند اختصاصی روی init و ادامهٔ غیرهم‌زمان، مستقل از فعال‌بودن WP-Cron.
     27- انتقال رویدادهای قبلی نبض به صف پایدار، قفل اجرای هم‌زمان و تلاش مجدد مستقل برای هر کار.
     28- اجرای محاسبهٔ دستی از همان صف و اعلام خطای واقعی در صورت ناموفق‌بودن ثبت کار.
     29
     30## [1.5.13] - 2026-10-18
     31
     32- افزودن کاوه‌نگار، SMS.ir و قاصدک برای ارسال متن و الگوی تأییدشده و OTP از پنل شخصی.
     33- اعتبارسنجی نام و مقدار متغیرهای کاوه‌نگار، رسید هر پنل و حفظ صف مستقل هنگام خروج از حساب نبض.
     34
     35## [1.5.12] - 2026-10-18
     36
     37- پشتیبانی از پنل شخصی ملی‌پیامک و فراز (ارسال متن، الگو و کد ورود) بدون حساب یا کیف پول نبض.
     38- نگهداری رمزگذاری‌شدهٔ کلید پنل و جلوگیری از ارسال دوباره پس از پاسخ نامطمئن.
     39- اصلاح ساختار بستهٔ راست‌چین، کاور شیشه‌ای و مسیر ثابت اینفوگرافی.
     40
    641## [Unreleased]
     42
     43## [1.5.11] - 2026-10-17
     44
     45- موجودی کیف پول کش‌بک درست پیش از ثبت checkout کلاسیک و به‌روزرسانی draft در Checkout Blocks دوباره خوانده می‌شود؛ اگر موجودی هم‌زمان تغییر کند، تخفیف و مبلغ سفارش با موجودی واقعی هماهنگ می‌مانند.
     46- در صورت شکست رزرو کش‌بک، کد خطا، مبلغ درخواستی، موجودی موجود، کاربر و سفارش در لاگ ووکامرس ثبت می‌شوند تا بررسی اختلاف‌های checkout قابل اتکا باشد.
     47- تست یکپارچهٔ checkout هم‌زمان به بستهٔ منبع اضافه شد.
    748
    849## [1.5.10] - 2026-10-16
  • nabz-lite/trunk/assets/css/admin.css

    r3737690 r3757421  
    59485948.nbz-account-logout-modal__actions { display: flex; align-items: center; justify-content: flex-start; gap: 10px; margin-top: 18px; }
    59495949.nbz-account-logout-modal__actions .button-primary { display: inline-flex; align-items: center; }
     5950
     5951/* Customer-owned SMS gateway settings. */
     5952.nabz-gateway-profile { border:1px solid var(--ss-border,#dce5df); border-radius:12px; padding:16px; margin-top:16px; }
     5953.nabz-gateway-profile summary { cursor:pointer; padding:6px 0; }
     5954.nabz-gateway-fields { display:grid; grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr)); gap:16px; margin-block:16px; }
     5955.nabz-gateway-fields label { display:flex; flex-direction:column; gap:8px; }
     5956.nabz-gateway-fields input { width:100%; max-width:100%; }
     5957.nabz-gateway-pattern { padding:10px 0; border-top:1px solid var(--ss-border,#dce5df); }
     5958.nabz-gateway-copy { line-height:1.9; padding:12px; background:#f4f8f5; border-radius:8px; overflow-wrap:anywhere; }
  • nabz-lite/trunk/assets/js/account-auth.js

    r3737123 r3757421  
    178178        var authenticated = !!state.authenticated;
    179179        card.setAttribute('data-authenticated', authenticated ? '1' : '0');
    180         if (login) login.hidden = authenticated;
     180        if (login) login.hidden = authenticated && !state.reauth_required;
     181        var reauthHint = card.querySelector('[data-nbz-account-reauth]');
     182        if (reauthHint) reauthHint.hidden = !state.reauth_required;
    181183        if (summary) summary.hidden = !authenticated;
    182184        if (details) details.hidden = !authenticated;
    … …  
    291293                    }
    292294                } else {
     295                    if (result && result.data && result.data.state) applyState(result.data.state);
    293296                    setMessage(summaryStatus, responseMessage(result, 'به‌روزرسانی وضعیت ناموفق بود.'), 'error');
    294297                }
    … …  
    304307    });
    305308
     309    document.addEventListener('nbz:account-state', function (event) {
     310        applyState(event.detail);
     311        if (event.detail && event.detail.reauth_required && mobileInput) mobileInput.focus();
     312    });
     313
    306314    if (card.getAttribute('data-authenticated') === '1') {
    307315        request('nbz_account_context', {}).then(function (result) {
    308             if (result && result.success) applyState(result.data && result.data.state);
     316            if (result && result.data && result.data.state) applyState(result.data.state);
    309317        });
    310318    }
    … …  
    315323        if (event.persisted && card.getAttribute('data-authenticated') === '1') {
    316324            request('nbz_account_context', {}).then(function (result) {
    317                 if (result && result.success) applyState(result.data && result.data.state);
     325                if (result && result.data && result.data.state) applyState(result.data.state);
    318326            });
    319327        }
  • nabz-lite/trunk/assets/js/wallet-topup.js

    r3737123 r3757421  
    7878        opener.focus();
    7979    }
     80    function renewSession(result) {
     81        if (!result || !result.data || result.data.code !== 'account_reauth_required') return false;
     82        busy(false);
     83        close();
     84        document.dispatchEvent(new CustomEvent('nbz:account-state', { detail: result.data.state }));
     85        return true;
     86    }
    8087    opener.addEventListener('click', function () {
    8188        modal.hidden = false;
    … …  
    9299        request('nbz_account_checkout_options', {}).then(function (result) {
    93100            if (current !== revision) return;
     101            if (renewSession(result)) return;
    94102            if (!result.success) throw new Error((result.data && result.data.msg) || 'دریافت اطلاعات شارژ ممکن نشد.');
    95103            var options = result.data || {};
    … …  
    134142        message('در حال ساخت فاکتور…');
    135143        request('nbz_account_create_invoice', { kind: 'sms_credit', amount_irr: amount * 10, request_id: requestId }).then(function (result) {
     144            if (renewSession(result)) return;
    136145            if (!result.success || !result.data || !result.data.invoice_url) {
    137146                throw new Error((result.data && result.data.msg) || 'ساخت فاکتور ممکن نشد.');
  • nabz-lite/trunk/build-meta/manifest.json

    r3750712 r3757421  
    22    "schema": 1,
    33    "product": "nabz",
    4     "version": "1.5.10",
     4    "version": "1.5.17",
    55    "flavor": "source",
    6     "source_date_epoch": 1792165464,
     6    "source_date_epoch": 1792526641,
    77    "requires": {
    88        "php": ">=7.4",
    … …  
    1414    "files": {
    1515        "CHANGELOG.md": {
    16             "sha256": "11e73183b59824d959be742e23d8f9c74d33bde6e6594f11774b79b721ed35de",
    17             "bytes": 44033
     16            "sha256": "a6c1ec5671a7aad323f7e48b70a68a6e5b39554fc717f7f63876a04672c7b522",
     17            "bytes": 48455
    1818        },
    1919        "LICENSE": {
    … …  
    3030        },
    3131        "assets/css/admin.css": {
    32             "sha256": "6b3a98e3f82b059256417d06affd886b3cdf02774588357def7bae965bbd619b",
    33             "bytes": 147275
     32            "sha256": "dd2fe2601f75a910bfd555218aaa07113e25c2929b97c453148fad1e83a44e0e",
     33            "bytes": 147982
    3434        },
    3535        "assets/css/cashback.css": {
    … …  
    178178        },
    179179        "assets/js/account-auth.js": {
    180             "sha256": "dd7a2783c591df9a8909bf4718d6fb41fee51d74ce34a8848780c0db771e7695",
    181             "bytes": 19908
     180            "sha256": "7e846cd3641b17b99a60cae3da5ee4275bc35817177487685716ec3ce84d8087",
     181            "bytes": 20388
    182182        },
    183183        "assets/js/admin-lite.js": {
    … …  
    250250        },
    251251        "assets/js/wallet-topup.js": {
    252             "sha256": "2903be9ec4595823f27ce1bc28e5bd4efeb77f2c539ec7e1c42d1894947f4712",
    253             "bytes": 7992
     252            "sha256": "4d5d0aa12018eb83fc8257bb6fde6d7f02ce6b7f6f4195e3b3ad2f9e6b15a79f",
     253            "bytes": 8387
    254254        },
    255255        "build-meta/sbom.spdx.json": {
    256             "sha256": "f8832246eae88d35880de89bb20bc8adbaf4e88081b9e228e2873b0a8106b490",
     256            "sha256": "fe232fe419ee9adcd82afb88ba1c539fcb08aa0e6854d0754cdc7689a1605227",
    257257            "bytes": 2092
    258258        },
    … …  
    262262        },
    263263        "nabz.php": {
    264             "sha256": "67264f59f16fb7154de3d5d5b4a8e82d2628476ba9fb7f937e64d18b12574b9c",
     264            "sha256": "63ac5b9f015bf508d98290f0bc114e94985a9b79f69d343f0bedb1cc6858539b",
    265265            "bytes": 2921
    266266        },
    267267        "readme.txt": {
    268             "sha256": "8b4c53a6e9b7c0bf6c7f03d9dd4768cfcd6b0e21b3ae27924516ab42dbdc77f6",
    269             "bytes": 18537
     268            "sha256": "bac6d910428e6db2a0e01444f777d37d26b2478ade6fda259d508c8c4a2a45b3",
     269            "bytes": 20533
    270270        },
    271271        "src/Admin/AccountGate.php": {
    272             "sha256": "0142b3044be9015970915ed64715ef2b600b94ddd95f1a78fbb9bda386565298",
    273             "bytes": 4344
     272            "sha256": "0bb1f0157532d669a2daefc8e2804438db10aa16ed8c9098d312d2073f8eb5c3",
     273            "bytes": 4681
    274274        },
    275275        "src/Admin/AdminRecipients.php": {
    … …  
    278278        },
    279279        "src/Admin/Menu.php": {
    280             "sha256": "7f359143c42539bfd39bbae71428fb63cb8185960325227aac92d15c8edde7c3",
    281             "bytes": 18744
     280            "sha256": "95cf7c57c293e632fdaad2538985a31c9dba1512b043ba7a4e3f0eeca34f5bb5",
     281            "bytes": 18787
    282282        },
    283283        "src/Admin/Onboarding.php": {
    … …  
    294294        },
    295295        "src/Admin/Pages/CashbackPage.php": {
    296             "sha256": "be332ab7dff5594046ab5b8e3e8641fa5c5b1183602400d7a66ad35d6a7c0f77",
    297             "bytes": 42278
     296            "sha256": "792305264d3e57c27826d70a968bf10d8b9437595d547a2576de74beb7159d56",
     297            "bytes": 42318
    298298        },
    299299        "src/Admin/Pages/CustomersPage.php": {
    300             "sha256": "eb5f1c1df867fc6f4d8b166a84f76098ecdb0e445ff37f6651209b2bdbe9f4cf",
    301             "bytes": 30772
     300            "sha256": "2787adf5e117d014d7fd55849fe7de94471189974e7209adbb6c40f358b4604f",
     301            "bytes": 30747
    302302        },
    303303        "src/Admin/Pages/FreeMessagesPage.php": {
    304             "sha256": "05968081a38f835c072ddaebf901562693d0a20c79c0c2c1f20ac2fad81700dc",
    305             "bytes": 17037
     304            "sha256": "376949e30ab3082c7374ca22d757b6afbb1d0942aa24cc6721a94a21cd876400",
     305            "bytes": 17049
    306306        },
    307307        "src/Admin/Pages/LicensePage.php": {
    308             "sha256": "6f50dd6df56fa92988787e47b3a0c3a818adb51d3debc4141358cad6201ba75e",
    309             "bytes": 32546
     308            "sha256": "f81f403de1f363c3e5783ad09d8e4cd2c94361650af7335d3a71372f4f317bf8",
     309            "bytes": 33029
    310310        },
    311311        "src/Admin/Pages/LogsPage.php": {
    … …  
    337337            "bytes": 5637
    338338        },
     339        "src/Admin/SmsGatewayForm.php": {
     340            "sha256": "1fcb1426c8984c460931ef60b2e2f1efee37ad124dcfa9c5c3574866a5bfd52c",
     341            "bytes": 9356
     342        },
    339343        "src/Admin/Views/AnalyticsView.php": {
    340344            "sha256": "1ff8692dbdc69d5699a71f6d7c69f50ef3baabee67aa93a3c68cef964805a5c7",
    … …  
    358362        },
    359363        "src/Admin/Views/MessengersView.php": {
    360             "sha256": "3f19d0ef1c351570351b0a965f241ec9f983f83411d5c27f0ef95678f8ade1a9",
    361             "bytes": 33646
     364            "sha256": "72aac06b011c976fac56de892b541a67cc4016e185abca1db10766b1255ae8f5",
     365            "bytes": 33791
    362366        },
    363367        "src/Admin/Views/SmsLoginView.php": {
    … …  
    389393            "bytes": 2779
    390394        },
     395        "src/Analytics/Sync.php": {
     396            "sha256": "d4972ee8b016b3b5fc560b770ef99c35295f3a345596403f31b4301608e2afac",
     397            "bytes": 7562
     398        },
    391399        "src/Api/CircuitBreaker.php": {
    392400            "sha256": "fda9f9a55680c2e8a9ced0edae533fb42f3c9cd346723808d7c01ce839e267f4",
    … …  
    394402        },
    395403        "src/Api/Client.php": {
    396             "sha256": "9e3d4ccb1bf4b22276bcf464c56f28e5da235157f87e84757c24c7046262ae29",
    397             "bytes": 34052
     404            "sha256": "79129f198e0f4c6c825236cd9dbafe53dd5e68a90ad28d36d2873edc7d50a275",
     405            "bytes": 35478
    398406        },
    399407        "src/Auth/BusinessAccount.php": {
    400             "sha256": "74b77bfc07947797774b54279c4e977e44282688d0dbbc884bf00a1f6c1fdcdb",
    401             "bytes": 18414
     408            "sha256": "a14947aa6550139f280cb1021f90bf7964da91e48c984332621529595dc21f6f",
     409            "bytes": 20388
    402410        },
    403411        "src/Auth/CheckoutOtp.php": {
    … …  
    422430        },
    423431        "src/Cashback/Cart.php": {
    424             "sha256": "a66350f4964c894dde737075b205ccc7185884663f1f4204e1f996c6b226a60b",
    425             "bytes": 11352
     432            "sha256": "0e2e24260aa8d77da1b2d870b329f8715b735c9ee7bd4921636647fc63c5c038",
     433            "bytes": 14047
    426434        },
    427435        "src/Cashback/CashbackWidget.php": {
    … …  
    430438        },
    431439        "src/Cashback/Expiry.php": {
    432             "sha256": "7de7101676626b0d93a200139e91990175ef9709ee7f3fed05790d455d9c506f",
    433             "bytes": 3593
     440            "sha256": "ba828b54eb4818b4af3b57faab02eccb92f99cba72024819c4905e01fc9ff3cc",
     441            "bytes": 3846
    434442        },
    435443        "src/Cashback/Frontend.php": {
    … …  
    442450        },
    443451        "src/Cashback/Lifecycle.php": {
    444             "sha256": "de1b23515a88e6ff8611ca24ed613df637f61764c0046315c9c429d17331a803",
    445             "bytes": 25289
     452            "sha256": "b5f0585bc612fbdbf89d86105b1bfb0ab856f29971f541482bc1bcbdf026b39f",
     453            "bytes": 26036
    446454        },
    447455        "src/Cashback/Schema.php": {
    … …  
    474482        },
    475483        "src/Crm/RfmCalculator.php": {
    476             "sha256": "e0827e438269e85d39012c8009c1bfe0c7febd1bcc72bbe7e3359dcec7b33383",
    477             "bytes": 18186
     484            "sha256": "a496d3bfc202c07704934d488c1d2d163fde83eb93405f817b01c240bb4317c9",
     485            "bytes": 17813
    478486        },
    479487        "src/Crm/RfmRepository.php": {
    … …  
    486494        },
    487495        "src/Crm/Schema.php": {
    488             "sha256": "501e50914102ef028837018510aeb7100b7dd0244a29fe15b46f7a6881d1f1ff",
    489             "bytes": 2249
     496            "sha256": "798a4282b329f87393840a270a681270de1877583a622756167e871b69ddddda",
     497            "bytes": 3317
    490498        },
    491499        "src/Crm/Segments.php": {
    … …  
    530538        },
    531539        "src/Jobs/Dispatcher.php": {
    532             "sha256": "01c5a1306cfa140a7aa951f00bd2372235fd704ef1fe856d211160eb694391f8",
    533             "bytes": 12154
     540            "sha256": "4872191ccd834d83ced6e4c5af9c22be916ab6074db91c19486f1d778ff9921d",
     541            "bytes": 12494
    534542        },
    535543        "src/Jobs/JobManager.php": {
    536             "sha256": "929d75066aae036067f6ab0a2a3f12a572dbca0a5476d850d073688a66971b54",
    537             "bytes": 29362
     544            "sha256": "e10ba07e47061d30702dfda88357f486a447e8d8651ba2c897e7bcf361d5ee0c",
     545            "bytes": 34210
     546        },
     547        "src/Jobs/Scheduler.php": {
     548            "sha256": "d9cbdc38e706c0602c382fa1d813e2cb52e1a009a2fe6fe643486fe098c8ce64",
     549            "bytes": 10320
    538550        },
    539551        "src/Jobs/Schema.php": {
    … …  
    542554        },
    543555        "src/Jobs/Worker.php": {
    544             "sha256": "9db2c781cb3ea33b26d0900b223399dfa2def2d6306800ae3cb5133202bd3927",
    545             "bytes": 6827
     556            "sha256": "19aaf282917bad345bb509a57adb3ca83568a20936fe068ff582b9672a79ecef",
     557            "bytes": 6798
    546558        },
    547559        "src/Orders/DeliveryEstimate.php": {
    … …  
    558570        },
    559571        "src/Plugin.php": {
    560             "sha256": "1fdb58f60ddf3d9350d4b88ba98df276ad0784a8d7e923fd06d9846a5f825969",
    561             "bytes": 28750
     572            "sha256": "9126d87a30c6cd4d1029a549c8427caaf2bb5a4998b0368e8abf0b125453aebf",
     573            "bytes": 23100
    562574        },
    563575        "src/Privacy.php": {
    564             "sha256": "af5384ca545065905db4d49e01cbc31c68c5839c7c08fa4fd0aada35a25c67ad",
    565             "bytes": 14599
     576            "sha256": "cb419fa4772e8b50531599c2974bffb0fd8c911aac1cadaa690e3c1390133faf",
     577            "bytes": 15332
    566578        },
    567579        "src/Product/Features.php": {
    … …  
    574586        },
    575587        "src/Settings/Options.php": {
    576             "sha256": "17b4547c038be9f5ec22f27d37de6118bdc2efd7821e7637ad34c3e96a6443fc",
    577             "bytes": 23952
     588            "sha256": "ad50ae08ecefb19213a041d7ec2ac37a800a6309852105f1c846cb5c9c2df6a3",
     589            "bytes": 24274
     590        },
     591        "src/Sms/ExternalGateway.php": {
     592            "sha256": "080334d5187a144388a34c563dd79313ef3a85a06d428280161593bc34a4d985",
     593            "bytes": 7557
     594        },
     595        "src/Sms/ExternalOtp.php": {
     596            "sha256": "719a9934aa54c22f5265b749d06e93a4dba725e5aff0b55c719f1fa392c3399e",
     597            "bytes": 5361
     598        },
     599        "src/Sms/GatewayAdapters.php": {
     600            "sha256": "7922fe394905997e09bb5feaf32cd58a35b442f8f87e53f678cf08879b184690",
     601            "bytes": 8458
     602        },
     603        "src/Sms/GatewaySettings.php": {
     604            "sha256": "5f2304b0afc715c131bfe6f0e19b4522575f2aadd4b60b0d6973355c6790f916",
     605            "bytes": 8647
     606        },
     607        "src/Sms/LocalTemplates.php": {
     608            "sha256": "fd2c7302ff541b448db45b67911424f858d74239b0b9897259475dac1e647c28",
     609            "bytes": 2857
    578610        },
    579611        "src/Sms/MessageGroups.php": {
    … …  
    582614        },
    583615        "src/Sms/Sender.php": {
    584             "sha256": "75c6e7362786978e38b1358c03652b35c0ff92f9d1e690fbe969f3222353b0e6",
    585             "bytes": 7794
     616            "sha256": "5557ccdfadc4cab18df989d59ff965eb5dea4831e8c48c6afc99ff5cdc3dd1ec",
     617            "bytes": 8445
     618        },
     619        "src/Sms/templates.json": {
     620            "sha256": "d42471824a08cb6b11dbe90ad07e7690d2f4efa064bab3b29b1190affd947708",
     621            "bytes": 17247
    586622        },
    587623        "src/Support/CouponCodes.php": {
    … …  
    602638        },
    603639        "src/Support/LogFormatter.php": {
    604             "sha256": "71aefed3bc776bddadfa5e98162a7bc67f6c8135d47fe60ab0009b9500902f1f",
    605             "bytes": 25923
     640            "sha256": "9648497f25fe2353c39e711fc103defbe7521f6cb81ba7741582ebb41a9377a8",
     641            "bytes": 26845
    606642        },
    607643        "src/Support/Logger.php": {
  • nabz-lite/trunk/build-meta/sbom.spdx.json

    r3750712 r3757421  
    33    "dataLicense": "CC0-1.0",
    44    "SPDXID": "SPDXRef-DOCUMENT",
    5     "name": "nabz-1.5.10-source",
    6     "documentNamespace": "https://nabz.business/spdx/nabz/1.5.10/source",
     5    "name": "nabz-1.5.17-source",
     6    "documentNamespace": "https://nabz.business/spdx/nabz/1.5.17/source",
    77    "creationInfo": {
    8         "created": "2026-10-16T15:44:24Z",
     8        "created": "2026-10-20T20:04:01Z",
    99        "creators": [
    1010            "Organization: Nabz",
    … …  
    1616            "name": "nabz",
    1717            "SPDXID": "SPDXRef-Package-Nabz",
    18             "versionInfo": "1.5.10",
     18            "versionInfo": "1.5.17",
    1919            "downloadLocation": "NOASSERTION",
    2020            "filesAnalyzed": false,
  • nabz-lite/trunk/nabz.php

    r3750712 r3757421  
    44 * Plugin URI:  https://nabz.business/
    55 * Description: ابزار رایگان افزایش فروش ووکامرس با مدیریت مشتریان، تحلیل فروش، کش‌بک، بازیابی سبد رهاشده و ورود پیامکی.
    6  * Version:     1.5.10
     6 * Version:     1.5.17
    77 * Author:      Ali Beheshti
    88 * Text Domain: nabz-lite
    … …  
    1616defined( 'ABSPATH' ) || exit;
    1717
    18 define( 'NABZ_VERSION', '1.5.10' );
     18define( 'NABZ_VERSION', '1.5.17' );
    1919define( 'NABZ_EDITION', 'lite' );
    2020define( 'NABZ_FILE', __FILE__ );
  • nabz-lite/trunk/readme.txt

    r3750712 r3757421  
    66Requires PHP: 7.4
    77Requires Plugins: woocommerce
    8 Stable tag: 1.5.10
     8Stable tag: 1.5.17
    99License: GPLv2 or later
    1010License URI: https://www.gnu.org/licenses/gpl-2.0.html
    … …  
    5151حساب متصل برای همگام‌سازی وضعیت و موجودی، دریافت پیش‌نمایش پیام، ساخت فاکتور شارژ و دریافت گزارش ارسال با نبض ارتباط دارد. ارسال پیام شامل کانال، رویداد، شمارهٔ گیرنده، شناسهٔ جلوگیری از ارسال تکراری و حداقل اطلاعات لازم است؛ مانند نام مشتری یا فروشگاه، شماره و مبلغ سفارش، وضعیت پرداخت یا مرسوله، کد رهگیری و لینک مرتبط. نبض متن نهایی و اطلاعات لازم گیرنده را به ارائه‌دهندهٔ ارسال می‌دهد.
    5252
     53پس از اتصال حساب، آمار ارسال موفق و کلیک به تفکیک نوع پیام نیز خودکار با نبض همگام می‌شود: شناسهٔ هش‌شدهٔ پیام، نوع پیام، تعداد کلیک و زمان ارسال و اولین/آخرین کلیک. این همگام‌سازی شماره موبایل، نام مشتری، IP، مرورگر، متن پیام یا نشانی مقصد را ارسال نمی‌کند.
     54
    5355شارژ کیف پول با لینک یک‌بارمصرف به پرداخت حساب نبض منتقل می‌شود و به همان فروشگاه و حساب متقاضی مقید است. افزونه ممکن است برای اجرای صف، به همان نصب وردپرس درخواست داخلی بفرستد.
    5456
    … …  
    111113== Changelog ==
    112114
     115= 1.5.17 =
     116- همگام‌سازی خودکار و قابل‌بازیابی آمار ارسال و کلیک با دیتابیس مرکزی نبض، مستقل از WP-Cron و با انتقال سوابق موجود.
     117
     118= 1.5.16 =
     119- حفظ اتصال مستقل فروشگاه، موجودی و صف پیام‌ها هنگام پایان نشست مدیریتی حساب.
     120
     121= 1.5.15 =
     122- تبدیل داده‌محور جدول قدیمی RFM از MyISAM/Aria به InnoDB پیش از محاسبه، با حفظ رکوردهای قبلی و توقف امن در صورت نداشتن دسترسی.
     123- نمایش علت شکست و زمان تلاش مجدد کارهای زمان‌بند در گزارش‌ها.
     124
     125= 1.5.14 =
     126- اجرای صف و محاسبات با زمان‌بند اختصاصی روی init و ادامهٔ غیرهم‌زمان، مستقل از فعال‌بودن WP-Cron.
     127- انتقال رویدادهای قبلی نبض به صف پایدار، قفل اجرای هم‌زمان و تلاش مجدد مستقل برای هر کار.
     128- اجرای محاسبهٔ دستی از همان صف و اعلام خطای واقعی در صورت ناموفق‌بودن ثبت کار.
     129
     130= 1.5.13 =
     131- افزودن کاوه‌نگار، SMS.ir و قاصدک برای ارسال متن و الگوی تأییدشده و OTP از پنل شخصی.
     132- اعتبارسنجی نام و مقدار متغیرهای کاوه‌نگار، رسید هر پنل و حفظ صف مستقل هنگام خروج از حساب نبض.
     133
     134
    113135= 1.5.10 =
    114136* گزینه و ارسال اعلان سبد رهاشده برای مدیر حذف شد؛ پیام‌های قدیمی این اعلان در صف نیز ارسال نمی‌شوند.
  • nabz-lite/trunk/src/Admin/AccountGate.php

    r3737123 r3757421  
    4949
    5050    /** Check account access before rendering forms or making API requests. */
    51     public static function page( string $title, string $icon, callable $renderer ): callable {
    52         return static function () use ( $title, $icon, $renderer ): void {
     51    public static function page( string $title, string $icon, callable $renderer, bool $allow_external_sms = true ): callable {
     52        return static function () use ( $title, $icon, $renderer, $allow_external_sms ): void {
    5353            if ( ! current_user_can( 'manage_options' ) ) {
    5454                return;
    5555            }
    56             if ( BusinessAccount::is_authenticated() ) {
     56            if ( BusinessAccount::is_authenticated() || ( $allow_external_sms && \Nabz\Sms\GatewaySettings::ready() ) ) {
    5757                $renderer();
    5858                return;
    … …  
    7777            <span class="nbz-account-gate__icon"><?php echo Icons::get( 'lock' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
    7878            <h2>لطفاً ابتدا وارد شوید</h2>
    79             <p>برای استفاده از این بخش، وارد حساب نبض شوید.</p>
     79            <p>برای استفاده از پیامک، در صفحهٔ اتصال و اعتبار پنل خود را تنظیم کنید یا وارد حساب نبض شوید.</p>
    8080            <a class="button button-primary" href="<?php echo esc_url( self::login_url() ); ?>">ورود به حساب نبض</a>
    8181        </section>
    … …  
    8686    public static function require_login(): void {
    8787        $can_manage = current_user_can( 'manage_options' );
    88         if ( $can_manage && BusinessAccount::is_authenticated() ) {
     88        $local_sms = strpos( current_filter(), 'nabz_messenger_' ) === false && \Nabz\Sms\GatewaySettings::ready();
     89        if ( $can_manage && ( BusinessAccount::is_authenticated() || $local_sms ) ) {
    8990            return;
    9091        }
  • nabz-lite/trunk/src/Admin/Menu.php

    r3743205 r3757421  
    6060        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
    6161        ( new PetReporter() )->register();
     62        SmsGatewayForm::register();
    6263
    6364        if ( defined( 'NABZ_DEV' ) && NABZ_DEV ) {
    … …  
    169170            AccountGate::page( 'پیام‌رسان‌ها', 'chat', static function () use ( $messengers ): void {
    170171                PremiumPreview::render_page( Features::MESSENGERS, $messengers ? [ $messengers, 'render' ] : null );
    171             } )
     172            }, false )
    172173        );
    173174        add_submenu_page(
  • nabz-lite/trunk/src/Admin/Pages/CashbackPage.php

    r3743205 r3757421  
    239239
    240240    private function render_sms( bool $cashback_enabled ): void {
    241         if ( ! \Nabz\Auth\BusinessAccount::is_authenticated() ) {
     241        if ( ! \Nabz\Auth\BusinessAccount::is_authenticated() && ! \Nabz\Sms\GatewaySettings::ready() ) {
    242242            \Nabz\Admin\AccountGate::render( true );
    243243            return;
  • nabz-lite/trunk/src/Admin/Pages/CustomersPage.php

    r3750451 r3757421  
    3232        }
    3333        check_admin_referer( 'nabz_rfm_recompute' );
    34         if ( ! wp_next_scheduled( 'nabz_rfm_recompute' ) ) {
    35             $now = time();
    36             wp_schedule_single_event( $now, 'nabz_rfm_recompute' );
    37             if ( function_exists( 'spawn_cron' ) ) {
    38                 spawn_cron( $now );
    39             }
     34        if ( ! \Nabz\Plugin::schedule_rfm_refresh( 0 ) ) {
     35            wp_die( 'ثبت محاسبه در صف انجام نشد؛ دوباره تلاش کنید.', 'خطای صف نبض', [ 'response' => 503, 'back_link' => true ] );
    4036        }
    4137        wp_safe_redirect( add_query_arg( [
  • nabz-lite/trunk/src/Admin/Pages/FreeMessagesPage.php

    r3750712 r3757421  
    3333
    3434        $previews = [];
    35         if ( (string) Options::get( 'installation_token', '' ) !== '' ) {
     35        if ( Options::delivery_connected() ) {
    3636            $response = $this->container->get( Client::class )->message_previews();
    3737            if ( ! empty( $response['ok'] ) && is_array( $response['body']['previews'] ?? null ) ) {
    … …  
    5050                            <?php echo wp_kses( HelpLink::get( 'message-types', 'مدیریت پیام‌ها' ), HelpLink::allowed_html() ); ?>
    5151                        </h1>
    52                         <p class="ss-header__subtitle">همهٔ رویدادهای پیام را ببینید و پیام‌های رایگان را مدیریت کنید. رویدادهای قفل‌شده با نبض پریمیوم فعال می‌شوند. هزینهٔ ارسال از کیف پول سرویس نبض کسر می‌شود.</p>
     52                        <p class="ss-header__subtitle">همهٔ رویدادهای پیام را ببینید و پیام‌های رایگان را مدیریت کنید. رویدادهای قفل‌شده با نبض پریمیوم فعال می‌شوند. هزینهٔ ارسال از پنل پیامکی انتخاب‌شده کسر می‌شود.</p>
    5353                    </div>
    5454                    <span class="ss-header__badge"><?php echo esc_html( number_format_i18n( count( $free_types ) ) ); ?> نوع پیام رایگان</span>
    … …  
    8282                            <?php $first = true; foreach ( $groups as $key => $group ) : ?>
    8383                                <div id="nbz-message-panel-<?php echo esc_attr( $key ); ?>" class="ss-tab-panel<?php echo $first ? ' is-active' : ''; ?>" data-tab-panel="<?php echo esc_attr( $key ); ?>" role="tabpanel" aria-labelledby="nbz-message-tab-<?php echo esc_attr( $key ); ?>">
    84                                     <?php if ( $key === 'cashback' ) : ?><p class="ss-field__hint">کش‌بک، کیف پول و پیامک‌های خودکار این بخش در لایت فعال‌اند؛ هزینهٔ ارسال از اعتبار حساب نبض کسر می‌شود.</p><?php endif; ?>
     84                                    <?php if ( $key === 'cashback' ) : ?><p class="ss-field__hint">کش‌بک، کیف پول و پیامک‌های خودکار این بخش در لایت فعال‌اند؛ هزینهٔ ارسال از اعتبار پنل انتخاب‌شده کسر می‌شود.</p><?php endif; ?>
    8585                                    <div class="ss-msg-grid">
    8686                                        <?php foreach ( $group['types'] as $type ) : ?>
    … …  
    154154            'order_tracking_auto_send' => ! empty( $_POST['order_tracking_auto_send'] ),
    155155        ], \Nabz\Settings\CartRecovery::posted_settings( $_POST, $enabled ) ) );
    156         if ( (string) Options::get( 'installation_token', '' ) !== '' ) {
     156        if ( ! \Nabz\Sms\GatewaySettings::external() && Options::delivery_connected() ) {
    157157            Options::set( 'last_heartbeat_attempt', 0 );
    158158            $this->container->get( Client::class )->announce();
  • nabz-lite/trunk/src/Admin/Pages/LicensePage.php

    r3750451 r3757421  
    7272                        <?php echo wp_kses( \Nabz\Support\HelpLink::get( 'activate-license', 'اتصال و اعتبار' ), \Nabz\Support\HelpLink::allowed_html() ); ?>
    7373                    </h1>
    74                     <p class="ss-header__subtitle" data-nbz-page-subtitle><?php echo $account_authenticated ? 'در این صفحه وضعیت اتصال سرویس‌ها و کیف پول را می‌بینید.' : 'برای اتصال به حساب نبض با کد تأیید پیامکی وارد شوید.'; ?></p>
     74                    <p class="ss-header__subtitle" data-nbz-page-subtitle><?php echo $account_authenticated ? 'در این صفحه وضعیت اتصال سرویس‌ها و کیف پول را می‌بینید.' : 'پنل پیامکی خود را انتخاب کنید؛ برای استفاده از سرویس نبض، با کد تأیید وارد شوید.'; ?></p>
    7575                </div>
    7676            </div>
    … …  
    9797            <?php // phpcs:enable WordPress.Security.NonceVerification.Recommended ?>
    9898
     99            <?php \Nabz\Admin\SmsGatewayForm::render(); ?>
    99100            <div class="ss-card nbz-account-card nbz-account-status-card" data-nbz-account-card data-authenticated="<?php echo $account_authenticated ? '1' : '0'; ?>">
    100101                <div class="ss-card__header">
    … …  
    105106                            <?php echo wp_kses( \Nabz\Support\HelpLink::get( 'activate-license', 'شماره موبایل حساب نبض' ), \Nabz\Support\HelpLink::allowed_html() ); ?>
    106107                        </h2>
    107                         <p class="ss-card__desc" data-nbz-account-description><?php echo $account_authenticated ? 'وضعیت حساب و اتصال همین دامنه را اینجا ببینید.' : 'برای اتصال به حساب نبض با کد تأیید پیامکی وارد شوید.'; ?></p>
     108                        <p class="ss-card__desc" data-nbz-account-description><?php echo $account_authenticated ? 'وضعیت حساب و اتصال همین دامنه را اینجا ببینید.' : 'پنل پیامکی خود را انتخاب کنید؛ برای استفاده از سرویس نبض، با کد تأیید وارد شوید.'; ?></p>
    108109                    </div>
    109110                    <span class="ss-badge ss-badge--success" data-nbz-account-badge<?php echo $account_authenticated ? '' : ' hidden'; ?>><span class="ss-dot"></span> واردشده</span>
    … …  
    380381        $error_message = (string) ( ( $account['last_error'] ?? '' ) );
    381382        ?>
    382                 <div class="nbz-account-login" data-nbz-account-login<?php echo $authenticated ? ' hidden' : ''; ?>>
     383                <div class="nbz-account-login" data-nbz-account-login<?php echo $authenticated && empty( $account['reauth_required'] ) ? ' hidden' : ''; ?>>
     384                    <p class="ss-field__hint" data-nbz-account-reauth<?php echo empty( $account['reauth_required'] ) ? ' hidden' : ''; ?>>اتصال ارسال پیام برقرار است. برای شارژ کیف پول، ورود با کد تأیید را تازه کنید.</p>
    383385                    <form data-nbz-account-mobile-form novalidate>
    384386                        <div class="ss-field">
  • nabz-lite/trunk/src/Admin/Views/MessengersView.php

    r3744674 r3757421  
    117117                                        <div class="nbz-msgr-account__track nbz-msgr-account__track--empty" aria-hidden="true"><i style="width:0%"></i></div>
    118118                                    </div>
     119                                    <?php if ( ! $sms_enabled || ! empty( $accounts ) ) : ?>
    119120                                    <div class="nbz-msgr-account__actions">
    120121                                        <form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
    … …  
    128129                                        </form>
    129130                                    </div>
     131                                    <?php endif; ?>
    130132                                </article>
    131133                            <?php endif; ?>
  • nabz-lite/trunk/src/Api/Client.php

    r3750451 r3757421  
    410410    }
    411411
    412     /** Customer login OTP uses the connected wallet in both editions. */
     412    /** Customer OTP uses the selected SMS service in both editions; Nabz account OTP stays central. */
    413413    public function otp_send( string $mobile, string $idempotency_key = '' ): array {
     414        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::request( $mobile ); }
    414415        $idempotency_key = $idempotency_key !== '' ? $idempotency_key : wp_generate_uuid4();
    415416        return $this->post( '/api/v1/plugin/otp/send',
    … …  
    419420
    420421    public function otp_retry( string $challenge_id, string $idempotency_key = '' ): array {
     422        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::retry( $challenge_id ); }
    421423        $idempotency_key = $idempotency_key !== '' ? $idempotency_key : wp_generate_uuid4();
    422424        return $this->post( '/api/v1/plugin/otp/retry',
    … …  
    427429    /** One storefront request: renew an expired challenge, never retry an uncertain send. */
    428430    public function otp_request( string $mobile, string $challenge_id = '' ): array {
     431        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::request( $mobile, $challenge_id ); }
    429432        if ( $challenge_id === '' ) {
    430433            return $this->otp_send( $mobile );
    … …  
    439442
    440443    public function otp_verify( string $challenge_id, string $code, string $mobile ): array {
     444        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\ExternalOtp::verify( $challenge_id, $code, $mobile ); }
    441445        return $this->post( '/api/v1/plugin/otp/verify',
    442446            array_merge( $this->connection_payload(), [
    … …  
    560564     */
    561565    public function send_event( string $message_type, string $customer_number, array $parameters, string $channel = 'sms', string $idempotency_key = '' ): array {
     566        if ( $channel === 'sms' && \Nabz\Sms\GatewaySettings::external() ) {
     567            return \Nabz\Sms\ExternalGateway::send( $message_type, $customer_number, $parameters, $idempotency_key );
     568        }
    562569        if ( ! $this->is_v1() ) {
    563570            return self::unsupported( 'ارسال متمرکز پیامک؛ بک‌اند قدیمی باید به نسخه v1 ارتقا پیدا کند' );
    … …  
    608615    }
    609616
     617    /** Send only non-personal analytics records; the token never enters the checkpoint. */
     618    public function analytics_sync( array $payload, string $idempotency_key ): array {
     619        return $this->post( '/api/v1/plugin/analytics/sync', array_merge( $payload, $this->connection_payload() ), 8.0,
     620            [ 'Idempotency-Key' => $idempotency_key ] );
     621    }
     622
     623    public function analytics_scope(): string {
     624        return hash( 'sha256', self::configured_api_base() . '|' . self::current_domain() . '|' . (int) Options::get( 'installation_account_id', 0 ) . '|' . (int) Options::get( 'account_user_id', 0 ) );
     625    }
     626
    610627    /**
    611628     * Pull the backend-side send log (message_logs) for this site. The backend
    … …  
    648665     */
    649666    public function message_previews(): array {
     667        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\LocalTemplates::previews(); }
    650668        if ( ! $this->is_v1() ) {
    651669            return self::unsupported( 'پیش‌نمایش متن متمرکز پیامک' );
  • nabz-lite/trunk/src/Auth/BusinessAccount.php

    r3750451 r3757421  
    3838        $last_error = (string) ( Options::get( 'account_last_error', '' ) ?: Options::get( 'last_sync_error', '' ) );
    3939        return [
    40             'authenticated' => $phone !== '' && trim( (string) Options::get( 'account_session_cookie', '' ) ) !== '',
     40            'authenticated' => self::portal_authenticated() || Options::account_connected(),
     41            'reauth_required' => Options::account_connected() && ! self::portal_authenticated(),
    4142            'phone'         => $phone,
    4243            'phone_display' => $display_phone,
    … …  
    6061        $state = self::state();
    6162        return ! empty( $state['authenticated'] );
     63    }
     64
     65    private static function portal_authenticated(): bool {
     66        return trim( (string) Options::get( 'account_phone', '' ) ) !== ''
     67            && trim( (string) Options::get( 'account_session_cookie', '' ) ) !== ''
     68            && trim( (string) Options::get( 'account_csrf_token', '' ) ) !== '';
     69    }
     70
     71    /** A portal 401 is not revocation of the separately authenticated site credential. */
     72    private static function expire_portal_session(): void {
     73        Options::update( [ 'account_session_cookie' => '', 'account_csrf_token' => '' ] );
     74    }
     75
     76    private static function require_portal_login(): void {
     77        wp_send_json_error( [
     78            'code' => 'account_reauth_required',
     79            'msg' => Options::account_connected()
     80                ? 'برای شارژ کیف پول دوباره کد تأیید را وارد کنید. اتصال ارسال پیام تغییری نکرده است.'
     81                : 'ابتدا با کد تأیید وارد حساب نبض شوید.',
     82            'state' => self::state(),
     83        ], 401 );
    6284    }
    6385
    … …  
    161183                'msg'  => $this->provider_error( $response, 'خواندن وضعیت حساب از nabz.business ناموفق بود.' ),
    162184                'code' => 'context_failed',
     185                'state' => self::state(),
    163186            ], $this->http_status( $response ) );
    164187        }
    … …  
    168191    public function ajax_checkout_options(): void {
    169192        $this->authorize_ajax();
    170         if ( ! self::is_authenticated() ) {
    171             wp_send_json_error( [ 'msg' => 'ابتدا وارد حساب نبض شوید.' ], 401 );
     193        if ( ! self::portal_authenticated() ) {
     194            self::require_portal_login();
    172195        }
    173196        $response = $this->client->account_checkout_options(
    … …  
    177200        if ( ! $response['ok'] || ! is_array( $response['body'] ?? null ) ) {
    178201            if ( (int) ( $response['status'] ?? 0 ) === 401 ) {
    179                 self::clear();
     202                self::expire_portal_session();
     203                self::require_portal_login();
    180204            }
    181205            wp_send_json_error( [ 'msg' => $this->provider_error( $response, 'دریافت گزینه‌های خرید ممکن نشد.' ) ], $this->http_status( $response ) );
    … …  
    186210    public function ajax_create_invoice(): void {
    187211        $this->authorize_ajax();
    188         if ( ! self::is_authenticated() ) {
    189             wp_send_json_error( [ 'msg' => 'ابتدا وارد حساب نبض شوید.' ], 401 );
     212        if ( ! self::portal_authenticated() ) {
     213            self::require_portal_login();
    190214        }
    191215        $kind = isset( $_POST['kind'] ) ? sanitize_key( (string) wp_unslash( $_POST['kind'] ) ) : '';
    … …  
    214238        if ( ! $response['ok'] || ! is_array( $response['body'] ?? null ) ) {
    215239            if ( (int) ( $response['status'] ?? 0 ) === 401 ) {
    216                 self::clear();
     240                self::expire_portal_session();
     241                self::require_portal_login();
    217242            }
    218243            wp_send_json_error( [ 'msg' => $this->provider_error( $response, 'ساخت فاکتور ممکن نشد.' ) ], $this->http_status( $response ) );
    … …  
    267292        $csrf    = trim( (string) Options::get( 'account_csrf_token', '' ) );
    268293        if ( $session === '' || $csrf === '' ) {
     294            if ( Options::account_connected() ) {
     295                return $this->sync_connection();
     296            }
    269297            return [ 'ok' => false, 'status' => 401, 'body' => null, 'error' => 'not_authenticated' ];
    270298        }
    … …  
    272300        if ( ! $response['ok'] || ! is_array( $response['body'] ?? null ) ) {
    273301            if ( (int) ( $response['status'] ?? 0 ) === 401 ) {
    274                 self::clear();
     302                self::expire_portal_session();
     303                if ( Options::account_connected() ) {
     304                    return $this->sync_connection();
     305                }
    275306            }
    276307            Options::set( 'account_last_error', (string) ( $response['error'] ?? 'context_failed' ) );
    … …  
    320351    }
    321352
     353    /** Check the existing site token with the API; never create or renew a portal session. */
     354    private function sync_connection(): array {
     355        $response = array_merge( [ 'status' => 0, 'body' => null, 'error' => '' ], $this->client->announce() );
     356        Options::set( 'account_last_error', empty( $response['ok'] ) ? (string) ( $response['error'] ?? 'context_failed' ) : '' );
     357        if ( ! empty( $response['ok'] ) ) {
     358            Options::set( 'account_last_sync', time() );
     359        }
     360        return $response;
     361    }
     362
    322363    private function authorize_ajax(): void {
    323364        if ( ! current_user_can( 'manage_options' ) ) {
  • nabz-lite/trunk/src/Cashback/Cart.php

    r3688753 r3757421  
    3131        add_filter( 'nabz_cashback_applied_amount', [ $this, 'applied_amount_irr' ], 10, 2 );
    3232        add_action( 'woocommerce_before_calculate_totals', [ $this, 'sync_coupon' ], 5, 1 );
     33        // A wallet can change while a customer keeps checkout open (for
     34        // example, after another tab finishes an order). Refresh the virtual
     35        // coupon immediately before classic checkout creates its order and
     36        // during Store API draft updates so the order total and ledger debit
     37        // use the same current balance.
     38        add_action( 'woocommerce_before_checkout_process', [ $this, 'refresh_checkout_coupon' ], 1 );
     39        add_action( 'woocommerce_store_api_checkout_update_draft', [ $this, 'refresh_checkout_coupon' ], 1 );
    3340        add_action( 'wp_ajax_nabz_cashback_toggle_wallet', [ $this, 'ajax_toggle' ] );
    3441        add_action( 'wp_ajax_nopriv_nabz_cashback_toggle_wallet', [ $this, 'ajax_guest' ] );
    … …  
    137144    }
    138145
     146    /**
     147     * Rebuild the wallet coupon from the authoritative balance before checkout.
     148     *
     149     * WooCommerce may keep the same applied coupon code in the session while
     150     * its virtual amount was calculated earlier. Removing and applying the
     151     * account-bound code again makes `virtual_coupon_data()` read the latest
     152     * ledger balance before WooCommerce copies cart totals into an order.
     153     */
     154    public function refresh_checkout_coupon( ...$ignored ): void {
     155        if ( function_exists( 'wc_load_cart' ) && ( ! function_exists( 'WC' ) || ! WC()->cart ) ) {
     156            wc_load_cart();
     157        }
     158        if ( ! function_exists( 'WC' ) || ! WC()->cart || ! is_object( WC()->cart ) ) {
     159            return;
     160        }
     161
     162        $cart = WC()->cart;
     163        if ( $this->syncing || ! method_exists( $cart, 'has_discount' ) ) {
     164            return;
     165        }
     166
     167        $user_id = get_current_user_id();
     168        $this->remove_foreign_wallet_coupons( $cart, $user_id );
     169        if ( $user_id <= 0 ) {
     170            return;
     171        }
     172        $code = self::coupon_code( $user_id );
     173        if ( $code === '' ) {
     174            return;
     175        }
     176
     177        $this->syncing = true;
     178        try {
     179            // Re-creating the virtual coupon is intentional. The current
     180            // balance may be lower or higher than the amount held by the
     181            // checkout page since its last totals calculation.
     182            if ( $cart->has_discount( $code ) && method_exists( $cart, 'remove_coupon' ) ) {
     183                $cart->remove_coupon( $code );
     184            }
     185
     186            $should_use = $this->should_use_wallet()
     187                && $this->service->enabled()
     188                && $this->service->balance_irr( $user_id ) > 0;
     189            if ( $should_use && method_exists( $cart, 'apply_coupon' ) ) {
     190                $cart->apply_coupon( $code );
     191            }
     192        } finally {
     193            $this->syncing = false;
     194        }
     195
     196        if ( method_exists( $cart, 'calculate_totals' ) ) {
     197            $cart->calculate_totals();
     198        }
     199        if ( method_exists( $cart, 'set_session' ) ) {
     200            $cart->set_session();
     201        }
     202    }
     203
    139204    public function ajax_guest(): void {
    140205        wp_send_json_error( [
  • nabz-lite/trunk/src/Cashback/Expiry.php

    r3688753 r3757421  
    1616    public function register(): void {
    1717        add_action( 'nabz_daily_refresh', [ $this, 'run' ], 30 );
     18        add_action( 'nabz_register_tasks', function ( \Nabz\Jobs\Scheduler $scheduler ): void {
     19            $scheduler->register( 'cashback_expiry', [ $this, 'run' ], DAY_IN_SECONDS, 30 );
     20        } );
    1821    }
    1922
    … …  
    2528            $result = $this->service->expire_all_due( null, 100 );
    2629            if ( is_wp_error( $result ) ) {
    27                 break;
     30                throw new \RuntimeException( $result->get_error_code() );
    2831            }
    2932            $count = is_array( $result ) ? (int) ( $result['processed'] ?? 0 ) : 0;
  • nabz-lite/trunk/src/Cashback/Lifecycle.php

    r3737123 r3757421  
    127127        ] );
    128128        if ( is_wp_error( $result ) ) {
     129            $error_data = $result->get_error_data();
     130            if ( ! is_array( $error_data ) ) {
     131                $error_data = [];
     132            }
     133            if ( function_exists( 'wc_get_logger' ) ) {
     134                wc_get_logger()->error( 'Cashback wallet reservation failed.', [
     135                    'source'        => 'nabz-cashback',
     136                    'error_code'    => $result->get_error_code(),
     137                    'user_id'       => $user_id,
     138                    'order_id'      => $order_id,
     139                    'requested_irr' => $amount,
     140                    'available_irr'  => isset( $error_data['available_irr'] ) ? (int) $error_data['available_irr'] : $this->service->balance_irr( $user_id ),
     141                ] );
     142            }
    129143            // Never let checkout continue with a discount that could not be
    130144            // reserved. WooCommerce turns this exception into a checkout notice.
  • nabz-lite/trunk/src/Crm/RfmCalculator.php

    r3750451 r3757421  
    5858    /** Perform the rebuild after the cross-request lock has been acquired. */
    5959    private function recompute_locked(): array {
     60
     61        if ( ! Schema::ensure_transactional_storage() ) {
     62            return [ 'customers' => 0, 'orders' => 0, 'failed' => 'storage_engine' ];
     63        }
    6064
    6165        $now_utc = time();
    … …  
    117121        // ── persist ──
    118122        global $wpdb;
    119         $engine = $wpdb->get_var( $wpdb->prepare(
    120             'SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s',
    121             Schema::rfm_table()
    122         ) );
    123         if ( strtoupper( (string) $engine ) !== 'INNODB' ) {
    124             // Legacy nontransactional tables must keep their previous snapshot
    125             // rather than silently losing it on an interrupted publication.
    126             return [ 'customers' => 0, 'orders' => $orders_seen, 'failed' => 'storage_engine' ];
    127         }
    128123        if ( false === $wpdb->query( 'START TRANSACTION' ) ) {
    129124            return [ 'customers' => 0, 'orders' => $orders_seen, 'failed' => 'transaction' ];
  • nabz-lite/trunk/src/Crm/Schema.php

    r3688753 r3757421  
    2121        global $wpdb;
    2222        return $wpdb->prefix . 'nabz_automation_runs';
     23    }
     24
     25    /** Upgrade only the derived snapshot; ALTER preserves all existing rows. */
     26    public static function ensure_transactional_storage(): bool {
     27        global $wpdb;
     28        $table = self::rfm_table();
     29        $read_engine = static function () use ( $wpdb, $table ): string {
     30            return strtoupper( (string) $wpdb->get_var( $wpdb->prepare(
     31                'SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=%s',
     32                $table
     33            ) ) );
     34        };
     35        $engine = $read_engine();
     36        if ( $engine === 'INNODB' ) {
     37            return true;
     38        }
     39        if ( ! in_array( $engine, [ 'MYISAM', 'ARIA' ], true ) ) {
     40            return false;
     41        }
     42        // Called under the RFM rebuild lock, before scanning or deleting rows.
     43        // If InnoDB/ALTER is unavailable, leave the previous snapshot in place.
     44        if ( false === $wpdb->query( "ALTER TABLE {$table} ENGINE=InnoDB" ) ) {
     45            return false;
     46        }
     47        return $read_engine() === 'INNODB';
    2348    }
    2449
    … …  
    5883            KEY idx_frequency (frequency),
    5984            KEY idx_last_order_at (last_order_at)
    60         ) {$charset};";
     85        ) ENGINE=InnoDB {$charset};";
    6186
    6287        dbDelta( $sql );
  • nabz-lite/trunk/src/Jobs/Dispatcher.php

    r3750712 r3757421  
    2929    private function route_for( string $message_type ): string {
    3030        try {
     31            if ( \Nabz\Sms\GatewaySettings::external() ) { return ''; }
    3132            return sanitize_key( (string) apply_filters( 'nabz_delivery_route', '', $message_type ) );
    3233        } catch ( \Throwable $e ) {
    … …  
    3839    private function sms_enabled(): bool {
    3940        try {
     41            if ( \Nabz\Sms\GatewaySettings::external() ) { return true; }
    4042            return (bool) apply_filters( 'nabz_sms_delivery_enabled', true );
    4143        } catch ( \Throwable $e ) {
    … …  
    4648    /** Explicit overrides must never degrade to another transport. */
    4749    private function channel_available( string $channel ): bool {
     50        if ( \Nabz\Sms\GatewaySettings::external() ) { return $channel === 'sms' && \Nabz\Sms\GatewaySettings::ready(); }
    4851        try {
    4952            return (bool) apply_filters(
    … …  
    240243            'parameters'      => $parameters,
    241244            'channel'         => 'sms',
     245            'sms_provider'    => \Nabz\Sms\GatewaySettings::provider(),
    242246            // Version the local tracking contract at enqueue time. Previously
    243247            // attempted jobs must keep their original backend fingerprint.
  • nabz-lite/trunk/src/Jobs/JobManager.php

    r3737123 r3757421  
    1818    }
    1919
    20     /** Prevent overlapping queue drains from Cron, admin heartbeat and watchdog. */
     20    /** Prevent overlapping native queue drains, admin heartbeats and watchdogs. */
    2121    public function acquire_worker_lock(): bool {
    2222        global $wpdb;
    … …  
    3939    private function worker_lock_name(): string {
    4040        return 'nabz_worker_' . sha1( $this->table() );
     41    }
     42
     43    /** One async batch, including its wait and successor reservation, per site. */
     44    public function acquire_runner_lock(): bool {
     45        global $wpdb;
     46        return (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', 'nabz_runner_' . sha1( $this->table() ) ) ) === '1';
     47    }
     48
     49    public function release_runner_lock(): void {
     50        global $wpdb;
     51        $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', 'nabz_runner_' . sha1( $this->table() ) ) );
    4152    }
    4253
    … …  
    251262    }
    252263
     264    /** Serialize coalescing so concurrent requests cannot insert duplicate maintenance. */
     265    public function enqueue_maintenance( string $type, int $delay = 0, bool $include_running = false, bool $expedite = true ): ?int {
     266        global $wpdb;
     267        if ( strpos( $type, 'maintenance_' ) !== 0 ) {
     268            return null;
     269        }
     270        $lock = 'nabz_schedule_' . sha1( $this->table() . $type );
     271        if ( (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $lock ) ) !== '1' ) {
     272            return null;
     273        }
     274        try {
     275            $states = $include_running ? "'queued','running'" : "'queued'";
     276            $row = $wpdb->get_row( $wpdb->prepare(
     277                "SELECT id, status FROM {$this->table()} WHERE job_type=%s AND status IN ({$states}) ORDER BY id ASC LIMIT 1",
     278                $type
     279            ), ARRAY_A );
     280            if ( $row ) {
     281                if ( $expedite && $row['status'] === 'queued' ) {
     282                    $updated = $wpdb->query( $wpdb->prepare(
     283                        "UPDATE {$this->table()} SET available_at=LEAST(available_at, %s) WHERE id=%d AND status='queued'",
     284                        gmdate( 'Y-m-d H:i:s', time() + max( 0, $delay ) ), (int) $row['id']
     285                    ) );
     286                    if ( $updated === false ) {
     287                        return null;
     288                    }
     289                }
     290                return (int) $row['id'];
     291            }
     292            return $this->enqueue( $type, [], sha1( wp_generate_uuid4() ), $delay, 2147483647 );
     293        } finally {
     294            $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) );
     295        }
     296    }
     297
     298    /** Next eligible task, including recovery of an interrupted worker. */
     299    public function next_available_at( array $maintenance_types, bool $delivery ): ?int {
     300        global $wpdb;
     301        $where = $this->type_condition( $maintenance_types, $delivery );
     302        $value = $wpdb->get_var(
     303            "SELECT MIN(CASE WHEN status='running' THEN DATE_ADD(locked_at, INTERVAL 30 MINUTE) ELSE available_at END)
     304             FROM {$this->table()} WHERE status IN ('queued','running') AND ({$where})"
     305        );
     306        return $value ? (int) strtotime( $value . ' UTC' ) : null;
     307    }
     308
     309    /** An explicit type list isolates local maintenance from the delivery worker. */
     310    private function type_condition( array $types, bool $delivery ): string {
     311        global $wpdb;
     312        $conditions = [];
     313        if ( $delivery ) {
     314            $conditions[] = $wpdb->prepare( 'job_type NOT LIKE %s', $wpdb->esc_like( 'maintenance_' ) . '%' );
     315        }
     316        if ( $types ) {
     317            $placeholders = implode( ',', array_fill( 0, count( $types ), '%s' ) );
     318            $conditions[] = $wpdb->prepare( "job_type IN ({$placeholders})", array_values( $types ) );
     319        }
     320        return $conditions ? implode( ' OR ', $conditions ) : '1=0';
     321    }
     322
    253323    /**
    254324     * Atomically claim the next runnable job. Returns the row array or null if none.
    … …  
    256326     * same UPDATE between the SELECT and our UPDATE will get affected_rows==0.
    257327     */
    258     public function claim_next(): ?array {
     328    public function claim_next( ?array $types = null ): ?array {
    259329        global $wpdb;
    260330        $table = $this->table();
    261331        $now   = current_time( 'mysql', true );
     332
     333        $where = $this->type_condition( $types ?? [], $types === null );
    262334
    263335        // Find a candidate.
    264336        $row = $wpdb->get_row( $wpdb->prepare(
    265337            "SELECT * FROM {$table}
    266              WHERE status='queued' AND available_at <= %s AND lock_key IS NULL
     338             WHERE status='queued' AND available_at <= %s AND lock_key IS NULL AND ({$where})
    267339             ORDER BY available_at ASC, id ASC
    268340             LIMIT 1",
    … …  
    272344            return null;
    273345        }
    274         $lock = wp_generate_uuid4();
    275         $affected = $wpdb->query( $wpdb->prepare(
    276             "UPDATE {$table}
    277              SET status='running', lock_key=%s, locked_at=%s,
    278                  first_attempted_at=COALESCE(first_attempted_at, %s),
    279                  attempts=attempts+1, updated_at=%s
    280              WHERE id=%d AND lock_key IS NULL AND status='queued'",
    281             $lock,
    282             $now,
    283             $now,
    284             $now,
    285             (int) $row['id']
    286         ) );
    287         if ( $affected !== 1 ) {
    288             return null; // another worker won the race
    289         }
    290         $row['lock_key']  = $lock;
    291         $row['locked_at'] = $now;
    292         $row['first_attempted_at'] = ! empty( $row['first_attempted_at'] )
    293             ? $row['first_attempted_at']
    294             : $now;
    295         $row['attempts']  = (int) $row['attempts'] + 1;
    296         $row['status']    = 'running';
    297         return $row;
     346        // Serialize a maintenance claim with coalescing. Otherwise a purchase
     347        // can observe a queued row just as the worker starts its snapshot,
     348        // then incorrectly attach itself to work that is already running.
     349        $schedule_lock = strpos( (string) $row['job_type'], 'maintenance_' ) === 0
     350            ? 'nabz_schedule_' . sha1( $this->table() . $row['job_type'] )
     351            : '';
     352        if ( $schedule_lock !== '' && (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', $schedule_lock ) ) !== '1' ) {
     353            return null;
     354        }
     355        try {
     356            $lock = wp_generate_uuid4();
     357            $affected = $wpdb->query( $wpdb->prepare(
     358                "UPDATE {$table}
     359                 SET status='running', lock_key=%s, locked_at=%s,
     360                     first_attempted_at=COALESCE(first_attempted_at, %s),
     361                     attempts=attempts+1, updated_at=%s
     362                 WHERE id=%d AND lock_key IS NULL AND status='queued'",
     363                $lock,
     364                $now,
     365                $now,
     366                $now,
     367                (int) $row['id']
     368            ) );
     369            if ( $affected !== 1 ) {
     370                return null; // another worker won the race
     371            }
     372            $row['lock_key']  = $lock;
     373            $row['locked_at'] = $now;
     374            $row['first_attempted_at'] = ! empty( $row['first_attempted_at'] )
     375                ? $row['first_attempted_at']
     376                : $now;
     377            $row['attempts']  = (int) $row['attempts'] + 1;
     378            $row['status']    = 'running';
     379            return $row;
     380        } finally {
     381            if ( $schedule_lock !== '' ) {
     382                $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $schedule_lock ) );
     383            }
     384        }
    298385    }
    299386
    … …  
    441528    public function last_run_unix(): int {
    442529        global $wpdb;
    443         $row = $wpdb->get_var( "SELECT MAX(locked_at) FROM {$this->table()} WHERE locked_at IS NOT NULL" );
     530        $where = $this->type_condition( [], true );
     531        $row = $wpdb->get_var( "SELECT MAX(locked_at) FROM {$this->table()} WHERE locked_at IS NOT NULL AND ({$where})" );
    444532        return $row ? strtotime( $row . ' UTC' ) : 0;
    445533    }
    … …  
    479567        $table = $this->table();
    480568        $error = 'لغو شد: اتصال حساب نبض قطع شد. ' . LogFormatter::error( $reason );
     569        $preserve = [];
     570        $arguments = [ mb_substr( $error, 0, 1000 ) ];
     571        foreach ( \Nabz\Sms\GatewaySettings::providers() as $provider => $label ) {
     572            $preserve[] = 'payload NOT LIKE %s';
     573            $arguments[] = '%' . $wpdb->esc_like( '"sms_provider":"' . $provider . '"' ) . '%';
     574        }
     575        $central_sms = implode( ' AND ', $preserve );
    481576        return (int) $wpdb->query( $wpdb->prepare(
    482577            "UPDATE {$table}
    483578             SET status='dead', lock_key=NULL, locked_at=NULL,
    484579                 last_error=%s, updated_at=UTC_TIMESTAMP()
    485              WHERE job_type IN ('sms_send','messenger_send') AND status IN ('queued','running')",
    486             mb_substr( $error, 0, 1000 )
     580             WHERE job_type IN ('sms_send','messenger_send') AND status IN ('queued','running')
     581               AND (job_type <> 'sms_send' OR ({$central_sms}))",
     582            ...$arguments
    487583        ) );
    488584    }
  • nabz-lite/trunk/src/Jobs/Worker.php

    r3737123 r3757421  
    2929
    3030    public function run( int $max_jobs = 25, int $time_budget_seconds = 25 ): void {
    31         if ( ! Options::delivery_connected() || (string) Options::get( 'installation_token', '' ) === '' ) {
     31        if ( ! Options::delivery_connected() ) {
    3232            return;
    3333        }
    … …  
    4444
    4545            for ( $i = 0; $i < $max_jobs; $i++ ) {
    46                 if ( ! Options::delivery_connected() || (string) Options::get( 'installation_token', '' ) === '' ) {
     46                if ( ! Options::delivery_connected() ) {
    4747                    break;
    4848                }
    … …  
    8484
    8585        // Breaker open → don't burn an attempt; reschedule after cooldown.
    86         if ( $this->breaker->is_open() ) {
     86        if ( ! ( (string) $job['job_type'] === 'sms_send' && \Nabz\Sms\GatewaySettings::external() ) && $this->breaker->is_open() ) {
    8787            $this->jobs->reschedule_without_attempt(
    8888                $id,
  • nabz-lite/trunk/src/Plugin.php

    r3750451 r3757421  
    3232use Nabz\Jobs\JobManager;
    3333use Nabz\Jobs\Schema;
     34use Nabz\Jobs\Scheduler;
    3435use Nabz\Jobs\Worker;
    3536use Nabz\Settings\Options;
    … …  
    4142    private Container $container;
    4243    private bool $booted = false;
    43     private ?string $daily_refresh_lock_token = null;
    4444
    4545    public static function instance(): self {
    … …  
    6060
    6161    public static function on_activate(): void {
    62         // The custom schedule must be registered before wp_schedule_event().
    63         // Activation runs before the normal boot hook, so registering this only
    64         // inside boot can silently leave low-traffic sites without a tick.
    65         add_filter( 'cron_schedules', [ self::class, 'cron_schedules' ] );
    6662        Privacy::register();
    6763        // Rename legacy SMART SMS tables/options before installing schemas,
    … …  
    7369        CrmSchema::install();
    7470        CashbackSchema::install();
    75         if ( ! wp_next_scheduled( 'nabz_tick' ) ) {
    76             wp_schedule_event( time() + 60, 'nabz_minute', 'nabz_tick' );
    77         }
    78         // Customer/RFM refreshes are scheduled as one-shot jobs by the init
    79         // watchdog below. A recurring event here made low-traffic stores depend
    80         // on an unreliable WP-Cron cadence and could overlap a manual rebuild.
    8171        // Lite owns short links, customer login and cart recovery.
    8272        add_rewrite_rule( '^ss/([a-zA-Z0-9]{4,12})/?$', 'index.php?nabz_track=$matches[1]', 'top' );
    … …  
    9484    }
    9585
    96     /** Register Nabz's one-minute queue tick for activation and normal boot. */
    97     public static function cron_schedules( array $schedules ): array {
    98         $schedules['nabz_minute'] = [
    99             'interval' => 60,
    100             'display'  => __( 'Every minute (Nabz)', 'nabz-lite' ),
    101         ];
    102         return $schedules;
    103     }
    104 
    10586    public static function on_deactivate(): void {
    10687        wp_clear_scheduled_hook( 'nabz_tick' );
    10788        wp_clear_scheduled_hook( 'nabz_daily_refresh' );
    10889        wp_clear_scheduled_hook( 'nabz_rfm_recompute' );
     90        wp_clear_scheduled_hook( 'nabz_rfm_currency_rebuild' );
     91        delete_option( 'nabz_runner_dispatch' );
    10992        flush_rewrite_rules( false );
    11093    }
    … …  
    142125        } );
    143126
    144         add_filter( 'cron_schedules', [ self::class, 'cron_schedules' ] );
    145         // Self-heal installs upgraded before the custom schedule was registered,
    146         // or sites where WP-Cron was cleared. The central watchdog can then wake
    147         // the standard wp-cron endpoint even when the storefront has no traffic.
    148         if ( ! wp_next_scheduled( 'nabz_tick' ) ) {
    149             wp_schedule_event( time() + 60, 'nabz_minute', 'nabz_tick' );
    150         }
    151 
    152         // Cron tick → kick a non-blocking loopback to admin-ajax to actually run the worker.
     127        // Old external tick callers remain compatible; init owns scheduling.
    153128        add_action( 'nabz_tick', [ $this, 'fire_tick_loopback' ] );
    154129
    … …  
    161136        add_action( 'nabz_rfm_recompute', [ self::class, 'run_rfm_recompute' ] );
    162137        add_action( 'woocommerce_order_status_changed', [ self::class, 'schedule_rfm_after_order' ], 90, 3 );
    163         add_action( 'user_register', [ self::class, 'schedule_rfm_refresh' ], 90 );
     138        add_action( 'user_register', [ self::class, 'schedule_rfm_refresh' ], 90, 0 );
    164139
    165140        // Optional server-cron endpoint. It uses the same per-install secret as
    … …  
    232207        add_action( 'nabz_daily_refresh', [ $this, 'run_daily_refresh' ], 10 );
    233208
    234         // The refresh watchdog runs from init and only schedules a one-shot
    235         // WP-Cron event when the last completed daily pipeline is older than
    236         // 24 hours.
    237         // The heavy scan therefore never runs inside a storefront/admin request.
    238         add_action( 'init', [ $this, 'maybe_schedule_daily_refresh' ], 20 );
    239 
    240209        // The paid add-on attaches its hooks here. The base plugin never boots paid
    241210        // execution paths, even though it renders their read-only previews.
    242211        do_action( 'nabz_premium_runtime', $this->container );
     212
     213        $scheduler = $this->container->get( Scheduler::class );
     214        $scheduler->register( 'rfm', [ self::class, 'run_rfm_recompute' ], DAY_IN_SECONDS, 10, 'last_customer_refresh' );
     215        $scheduler->register( 'currency_rebuild', [ self::class, 'repair_rfm_currency_units' ] );
     216        $scheduler->register( 'inventory', [ $this, 'refresh_inventory' ], DAY_IN_SECONDS, 90 );
     217        $analytics_sync = new \Nabz\Analytics\Sync( $this->container->get( Client::class ) );
     218        $scheduler->register( 'analytics_sync', [ $analytics_sync, 'run' ], MINUTE_IN_SECONDS, 95 );
     219        $scheduler->register( 'pulse', function (): void {
     220            $this->maybe_heartbeat();
     221            do_action( 'nabz_worker_tick' );
     222        }, MINUTE_IN_SECONDS, 100 );
     223        do_action( 'nabz_register_tasks', $scheduler );
     224        add_action( 'init', [ $scheduler, 'on_init' ], 100 );
     225        add_action( 'shutdown', [ $scheduler, 'on_shutdown' ], 2 );
    243226    }
    244227
    … …  
    256239        $c->set( Client::class,         fn ( $c ) => new Client( $c->get( CircuitBreaker::class ) ) );
    257240        $c->set( JobManager::class,     fn () => new JobManager() );
     241        $c->set( Scheduler::class, fn ( $c ) => new Scheduler(
     242            $c->get( JobManager::class ),
     243            $c->get( Worker::class ),
     244            [ $this, 'fire_tick_loopback' ]
     245        ) );
    258246        $c->set( Sender::class,         fn ( $c ) => new Sender( $c->get( Client::class ) ) );
    259247        $c->set( Dispatcher::class,     fn ( $c ) => new Dispatcher( $c->get( JobManager::class ) ) );
    … …  
    268256    }
    269257
    270     /** Fired by WP-Cron each minute. Sends a non-blocking loopback so the worker runs in its own request. */
    271     public function fire_tick_loopback(): void {
    272         $url = admin_url( 'admin-ajax.php?action=nabz_tick&token=' . $this->tick_token() );
    273         wp_remote_post( $url, [
     258    /** Signed non-blocking handoff to the native queue runner. */
     259    public function fire_tick_loopback() {
     260        $url = admin_url( 'admin-ajax.php?action=nabz_tick' );
     261        return wp_remote_post( $url, [
    274262            'timeout'   => 0.1,
    275263            'blocking'  => false,
    276264            // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- `https_local_ssl_verify` is a WordPress core filter, not a plugin-defined hook.
    277265            'sslverify' => apply_filters( 'https_local_ssl_verify', false ),
    278             'body'      => [],
     266            'body'      => [ 'token' => $this->tick_token() ],
    279267        ] );
    280268    }
    … …  
    290278            wp_die();
    291279        }
    292         // Backend heartbeat — keeps the site marked "online" and refreshes cached
    293         // connection settings. Throttled to ~10 min so the per-minute tick stays cheap.
    294         $this->maybe_heartbeat();
    295 
    296         if ( ! Options::delivery_connected() ) {
    297             if ( wp_doing_ajax() ) {
    298                 wp_send_json_success( [ 'ok' => true, 'delivery_connected' => false ] );
    299             }
    300             return;
    301         }
    302 
    303         /** @var Worker $worker */
    304         $worker = $this->container->get( Worker::class );
    305         $worker->run( 25 ); // up to 25 jobs per tick or until budget elapses
    306 
    307         // Periodic maintenance that must run in the same (loopback/heartbeat) request
    308         // as the worker — e.g. the abandoned-cart sweep. Runs more reliably here than
    309         // on the raw WP-Cron `nabz_tick` event, which low-traffic sites rarely fire.
    310         do_action( 'nabz_worker_tick' );
     280        $this->container->get( Scheduler::class )->run();
    311281
    312282        if ( wp_doing_ajax() ) {
    … …  
    369339
    370340        // v12: rebuild the derived RFM cache once so historical IRR and IRT
    371         // orders are stored in one unit. Use cron to keep plugin boot fast on
     341        // orders are stored in one unit. Use the native queue to keep boot fast on
    372342        // large stores; the version is advanced only after a successful run.
    373343        if ( $current < 12 ) {
    374             if ( ! wp_next_scheduled( 'nabz_rfm_currency_rebuild' ) ) {
    375                 wp_schedule_single_event( time() + 30, 'nabz_rfm_currency_rebuild' );
    376             }
     344            $this->container->get( Scheduler::class )->enqueue( 'currency_rebuild', 30, true, false );
    377345            return;
    378346        }
    … …  
    432400
    433401    public static function repair_rfm_currency_units(): void {
     402        self::run_rfm_recompute();
     403        if ( (int) Options::get( 'db_version', 0 ) < 12 ) {
     404            Options::set( 'db_version', 12 );
     405        }
     406    }
     407
     408    /** Compatibility entry point for integrations using the former daily hook. */
     409    public function run_daily_refresh(): void {
     410        $this->maybe_schedule_daily_refresh();
     411    }
     412
     413    public function maybe_schedule_daily_refresh(): void {
     414        $this->container->get( Scheduler::class )->schedule_due();
     415    }
     416
     417    /** Queue retries own failures; never publish a successful timestamp early. */
     418    public static function run_rfm_recompute(): void {
    434419        if ( ! function_exists( 'wc_get_orders' ) ) {
    435             return;
     420            throw new \RuntimeException( 'woocommerce_unavailable' );
    436421        }
    437422        $result = ( new RfmCalculator() )->recompute();
    438         if ( empty( $result['skipped'] ) && empty( $result['failed'] ) && (int) Options::get( 'db_version', 0 ) < 12 ) {
    439             Options::set( 'db_version', 12 );
    440         }
    441     }
    442 
    443     /**
    444      * Schedule the customer refresh at most once per 24 hours from init.
    445      *
    446      * This is deliberately a one-shot WP-Cron event rather than a recurring
    447      * event. The cheap staleness check runs on normal requests, while the full
    448      * WooCommerce order scan runs in a separate cron request and never blocks a
    449      * storefront or the customers admin page.
    450      */
    451     public function maybe_schedule_daily_refresh(): void {
    452         if ( ! function_exists( 'wc_get_orders' ) || ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() ) ) {
    453             return;
    454         }
    455         // Let older one-shot migrations (notably the currency rebuild) finish
    456         // before the new customer scheduler starts another full scan.
    457         if ( (int) Options::get( 'db_version', 0 ) < 15 ) {
    458             return;
    459         }
    460 
    461         $last = (int) Options::get( 'last_daily_refresh', 0 );
    462         if ( $last > 0 && ( time() - $last ) < DAY_IN_SECONDS ) {
    463             return;
    464         }
    465         $scheduled = function_exists( 'wp_get_scheduled_event' )
    466             ? wp_get_scheduled_event( 'nabz_daily_refresh' )
    467             : null;
    468         if ( $scheduled && ! empty( $scheduled->schedule ) ) {
    469             // Remove a recurring event left by <=1.1.10 upgrades. New events
    470             // are intentionally one-shot and must remain scheduled.
    471             wp_clear_scheduled_hook( 'nabz_daily_refresh' );
    472             $scheduled = null;
    473         }
    474         if ( $scheduled || wp_next_scheduled( 'nabz_daily_refresh' ) ) {
    475             // Retry the non-blocking loopback on later traffic when a hosting
    476             // firewall dropped the first spawn attempt.
    477             $due_at = $scheduled && isset( $scheduled->timestamp )
    478                 ? (int) $scheduled->timestamp
    479                 : (int) wp_next_scheduled( 'nabz_daily_refresh' );
    480             if ( $due_at > 0 && $due_at <= time() && function_exists( 'spawn_cron' ) ) {
    481                 spawn_cron( time() );
    482             }
    483             return;
    484         }
    485 
    486         // Run the job in a separate, non-blocking cron request immediately.
    487         // If loopback is unavailable, the due single event is still picked up
    488         // by the next normal WordPress cron opportunity.
    489         $now = time();
    490         wp_schedule_single_event( $now, 'nabz_daily_refresh' );
    491         if ( function_exists( 'spawn_cron' ) ) {
    492             spawn_cron( $now );
    493         }
    494     }
    495 
    496     /** Run the expensive daily pipeline behind a cross-request lock. */
    497     public function run_daily_refresh(): void {
    498         $last = (int) Options::get( 'last_daily_refresh', 0 );
    499         if ( $last > 0 && ( time() - $last ) < DAY_IN_SECONDS ) {
    500             // A previous one-shot event (or an overlapping cron runner) has
    501             // already completed today's maintenance pipeline.
    502             return;
    503         }
    504         if ( ! $this->acquire_daily_refresh_lock() ) {
    505             return;
    506         }
    507 
    508         try {
    509             $customer_last = (int) Options::get( 'last_customer_refresh', 0 );
    510             if ( $customer_last <= 0 || ( time() - $customer_last ) >= DAY_IN_SECONDS ) {
    511                 $result = ( new RfmCalculator() )->recompute();
    512                 if ( ! empty( $result['skipped'] ) || ! empty( $result['failed'] ) ) {
    513                     return;
    514                 }
    515                 Options::set( 'last_customer_refresh', time() );
    516             }
    517             Options::set( 'last_daily_refresh', time() );
    518         } finally {
    519             $this->release_daily_refresh_lock();
    520         }
    521     }
    522 
    523     /** Async handler used by the admin «recompute now» button. */
    524     public static function run_rfm_recompute(): void {
    525         $result = ( new RfmCalculator() )->recompute();
    526         if ( empty( $result['skipped'] ) && empty( $result['failed'] ) ) {
    527             Options::set( 'last_customer_refresh', time() );
    528         } elseif ( ( $result['failed'] ?? '' ) !== 'storage_engine' ) {
    529             self::schedule_rfm_refresh();
    530         }
     423        if ( ! empty( $result['skipped'] ) || ! empty( $result['failed'] ) ) {
     424            throw new \RuntimeException( 'rfm_' . (string) ( $result['skipped'] ?? $result['failed'] ) );
     425        }
     426        Options::set( 'last_customer_refresh', time() );
    531427    }
    532428
    … …  
    538434    }
    539435
    540     /** Debounce new purchases/registrations into one background rebuild. */
    541     public static function schedule_rfm_refresh(): void {
    542         if ( ! wp_next_scheduled( 'nabz_rfm_recompute' ) ) {
    543             wp_schedule_single_event( time() + 60, 'nabz_rfm_recompute' );
    544         }
    545     }
    546 
    547     private function acquire_daily_refresh_lock(): bool {
    548         $now      = time();
    549         $existing = get_option( 'nabz_daily_refresh_lock', false );
    550         if ( is_array( $existing ) && (int) ( $existing['expires'] ?? 0 ) > $now ) {
    551             return false;
    552         }
    553         if ( false !== $existing ) {
    554             delete_option( 'nabz_daily_refresh_lock' );
    555         }
    556         $token = function_exists( 'wp_generate_uuid4' ) ? wp_generate_uuid4() : uniqid( 'nabz_daily_', true );
    557         if ( ! add_option( 'nabz_daily_refresh_lock', [ 'token' => $token, 'expires' => $now + 1800 ], '', 'no' ) ) {
    558             return false;
    559         }
    560         $this->daily_refresh_lock_token = $token;
    561         return true;
    562     }
    563 
    564     private function release_daily_refresh_lock(): void {
    565         if ( $this->daily_refresh_lock_token === null ) {
    566             return;
    567         }
    568         $current = get_option( 'nabz_daily_refresh_lock', false );
    569         if ( is_array( $current ) && (string) ( $current['token'] ?? '' ) === $this->daily_refresh_lock_token ) {
    570             delete_option( 'nabz_daily_refresh_lock' );
    571         }
    572         $this->daily_refresh_lock_token = null;
    573     }
    574 
    575     public function refresh_inventory(): void {
     436    /** Coalesce untouched purchases; an order during a scan gets a successor. */
     437    public static function schedule_rfm_refresh( int $delay = 60 ): ?int {
     438        $id = self::instance()->container()->get( Scheduler::class )->enqueue( 'rfm', $delay );
     439        if ( ! $id ) {
     440            \Nabz\Support\Logger::error( 'maintenance_enqueue_failed', 'Could not queue the customer refresh.' );
     441        }
     442        return $id;
     443    }
     444
     445    public function refresh_inventory(): bool {
     446        if ( (string) Options::get( 'installation_token', '' ) === '' ) {
     447            return true;
     448        }
    576449        /** @var Client $client */
    577450        $client = $this->container->get( Client::class );
    578451        // Report liveness and package inventory; refresh delivery and wallet settings.
    579         $client->announce();
     452        $result = $client->announce();
     453        return ! empty( $result['ok'] );
    580454    }
    581455
    … …  
    617491    }
    618492
    619     /** Catch up a missed daily cron on the first request after 24 hours. */
     493    /** Catch up inventory on the first request after 24 hours. */
    620494    private function maybe_daily_inventory_sync(): void {
    621495        if ( (string) Options::get( 'installation_token', '' ) === '' ) {
  • nabz-lite/trunk/src/Privacy.php

    r3688753 r3757421  
    2121        add_filter( 'wp_privacy_personal_data_erasers', [ self::class, 'erasers' ] );
    2222        add_action( 'nabz_daily_refresh', [ self::class, 'cleanup' ], 100 );
     23        add_action( 'nabz_register_tasks', function ( \Nabz\Jobs\Scheduler $scheduler ): void {
     24            $scheduler->register( 'privacy_cleanup', [ self::class, 'cleanup' ], DAY_IN_SECONDS, 100 );
     25        } );
    2326    }
    2427
    … …  
    3134            . '</p><p>'
    3235            . esc_html__( 'تا پیش از اقدام مدیر برای اتصال سرویس، نبض اطلاعات فروشگاه را به سرویس بیرونی ارسال نمی‌کند. پس از اتصال، افزونه برای اعتبارسنجی و ارسال پیام با nabz.business ارتباط می‌گیرد. داده‌های ارسالی می‌توانند شامل دامنه، نسخه‌های وردپرس/ووکامرس/افزونه، شناسه و کلید عمومی نصب، توکن نصب، نوع رویداد، شماره موبایل گیرنده و پارامترهای لازم پیام مانند نام مشتری، شماره سفارش، مبلغ و لینک مرتبط باشند. متن نهایی پیام و وضعیت تحویل روی سرویس نبض پردازش می‌شوند. سیاست کامل حریم خصوصی و شرایط سرویس در https://nabz.business/legal.html در دسترس است.', 'nabz-lite' )
     36            . '</p><p>'
     37            . esc_html__( 'پس از اتصال حساب نبض، آمار ارسال موفق و کلیک شامل شناسهٔ هش‌شدهٔ پیام، نوع پیام، تعداد کلیک و زمان ارسال و اولین/آخرین کلیک نیز با سرویس نبض همگام می‌شود. همگام‌سازی آمار، شماره موبایل، نام مشتری، IP، مرورگر، متن پیام یا نشانی مقصد را ارسال نمی‌کند.', 'nabz-lite' )
    3338            . '</p><p>'
    3439            . esc_html__( 'نبض برای احراز درخواست‌ها یک کلید خصوصی Ed25519 را فقط در پایگاه داده همین وردپرس ذخیره می‌کند و کلید خصوصی را به سرویس ارسال نمی‌کند. حذف افزونه، داده‌های محلی اختصاصی نبض را پاک می‌کند؛ حذف داده‌های ذخیره‌شده روی سرویس بیرونی باید از حساب یا پشتیبانی نبض درخواست شود.', 'nabz-lite' )
  • nabz-lite/trunk/src/Settings/Options.php

    r3750451 r3757421  
    407407    }
    408408
    409     /** API access is tied to the signed-in wallet account, not a product license. */
     409    /** The revocable site credential survives expiry of the owner's portal session. */
     410    public static function account_connected(): bool {
     411        return strlen( trim( (string) self::get( 'installation_token', '' ) ) ) >= 8
     412            && (int) self::get( 'account_user_id', 0 ) > 0;
     413    }
     414
     415    /** Delivery uses the configured personal panel or the connected Nabz account. */
    410416    public static function delivery_connected(): bool {
    411         return strlen( trim( (string) self::get( 'installation_token', '' ) ) ) >= 8
    412             && trim( (string) self::get( 'account_session_cookie', '' ) ) !== ''
    413             && (int) self::get( 'account_user_id', 0 ) > 0;
     417        if ( \Nabz\Sms\GatewaySettings::external() ) { return \Nabz\Sms\GatewaySettings::ready(); }
     418        return self::account_connected();
    414419    }
    415420
    … …  
    419424
    420425    public static function active_message_types(): array {
     426        if ( \Nabz\Sms\GatewaySettings::external() ) { return array_keys( \Nabz\Sms\LocalTemplates::all() ); }
    421427        $types = self::get( 'active_message_types', [] );
    422428        return is_array( $types ) ? $types : [];
  • nabz-lite/trunk/src/Sms/Sender.php

    r3750712 r3757421  
    3131            ];
    3232        }
     33        if ( $job_type === 'messenger_send' && GatewaySettings::external() ) {
     34            return ExternalGateway::failure( 'پنل ارسال پس از ایجاد صف تغییر کرده است؛ صف پیام‌رسان قبلی را بررسی کنید.', 409 );
     35        }
    3336        if ( $job_type !== 'sms_send' ) {
    3437            $extension_response = apply_filters( 'nabz_dispatch_extension_job', null, $job_type, $payload );
    … …  
    3740            }
    3841            return [ 'ok' => false, 'status' => 0, 'body' => null, 'error' => 'unknown_job_type' ];
     42        }
     43        $queued_provider = (string) ( $payload['sms_provider'] ?? 'nabz' );
     44        if ( $queued_provider !== GatewaySettings::provider() ) {
     45            return ExternalGateway::failure( 'پنل پیامکی پس از ایجاد صف تغییر کرده است؛ پیام قبلی برای جلوگیری از ارسال ناخواسته متوقف شد.', 409 );
    3946        }
    4047        $message_type   = (string) ( $payload['message_type'] ?? '' );
  • nabz-lite/trunk/src/Support/LogFormatter.php

    r3750451 r3757421  
    5757            'winback'                   => 'بازگشت مشتری',
    5858            'rfm_recompute'             => 'به‌روزرسانی دسته‌بندی مشتریان',
     59            'maintenance_retry'         => 'تلاش مجدد محاسبات و نگهداری',
    5960        ][ $event ] ?? 'رویداد سامانه';
    6061    }
    … …  
    8889    public static function error_code_message( string $code ): string {
    8990        $exact = [
     91            'rfm_storage_engine'               => 'جدول محاسبات مشتریان به InnoDB نیاز دارد؛ تبدیل خودکار جدول انجام نشد. دسترسی ALTER و پشتیبانی InnoDB پایگاه‌داده را بررسی کنید.',
     92            'rfm_busy'                         => 'محاسبهٔ دیگری در حال اجراست؛ پس از آزادشدن قفل دوباره تلاش می‌شود.',
    9093            'connection_invalid'               => 'اعتبار اتصال حساب نامعتبر است؛ دوباره وارد حساب نبض شوید.',
    9194            'account_connection_required'       => 'اتصال حساب نبض برقرار نیست؛ در پیشخوان نبض دوباره وارد حساب شوید یا وضعیت اتصال را همگام کنید.',
    … …  
    187190            return 'کار' . $job_number . ' ناموفق بود و برای تلاش مجدد در صف قرار گرفت: ' . self::error( (string) $raw );
    188191        }
     192        if ( $event === 'maintenance_retry' ) {
     193            return 'اجرای محاسبات یا نگهداری ناموفق بود و دوباره تلاش می‌شود: ' . self::error( (string) ( $context['error'] ?? $message ) );
     194        }
    189195        if ( $event === 'job_dead' ) {
    190196            $raw = preg_replace( '/^.*?dropped:\s*/is', '', $message );
    … …  
    272278            'retry'             => 'ارسال مجدد',
    273279            'error'             => 'خطا',
     280            'task'              => 'نام کار',
     281            'retry_after'       => 'تلاش مجدد پس از (ثانیه)',
    274282            'response'          => 'پاسخ سرور',
    275283            'backend'           => 'نتیجه سرور',
Note: See TracChangeset for help on using the changeset viewer.