Changeset 3782421
- Timestamp:
- 11/03/2026 06:23:52 PM (3 weeks ago)
- Location:
- sanbar-express-nfe-xml-import-br
- Files:
-
- 653 added
- 36 edited
-
tags/2.0 (added)
-
tags/2.0/assets (added)
-
tags/2.0/assets/css (added)
-
tags/2.0/assets/css/core.css (added)
-
tags/2.0/assets/css/design-tokens.css (added)
-
tags/2.0/assets/css/library-notes.css (added)
-
tags/2.0/assets/css/library-supplier.css (added)
-
tags/2.0/assets/css/nfebr-welcome.css (added)
-
tags/2.0/assets/css/price-history.css (added)
-
tags/2.0/assets/css/sheet-bridge.css (added)
-
tags/2.0/assets/js (added)
-
tags/2.0/assets/js/nfebr-core.js (added)
-
tags/2.0/assets/js/nfebr-diff-card.js (added)
-
tags/2.0/assets/js/nfebr-error-log.js (added)
-
tags/2.0/assets/js/nfebr-grid.js (added)
-
tags/2.0/assets/js/nfebr-item-actions.js (added)
-
tags/2.0/assets/js/nfebr-library-notes.js (added)
-
tags/2.0/assets/js/nfebr-library-supplier.js (added)
-
tags/2.0/assets/js/nfebr-main.js (added)
-
tags/2.0/assets/js/nfebr-note-info.js (added)
-
tags/2.0/assets/js/nfebr-price-history.js (added)
-
tags/2.0/assets/js/nfebr-registry-check.js (added)
-
tags/2.0/assets/js/nfebr-sefaz.js (added)
-
tags/2.0/assets/js/nfebr-sheet-bridge.js (added)
-
tags/2.0/assets/js/nfebr-toast.js (added)
-
tags/2.0/assets/js/nfebr-welcome.js (added)
-
tags/2.0/assets/js/nfebr-workflow.js (added)
-
tags/2.0/data (added)
-
tags/2.0/data/cest.json (added)
-
tags/2.0/includes (added)
-
tags/2.0/includes/class-sbnfebr-admin.php (added)
-
tags/2.0/includes/class-sbnfebr-rest.php (added)
-
tags/2.0/includes/class-sbnfebr-uninstall.php (added)
-
tags/2.0/includes/controllers (added)
-
tags/2.0/includes/controllers/class-sbnfebr-draft-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-error-log-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-fiscal-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-full-backup-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-import-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-items-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-match-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-settings-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-suppliers-library-controller.php (added)
-
tags/2.0/includes/controllers/class-sbnfebr-workflow-controller.php (added)
-
tags/2.0/includes/services (added)
-
tags/2.0/includes/services/class-sbnfebr-audit-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-cert-legacy.php (added)
-
tags/2.0/includes/services/class-sbnfebr-cert.php (added)
-
tags/2.0/includes/services/class-sbnfebr-cest-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-draft-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-error-log-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-fiscal-check-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-fiscal-rules.php (added)
-
tags/2.0/includes/services/class-sbnfebr-fiscal-settings.php (added)
-
tags/2.0/includes/services/class-sbnfebr-fiscal-tables.php (added)
-
tags/2.0/includes/services/class-sbnfebr-full-backup-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-gtin-lookup.php (added)
-
tags/2.0/includes/services/class-sbnfebr-match-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-notes-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-sefaz-gtin.php (added)
-
tags/2.0/includes/services/class-sbnfebr-supplier-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-workflow-service.php (added)
-
tags/2.0/includes/services/class-sbnfebr-xml-parser-service.php (added)
-
tags/2.0/includes/services/trait-sbnfebr-product-data-writers.php (added)
-
tags/2.0/lib (added)
-
tags/2.0/lib/MODIFICATIONS.txt (added)
-
tags/2.0/lib/autoload.php (added)
-
tags/2.0/lib/psr-log (added)
-
tags/2.0/lib/psr-log/LICENSE (added)
-
tags/2.0/lib/psr-log/src (added)
-
tags/2.0/lib/psr-log/src/AbstractLogger.php (added)
-
tags/2.0/lib/psr-log/src/InvalidArgumentException.php (added)
-
tags/2.0/lib/psr-log/src/LogLevel.php (added)
-
tags/2.0/lib/psr-log/src/LoggerAwareInterface.php (added)
-
tags/2.0/lib/psr-log/src/LoggerAwareTrait.php (added)
-
tags/2.0/lib/psr-log/src/LoggerInterface.php (added)
-
tags/2.0/lib/psr-log/src/LoggerTrait.php (added)
-
tags/2.0/lib/psr-log/src/NullLogger.php (added)
-
tags/2.0/lib/sped-common (added)
-
tags/2.0/lib/sped-common/VERSION (added)
-
tags/2.0/lib/sped-common/src (added)
-
tags/2.0/lib/sped-common/src/Certificate (added)
-
tags/2.0/lib/sped-common/src/Certificate.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/Asn1.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/CertificationChain.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/Exception (added)
-
tags/2.0/lib/sped-common/src/Certificate/Exception/Expired.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/Oids.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/PrivateKey.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/PublicKey.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/SignatureInterface.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/VerificationInterface.php (added)
-
tags/2.0/lib/sped-common/src/Certificate/oids.json (added)
-
tags/2.0/lib/sped-common/src/DOMImproved.php (added)
-
tags/2.0/lib/sped-common/src/Encoding.php (added)
-
tags/2.0/lib/sped-common/src/Exception (added)
-
tags/2.0/lib/sped-common/src/Exception/CertificateException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/ExceptionCollection.php (added)
-
tags/2.0/lib/sped-common/src/Exception/ExceptionInterface.php (added)
-
tags/2.0/lib/sped-common/src/Exception/IOException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/InvalidArgumentException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/InvalidXmlException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/LogicException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/RuntimeException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/SignerException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/SoapException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/UnexpectedValueException.php (added)
-
tags/2.0/lib/sped-common/src/Exception/ValidatorException.php (added)
-
tags/2.0/lib/sped-common/src/Files.php (added)
-
tags/2.0/lib/sped-common/src/Keys.php (added)
-
tags/2.0/lib/sped-common/src/Soap (added)
-
tags/2.0/lib/sped-common/src/Soap/SoapBase.php (added)
-
tags/2.0/lib/sped-common/src/Soap/SoapCode.php (added)
-
tags/2.0/lib/sped-common/src/Soap/SoapInterface.php (added)
-
tags/2.0/lib/sped-common/src/Soap/httpcodes.json (added)
-
tags/2.0/lib/sped-common/src/Strings.php (added)
-
tags/2.0/lib/sped-gtin (added)
-
tags/2.0/lib/sped-gtin/VERSION.txt (added)
-
tags/2.0/lib/sped-gtin/src (added)
-
tags/2.0/lib/sped-gtin/src/Common (added)
-
tags/2.0/lib/sped-gtin/src/Common/Consulta.php (added)
-
tags/2.0/lib/sped-gtin/src/Tabela_Prefixo_GS1.csv (added)
-
tags/2.0/readme.txt (added)
-
tags/2.0/sanbar-express-nfe-xml-import-br.php (added)
-
tags/2.0/vendor (added)
-
tags/2.0/vendor/freemius (added)
-
tags/2.0/vendor/freemius/LICENSE.txt (added)
-
tags/2.0/vendor/freemius/assets (added)
-
tags/2.0/vendor/freemius/assets/css (added)
-
tags/2.0/vendor/freemius/assets/css/admin (added)
-
tags/2.0/vendor/freemius/assets/css/admin/account.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/add-ons.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/affiliation.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/checkout.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/clone-resolution.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/common.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/connect.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/debug.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/dialog-boxes.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/gdpr-optin-notice.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/index.php (added)
-
tags/2.0/vendor/freemius/assets/css/admin/optout.css (added)
-
tags/2.0/vendor/freemius/assets/css/admin/plugins.css (added)
-
tags/2.0/vendor/freemius/assets/css/customizer.css (added)
-
tags/2.0/vendor/freemius/assets/css/index.php (added)
-
tags/2.0/vendor/freemius/assets/img (added)
-
tags/2.0/vendor/freemius/assets/img/index.php (added)
-
tags/2.0/vendor/freemius/assets/img/plugin-icon.png (added)
-
tags/2.0/vendor/freemius/assets/img/theme-icon.png (added)
-
tags/2.0/vendor/freemius/assets/index.php (added)
-
tags/2.0/vendor/freemius/assets/js (added)
-
tags/2.0/vendor/freemius/assets/js/index.php (added)
-
tags/2.0/vendor/freemius/assets/js/jquery.form.js (added)
-
tags/2.0/vendor/freemius/assets/js/nojquery.ba-postmessage.js (added)
-
tags/2.0/vendor/freemius/assets/js/postmessage.js (added)
-
tags/2.0/vendor/freemius/assets/js/pricing (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/14fb1bd5b7c41648488b06147f50a0dc.svg (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/178afa6030e76635dbe835e111d2c507.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/27b5a722a5553d9de0170325267fccec.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/4375c4a3ddc6f637c2ab9a2d7220f91e.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/45da596e2b512ffc3bb638baaf0fdc4e.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/a34e046aee1702a5690679750a7f4d0f.svg (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/b09d0b38b627c2fa564d050f79f2f064.svg (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/c03f665db27af43971565560adfba594.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/cb5fc4f6ec7ada72e986f6e7dde365bf.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/d65812c447b4523b42d59018e1c0bb53.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/f3aac72a8e63997d6bb888f816457e9b.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/fde48e4609a6ddc11d639fc2421f2afd.png (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/freemius-pricing.js (added)
-
tags/2.0/vendor/freemius/assets/js/pricing/freemius-pricing.js.LICENSE.txt (added)
-
tags/2.0/vendor/freemius/composer.json (added)
-
tags/2.0/vendor/freemius/config.php (added)
-
tags/2.0/vendor/freemius/includes (added)
-
tags/2.0/vendor/freemius/includes/class-freemius-abstract.php (added)
-
tags/2.0/vendor/freemius/includes/class-freemius.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-admin-notices.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-api.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-garbage-collector.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-hook-snapshot.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-lock.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-logger.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-options.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-plugin-updater.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-security.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-storage.php (added)
-
tags/2.0/vendor/freemius/includes/class-fs-user-lock.php (added)
-
tags/2.0/vendor/freemius/includes/customizer (added)
-
tags/2.0/vendor/freemius/includes/customizer/class-fs-customizer-support-section.php (added)
-
tags/2.0/vendor/freemius/includes/customizer/class-fs-customizer-upsell-control.php (added)
-
tags/2.0/vendor/freemius/includes/customizer/index.php (added)
-
tags/2.0/vendor/freemius/includes/debug (added)
-
tags/2.0/vendor/freemius/includes/debug/class-fs-debug-bar-panel.php (added)
-
tags/2.0/vendor/freemius/includes/debug/debug-bar-start.php (added)
-
tags/2.0/vendor/freemius/includes/debug/index.php (added)
-
tags/2.0/vendor/freemius/includes/entities (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-affiliate-terms.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-affiliate.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-billing.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-entity.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-payment.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-plugin-info.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-plugin-license.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-plugin-plan.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-plugin-tag.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-plugin.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-pricing.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-scope-entity.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-site.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-subscription.php (added)
-
tags/2.0/vendor/freemius/includes/entities/class-fs-user.php (added)
-
tags/2.0/vendor/freemius/includes/entities/index.php (added)
-
tags/2.0/vendor/freemius/includes/fs-core-functions.php (added)
-
tags/2.0/vendor/freemius/includes/fs-essential-functions.php (added)
-
tags/2.0/vendor/freemius/includes/fs-html-escaping-functions.php (added)
-
tags/2.0/vendor/freemius/includes/fs-plugin-info-dialog.php (added)
-
tags/2.0/vendor/freemius/includes/index.php (added)
-
tags/2.0/vendor/freemius/includes/l10n.php (added)
-
tags/2.0/vendor/freemius/includes/managers (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-admin-menu-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-admin-notice-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-cache-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-checkout-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-clone-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-contact-form-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-debug-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-gdpr-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-key-value-storage.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-license-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-option-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-permission-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-plan-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/class-fs-plugin-manager.php (added)
-
tags/2.0/vendor/freemius/includes/managers/index.php (added)
-
tags/2.0/vendor/freemius/includes/sdk (added)
-
tags/2.0/vendor/freemius/includes/sdk/Exceptions (added)
-
tags/2.0/vendor/freemius/includes/sdk/Exceptions/ArgumentNotExistException.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/Exceptions/EmptyArgumentException.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/Exceptions/Exception.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/Exceptions/InvalidArgumentException.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/Exceptions/OAuthException.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/Exceptions/index.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/FreemiusBase.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/FreemiusWordPress.php (added)
-
tags/2.0/vendor/freemius/includes/sdk/LICENSE.txt (added)
-
tags/2.0/vendor/freemius/includes/sdk/index.php (added)
-
tags/2.0/vendor/freemius/includes/supplements (added)
-
tags/2.0/vendor/freemius/includes/supplements/fs-essential-functions-1.1.7.1.php (added)
-
tags/2.0/vendor/freemius/includes/supplements/fs-essential-functions-2.2.1.php (added)
-
tags/2.0/vendor/freemius/includes/supplements/fs-migration-2.5.1.php (added)
-
tags/2.0/vendor/freemius/includes/supplements/index.php (added)
-
tags/2.0/vendor/freemius/index.php (added)
-
tags/2.0/vendor/freemius/languages (added)
-
tags/2.0/vendor/freemius/languages/freemius-cs_CZ.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-da_DK.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-de_DE.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-es_ES.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-fr_FR.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-he_IL.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-hu_HU.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-it_IT.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-ja.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-nl_NL.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-ru_RU.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-ta.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius-zh_CN.mo (added)
-
tags/2.0/vendor/freemius/languages/freemius.pot (added)
-
tags/2.0/vendor/freemius/languages/index.php (added)
-
tags/2.0/vendor/freemius/require.php (added)
-
tags/2.0/vendor/freemius/start.php (added)
-
tags/2.0/vendor/freemius/templates (added)
-
tags/2.0/vendor/freemius/templates/account (added)
-
tags/2.0/vendor/freemius/templates/account.php (added)
-
tags/2.0/vendor/freemius/templates/account/billing.php (added)
-
tags/2.0/vendor/freemius/templates/account/index.php (added)
-
tags/2.0/vendor/freemius/templates/account/partials (added)
-
tags/2.0/vendor/freemius/templates/account/partials/activate-license-button.php (added)
-
tags/2.0/vendor/freemius/templates/account/partials/addon.php (added)
-
tags/2.0/vendor/freemius/templates/account/partials/deactivate-license-button.php (added)
-
tags/2.0/vendor/freemius/templates/account/partials/disconnect-button.php (added)
-
tags/2.0/vendor/freemius/templates/account/partials/index.php (added)
-
tags/2.0/vendor/freemius/templates/account/partials/site.php (added)
-
tags/2.0/vendor/freemius/templates/account/payments.php (added)
-
tags/2.0/vendor/freemius/templates/add-ons.php (added)
-
tags/2.0/vendor/freemius/templates/add-trial-to-pricing.php (added)
-
tags/2.0/vendor/freemius/templates/admin-notice.php (added)
-
tags/2.0/vendor/freemius/templates/ajax-loader.php (added)
-
tags/2.0/vendor/freemius/templates/api-connectivity-message-js.php (added)
-
tags/2.0/vendor/freemius/templates/auto-installation.php (added)
-
tags/2.0/vendor/freemius/templates/checkout (added)
-
tags/2.0/vendor/freemius/templates/checkout.php (added)
-
tags/2.0/vendor/freemius/templates/checkout/frame.php (added)
-
tags/2.0/vendor/freemius/templates/checkout/process-redirect.php (added)
-
tags/2.0/vendor/freemius/templates/checkout/redirect.php (added)
-
tags/2.0/vendor/freemius/templates/clone-resolution-js.php (added)
-
tags/2.0/vendor/freemius/templates/connect (added)
-
tags/2.0/vendor/freemius/templates/connect.php (added)
-
tags/2.0/vendor/freemius/templates/connect/index.php (added)
-
tags/2.0/vendor/freemius/templates/connect/permission.php (added)
-
tags/2.0/vendor/freemius/templates/connect/permissions-group.php (added)
-
tags/2.0/vendor/freemius/templates/contact.php (added)
-
tags/2.0/vendor/freemius/templates/debug (added)
-
tags/2.0/vendor/freemius/templates/debug.php (added)
-
tags/2.0/vendor/freemius/templates/debug/api-calls.php (added)
-
tags/2.0/vendor/freemius/templates/debug/index.php (added)
-
tags/2.0/vendor/freemius/templates/debug/logger.php (added)
-
tags/2.0/vendor/freemius/templates/debug/plugins-themes-sync.php (added)
-
tags/2.0/vendor/freemius/templates/debug/scheduled-crons.php (added)
-
tags/2.0/vendor/freemius/templates/email.php (added)
-
tags/2.0/vendor/freemius/templates/forms (added)
-
tags/2.0/vendor/freemius/templates/forms/affiliation.php (added)
-
tags/2.0/vendor/freemius/templates/forms/data-debug-mode.php (added)
-
tags/2.0/vendor/freemius/templates/forms/deactivation (added)
-
tags/2.0/vendor/freemius/templates/forms/deactivation/contact.php (added)
-
tags/2.0/vendor/freemius/templates/forms/deactivation/form.php (added)
-
tags/2.0/vendor/freemius/templates/forms/deactivation/index.php (added)
-
tags/2.0/vendor/freemius/templates/forms/deactivation/retry-skip.php (added)
-
tags/2.0/vendor/freemius/templates/forms/email-address-update.php (added)
-
tags/2.0/vendor/freemius/templates/forms/index.php (added)
-
tags/2.0/vendor/freemius/templates/forms/license-activation.php (added)
-
tags/2.0/vendor/freemius/templates/forms/optout.php (added)
-
tags/2.0/vendor/freemius/templates/forms/premium-versions-upgrade-handler.php (added)
-
tags/2.0/vendor/freemius/templates/forms/premium-versions-upgrade-metadata.php (added)
-
tags/2.0/vendor/freemius/templates/forms/resend-key.php (added)
-
tags/2.0/vendor/freemius/templates/forms/subscription-cancellation.php (added)
-
tags/2.0/vendor/freemius/templates/forms/trial-start.php (added)
-
tags/2.0/vendor/freemius/templates/forms/user-change.php (added)
-
tags/2.0/vendor/freemius/templates/gdpr-optin-js.php (added)
-
tags/2.0/vendor/freemius/templates/index.php (added)
-
tags/2.0/vendor/freemius/templates/js (added)
-
tags/2.0/vendor/freemius/templates/js/index.php (added)
-
tags/2.0/vendor/freemius/templates/js/jquery.content-change.php (added)
-
tags/2.0/vendor/freemius/templates/js/open-license-activation.php (added)
-
tags/2.0/vendor/freemius/templates/js/permissions.php (added)
-
tags/2.0/vendor/freemius/templates/js/style-premium-theme.php (added)
-
tags/2.0/vendor/freemius/templates/partials (added)
-
tags/2.0/vendor/freemius/templates/partials/index.php (added)
-
tags/2.0/vendor/freemius/templates/partials/network-activation.php (added)
-
tags/2.0/vendor/freemius/templates/plugin-icon.php (added)
-
tags/2.0/vendor/freemius/templates/plugin-info (added)
-
tags/2.0/vendor/freemius/templates/plugin-info/description.php (added)
-
tags/2.0/vendor/freemius/templates/plugin-info/features.php (added)
-
tags/2.0/vendor/freemius/templates/plugin-info/index.php (added)
-
tags/2.0/vendor/freemius/templates/plugin-info/screenshots.php (added)
-
tags/2.0/vendor/freemius/templates/pricing.php (added)
-
tags/2.0/vendor/freemius/templates/secure-https-header.php (added)
-
tags/2.0/vendor/freemius/templates/sticky-admin-notice-js.php (added)
-
tags/2.0/vendor/freemius/templates/tabs-capture-js.php (added)
-
tags/2.0/vendor/freemius/templates/tabs.php (added)
-
trunk/assets/css/core.css (modified) (53 diffs)
-
trunk/assets/css/design-tokens.css (added)
-
trunk/assets/css/library-notes.css (modified) (15 diffs)
-
trunk/assets/css/library-supplier.css (modified) (7 diffs)
-
trunk/assets/css/nfebr-welcome.css (added)
-
trunk/assets/css/price-history.css (modified) (1 diff)
-
trunk/assets/css/sheet-bridge.css (modified) (3 diffs)
-
trunk/assets/js/nfebr-core.js (modified) (10 diffs)
-
trunk/assets/js/nfebr-diff-card.js (modified) (6 diffs)
-
trunk/assets/js/nfebr-error-log.js (modified) (5 diffs)
-
trunk/assets/js/nfebr-grid.js (modified) (15 diffs)
-
trunk/assets/js/nfebr-item-actions.js (modified) (1 diff)
-
trunk/assets/js/nfebr-library-notes.js (modified) (7 diffs)
-
trunk/assets/js/nfebr-library-supplier.js (modified) (11 diffs)
-
trunk/assets/js/nfebr-main.js (modified) (61 diffs)
-
trunk/assets/js/nfebr-note-info.js (modified) (7 diffs)
-
trunk/assets/js/nfebr-price-history.js (modified) (2 diffs)
-
trunk/assets/js/nfebr-registry-check.js (modified) (11 diffs)
-
trunk/assets/js/nfebr-sefaz.js (added)
-
trunk/assets/js/nfebr-sheet-bridge.js (modified) (6 diffs)
-
trunk/assets/js/nfebr-toast.js (modified) (4 diffs)
-
trunk/assets/js/nfebr-welcome.js (added)
-
trunk/assets/js/nfebr-workflow.js (added)
-
trunk/data (added)
-
trunk/data/cest.json (added)
-
trunk/includes/class-sbnfebr-admin.php (modified) (27 diffs)
-
trunk/includes/class-sbnfebr-rest.php (modified) (3 diffs)
-
trunk/includes/class-sbnfebr-uninstall.php (added)
-
trunk/includes/controllers/class-sbnfebr-draft-controller.php (modified) (3 diffs)
-
trunk/includes/controllers/class-sbnfebr-error-log-controller.php (modified) (3 diffs)
-
trunk/includes/controllers/class-sbnfebr-fiscal-controller.php (added)
-
trunk/includes/controllers/class-sbnfebr-full-backup-controller.php (added)
-
trunk/includes/controllers/class-sbnfebr-import-controller.php (modified) (7 diffs)
-
trunk/includes/controllers/class-sbnfebr-items-controller.php (modified) (13 diffs)
-
trunk/includes/controllers/class-sbnfebr-match-controller.php (modified) (8 diffs)
-
trunk/includes/controllers/class-sbnfebr-settings-controller.php (modified) (9 diffs)
-
trunk/includes/controllers/class-sbnfebr-suppliers-library-controller.php (modified) (7 diffs)
-
trunk/includes/controllers/class-sbnfebr-workflow-controller.php (added)
-
trunk/includes/services/class-sbnfebr-audit-service.php (modified) (8 diffs)
-
trunk/includes/services/class-sbnfebr-cert-legacy.php (added)
-
trunk/includes/services/class-sbnfebr-cert.php (added)
-
trunk/includes/services/class-sbnfebr-cest-service.php (added)
-
trunk/includes/services/class-sbnfebr-draft-service.php (modified) (15 diffs)
-
trunk/includes/services/class-sbnfebr-error-log-service.php (modified) (15 diffs)
-
trunk/includes/services/class-sbnfebr-fiscal-check-service.php (added)
-
trunk/includes/services/class-sbnfebr-fiscal-rules.php (added)
-
trunk/includes/services/class-sbnfebr-fiscal-settings.php (added)
-
trunk/includes/services/class-sbnfebr-fiscal-tables.php (added)
-
trunk/includes/services/class-sbnfebr-full-backup-service.php (added)
-
trunk/includes/services/class-sbnfebr-gtin-lookup.php (added)
-
trunk/includes/services/class-sbnfebr-match-service.php (modified) (18 diffs)
-
trunk/includes/services/class-sbnfebr-notes-service.php (modified) (79 diffs)
-
trunk/includes/services/class-sbnfebr-sefaz-gtin.php (added)
-
trunk/includes/services/class-sbnfebr-supplier-service.php (modified) (25 diffs)
-
trunk/includes/services/class-sbnfebr-workflow-service.php (added)
-
trunk/includes/services/class-sbnfebr-xml-parser-service.php (modified) (24 diffs)
-
trunk/includes/services/trait-sbnfebr-product-data-writers.php (added)
-
trunk/lib (added)
-
trunk/lib/MODIFICATIONS.txt (added)
-
trunk/lib/autoload.php (added)
-
trunk/lib/psr-log (added)
-
trunk/lib/psr-log/LICENSE (added)
-
trunk/lib/psr-log/src (added)
-
trunk/lib/psr-log/src/AbstractLogger.php (added)
-
trunk/lib/psr-log/src/InvalidArgumentException.php (added)
-
trunk/lib/psr-log/src/LogLevel.php (added)
-
trunk/lib/psr-log/src/LoggerAwareInterface.php (added)
-
trunk/lib/psr-log/src/LoggerAwareTrait.php (added)
-
trunk/lib/psr-log/src/LoggerInterface.php (added)
-
trunk/lib/psr-log/src/LoggerTrait.php (added)
-
trunk/lib/psr-log/src/NullLogger.php (added)
-
trunk/lib/sped-common (added)
-
trunk/lib/sped-common/VERSION (added)
-
trunk/lib/sped-common/src (added)
-
trunk/lib/sped-common/src/Certificate (added)
-
trunk/lib/sped-common/src/Certificate.php (added)
-
trunk/lib/sped-common/src/Certificate/Asn1.php (added)
-
trunk/lib/sped-common/src/Certificate/CertificationChain.php (added)
-
trunk/lib/sped-common/src/Certificate/Exception (added)
-
trunk/lib/sped-common/src/Certificate/Exception/Expired.php (added)
-
trunk/lib/sped-common/src/Certificate/Oids.php (added)
-
trunk/lib/sped-common/src/Certificate/PrivateKey.php (added)
-
trunk/lib/sped-common/src/Certificate/PublicKey.php (added)
-
trunk/lib/sped-common/src/Certificate/SignatureInterface.php (added)
-
trunk/lib/sped-common/src/Certificate/VerificationInterface.php (added)
-
trunk/lib/sped-common/src/Certificate/oids.json (added)
-
trunk/lib/sped-common/src/DOMImproved.php (added)
-
trunk/lib/sped-common/src/Encoding.php (added)
-
trunk/lib/sped-common/src/Exception (added)
-
trunk/lib/sped-common/src/Exception/CertificateException.php (added)
-
trunk/lib/sped-common/src/Exception/ExceptionCollection.php (added)
-
trunk/lib/sped-common/src/Exception/ExceptionInterface.php (added)
-
trunk/lib/sped-common/src/Exception/IOException.php (added)
-
trunk/lib/sped-common/src/Exception/InvalidArgumentException.php (added)
-
trunk/lib/sped-common/src/Exception/InvalidXmlException.php (added)
-
trunk/lib/sped-common/src/Exception/LogicException.php (added)
-
trunk/lib/sped-common/src/Exception/RuntimeException.php (added)
-
trunk/lib/sped-common/src/Exception/SignerException.php (added)
-
trunk/lib/sped-common/src/Exception/SoapException.php (added)
-
trunk/lib/sped-common/src/Exception/UnexpectedValueException.php (added)
-
trunk/lib/sped-common/src/Exception/ValidatorException.php (added)
-
trunk/lib/sped-common/src/Files.php (added)
-
trunk/lib/sped-common/src/Keys.php (added)
-
trunk/lib/sped-common/src/Soap (added)
-
trunk/lib/sped-common/src/Soap/SoapBase.php (added)
-
trunk/lib/sped-common/src/Soap/SoapCode.php (added)
-
trunk/lib/sped-common/src/Soap/SoapInterface.php (added)
-
trunk/lib/sped-common/src/Soap/httpcodes.json (added)
-
trunk/lib/sped-common/src/Strings.php (added)
-
trunk/lib/sped-gtin (added)
-
trunk/lib/sped-gtin/VERSION.txt (added)
-
trunk/lib/sped-gtin/src (added)
-
trunk/lib/sped-gtin/src/Common (added)
-
trunk/lib/sped-gtin/src/Common/Consulta.php (added)
-
trunk/lib/sped-gtin/src/Tabela_Prefixo_GS1.csv (added)
-
trunk/readme.txt (modified) (4 diffs)
-
trunk/sanbar-express-nfe-xml-import-br.php (modified) (7 diffs)
-
trunk/vendor (added)
-
trunk/vendor/freemius (added)
-
trunk/vendor/freemius/LICENSE.txt (added)
-
trunk/vendor/freemius/assets (added)
-
trunk/vendor/freemius/assets/css (added)
-
trunk/vendor/freemius/assets/css/admin (added)
-
trunk/vendor/freemius/assets/css/admin/account.css (added)
-
trunk/vendor/freemius/assets/css/admin/add-ons.css (added)
-
trunk/vendor/freemius/assets/css/admin/affiliation.css (added)
-
trunk/vendor/freemius/assets/css/admin/checkout.css (added)
-
trunk/vendor/freemius/assets/css/admin/clone-resolution.css (added)
-
trunk/vendor/freemius/assets/css/admin/common.css (added)
-
trunk/vendor/freemius/assets/css/admin/connect.css (added)
-
trunk/vendor/freemius/assets/css/admin/debug.css (added)
-
trunk/vendor/freemius/assets/css/admin/dialog-boxes.css (added)
-
trunk/vendor/freemius/assets/css/admin/gdpr-optin-notice.css (added)
-
trunk/vendor/freemius/assets/css/admin/index.php (added)
-
trunk/vendor/freemius/assets/css/admin/optout.css (added)
-
trunk/vendor/freemius/assets/css/admin/plugins.css (added)
-
trunk/vendor/freemius/assets/css/customizer.css (added)
-
trunk/vendor/freemius/assets/css/index.php (added)
-
trunk/vendor/freemius/assets/img (added)
-
trunk/vendor/freemius/assets/img/index.php (added)
-
trunk/vendor/freemius/assets/img/plugin-icon.png (added)
-
trunk/vendor/freemius/assets/img/theme-icon.png (added)
-
trunk/vendor/freemius/assets/index.php (added)
-
trunk/vendor/freemius/assets/js (added)
-
trunk/vendor/freemius/assets/js/index.php (added)
-
trunk/vendor/freemius/assets/js/jquery.form.js (added)
-
trunk/vendor/freemius/assets/js/nojquery.ba-postmessage.js (added)
-
trunk/vendor/freemius/assets/js/postmessage.js (added)
-
trunk/vendor/freemius/assets/js/pricing (added)
-
trunk/vendor/freemius/assets/js/pricing/14fb1bd5b7c41648488b06147f50a0dc.svg (added)
-
trunk/vendor/freemius/assets/js/pricing/178afa6030e76635dbe835e111d2c507.png (added)
-
trunk/vendor/freemius/assets/js/pricing/27b5a722a5553d9de0170325267fccec.png (added)
-
trunk/vendor/freemius/assets/js/pricing/4375c4a3ddc6f637c2ab9a2d7220f91e.png (added)
-
trunk/vendor/freemius/assets/js/pricing/45da596e2b512ffc3bb638baaf0fdc4e.png (added)
-
trunk/vendor/freemius/assets/js/pricing/a34e046aee1702a5690679750a7f4d0f.svg (added)
-
trunk/vendor/freemius/assets/js/pricing/b09d0b38b627c2fa564d050f79f2f064.svg (added)
-
trunk/vendor/freemius/assets/js/pricing/c03f665db27af43971565560adfba594.png (added)
-
trunk/vendor/freemius/assets/js/pricing/cb5fc4f6ec7ada72e986f6e7dde365bf.png (added)
-
trunk/vendor/freemius/assets/js/pricing/d65812c447b4523b42d59018e1c0bb53.png (added)
-
trunk/vendor/freemius/assets/js/pricing/f3aac72a8e63997d6bb888f816457e9b.png (added)
-
trunk/vendor/freemius/assets/js/pricing/fde48e4609a6ddc11d639fc2421f2afd.png (added)
-
trunk/vendor/freemius/assets/js/pricing/freemius-pricing.js (added)
-
trunk/vendor/freemius/assets/js/pricing/freemius-pricing.js.LICENSE.txt (added)
-
trunk/vendor/freemius/composer.json (added)
-
trunk/vendor/freemius/config.php (added)
-
trunk/vendor/freemius/includes (added)
-
trunk/vendor/freemius/includes/class-freemius-abstract.php (added)
-
trunk/vendor/freemius/includes/class-freemius.php (added)
-
trunk/vendor/freemius/includes/class-fs-admin-notices.php (added)
-
trunk/vendor/freemius/includes/class-fs-api.php (added)
-
trunk/vendor/freemius/includes/class-fs-garbage-collector.php (added)
-
trunk/vendor/freemius/includes/class-fs-hook-snapshot.php (added)
-
trunk/vendor/freemius/includes/class-fs-lock.php (added)
-
trunk/vendor/freemius/includes/class-fs-logger.php (added)
-
trunk/vendor/freemius/includes/class-fs-options.php (added)
-
trunk/vendor/freemius/includes/class-fs-plugin-updater.php (added)
-
trunk/vendor/freemius/includes/class-fs-security.php (added)
-
trunk/vendor/freemius/includes/class-fs-storage.php (added)
-
trunk/vendor/freemius/includes/class-fs-user-lock.php (added)
-
trunk/vendor/freemius/includes/customizer (added)
-
trunk/vendor/freemius/includes/customizer/class-fs-customizer-support-section.php (added)
-
trunk/vendor/freemius/includes/customizer/class-fs-customizer-upsell-control.php (added)
-
trunk/vendor/freemius/includes/customizer/index.php (added)
-
trunk/vendor/freemius/includes/debug (added)
-
trunk/vendor/freemius/includes/debug/class-fs-debug-bar-panel.php (added)
-
trunk/vendor/freemius/includes/debug/debug-bar-start.php (added)
-
trunk/vendor/freemius/includes/debug/index.php (added)
-
trunk/vendor/freemius/includes/entities (added)
-
trunk/vendor/freemius/includes/entities/class-fs-affiliate-terms.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-affiliate.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-billing.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-entity.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-payment.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-plugin-info.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-plugin-license.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-plugin-plan.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-plugin-tag.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-plugin.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-pricing.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-scope-entity.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-site.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-subscription.php (added)
-
trunk/vendor/freemius/includes/entities/class-fs-user.php (added)
-
trunk/vendor/freemius/includes/entities/index.php (added)
-
trunk/vendor/freemius/includes/fs-core-functions.php (added)
-
trunk/vendor/freemius/includes/fs-essential-functions.php (added)
-
trunk/vendor/freemius/includes/fs-html-escaping-functions.php (added)
-
trunk/vendor/freemius/includes/fs-plugin-info-dialog.php (added)
-
trunk/vendor/freemius/includes/index.php (added)
-
trunk/vendor/freemius/includes/l10n.php (added)
-
trunk/vendor/freemius/includes/managers (added)
-
trunk/vendor/freemius/includes/managers/class-fs-admin-menu-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-admin-notice-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-cache-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-checkout-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-clone-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-contact-form-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-debug-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-gdpr-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-key-value-storage.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-license-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-option-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-permission-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-plan-manager.php (added)
-
trunk/vendor/freemius/includes/managers/class-fs-plugin-manager.php (added)
-
trunk/vendor/freemius/includes/managers/index.php (added)
-
trunk/vendor/freemius/includes/sdk (added)
-
trunk/vendor/freemius/includes/sdk/Exceptions (added)
-
trunk/vendor/freemius/includes/sdk/Exceptions/ArgumentNotExistException.php (added)
-
trunk/vendor/freemius/includes/sdk/Exceptions/EmptyArgumentException.php (added)
-
trunk/vendor/freemius/includes/sdk/Exceptions/Exception.php (added)
-
trunk/vendor/freemius/includes/sdk/Exceptions/InvalidArgumentException.php (added)
-
trunk/vendor/freemius/includes/sdk/Exceptions/OAuthException.php (added)
-
trunk/vendor/freemius/includes/sdk/Exceptions/index.php (added)
-
trunk/vendor/freemius/includes/sdk/FreemiusBase.php (added)
-
trunk/vendor/freemius/includes/sdk/FreemiusWordPress.php (added)
-
trunk/vendor/freemius/includes/sdk/LICENSE.txt (added)
-
trunk/vendor/freemius/includes/sdk/index.php (added)
-
trunk/vendor/freemius/includes/supplements (added)
-
trunk/vendor/freemius/includes/supplements/fs-essential-functions-1.1.7.1.php (added)
-
trunk/vendor/freemius/includes/supplements/fs-essential-functions-2.2.1.php (added)
-
trunk/vendor/freemius/includes/supplements/fs-migration-2.5.1.php (added)
-
trunk/vendor/freemius/includes/supplements/index.php (added)
-
trunk/vendor/freemius/index.php (added)
-
trunk/vendor/freemius/languages (added)
-
trunk/vendor/freemius/languages/freemius-cs_CZ.mo (added)
-
trunk/vendor/freemius/languages/freemius-da_DK.mo (added)
-
trunk/vendor/freemius/languages/freemius-de_DE.mo (added)
-
trunk/vendor/freemius/languages/freemius-es_ES.mo (added)
-
trunk/vendor/freemius/languages/freemius-fr_FR.mo (added)
-
trunk/vendor/freemius/languages/freemius-he_IL.mo (added)
-
trunk/vendor/freemius/languages/freemius-hu_HU.mo (added)
-
trunk/vendor/freemius/languages/freemius-it_IT.mo (added)
-
trunk/vendor/freemius/languages/freemius-ja.mo (added)
-
trunk/vendor/freemius/languages/freemius-nl_NL.mo (added)
-
trunk/vendor/freemius/languages/freemius-ru_RU.mo (added)
-
trunk/vendor/freemius/languages/freemius-ta.mo (added)
-
trunk/vendor/freemius/languages/freemius-zh_CN.mo (added)
-
trunk/vendor/freemius/languages/freemius.pot (added)
-
trunk/vendor/freemius/languages/index.php (added)
-
trunk/vendor/freemius/require.php (added)
-
trunk/vendor/freemius/start.php (added)
-
trunk/vendor/freemius/templates (added)
-
trunk/vendor/freemius/templates/account (added)
-
trunk/vendor/freemius/templates/account.php (added)
-
trunk/vendor/freemius/templates/account/billing.php (added)
-
trunk/vendor/freemius/templates/account/index.php (added)
-
trunk/vendor/freemius/templates/account/partials (added)
-
trunk/vendor/freemius/templates/account/partials/activate-license-button.php (added)
-
trunk/vendor/freemius/templates/account/partials/addon.php (added)
-
trunk/vendor/freemius/templates/account/partials/deactivate-license-button.php (added)
-
trunk/vendor/freemius/templates/account/partials/disconnect-button.php (added)
-
trunk/vendor/freemius/templates/account/partials/index.php (added)
-
trunk/vendor/freemius/templates/account/partials/site.php (added)
-
trunk/vendor/freemius/templates/account/payments.php (added)
-
trunk/vendor/freemius/templates/add-ons.php (added)
-
trunk/vendor/freemius/templates/add-trial-to-pricing.php (added)
-
trunk/vendor/freemius/templates/admin-notice.php (added)
-
trunk/vendor/freemius/templates/ajax-loader.php (added)
-
trunk/vendor/freemius/templates/api-connectivity-message-js.php (added)
-
trunk/vendor/freemius/templates/auto-installation.php (added)
-
trunk/vendor/freemius/templates/checkout (added)
-
trunk/vendor/freemius/templates/checkout.php (added)
-
trunk/vendor/freemius/templates/checkout/frame.php (added)
-
trunk/vendor/freemius/templates/checkout/process-redirect.php (added)
-
trunk/vendor/freemius/templates/checkout/redirect.php (added)
-
trunk/vendor/freemius/templates/clone-resolution-js.php (added)
-
trunk/vendor/freemius/templates/connect (added)
-
trunk/vendor/freemius/templates/connect.php (added)
-
trunk/vendor/freemius/templates/connect/index.php (added)
-
trunk/vendor/freemius/templates/connect/permission.php (added)
-
trunk/vendor/freemius/templates/connect/permissions-group.php (added)
-
trunk/vendor/freemius/templates/contact.php (added)
-
trunk/vendor/freemius/templates/debug (added)
-
trunk/vendor/freemius/templates/debug.php (added)
-
trunk/vendor/freemius/templates/debug/api-calls.php (added)
-
trunk/vendor/freemius/templates/debug/index.php (added)
-
trunk/vendor/freemius/templates/debug/logger.php (added)
-
trunk/vendor/freemius/templates/debug/plugins-themes-sync.php (added)
-
trunk/vendor/freemius/templates/debug/scheduled-crons.php (added)
-
trunk/vendor/freemius/templates/email.php (added)
-
trunk/vendor/freemius/templates/forms (added)
-
trunk/vendor/freemius/templates/forms/affiliation.php (added)
-
trunk/vendor/freemius/templates/forms/data-debug-mode.php (added)
-
trunk/vendor/freemius/templates/forms/deactivation (added)
-
trunk/vendor/freemius/templates/forms/deactivation/contact.php (added)
-
trunk/vendor/freemius/templates/forms/deactivation/form.php (added)
-
trunk/vendor/freemius/templates/forms/deactivation/index.php (added)
-
trunk/vendor/freemius/templates/forms/deactivation/retry-skip.php (added)
-
trunk/vendor/freemius/templates/forms/email-address-update.php (added)
-
trunk/vendor/freemius/templates/forms/index.php (added)
-
trunk/vendor/freemius/templates/forms/license-activation.php (added)
-
trunk/vendor/freemius/templates/forms/optout.php (added)
-
trunk/vendor/freemius/templates/forms/premium-versions-upgrade-handler.php (added)
-
trunk/vendor/freemius/templates/forms/premium-versions-upgrade-metadata.php (added)
-
trunk/vendor/freemius/templates/forms/resend-key.php (added)
-
trunk/vendor/freemius/templates/forms/subscription-cancellation.php (added)
-
trunk/vendor/freemius/templates/forms/trial-start.php (added)
-
trunk/vendor/freemius/templates/forms/user-change.php (added)
-
trunk/vendor/freemius/templates/gdpr-optin-js.php (added)
-
trunk/vendor/freemius/templates/index.php (added)
-
trunk/vendor/freemius/templates/js (added)
-
trunk/vendor/freemius/templates/js/index.php (added)
-
trunk/vendor/freemius/templates/js/jquery.content-change.php (added)
-
trunk/vendor/freemius/templates/js/open-license-activation.php (added)
-
trunk/vendor/freemius/templates/js/permissions.php (added)
-
trunk/vendor/freemius/templates/js/style-premium-theme.php (added)
-
trunk/vendor/freemius/templates/partials (added)
-
trunk/vendor/freemius/templates/partials/index.php (added)
-
trunk/vendor/freemius/templates/partials/network-activation.php (added)
-
trunk/vendor/freemius/templates/plugin-icon.php (added)
-
trunk/vendor/freemius/templates/plugin-info (added)
-
trunk/vendor/freemius/templates/plugin-info/description.php (added)
-
trunk/vendor/freemius/templates/plugin-info/features.php (added)
-
trunk/vendor/freemius/templates/plugin-info/index.php (added)
-
trunk/vendor/freemius/templates/plugin-info/screenshots.php (added)
-
trunk/vendor/freemius/templates/pricing.php (added)
-
trunk/vendor/freemius/templates/secure-https-header.php (added)
-
trunk/vendor/freemius/templates/sticky-admin-notice-js.php (added)
-
trunk/vendor/freemius/templates/tabs-capture-js.php (added)
-
trunk/vendor/freemius/templates/tabs.php (added)
Legend:
- Unmodified
- Added
- Removed
-
sanbar-express-nfe-xml-import-br/trunk/assets/css/core.css
r3725460 r3782421 1 /* Core visual foundation for the plugin. Reuses the color tokens, 2 typography, and components (.sbnfebr-btn, .sb-brand, .sb-edition-*) 3 from SanBar EXPress Sheet for a consistent suite look. 4 Classes are scoped under #sbnfebr-wrap with the sbnfebr- prefix 5 (this plugin) and sb- prefix (shared suite identity) so they never 6 collide with the Sheet plugin when both are active. */ 1 7 2 8 3 :root { … … 24 19 } 25 20 26 /* Standard 4px border-radius on every input/select/button. Scoped to27 the plugin's 3 containers (main grid + the 2 modal skeletons) so it28 never leaks into the rest of wp-admin. More specific rules later in29 the file (e.g. pill shapes with border-radius:10px/50%) win by30 normal specificity, no !important needed here. */31 21 #sbnfebr-wrap input, 32 22 #sbnfebr-wrap select, … … 65 55 } 66 56 .sb-brand { display: inline-flex; align-items: baseline; gap: 5px; } 57 .sb-brand__mobile { display: none; } 67 58 .sb-brand__prefix, 68 59 .sb-brand__suffix { font-size: 15px; font-weight: 600; color: #1d2327; } … … 126 117 gap: 6px; 127 118 } 128 129 /* ===== ROW 2 — supplier/note selector + search ===== */ 119 .sbnfebr-row1__actions { 120 display: flex; 121 align-items: center; 122 gap: 6px; 123 } 124 .sbnfebr-mobile-drawer-toggle { display: none; } 125 .sbnfebr-mobile-drawer { display: contents; } 126 130 127 .sbnfebr-row2 { 131 128 display: flex; … … 146 143 } 147 144 #sbnfebr-search { flex: 1 1 220px; min-width: 180px; } 148 /* +50% over the browser's default width (~157px) — supplier name and 149 note number/series didn't fit at the original size. */ 145 150 146 #sbnfebr-filter-supplier, 151 147 #sbnfebr-filter-note { min-width: 235px; } … … 167 163 .sbnfebr-stats__left, 168 164 .sbnfebr-stats__right { display: flex; align-items: center; gap: 8px; } 169 /* Note/product view toggle — dual segment, both always visible, active 170 one highlighted. Sits to the left of the pagination. */ 165 171 166 .sbnfebr-view-toggle { 172 167 display: inline-flex; … … 200 195 font-size: 12px; 201 196 } 197 .sbnfebr-pagination__per-page { color: #6b7280; white-space: nowrap; } 202 198 .sbnfebr-pagination #sbnfebr-page-prev, 203 199 .sbnfebr-pagination #sbnfebr-page-next { … … 218 214 line-height: 1.2; 219 215 box-sizing: border-box; 220 /* 2x the default width — native select arrow overlapped the number 221 at the previous, tighter size. */ 216 222 217 width: 76px; 223 218 padding: 1px 20px 1px 6px; … … 225 220 border-color: #d1d5db; 226 221 } 227 /* Badge (Items/Notes) — informational only, not clickable: neutral 228 background, no shadow, default cursor. The button variant 229 (.sbnfebr-stat--link, below) adds affordance to signal it's 230 clickable. */ 222 231 223 .sbnfebr-stat { 232 224 display: inline-flex; … … 260 252 } 261 253 .sbnfebr-stat--link:hover { background: #eff6ff; border-color: #93c5fd; } 262 /* Separates the clickable button group from the informational badges. */ 254 .sbnfebr-ignored-drawer.is-active { 255 background: #eff6ff; 256 border-color: #3b82f6; 257 box-shadow: inset 3px 0 0 #2563eb; 258 } 259 .sbnfebr-ignored-drawer.is-active .sbnfebr-stat__label, 260 .sbnfebr-ignored-drawer.is-active .sbnfebr-stat__val { color: #1d4ed8; } 261 263 262 .sbnfebr-stat--link-first { margin-left: 10px; } 263 264 .sbnfebr-bulk-toolbar { 265 display: inline-flex; 266 align-items: center; 267 gap: 6px; 268 flex-wrap: wrap; 269 } 264 270 265 271 /* ===== BUTTONS ===== */ … … 280 286 .sbnfebr-btn--blue { background: #3b82f6; color: #fff; border-color: #2563eb; } 281 287 .sbnfebr-btn--blue:hover { background: #2563eb; } 282 /* Import XML button — taller with a sharper icon than the other 283 toolbar buttons, since it's the screen's primary action. */ 288 284 289 #sbnfebr-btn-upload, 285 290 #sbnfebr-btn-upload-empty { … … 293 298 font-weight: 600; 294 299 } 295 /* Bulk Draft+ — amber matches the "Plus feature" visual indicator 296 already used on the supplier+code match icons. */ 300 297 301 .sbnfebr-btn--amber { background: #f59e0b; color: #fff; border-color: #d97706; } 298 302 .sbnfebr-btn--amber:hover { background: #d97706; } 303 #sbnfebr-btn-upgrade { text-decoration: none; } 304 #sbnfebr-btn-upgrade:hover { color: #fff; } 299 305 #sbnfebr-btn-bulk-draft-plus, 300 306 #sbnfebr-btn-bulk-ignore, … … 315 321 box-sizing: border-box; 316 322 } 317 /* "X clear" — shows/hides together with the bulk button. */ 323 318 324 #sbnfebr-btn-bulk-clear { 319 325 width: 30px; … … 360 366 .sbnfebr-notice--warning { background: #fef3c7; color: #92400e; border-color: #fcd34d; } 361 367 .sbnfebr-notice--progress { background: #eff6ff; border-color: #bfdbfe; } 362 /* Notice with action buttons — "Open in editor"/"Open in Store 363 Manager" shown after creation. */ 368 364 369 .sbnfebr-notice--actions { 365 370 display: flex; … … 451 456 } 452 457 453 /* Product view — larger, more spaced-out layout than the note view:454 fewer columns on screen, more room to breathe. ~14px font, wider455 column gaps, action buttons proportionally ~30% larger. */456 458 .sbnfebr-grid--product thead th { 457 459 padding: 10px 16px; … … 463 465 } 464 466 .sbnfebr-grid--product .sbnfebr-col-actions { 465 /* Column fits up to 7 icons (group of 5 + history + ignored): 466 5×26px + 4×2px gap in the group (138px) + history/ignored 467 (26px each) + spacing between groups. */ 468 width: 200px; 469 min-width: 200px; 470 max-width: 200px; 467 width: 120px; 468 min-width: 120px; 469 max-width: 120px; 471 470 } 472 471 .sbnfebr-grid--product .sbnfebr-action-btn { … … 481 480 font-size: 13px; 482 481 } 483 .sbnfebr-grid--product .sbnfebr-price-variant-badge { 484 font-size: 10px; 485 } 486 /* Suppliers/Notes columns — number centered, header and cell aligned 487 together. */ 482 488 483 .sbnfebr-grid--product .sbnfebr-col-product_supplier_count, 489 484 .sbnfebr-grid--product .sbnfebr-col-product_note_count, … … 494 489 } 495 490 496 /* Soft rectangular badges — price, stock, last purchase in the497 product view. Color is FIXED per column (decorative, helps scan the498 row faster) rather than representing state; the ⚠ inside the badge499 signals attention (price changed / stock at zero), not the500 background color. */501 491 .sbnfebr-value-badge { 502 492 display: inline-block; … … 517 507 } 518 508 519 /* Action column — always first, fixed and narrow (fits only the520 buttons, never grows with content). */521 509 .sbnfebr-col-select { 522 510 width: 24px; … … 530 518 #sbnfebr-select-all { 531 519 vertical-align: middle; 532 margin: 0 0 2px 0 !important; /* WP core's ".form-table input.tog" has higher specificity 533 (margin-bottom:-1px) — !important is needed to override it */ 520 margin: 0 0 2px 0 !important; 534 521 } 535 522 .sbnfebr-col-actions { 536 /* Cell fits up to 7 icons (group of 5 + history + ignored): 537 5×20px + 4×2px gap in the group (88px) + history/ignored 538 (20px each) + spacing between groups. */ 539 width: 140px; 540 min-width: 140px; 541 max-width: 140px; 542 /* left, not center: with only 2 of 3 icons visible on most rows, 543 centering in a cell wide enough for the 3rd icon left a large 544 gap after the checkbox. */ 523 width: 94px; 524 min-width: 94px; 525 max-width: 94px; 545 526 text-align: left; 546 527 padding: 3px 3px 3px 1px !important; … … 563 544 .sbnfebr-action-btn + .sbnfebr-action-btn { margin-left: 2px; } 564 545 565 /* History button states — amber (price changed with the same566 supplier) and red (same GTIN across different suppliers, takes567 priority over amber). */568 546 .sbnfebr-action-btn--warn { 569 547 background: #fffbeb; … … 576 554 } 577 555 .sbnfebr-action-btn--alert:hover { background: #fee2e2; } 578 /* "Ignored" — only exists in the DOM when the item is already ignored 579 (see actionButtonsHTML), strikethrough + red. */ 556 580 557 .sbnfebr-action-btn--ignored { 581 558 background: #fef2f2; … … 585 562 } 586 563 .sbnfebr-action-btn--ignored:hover { background: #fee2e2; } 587 /* Price changed between notes — small numbered badge, same pattern as 588 .sb-media-badge on the image column in Store Manager. Positioned 589 inside .sbnfebr-ac-gicon-wrap. */ 590 .sbnfebr-price-variant-badge { 591 display: inline-block; 592 background: #f59e0b; 593 color: #fff; 594 font-size: 9px; 595 font-weight: 700; 596 padding: 0 4px; 597 min-width: 0; 598 text-align: center; 599 border-radius: 8px; 600 position: absolute; 601 bottom: -1px; 602 right: -1px; 603 line-height: 1.4; 604 pointer-events: none; 605 } 606 .sbnfebr-stale-badge { 607 display: inline-block; 608 font-size: 10px; 609 position: absolute; 610 top: -3px; 611 right: -3px; 612 line-height: 1; 613 pointer-events: none; 614 } 615 .sbnfebr-grid--product .sbnfebr-stale-badge { 616 font-size: 12px; 617 } 618 619 /* Group of 5 icons in the action cell: "⋯" opens the full Action 620 Modal, the other 4 open the matching popup directly. 20×20 here 621 (note view); .sbnfebr-grid--product overrides to 26×26 above. */ 564 /* Workflow actions in the Entrada grid. */ 622 565 .sbnfebr-ac-gicon-group { display: inline-flex; align-items: center; gap: 2px; } 623 .sbnfebr-ac-gicon-wrap { position: relative; display: inline-block; }624 566 .sbnfebr-ac-gicon { 625 567 width: 20px; … … 637 579 .sbnfebr-ac-gicon:hover { background: #f3f4f6; } 638 580 .sbnfebr-ac-gicon--neutral { color: #4b5563; } 639 .sbnfebr-ac-gicon--alert { background: #fffbeb; border-color: #d97706; color: #92400e; } 640 .sbnfebr-ac-gicon--alert:hover { background: #fef3c7; } 641 .sbnfebr-ac-gicon--quiet { opacity: .45; } 642 .sbnfebr-ac-gicon--quiet:hover { opacity: .8; } 643 .sbnfebr-ac-gicon--done { background: #d1fae5; border-color: #6ee7b7; color: #065f46; } 644 .sbnfebr-ac-gicon--done:hover { background: #a7f3d0; } 645 .sbnfebr-ac-gicon--done-plus { background: #fef3c7; border-color: #f59e0b; color: #92400e; } 646 .sbnfebr-ac-gicon--done-plus:hover { background: #fde68a; } 647 .sbnfebr-ac-gicon--locked { background: #f3f4f6; color: #9ca3af; border-style: dashed; } 648 649 /* Action button mini menu (Make Draft / Link) — small popup anchored 650 near the button, not the full Library overlay. */ 651 .sbnfebr-action-menu { 652 position: fixed; 653 z-index: var(--sb-z-overlay, 100000); 654 background: #fff; 655 border: 1px solid #d1d5db; 656 border-radius: 6px; 657 box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15); 658 padding: 4px; 659 min-width: 170px; 660 } 661 .sbnfebr-action-menu-item { 662 display: flex; 663 align-items: center; 664 justify-content: space-between; 665 gap: 8px; 666 width: 100%; 667 padding: 7px 10px; 668 border: none; 669 background: none; 670 text-align: left; 671 font-size: 12px; 672 border-radius: 4px; 673 cursor: pointer; 674 box-sizing: border-box; 675 } 676 .sbnfebr-action-menu-item:hover:not(:disabled) { background: #f3f4f6; } 677 .sbnfebr-action-menu-item:disabled { 678 color: #9ca3af; 679 cursor: not-allowed; 680 } 681 .sbnfebr-action-menu-badge { 682 font-size: 8px; 683 font-weight: 800; 684 letter-spacing: 0.5px; 685 color: #fff; 686 background: linear-gradient(135deg, #f59e0b, #d97706); 687 padding: 2px 5px; 688 border-radius: 8px; 689 } 690 691 /* Modal --narrow (used for price history — doesn't need the full 692 800px width of the standard Library modal). */ 581 693 582 .sb-library-overlay--narrow { width: 560px; max-width: 92vw; height: auto; max-height: 80vh; } 694 583 695 /* Modal --registry. Width is the sum of columns: note group 554px +696 divider 20px + registry group 574px + actions 200px (5-icon group697 20px + 4×2px gap = 108px, + ↗ 24px + SM 48px + group gaps)698 = 1348px content + gaps between columns (3×6px) + row padding699 (20px) + modal padding (16px 20px, from library-supplier.css)700 ≈ 1426px, rounded to 1450px.701 !important is needed: library-supplier.css loads after core.css, so702 .sb-library-overlay (base, 800px/88vh) wins the specificity tie703 (same weight, single class) by cascade order — without it the modal704 renders at the base size. Height grows with content up to an 85vh705 cap rather than staying fixed at 88vh. */706 584 .sb-library-overlay--registry { 707 585 width: 1450px !important; … … 711 589 } 712 590 .sb-library-overlay--registry .sbnfebr-regcheck-body { 713 overflow-x: hidden; 714 } 715 716 /* Subtitle "note N/S · Supplier" — only present on the post-import 717 auto-open (empty when opened manually). */ 591 overflow-x: auto; 592 } 593 718 594 .sbnfebr-regcheck-subtitle { 719 595 font-size: 12px; … … 838 714 839 715 .sbnfebr-regcheck-actions { 840 display: flex; 841 align-items: center; 842 justify-content: center; 716 display: grid; 717 grid-template-columns: 104px 56px 30px; 843 718 gap: 4px; 844 } 845 .sbnfebr-regcheck-actions .sbnfebr-btn { 846 width: 24px; 847 height: 24px; 848 padding: 0; 849 display: flex; 850 align-items: center; 851 justify-content: center; 852 font-size: 12px; 853 line-height: 1; 854 } 855 /* SM button — same arrow as "Open in editor" + "SM" label, double the 856 width of the other 2 buttons (48px), amber outline (same visual as 857 .sbnfebr-ia-open-sm-btn in the action modal). */ 858 .sbnfebr-regcheck-open-sm-btn { 859 width: 48px !important; 860 background: #fff !important; 861 color: #b45309 !important; 862 border: 1px solid #f59e0b !important; 863 font-size: 10px !important; 864 font-weight: 600; 865 gap: 2px; 866 } 867 .sbnfebr-regcheck-open-sm-btn:hover { 868 background: #fffbeb !important; 869 } 870 871 /* === Grid action modal (Make Draft / Link / Draft+ Sync) — reuses the 872 .sbnfebr-danger-backdrop/.sbnfebr-danger-modal skeleton from 873 library-notes.css, without the red top border. === */ 719 align-items: center; 720 justify-content: end; 721 } 722 874 723 .sbnfebr-danger-modal.sbnfebr-itemaction-modal { 875 724 border-top: 4px solid #3b82f6; … … 880 729 box-sizing: border-box; 881 730 } 882 /* Source column sits beside the content, not stacked — only on 883 screens wide enough (desktop). Mobile keeps it stacked (modal width 884 is already 92vw there, a 220px side column wouldn't fit without 885 squeezing the rest). 886 Doubled specificity (.sbnfebr-danger-modal.sbnfebr-itemaction- 887 modal-...) is intentional: .sbnfebr-danger-modal (420px) lives in 888 library-notes.css, which loads after core.css — with a single class 889 on both sides, load order would decide the tie and the generic 890 420px would always win over the 440px/720px defined here. */ 731 891 732 @media (min-width: 700px) { 892 733 .sbnfebr-danger-modal.sbnfebr-itemaction-modal--has-source { … … 945 786 } 946 787 947 /* Standardized alert card — short title + optional technical detail,948 standard palette (danger=risky decision, warn=worth checking,949 info=context only, good=positive confirmation). Used across several950 screens (item modal, import), hence living in core.css rather than951 a screen-specific file. */952 788 .sbnfebr-alert { 953 789 border: 1px solid; … … 985 821 .sbnfebr-ia-product-info-line { opacity: 0.9; } 986 822 .sbnfebr-itemaction-name-input { 987 /* Every select/input uses 4px border-radius, no exception — see the 988 same rule in .sbnfebr-danger-input (library-notes.css) and 989 #sbnfebr-per-page. */ 823 990 824 border: 1px solid #d1d5db; 991 825 border-radius: 4px; … … 998 832 .sbnfebr-itemaction-name-input:disabled { background: #f3f4f6; color: #9ca3af; } 999 833 1000 /* Make Draft block buttons — 2 lines of text, fixed size: "create1001 draft" and "link" share the same size (150x50); "identity only" is1002 smaller (150x25). */1003 834 .sbnfebr-ia-draft-btn, 1004 835 .sbnfebr-ia-manual-link-toggle { … … 1026 857 border: 1px solid #d1d5db !important; 1027 858 } 1028 /* SM button — amber outline only on this one, so it doesn't compete 1029 with the blue/amber of the primary action. Spaced from "Open in 1030 editor" right after it. */ 859 1031 860 .sbnfebr-ia-open-sm-btn { 1032 861 margin-right: 5px; … … 1037 866 .sbnfebr-ia-open-sm-btn:hover { background: #fffbeb !important; } 1038 867 1039 /* Four separate, atomic action cards (Draft/Link, Stock, Price/Source,1040 Tax data). Never `disabled` — only switches between pulsing (has a1041 difference to apply) and dimmed (nothing new, still clickable). */1042 868 .sbnfebr-ac-cards { 1043 869 display: flex; … … 1078 904 } 1079 905 1080 /* Alert — has a difference to apply, pulsing ring on the icon. */1081 906 .sbnfebr-ac-card--alert { border-color: #d97706; background: #fffbeb; } 1082 907 .sbnfebr-ac-card--alert .sbnfebr-ac-icon { border-color: #d97706; position: relative; } … … 1101 926 .sbnfebr-ac-card--alert .sbnfebr-ac-btn { background: #f59e0b; border: 1px solid #d97706; color: #fff; } 1102 927 1103 /* Dimmed — nothing new, but still clickable (the decision is always the user's). */1104 928 .sbnfebr-ac-card--quiet { background: #f8f9fb; } 1105 929 .sbnfebr-ac-card--quiet .sbnfebr-ac-btn { background: #fff; border: 1px solid #d1d5db; color: #9ca3af; } … … 1111 935 .sbnfebr-ac-card--done .sbnfebr-ac-btn { background: #fff; border: 1px solid #a7f3d0; color: #065f46; } 1112 936 1113 /* Locked Plus feature, shown flagged (not hidden) in Lite. "Learn1114 more" opens static text only — no Plus logic ships in the Lite build. */1115 937 .sbnfebr-ac-card--locked { background: #f8f9fb; } 1116 938 .sbnfebr-ac-card--locked .sbnfebr-ac-icon { background: #f3f4f6; color: #9ca3af; border-style: dashed; } 1117 939 .sbnfebr-ac-card--locked .sbnfebr-ac-btn { background: #fff; border: 1px solid #f59e0b; color: #b45309; } 1118 940 1119 /* Individual popup — same .sbnfebr-danger-backdrop/.sbnfebr-danger-modal1120 skeleton, without the standard red top border. */1121 941 .sbnfebr-ac-popup { 1122 942 position: relative; … … 1148 968 font-size: 9px !important; 1149 969 } 1150 /* Locked-feature ribbon inside a popup — same top-right corner as the 1151 close button; the button sits above it (z-index) so it stays fully 1152 clickable even where the two overlap. */ 970 1153 971 .sbnfebr-ac-popup .sbnfebr-ac-ribbon { 1154 972 z-index: 0; … … 1214 1032 padding: 0 6px; 1215 1033 } 1216 /* Icon glossary — same .sbnfebr-danger-backdrop/.sbnfebr-danger-modal 1217 skeleton as usual. */ 1034 1218 1035 .sbnfebr-glossary-modal { 1219 1036 border-top: 4px solid #3b82f6; … … 1261 1078 .sbnfebr-ac-popup-btnrow { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; } 1262 1079 1263 /* Fiscal popup — note × product table, same look as .sbnfebr-noteinfo-dup-table. */1264 1080 .sbnfebr-ac-popup--wide { width: 540px; } 1265 1081 .sbnfebr-ac-fiscal-table { … … 1287 1103 .sbnfebr-ac-fiscal-empty { color: #9ca3af; font-style: italic; } 1288 1104 1289 /* "Choose" (Draft/Link with match) — 2-3 options as cards. */1290 1105 .sbnfebr-ac-choose-list { display: flex; flex-direction: column; gap: 8px; } 1291 1106 .sbnfebr-ac-choose-opt { … … 1302 1117 .sbnfebr-ac-choose-btn { font-size: 11px; padding: 5px 10px; } 1303 1118 1304 /* Progress toast — bottom right corner, z-index above any modal1305 (.sbnfebr-danger-backdrop already uses high values, this needs to1306 win). */1307 1119 #sbnfebr-toast-stack { 1308 1120 position: fixed; … … 1341 1153 .sbnfebr-toast-pct { font-weight: 600; } 1342 1154 1343 /* Confirmation toast — green, checkmark instead of spinner, dismisses1344 itself. */1345 1155 .sbnfebr-toast--success { background: #065f46; } 1346 1156 .sbnfebr-toast--error { background: #b91c1c; } … … 1358 1168 } 1359 1169 1360 /* Temporary highlight on a row that just changed — fades out after1361 FLASH_MS (see renderGrid() in nfebr-main.js). Stays above the1362 normal row colors (even/odd/selected) via source order, no1363 !important needed. */1364 1170 @keyframes sbnfebr-row-flash { 1365 1171 0% { background-color: #bbf7d0; } … … 1370 1176 } 1371 1177 1372 /* "Update information" card (Plus) — same diagonal PLUS ribbon the1373 Sheet uses on locked-feature cards in Lite. */1374 1178 .sbnfebr-sync-card { 1375 1179 position: relative; … … 1417 1221 font-weight: 700; 1418 1222 } 1419 /* "Already synced or not" status for the already-linked item card — 1420 empty until the async check resolves. */ 1223 1421 1224 .sbnfebr-ia-sync-status:empty { display: none; } 1422 1225 .sbnfebr-ia-sync-status { … … 1436 1239 border: 1px solid #fde68a; 1437 1240 } 1438 /* "Never synced" — neither matching nor changed: has never received 1439 any tax data yet (e.g. linked via Lite). */ 1241 1440 1242 .sbnfebr-ia-sync-status--neutral { 1441 1243 background: #eff6ff; … … 1447 1249 font-size: 11px; 1448 1250 } 1449 /* Field-by-field list of what changed (e.g. "NCM: 1234 → 5678, 1450 CEST: ...") — secondary line below the "X of Y fields outdated" 1451 summary, same visual style as the warning above (smaller, more 1452 subdued). */ 1251 1453 1252 .sbnfebr-ia-sync-status-detail { 1454 1253 margin-top: 4px; … … 1457 1256 } 1458 1257 1459 /* diffCard (nfebr-diff-card.js) — diverging field row (batch review). */1460 1258 .sbnfebr-diffcard-row { 1461 1259 display: flex; … … 1471 1269 .sbnfebr-diffcard-incoming { color: #1d2327; font-weight: 700; } 1472 1270 1473 /* diffCard — source selector row (multiple occurrences of the GTIN). */1474 1271 .sbnfebr-diffcard-source { 1475 1272 all: unset; … … 1491 1288 background: #eff6ff; 1492 1289 } 1290 .sbnfebr-diffcard-source:disabled { cursor: default; } 1291 .sbnfebr-diffcard-source.is-loading { opacity: .65; } 1493 1292 .sbnfebr-diffcard-source-main { display: flex; flex-direction: column; gap: 2px; font-size: 12px; } 1494 1293 .sbnfebr-diffcard-source-note { font-weight: 700; color: #1d2327; } … … 1500 1299 .sbnfebr-diffcard-source-delta--down { color: #059669; } 1501 1300 .sbnfebr-diffcard-flag { font-style: normal; font-size: 13px; } 1502 1503 /* Post-import review (nfebr-review-modal.js) */ 1504 /* Doubled specificity is intentional — same reason as 1505 .sbnfebr-itemaction-modal above: .sbnfebr-danger-modal (420px) 1506 lives in library-notes.css, which loads after core.css, so a single 1507 class on both sides would let load order decide the tie. */ 1508 .sbnfebr-danger-modal.sbnfebr-review-modal { 1509 border-top: 4px solid #3b82f6; 1510 width: 720px; 1511 max-width: 95vw; 1512 max-height: 88vh; 1513 overflow-y: auto; 1514 box-sizing: border-box; 1515 } 1516 .sbnfebr-review-upgrades { margin-bottom: 14px; } 1517 .sbnfebr-review-upgrade-card { 1518 background: #eff6ff; 1301 .sbnfebr-diffcard-source-action { 1302 padding: 2px 7px; 1303 background: #fff; 1304 border: 1px solid #cbd5e1; 1305 color: #334155; 1306 font-size: 10px; 1307 font-style: normal; 1308 font-weight: 700; 1309 white-space: nowrap; 1310 } 1311 .sbnfebr-diffcard-source--selected .sbnfebr-diffcard-source-action { 1312 background: #dcfce7; 1313 border-color: #86efac; 1314 color: #166534; 1315 } 1316 1317 .sbnfebr-workflow-reference { 1318 margin-bottom: 10px; 1319 padding: 10px; 1519 1320 border: 1px solid #bfdbfe; 1520 border-radius: 6px; 1521 padding: 10px 12px; 1522 font-size: 12px; 1523 color: #1e40af; 1524 margin-bottom: 8px; 1525 } 1526 .sbnfebr-review-upgrade-title { font-size: 12px; color: #1d2327; margin-bottom: 4px; } 1527 .sbnfebr-review-upgrade-actions { display: flex; gap: 8px; margin-top: 8px; } 1528 .sbnfebr-review-list { display: flex; flex-direction: column; gap: 4px; margin-bottom: 12px; } 1529 .sbnfebr-review-card { 1530 background: #f8fafc; 1531 border: 1px solid #f1f5f9; 1532 border-radius: 6px; 1533 padding: 6px 10px; 1534 display: flex; 1535 align-items: center; 1536 flex-wrap: wrap; 1537 gap: 10px; 1538 font-size: 12px; 1539 } 1540 .sbnfebr-review-card-head { display: flex; align-items: center; gap: 8px; cursor: pointer; flex: 1 1 220px; min-width: 0; } 1541 .sbnfebr-review-card-head input[type="checkbox"] { width: auto; flex-shrink: 0; } 1542 .sbnfebr-review-card-title { color: #1d2327; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } 1543 .sbnfebr-review-diff { color: #6b7280; white-space: nowrap; } 1544 .sbnfebr-review-diff strong { color: #1d2327; } 1545 .sbnfebr-review-stock { 1546 display: inline-flex; 1547 align-items: center; 1548 gap: 5px; 1549 color: #6b7280; 1550 white-space: nowrap; 1551 } 1552 .sbnfebr-review-stock select, 1553 .sbnfebr-review-stock input { 1554 height: var(--sb-input-height); 1555 min-height: var(--sb-input-height); 1556 line-height: 1.2; 1557 font-size: 12px; 1558 box-sizing: border-box; 1559 } 1560 .sbnfebr-review-stock select { padding: 1px 20px 1px 6px; } 1561 .sbnfebr-review-stock input { width: 60px; padding: 1px 6px; font-family: inherit; } 1562 .sbnfebr-review-footer { 1321 border-radius: var(--sbnfebr-radius-surface); 1322 background: #f8fbff; 1323 } 1324 .sbnfebr-workflow-reference__title, 1325 .sbnfebr-workflow-reference__current { 1563 1326 display: flex; 1564 1327 align-items: center; 1565 1328 justify-content: space-between; 1566 border-top: 1px solid #e5e7eb; 1567 padding-top: 12px; 1568 } 1329 gap: 8px; 1330 } 1331 .sbnfebr-workflow-reference__title { margin-bottom: 6px; font-size: 11px; font-weight: 700; color: #475569; } 1332 .sbnfebr-workflow-reference__title em { color: #15803d; font-style: normal; } 1333 .sbnfebr-workflow-reference__current { padding: 7px 0; border-top: 1px solid #dbeafe; border-bottom: 1px solid #dbeafe; } 1334 .sbnfebr-workflow-reference__current strong { color: #1e3a8a; } 1335 .sbnfebr-workflow-reference__current span { flex: 1 1 auto; color: #64748b; font-size: 11px; } 1336 .sbnfebr-workflow-reference__current b { color: #111827; white-space: nowrap; } 1337 .sbnfebr-workflow-reference details { margin-top: 7px; } 1338 .sbnfebr-workflow-reference summary { cursor: pointer; color: #1d4ed8; font-weight: 600; } 1339 .sbnfebr-workflow-reference details > p { margin: 6px 0; color: #64748b; font-size: 11px; } 1340 .sbnfebr-workflow-reference__options { max-height: 210px; overflow-y: auto; overscroll-behavior: contain; } 1341 .sbnfebr-workflow-reference__empty { display: block; padding: 5px 0; color: #64748b; } 1342 1343 @media (max-width: 720px) { 1344 .sbnfebr-workflow-reference__current { align-items: flex-start; flex-wrap: wrap; } 1345 .sbnfebr-diffcard-source { align-items: flex-start; flex-direction: column; } 1346 .sbnfebr-diffcard-source-meta { width: 100%; flex-wrap: wrap; } 1347 .sbnfebr-diffcard-source-action { margin-left: auto; } 1348 } 1349 1569 1350 .sbnfebr-diffcard-supplier-warn { 1570 1351 background: #fffbeb; … … 1578 1359 } 1579 1360 1580 /* Note info "i" modal (nfebr-note-info.js). Doubled specificity is 1581 intentional — same reason as .sbnfebr-itemaction-modal/ 1582 .sbnfebr-review-modal above. */ 1361 /* Note info "i" modal (nfebr-note-info.js). */ 1583 1362 .sbnfebr-danger-modal.sbnfebr-noteinfo-modal { 1584 1363 width: 480px; … … 1634 1413 border-bottom: 1px solid #f1f5f9; 1635 1414 } 1636 /* Supplementary info — free text from the supplier, can be long, 1637 wraps normally. */ 1415 1638 1416 .sbnfebr-noteinfo-freetext { 1639 1417 white-space: pre-wrap; … … 1653 1431 .sb-suite-tab--active { background: #eff6ff; color: #1d4ed8; cursor: default; } 1654 1432 .sb-suite-tab--active:hover { background: #eff6ff; color: #1d4ed8; } 1433 1434 .sbnfebr-workflow-tabs { 1435 display: flex; 1436 align-items: stretch; 1437 gap: 0; 1438 margin: 8px 0 10px; 1439 border-bottom: 1px solid #d8dee8; 1440 } 1441 .sbnfebr-workflow-tab { 1442 display: inline-flex; 1443 align-items: center; 1444 gap: 7px; 1445 min-height: 38px; 1446 padding: 0 18px; 1447 border: 0; 1448 border-bottom: 3px solid transparent; 1449 background: transparent; 1450 color: #526071; 1451 font-size: 13px; 1452 font-weight: 650; 1453 cursor: pointer; 1454 } 1455 .sbnfebr-workflow-tab:hover { color: #1d4ed8; background: #f7f9fc; } 1456 .sbnfebr-workflow-tab.is-active { color: #1d4ed8; border-bottom-color: #2563eb; background: #eff6ff; } 1457 .sbnfebr-workflow-tab__index { 1458 display: inline-grid; 1459 place-items: center; 1460 width: 20px; 1461 height: 20px; 1462 border-radius: 50%; 1463 background: #dfe6ef; 1464 font-size: 11px; 1465 } 1466 .sbnfebr-workflow-tab.is-active .sbnfebr-workflow-tab__index { color: #fff; background: #2563eb; } 1467 .sbnfebr-area--catalog .sbnfebr-row2, 1468 .sbnfebr-area--catalog .sbnfebr-stats, 1469 .sbnfebr-area--catalog #sbnfebr-grid-wrap { display: none !important; } 1470 @media (max-width: 720px) { 1471 .sbnfebr-area--catalog #sbnfebr-btn-upload { display: none; } 1472 } 1473 .sbnfebr-catalog-area { min-height: 280px; } 1474 .sbnfebr-catalog-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; padding: 10px 12px; border: 1px solid #d8dee8; border-radius: 7px; background: #f8fafc; } 1475 .sbnfebr-catalog-head strong, 1476 .sbnfebr-catalog-head span { display: block; } 1477 .sbnfebr-catalog-head span { margin-top: 2px; color: #64748b; font-size: 12px; } 1478 .sbnfebr-catalog-head__controls { display: flex; align-items: center; gap: 8px; min-width: 0; } 1479 .sbnfebr-catalog-views { display: flex; padding: 3px; border: 1px solid #d8dee8; border-radius: 6px; background: #fff; } 1480 .sbnfebr-catalog-views button { min-height: 30px; padding: 0 9px; border: 0; border-radius: 4px; background: transparent; color: #526071; font-size: 11px; font-weight: 700; cursor: pointer; } 1481 .sbnfebr-catalog-views button.is-active { color: #1d4ed8; background: #dbeafe; } 1482 .sbnfebr-catalog-filters { display: flex; gap: 4px; padding: 3px; border: 1px solid #d8dee8; border-radius: 6px; background: #fff; } 1483 .sbnfebr-catalog-filter { min-height: 30px; padding: 0 11px; border: 0; border-radius: 4px; background: transparent; color: #526071; font-size: 11px; font-weight: 700; cursor: pointer; } 1484 .sbnfebr-catalog-filter:hover { color: #1d4ed8; background: #f1f5f9; } 1485 .sbnfebr-catalog-filter.is-active { color: #1d4ed8; background: #dbeafe; } 1486 .sbnfebr-label-mobile { display: none !important; } 1487 .sbnfebr-workflow-panel { min-height: 280px; background: #fff; border: 1px solid #d8dee8; border-radius: 7px; overflow: hidden; } 1488 .sbnfebr-workflow-toolbar { display: flex; justify-content: space-between; align-items: center; gap: 12px; min-height: 48px; padding: 8px 12px; border-bottom: 1px solid #d8dee8; background: #f8fafc; } 1489 .sbnfebr-workflow-toolbar strong, 1490 .sbnfebr-workflow-toolbar span { display: block; } 1491 .sbnfebr-workflow-toolbar span { margin-top: 2px; color: #64748b; font-size: 12px; } 1492 .sbnfebr-workflow-toolbar__actions { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; } 1493 .sbnfebr-workflow-filters { display: flex; gap: 6px; } 1494 .sbnfebr-workflow-filters input, 1495 .sbnfebr-workflow-filters select { min-height: 32px; max-width: 210px; } 1496 .sbnfebr-workflow-tablewrap { width: 100%; overflow: auto; } 1497 .sbnfebr-workflow-grid { width: 100%; min-width: 1120px; border-collapse: collapse; table-layout: fixed; } 1498 .sbnfebr-workflow-grid th { position: sticky; top: 0; z-index: 1; padding: 8px 9px; border-bottom: 1px solid #d8dee8; background: #f4f6f8; color: #475569; font-size: 11px; text-align: left; text-transform: uppercase; letter-spacing: .025em; } 1499 .sbnfebr-workflow-grid td { min-width: 0; overflow: hidden; padding: 8px 9px; border-bottom: 1px solid #e8ecf1; color: #273444; font-size: 12px; text-overflow: ellipsis; vertical-align: middle; } 1500 .sbnfebr-workflow-grid tbody tr:hover { background: #f8fbff; } 1501 .sbnfebr-workflow-grid th:first-child, 1502 .sbnfebr-workflow-grid td:first-child { text-align: left; } 1503 .sbnfebr-wcol-action { width: var(--sbnfebr-workflow-action-column-width); } 1504 .sbnfebr-wcol-product { width: auto; } 1505 .sbnfebr-wcol-gtin { width: var(--sbnfebr-workflow-col-gtin); } 1506 .sbnfebr-wcol-cost { width: 78px; } 1507 .sbnfebr-wcol-ncm { width: var(--sbnfebr-workflow-col-ncm); } 1508 .sbnfebr-wcol-cest { width: var(--sbnfebr-workflow-col-cest); } 1509 .sbnfebr-wcol-csosn, 1510 .sbnfebr-wcol-cfop { width: var(--sbnfebr-workflow-col-tax); } 1511 .sbnfebr-wcol-regime { width: var(--sbnfebr-workflow-col-regime); } 1512 .sbnfebr-wcol-status { width: var(--sbnfebr-workflow-col-status); } 1513 .sbnfebr-wcol-product-id { width: 130px; } 1514 .sbnfebr-wcol-result { width: 126px; } 1515 .sbnfebr-wcol-attempts { width: 92px; } 1516 .sbnfebr-wcol-activity { width: 150px; } 1517 .sbnfebr-workflow-product { min-width: 0; overflow: hidden; } 1518 .sbnfebr-workflow-product strong, 1519 .sbnfebr-workflow-product small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } 1520 .sbnfebr-workflow-product small { margin-top: 2px; color: #718096; font-size: 10px; } 1521 .sbnfebr-workflow-sync-grid { min-width: 940px; } 1522 .sbnfebr-workflow-sync-grid th:nth-child(2) { width: 26%; } 1523 .sbnfebr-workflow-sync-grid td:nth-child(7) small { display: block; margin-top: 2px; color: #64748b; font-size: 9px; } 1524 .sbnfebr-sync-attempts { font-size: 13px; } 1525 .sbnfebr-workflow-action, 1526 .sbnfebr-workflow-review-btn { display: inline-grid; place-items: center; width: 28px; height: 26px; padding: 0; border: 1px solid #cbd5e1; border-radius: 5px; background: #fff; color: #334155; text-decoration: none; font-weight: 700; cursor: pointer; } 1527 .sbnfebr-workflow-action { display: inline-flex; align-items: center; justify-content: center; gap: 5px; min-width: 80px; height: 28px; padding: 0 8px; border: 1px solid #93c5fd; border-radius: 5px; background: #eff6ff; color: #1d4ed8; text-decoration: none; font-size: 11px; font-style: normal; font-weight: 700; cursor: pointer; } 1528 .sbnfebr-workflow-action em { font-style: normal; } 1529 .sbnfebr-workflow-action.is-resolve { border-color: #fca5a5; background: #fef2f2; color: #b91c1c; } 1530 .sbnfebr-workflow-action.is-done { border-color: #86efac; background: #f0fdf4; color: #15803d; } 1531 .sbnfebr-workflow-review-btn { margin: 0 1px; } 1532 .sbnfebr-workflow-review-btn.is-sent { color: #15803d; border-color: #86efac; background: #f0fdf4; } 1533 .sbnfebr-workflow-review-btn.is-checked { color: #0369a1; border-color: #7dd3fc; background: #f0f9ff; } 1534 .sbnfebr-workflow-review-btn.is-warning { color: #a16207; border-color: #fcd34d; background: #fffbeb; } 1535 .sbnfebr-workflow-review-btn.is-error { color: #b91c1c; border-color: #fca5a5; background: #fef2f2; } 1536 .sbnfebr-workflow-review-btn.is-approved { color: #15803d; border-color: #4ade80; background: #dcfce7; } 1537 .sbnfebr-workflow-review-btn.is-synced { color: #166534; border-color: #22c55e; background: #bbf7d0; } 1538 .sbnfebr-workflow-action:hover, 1539 .sbnfebr-workflow-review-btn:hover { border-color: #2563eb; color: #1d4ed8; background: #eff6ff; } 1540 .sbnfebr-workflow-review-btn:disabled { cursor: default; } 1541 .sbnfebr-workflow-badge { display: inline-flex; align-items: center; box-sizing: border-box; width: fit-content; min-width: 0; max-width: var(--sbnfebr-workflow-badge-max-width); height: var(--sbnfebr-workflow-badge-height); padding: 0 var(--sbnfebr-workflow-badge-pad-x); overflow: hidden; border-radius: 999px; font-size: var(--sbnfebr-workflow-badge-font-size); font-weight: 700; line-height: 1; text-overflow: ellipsis; white-space: nowrap; } 1542 .sbnfebr-workflow-badge.is-approved { color: #166534; background: #dcfce7; } 1543 .sbnfebr-workflow-badge.is-stale { color: #9a3412; background: #ffedd5; } 1544 .sbnfebr-workflow-badge.is-pending { color: #92400e; background: #fef3c7; } 1545 .sbnfebr-workflow-badge.is-error { color: #991b1b; background: #fee2e2; } 1546 .sbnfebr-workflow-badge.is-warning { color: #92400e; background: #fef3c7; } 1547 .sbnfebr-workflow-badge.is-checked { color: #166534; background: #dcfce7; } 1548 .sbnfebr-workflow-badge.is-linked { color: #166534; background: #dcfce7; } 1549 .sbnfebr-workflow-badge.is-match { color: #1d4ed8; background: #dbeafe; } 1550 .sbnfebr-workflow-badge.is-new { color: #475569; background: #e2e8f0; } 1551 .sbnfebr-workflow-status { display: flex; align-items: flex-start; flex-direction: column; justify-content: center; min-width: 0; max-width: 100%; height: 30px; overflow: hidden; } 1552 .sbnfebr-workflow-status small { display: block; height: 10px; margin-top: 1px; overflow: hidden; color: #64748b; font-size: 9px; line-height: 10px; text-overflow: ellipsis; white-space: nowrap; } 1553 .sbnfebr-workflow-row-actions { display: flex; align-items: center; gap: 5px; width: 100%; min-width: 0; height: 30px; overflow: hidden; white-space: nowrap; } 1554 .sbnfebr-workflow-row-actions .sbnfebr-workflow-action { flex: 0 0 auto; } 1555 .sbnfebr-workflow-row-actions > input[type="checkbox"] { flex: 0 0 16px; width: 16px; height: 16px; margin: 0; } 1556 .sbnfebr-workflow-grid thead input[type="checkbox"] { width: 16px; height: 16px; margin: 0; vertical-align: middle; } 1557 .sbnfebr-workflow-group th { box-sizing: border-box; height: var(--sbnfebr-row-height); padding: 2px 0 !important; background: #eef2f7; } 1558 .sbnfebr-workflow-group button { display: flex; align-items: center; gap: 7px; width: 100%; height: 30px; min-height: 30px; padding: 0 10px; border: 0; background: transparent; color: #334155; text-align: left; cursor: pointer; } 1559 .sbnfebr-workflow-group button i { width: 12px; font-style: normal; } 1560 .sbnfebr-workflow-group button span { margin-left: auto; padding: 2px 7px; border-radius: 999px; background: #fff; color: #64748b; font-size: 10px; } 1561 .sbnfebr-workflow-match-note { display: flex; justify-content: space-between; gap: 12px; margin: 12px 0 4px; padding: 9px 11px; border: 1px solid #bfdbfe; border-radius: 6px; background: #eff6ff; color: #1e3a8a; } 1562 .sbnfebr-workflow-match-note span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } 1563 .sbnfebr-workflow-sync-error { margin: 10px 0; padding: 9px 11px; border: 1px solid #fca5a5; border-radius: 6px; background: #fef2f2; color: #991b1b; } 1564 .sbnfebr-workflow-sync-error strong, 1565 .sbnfebr-workflow-sync-error span, 1566 .sbnfebr-workflow-sync-error small { display: block; } 1567 .sbnfebr-workflow-sync-error span { margin-top: 3px; overflow-wrap: anywhere; } 1568 .sbnfebr-workflow-sync-error small { margin-top: 4px; color: #7f1d1d; } 1569 .sbnfebr-sync-summary { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; margin: 12px 0; } 1570 .sbnfebr-sync-summary > div { min-width: 0; padding: 10px; border: 1px solid #d8dee8; border-radius: 6px; background: #f8fafc; } 1571 .sbnfebr-sync-summary span, 1572 .sbnfebr-sync-summary strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } 1573 .sbnfebr-sync-summary span { margin-bottom: 3px; color: #64748b; font-size: 10px; } 1574 .sbnfebr-workflow-empty { padding: 60px 20px; color: #64748b; text-align: center; } 1575 .sbnfebr-workflow-pager { display: flex; align-items: center; justify-content: flex-end; gap: 8px; padding: 8px 12px; border-top: 1px solid #e5e7eb; background: #f8fafc; } 1576 .sbnfebr-workflow-pager span { min-width: 150px; color: #64748b; font-size: 11px; text-align: center; } 1577 .sbnfebr-danger-modal.sbnfebr-workflow-modal { width: min(680px, calc(100vw - 32px)); max-width: none; max-height: calc(100vh - 32px); overflow-x: hidden; overflow-y: auto; } 1578 .sbnfebr-workflow-modal .sbnfebr-itemaction-header { position: sticky; top: -20px; z-index: 4; margin: -20px -20px 12px; padding: 16px 20px 12px; border-bottom: 1px solid #e5e7eb; background: #fff; } 1579 .sbnfebr-workflow-modal .sbnfebr-danger-actions { position: sticky; bottom: -20px; z-index: 4; margin: 12px -20px -20px; padding: 12px 20px 16px; border-top: 1px solid #e5e7eb; background: #fff; } 1580 .sbnfebr-workflow-form { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; margin: 16px 0; } 1581 .sbnfebr-workflow-identity { display: grid; grid-template-columns: minmax(180px, 260px) 1fr; align-items: end; gap: 10px; margin: 14px 0 0; padding: 10px; border: 1px solid #d8dee8; border-radius: 6px; background: #f8fafc; } 1582 .sbnfebr-workflow-identity label span { display: block; margin-bottom: 4px; color: #526071; font-size: 11px; font-weight: 650; } 1583 .sbnfebr-workflow-identity input { width: 100%; min-height: 34px; } 1584 .sbnfebr-workflow-identity > small { align-self: center; color: #64748b; } 1585 .sbnfebr-cest-decision { margin: -6px 0 14px; padding: 9px 10px; border: 1px solid #d8dee8; border-radius: 6px; background: #f8fafc; } 1586 .sbnfebr-cest-decision label { display: flex; align-items: flex-start; gap: 7px; cursor: pointer; } 1587 .sbnfebr-cest-decision label span, 1588 .sbnfebr-cest-decision label strong, 1589 .sbnfebr-cest-decision label small { display: block; } 1590 .sbnfebr-cest-decision label small { margin-top: 2px; color: #64748b; font-size: 10px; } 1591 .sbnfebr-cest-decision.is-resolved { border-color: #86efac; background: #f0fdf4; } 1592 .sbnfebr-cest-decision-status:not(:empty) { margin-top: 8px; padding-top: 8px; border-top: 1px solid #d8dee8; } 1593 .sbnfebr-cest-decision-status strong, 1594 .sbnfebr-cest-decision-status span, 1595 .sbnfebr-cest-decision-status small { display: block; } 1596 .sbnfebr-cest-decision-status strong { color: #166534; font-size: 11px; } 1597 .sbnfebr-cest-decision-status span { margin-top: 3px; color: #334155; font-size: 10px; } 1598 .sbnfebr-cest-decision-status small { margin-top: 3px; color: #64748b; font-size: 9px; } 1599 .sbnfebr-workflow-form label span, 1600 .sbnfebr-workflow-regime span { display: block; margin-bottom: 4px; color: #526071; font-size: 11px; font-weight: 650; } 1601 .sbnfebr-field-source { display: inline-flex; align-items: center; min-height: 17px; margin-left: 6px; padding: 1px 5px; border: 1px solid #cbd5e1; border-radius: 999px; background: #f8fafc; color: #475569; font-size: 9px; font-style: normal; font-weight: 650; line-height: 1; vertical-align: middle; } 1602 .sbnfebr-workflow-history { margin: 12px 0; border: 1px solid #d8dee8; border-radius: 6px; background: #f8fafc; } 1603 .sbnfebr-workflow-history summary { padding: 9px 11px; color: #334155; font-size: 11px; font-weight: 700; cursor: pointer; } 1604 .sbnfebr-workflow-history > div { max-height: 180px; padding: 0 11px 10px; overflow: auto; color: #64748b; font-size: 11px; } 1605 .sbnfebr-workflow-history ol { margin: 0; padding-left: 20px; } 1606 .sbnfebr-workflow-history li { padding: 6px 0; border-top: 1px solid #e2e8f0; } 1607 .sbnfebr-workflow-history li strong, 1608 .sbnfebr-workflow-history li span { display: block; } 1609 .sbnfebr-workflow-history li span { margin-top: 2px; color: #64748b; font-size: 10px; } 1610 .sbnfebr-workflow-comparison { margin: 12px 0; border: 1px solid #fdba74; border-radius: 6px; background: #fff7ed; } 1611 .sbnfebr-workflow-comparison summary { padding: 9px 11px; color: #9a3412; font-size: 11px; font-weight: 700; cursor: pointer; } 1612 .sbnfebr-workflow-comparison > div { padding: 0 10px 10px; } 1613 .sbnfebr-workflow-comparison p { margin: 0; color: #64748b; font-size: 11px; } 1614 .sbnfebr-workflow-comparison-scroll { overflow-x: auto; } 1615 .sbnfebr-workflow-comparison table { width: 100%; min-width: 510px; border-collapse: collapse; background: #fff; font-size: 10px; } 1616 .sbnfebr-workflow-comparison th, 1617 .sbnfebr-workflow-comparison td { padding: 6px 7px; border: 1px solid #fed7aa; text-align: left; } 1618 .sbnfebr-workflow-comparison thead th { background: #ffedd5; color: #7c2d12; } 1619 .sbnfebr-workflow-write-plan { margin: 12px 0; border: 1px solid #93c5fd; border-radius: 6px; background: #eff6ff; } 1620 .sbnfebr-workflow-write-plan summary { padding: 9px 11px; color: #1e40af; font-size: 11px; font-weight: 700; cursor: pointer; } 1621 .sbnfebr-workflow-write-plan > div { padding: 0 10px 10px; } 1622 .sbnfebr-write-plan-target { display: flex; justify-content: space-between; gap: 10px; padding: 8px; border: 1px solid #bfdbfe; border-radius: 5px; background: #fff; } 1623 .sbnfebr-write-plan-target strong, 1624 .sbnfebr-write-plan-target span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } 1625 .sbnfebr-write-plan-target span { color: #64748b; font-size: 10px; } 1626 .sbnfebr-write-plan-operations { margin: 8px 0; padding-left: 20px; color: #334155; font-size: 10px; } 1627 .sbnfebr-write-plan-operations li { margin: 4px 0; } 1628 .sbnfebr-write-plan-operations span { color: #64748b; } 1629 .sbnfebr-write-plan-scroll { max-height: 240px; overflow: auto; background: #fff; } 1630 .sbnfebr-write-plan-scroll table { width: 100%; min-width: 600px; border-collapse: collapse; font-size: 10px; } 1631 .sbnfebr-write-plan-scroll th, 1632 .sbnfebr-write-plan-scroll td { padding: 6px 7px; border: 1px solid #dbeafe; text-align: left; } 1633 .sbnfebr-write-plan-scroll thead th { position: sticky; top: 0; background: #dbeafe; color: #1e3a8a; } 1634 .sbnfebr-workflow-form input, 1635 .sbnfebr-workflow-regime select { width: 100%; min-height: 34px; } 1636 .sbnfebr-workflow-regime { display: block; max-width: 260px; margin-bottom: 16px; } 1637 .sbnfebr-workflow-source-fiscal { display: flex; justify-content: space-between; gap: 10px; margin-top: 12px; padding: 8px 10px; border: 1px solid #d8dee8; border-radius: 6px; background: #f8fafc; font-size: 11px; } 1638 .sbnfebr-workflow-source-fiscal span { color: #64748b; } 1639 .sbnfebr-fiscal-report { margin: 12px 0; padding: 10px 12px; border: 1px solid #d8dee8; border-radius: 6px; background: #f8fafc; } 1640 .sbnfebr-fiscal-report.is-ok { border-color: #86efac; background: #f0fdf4; } 1641 .sbnfebr-ncm-search { margin: 12px 0; padding: 10px; border: 1px solid #d8dee8; border-radius: 6px; background: #fff; } 1642 .sbnfebr-ncm-search > div:first-child { display: flex; gap: 8px; } 1643 .sbnfebr-ncm-search input { flex: 1; min-width: 0; } 1644 .sbnfebr-ncm-selection { margin-top: 8px; padding: 8px 10px; border: 1px solid #86efac; border-radius: var(--sbnfebr-radius-surface, 6px); background: #f0fdf4; color: #166534; } 1645 .sbnfebr-ncm-selection > div { display: flex; align-items: center; gap: 7px; } 1646 .sbnfebr-ncm-selection > div span { display: inline-grid; place-items: center; width: 18px; height: 18px; border-radius: 50%; background: #16a34a; color: #fff; font-size: 11px; font-weight: 800; } 1647 .sbnfebr-ncm-selection > div b { margin-left: auto; font-family: ui-monospace, Consolas, monospace; font-size: 13px; } 1648 .sbnfebr-ncm-selection p { margin: 5px 0 0 25px; overflow: hidden; color: #334155; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; } 1649 .sbnfebr-ncm-selection small { display: block; margin: 4px 0 0 25px; color: #64748b; font-size: 10px; } 1650 .sbnfebr-ncm-selection.is-empty { border-color: #cbd5e1; background: #f8fafc; color: #475569; } 1651 .sbnfebr-ncm-selection.is-empty strong, 1652 .sbnfebr-ncm-selection.is-empty small { display: block; margin: 0; } 1653 .sbnfebr-ncm-selection.is-empty small { margin-top: 3px; } 1654 .sbnfebr-ncm-results { max-height: 280px; margin-top: 8px; overflow-y: auto; overscroll-behavior: contain; scrollbar-gutter: stable; } 1655 .sbnfebr-ncm-results section { margin-top: 10px; } 1656 .sbnfebr-ncm-result { display: grid; grid-template-columns: 90px minmax(0, 1fr) auto; align-items: start; width: 100%; gap: 8px; padding: 7px 8px; border: 0; border-top: 1px solid #e5e7eb; background: transparent; text-align: left; cursor: pointer; } 1657 .sbnfebr-ncm-result:hover { background: #f1f5f9; } 1658 .sbnfebr-ncm-result span { display: -webkit-box; overflow: hidden; color: #64748b; -webkit-box-orient: vertical; -webkit-line-clamp: 3; line-clamp: 3; } 1659 .sbnfebr-ncm-result-selected { display: none; align-items: center; min-height: 20px; padding: 0 7px; border-radius: var(--sbnfebr-radius-pill, 999px); background: #dcfce7; color: #166534; font-size: 9px; font-style: normal; font-weight: 800; white-space: nowrap; } 1660 .sbnfebr-ncm-result.is-selected { position: relative; border-top-color: #86efac; background: #f0fdf4; box-shadow: inset 3px 0 #16a34a; } 1661 .sbnfebr-ncm-result.is-selected:hover { background: #dcfce7; } 1662 .sbnfebr-ncm-result.is-selected .sbnfebr-ncm-result-selected { display: inline-flex; } 1663 .sbnfebr-ncm-table-note { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 10px; color: #64748b; } 1664 .sbnfebr-cest-options { display: grid; gap: 3px; margin-top: 10px; } 1665 .sbnfebr-cest-guidance { margin-top: 10px; padding: 9px 10px; border: 1px solid #fbbf24; border-radius: 6px; background: #fff; } 1666 .sbnfebr-cest-guidance > strong, 1667 .sbnfebr-cest-guidance p { display: block; } 1668 .sbnfebr-cest-guidance p { margin: 4px 0 0; color: #64748b; font-size: 11px; } 1669 .sbnfebr-cest-guidance.is-special { border-color: #fdba74; background: #fff7ed; } 1670 .sbnfebr-cest-guidance.is-empty { border-color: #cbd5e1; background: #f8fafc; } 1671 .sbnfebr-guided-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; margin-top: 8px; } 1672 .sbnfebr-guided-actions small { color: #166534; font-size: 10px; } 1673 .sbnfebr-guided-actions .sbnfebr-btn.is-applied { border-color: #86efac; background: #dcfce7; color: #166534; } 1674 .sbnfebr-cest-special-review { margin-top: 8px; border-top: 1px solid #fed7aa; } 1675 .sbnfebr-cest-special-review summary { padding: 8px 0 0; color: #9a3412; font-size: 11px; font-weight: 700; cursor: pointer; } 1676 .sbnfebr-cest-special-review .sbnfebr-cest-options { margin-top: 8px; } 1677 .sbnfebr-sefaz-cest-note { display: block; margin-top: 6px; color: #7c2d12; line-height: 1.4; } 1678 .sbnfebr-sefaz-box { margin: 12px 0; padding: 11px; border: 1px solid #f0c36a; border-radius: 7px; background: #fffbeb; } 1679 .sbnfebr-sefaz-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; } 1680 .sbnfebr-sefaz-head strong, 1681 .sbnfebr-sefaz-head span, 1682 .sbnfebr-sefaz-cert strong, 1683 .sbnfebr-sefaz-cert span, 1684 .sbnfebr-sefaz-result strong, 1685 .sbnfebr-sefaz-result span { display: block; } 1686 .sbnfebr-sefaz-head span, 1687 .sbnfebr-sefaz-cert span, 1688 .sbnfebr-sefaz-result span { margin-top: 3px; color: #64748b; font-size: 11px; } 1689 .sbnfebr-sefaz-cert, 1690 .sbnfebr-sefaz-result { margin-top: 9px; padding-top: 9px; border-top: 1px solid #fde68a; } 1691 .sbnfebr-sefaz-box .sbnfebr-workflow-identity { grid-template-columns: minmax(180px, 260px) 1fr; margin: 9px 0 0; border-color: #fde68a; background: #fff; } 1692 .sbnfebr-sefaz-upload { display: grid; grid-template-columns: 1fr 1fr auto; gap: 6px; margin-top: 8px; } 1693 .sbnfebr-sefaz-result .sbnfebr-btn { margin-top: 8px; } 1694 @media (max-width: 420px) { 1695 .sbnfebr-sefaz-head { align-items: stretch; flex-direction: column; } 1696 .sbnfebr-sefaz-upload { grid-template-columns: 1fr; } 1697 .sbnfebr-sefaz-box .sbnfebr-workflow-identity { grid-template-columns: 1fr; } 1698 } 1699 @media (max-width: 420px) { 1700 .sbnfebr-danger-backdrop { align-items: stretch; padding: 8px; } 1701 .sbnfebr-danger-modal.sbnfebr-workflow-modal { width: 100%; max-height: calc(100vh - 16px); padding: 14px; } 1702 .sbnfebr-workflow-modal .sbnfebr-itemaction-header { top: -14px; margin: -14px -14px 10px; padding: 12px 14px 10px; } 1703 .sbnfebr-workflow-modal .sbnfebr-danger-actions { bottom: -14px; margin: 10px -14px -14px; padding: 10px 14px 12px; } 1704 .sbnfebr-ncm-search > div:first-child { flex-direction: column; } 1705 .sbnfebr-ncm-selection p, 1706 .sbnfebr-ncm-selection small { margin-left: 0; } 1707 .sbnfebr-ncm-result { grid-template-columns: minmax(0, 1fr) auto; } 1708 .sbnfebr-ncm-result span { grid-column: 1 / -1; } 1709 .sbnfebr-ncm-results { max-height: 220px; } 1710 } 1711 .sbnfebr-fiscal-report.is-warning { border-color: #fcd34d; background: #fffbeb; } 1712 .sbnfebr-fiscal-report.is-error { border-color: #fca5a5; background: #fef2f2; } 1713 .sbnfebr-fiscal-report ul { margin: 8px 0 0 18px; } 1714 .sbnfebr-fiscal-report li { margin: 5px 0; } 1715 .sbnfebr-fiscal-report li strong, 1716 .sbnfebr-fiscal-report li span { display: block; } 1717 .sbnfebr-fiscal-report li span { color: #64748b; font-size: 11px; } 1718 1719 @media (max-width: 1200px) { 1720 .sbnfebr-grid .sbnfebr-col-discount_value, 1721 .sbnfebr-grid .sbnfebr-col-icms_base, 1722 .sbnfebr-grid .sbnfebr-col-icms_value, 1723 .sbnfebr-grid .sbnfebr-col-icms_st_base, 1724 .sbnfebr-grid .sbnfebr-col-icms_st_value, 1725 .sbnfebr-grid .sbnfebr-col-ipi_value, 1726 .sbnfebr-grid .sbnfebr-col-icms_rate, 1727 .sbnfebr-grid .sbnfebr-col-ipi_rate { display: none; } 1728 } 1729 @media (max-width: 720px) { 1730 #sbnfebr-wrap { 1731 height: auto; 1732 min-height: calc(100vh - var(--sb-adminbar)); 1733 overflow: visible; 1734 } 1735 #sbnfebr-wrap > .sbnfebr-tablewrap { 1736 flex: 0 0 auto; 1737 min-height: var(--sbnfebr-mobile-list-min-height); 1738 max-height: none; 1739 overflow-x: auto; 1740 overflow-y: visible; 1741 } 1742 .sbnfebr-mobile-drawer-toggle { 1743 box-sizing: border-box; 1744 display: flex; 1745 align-items: center; 1746 justify-content: space-between; 1747 gap: var(--sbnfebr-mobile-drawer-gap); 1748 width: 100%; 1749 height: var(--sbnfebr-control-height); 1750 margin-bottom: var(--sbnfebr-section-gap); 1751 padding: 0 var(--sbnfebr-control-pad-x); 1752 border: 1px solid var(--sbnfebr-border); 1753 border-radius: var(--sbnfebr-radius-control); 1754 background: var(--sbnfebr-surface); 1755 color: var(--sbnfebr-text); 1756 font-size: var(--sbnfebr-font-control); 1757 font-weight: 700; 1758 cursor: pointer; 1759 } 1760 .sbnfebr-mobile-drawer-toggle i { font-style: normal; transition: transform 120ms ease; } 1761 .sbnfebr-mobile-drawer-toggle.is-open i { transform: rotate(180deg); } 1762 .sbnfebr-mobile-drawer { display: none !important; } 1763 .sbnfebr-mobile-drawer.is-open { display: block !important; } 1764 .sbnfebr-area--catalog [data-mobile-drawer-toggle="sbnfebr-entry-tools"], 1765 .sbnfebr-area--catalog #sbnfebr-entry-tools { display: none !important; } 1766 #sbnfebr-entry-tools.is-open { 1767 padding: var(--sbnfebr-mobile-drawer-padding); 1768 border: 1px solid var(--sbnfebr-border-soft); 1769 background: var(--sbnfebr-surface-soft); 1770 } 1771 .sbnfebr-workflow-toolbar__actions.sbnfebr-mobile-drawer.is-open { 1772 display: flex !important; 1773 width: 100%; 1774 padding-top: var(--sbnfebr-mobile-drawer-padding); 1775 } 1776 .sbnfebr-catalog-area, 1777 .sbnfebr-workflow-panel { min-height: 0; overflow: visible; } 1778 .sbnfebr-workflow-tablewrap { overflow-x: auto; overflow-y: visible; } 1779 .sbnfebr-catalog-head { align-items: stretch; flex-direction: column; } 1780 .sbnfebr-catalog-head__controls { align-items: stretch; flex-direction: column; } 1781 .sbnfebr-catalog-views { width: 100%; overflow-x: auto; } 1782 .sbnfebr-catalog-views button { flex: 1 0 auto; } 1783 .sbnfebr-catalog-filters { width: 100%; overflow-x: auto; } 1784 .sbnfebr-catalog-filter { flex: 1 0 auto; } 1785 .sb-library-overlay--registry { width: 100% !important; max-width: calc(100vw - 16px) !important; max-height: calc(100vh - 16px) !important; } 1786 .sbnfebr-regcheck-colheads { display: none; } 1787 .sbnfebr-regcheck-row { display: grid; grid-template-columns: 1fr; gap: 8px; min-height: 0; padding: 12px; } 1788 .sbnfebr-regcheck-divider { display: none; } 1789 .sbnfebr-regcheck-grp, 1790 .sbnfebr-regcheck-grp--wc { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px 12px; padding: 10px; border: 1px solid #e5e7eb; border-radius: 6px; align-items: start; } 1791 .sbnfebr-regcheck-grp--note { background: #f8fafc; } 1792 .sbnfebr-regcheck-grp--wc { background: #f0fdf4; } 1793 .sbnfebr-regcheck-grp > div { white-space: normal; overflow: visible; } 1794 .sbnfebr-regcheck-grp > div::before { content: attr(data-label); display: block; margin-bottom: 2px; color: #64748b; font: 700 9px/1.2 sans-serif; text-transform: uppercase; } 1795 .sbnfebr-regcheck-actions { justify-content: flex-start; flex-wrap: wrap; } 1796 .sbnfebr-workflow-tabs { overflow-x: auto; } 1797 .sbnfebr-workflow-tab { flex: 1 0 auto; justify-content: center; padding: 0 11px; } 1798 .sbnfebr-workflow-toolbar { align-items: flex-start; flex-direction: column; } 1799 .sbnfebr-workflow-toolbar__actions { width: 100%; } 1800 .sbnfebr-workflow-grid { min-width: 680px; table-layout: fixed; } 1801 #sbnfebr-workflow-review .sbnfebr-workflow-cell--cest, 1802 #sbnfebr-workflow-review .sbnfebr-workflow-cell--csosn, 1803 #sbnfebr-workflow-review .sbnfebr-workflow-cell--cfop, 1804 #sbnfebr-workflow-review .sbnfebr-workflow-cell--regime { display: none; } 1805 #sbnfebr-workflow-review .sbnfebr-wcol-cest, 1806 #sbnfebr-workflow-review .sbnfebr-wcol-csosn, 1807 #sbnfebr-workflow-review .sbnfebr-wcol-cfop, 1808 #sbnfebr-workflow-review .sbnfebr-wcol-regime { visibility: collapse; width: 0; } 1809 #sbnfebr-workflow-sync .sbnfebr-workflow-grid { min-width: 0; } 1810 #sbnfebr-workflow-sync .sbnfebr-workflow-grid th:nth-child(2), 1811 #sbnfebr-workflow-sync .sbnfebr-workflow-grid td:nth-child(2) { width: 34%; } 1812 #sbnfebr-workflow-sync .sbnfebr-workflow-grid th:nth-child(4), 1813 #sbnfebr-workflow-sync .sbnfebr-workflow-grid td:nth-child(4), 1814 #sbnfebr-workflow-sync .sbnfebr-workflow-grid th:nth-child(5), 1815 #sbnfebr-workflow-sync .sbnfebr-workflow-grid td:nth-child(5) { display: none; } 1816 #sbnfebr-workflow-sync .sbnfebr-wcol-ncm, 1817 #sbnfebr-workflow-sync .sbnfebr-wcol-product-id { visibility: collapse; width: 0; } 1818 .sbnfebr-grid .sbnfebr-col-supplier_name, 1819 .sbnfebr-grid .sbnfebr-col-note_ref, 1820 .sbnfebr-grid .sbnfebr-col-product_code, 1821 .sbnfebr-grid .sbnfebr-col-cest, 1822 .sbnfebr-grid .sbnfebr-col-cst_csosn, 1823 .sbnfebr-grid .sbnfebr-col-cfop, 1824 .sbnfebr-grid .sbnfebr-col-unit, 1825 .sbnfebr-grid .sbnfebr-col-total_value { display: none; } 1826 .sbnfebr-workflow-form { grid-template-columns: repeat(2, minmax(0, 1fr)); } 1827 } 1828 @media (max-width: 420px) { 1829 .sbnfebr-regcheck-grp, 1830 .sbnfebr-regcheck-grp--wc { grid-template-columns: 1fr; } 1831 .sbnfebr-workflow-tab { gap: 4px; padding: 0 8px; font-size: 12px; } 1832 .sbnfebr-workflow-tab__index { width: 18px; height: 18px; } 1833 .sbnfebr-workflow-toolbar__actions { width: 100%; } 1834 .sbnfebr-workflow-filters { width: 100%; } 1835 .sbnfebr-workflow-filters { flex-direction: column; } 1836 .sbnfebr-workflow-filters input, 1837 .sbnfebr-workflow-filters select { flex: 1; width: 100%; max-width: none; min-width: 0; } 1838 .sbnfebr-workflow-grid { min-width: 0; table-layout: fixed; } 1839 #sbnfebr-workflow-review th:nth-child(2), 1840 #sbnfebr-workflow-review .sbnfebr-workflow-cell--status, 1841 #sbnfebr-workflow-review th:nth-child(n+5), 1842 #sbnfebr-workflow-review .sbnfebr-workflow-cell--ncm, 1843 #sbnfebr-workflow-review .sbnfebr-workflow-cell--cest, 1844 #sbnfebr-workflow-review .sbnfebr-workflow-cell--csosn, 1845 #sbnfebr-workflow-review .sbnfebr-workflow-cell--cfop, 1846 #sbnfebr-workflow-review .sbnfebr-workflow-cell--regime, 1847 #sbnfebr-workflow-sync .sbnfebr-workflow-grid th:nth-child(n+4), 1848 #sbnfebr-workflow-sync .sbnfebr-workflow-grid td:nth-child(n+4) { display: none !important; } 1849 #sbnfebr-workflow-review .sbnfebr-wcol-ncm, 1850 #sbnfebr-workflow-review .sbnfebr-wcol-cest, 1851 #sbnfebr-workflow-review .sbnfebr-wcol-csosn, 1852 #sbnfebr-workflow-review .sbnfebr-wcol-cfop, 1853 #sbnfebr-workflow-review .sbnfebr-wcol-regime, 1854 #sbnfebr-workflow-review .sbnfebr-wcol-status, 1855 #sbnfebr-workflow-sync col:nth-child(n+4) { visibility: collapse; width: 0; } 1856 .sbnfebr-workflow-grid th:first-child, 1857 .sbnfebr-workflow-grid td:first-child { width: var(--sbnfebr-workflow-action-column-width); } 1858 #sbnfebr-workflow-review .sbnfebr-workflow-grid th:nth-child(3), 1859 #sbnfebr-workflow-review .sbnfebr-workflow-grid td:nth-child(3) { display: table-cell !important; width: auto !important; min-width: 112px; } 1860 #sbnfebr-workflow-review .sbnfebr-workflow-grid th:nth-child(4), 1861 #sbnfebr-workflow-review .sbnfebr-workflow-grid td:nth-child(4) { width: var(--sbnfebr-workflow-col-gtin) !important; font-size: 11px; } 1862 #sbnfebr-workflow-sync .sbnfebr-workflow-grid th:nth-child(2), 1863 #sbnfebr-workflow-sync .sbnfebr-workflow-grid td:nth-child(2) { display: table-cell !important; width: auto !important; min-width: 112px; } 1864 #sbnfebr-workflow-sync .sbnfebr-workflow-grid th:nth-child(3), 1865 #sbnfebr-workflow-sync .sbnfebr-workflow-grid td:nth-child(3) { width: var(--sbnfebr-workflow-col-gtin) !important; } 1866 .sbnfebr-workflow-action em { display: none; } 1867 .sbnfebr-workflow-row-actions { gap: 4px; } 1868 .sbnfebr-label-wide { display: none !important; } 1869 .sbnfebr-label-mobile { display: inline !important; } 1870 .sbnfebr-sync-summary { grid-template-columns: 1fr; } 1871 .sbnfebr-workflow-identity { grid-template-columns: 1fr; } 1872 .sbnfebr-workflow-pager { justify-content: center; } 1873 .sbnfebr-grid .sbnfebr-col-ncm, 1874 .sbnfebr-grid .sbnfebr-col-quantity, 1875 .sbnfebr-grid .sbnfebr-col-unit_value { display: none; } 1876 .sbnfebr-workflow-form { grid-template-columns: 1fr; } 1877 } -
sanbar-express-nfe-xml-import-br/trunk/assets/css/library-notes.css
r3725460 r3782421 1 /* "Manage Notes" modal — reuses the .sb-library-* skeleton 2 (backdrop/overlay/head/toolbar/body/row) from library-supplier.css, 3 adding supplier grouping, note row columns, and a destructive 4 delete sub-modal (type "DELETE" to confirm). */ 1 5 2 6 3 .sbnfebr-notes-group { … … 9 6 .sbnfebr-notes-group:last-child { border-bottom: none; } 10 7 11 /* Per-supplier accordion — header is a clickable button, body is12 collapsed by default (max-height:0), chevron rotates 90° when open. */13 8 .sbnfebr-notes-group-head { 14 9 display: flex; … … 90 85 .sbnfebr-protocol-badge--neutral { background: #e5e7eb; color: #374151; } 91 86 92 /* === Destructive sub-modal (type "DELETE" to confirm) === */93 87 .sbnfebr-danger-backdrop { 94 88 position: fixed; … … 133 127 margin: 0 0 14px; 134 128 } 135 /* Bullet list in SB.confirm() (opts.list) — same visual as the 136 "Update information" card. */ 129 137 130 .sbnfebr-danger-list { 138 131 list-style: none; … … 193 186 margin-top: 16px; 194 187 } 195 /* Regime tributário no modal de Dados da empresa — somente leitura, 196 dado real vem do NF-e PDV. Fica acima do rodapé Cancelar/Salvar. */ 188 197 189 .sbnfebr-company-regime-badge { 198 190 font-size: 12px; … … 215 207 } 216 208 217 /* === Import confirmation modal — reuses the218 .sbnfebr-danger-backdrop/.sbnfebr-danger-modal/.sbnfebr-danger-actions219 skeleton from the destructive modal, without the red top border220 since this action isn't destructive. === */221 209 .sbnfebr-import-modal { 222 210 border-top: 4px solid #3b82f6; … … 279 267 } 280 268 281 /* === "Configure" modal — same skeleton as the danger modal, without282 the red border. Sections (.sbnfebr-configure-section) let the modal283 grow with more option groups beyond "Company data". === */284 269 .sbnfebr-configure-modal { 285 270 border-top: 4px solid #3b82f6; … … 289 274 overflow-y: auto; 290 275 } 291 /* Small hub — "Configure" opens this first, one button per settings group. */ 276 292 277 .sbnfebr-configure-modal--hub { 293 278 width: 300px; … … 309 294 font-size: 13px; 310 295 } 296 .sbnfebr-license-actions { 297 display: flex; 298 flex-wrap: wrap; 299 gap: 6px; 300 margin: 8px 0 0; 301 } 302 .sbnfebr-license-actions .sbnfebr-btn { 303 text-decoration: none; 304 } 311 305 .sbnfebr-configure-hint { 312 306 font-size: 11px; … … 329 323 cursor: pointer; 330 324 } 331 /* Standalone layout rule for .sbnfebr-radio-group, not dependent on an 332 ancestor — the action popups (nfebr-item-actions.js, 333 openEstoquePopup()/openPrecoPopup()) use this class outside of 334 .sbnfebr-ia-diff-row and need the gap between options regardless. */ 325 335 326 .sbnfebr-radio-group { 336 327 display: flex; … … 359 350 } 360 351 361 /* .sbnfebr-ia-diff-loading is still used by the manual link search362 (openManualLinkPopup() in nfebr-item-actions.js). */363 352 .sbnfebr-ia-diff-loading { 364 353 font-size: 12px; … … 367 356 } 368 357 369 /* Draft+ row with the manual link button alongside it, in Plus. */370 358 .sbnfebr-ia-draft-row { 371 359 display: flex; … … 432 420 font-size: 11px; 433 421 } 434 /* Separates the manual link from the rest of the Draft block so it 435 doesn't read as part of the same group — larger margin plus a 436 subtle divider line. */ 422 437 423 .sbnfebr-ia-manual-link-toggle--spaced { 438 424 display: block; … … 442 428 } 443 429 444 /* "Already in use by another item" — visible before selection. */445 430 .sbnfebr-ia-manual-link-item--inuse { 446 431 border-color: #fde68a; … … 491 476 } 492 477 493 /* === Error log popup — reuses .sb-library-* for the skeleton === */494 478 .sbnfebr-errorlog-overlay { width: 640px; height: 70vh; } 495 479 .sbnfebr-errorlog-toolbar { -
sanbar-express-nfe-xml-import-br/trunk/assets/css/library-supplier.css
r3725460 r3782421 1 /* Supplier Library modal — mirrors the .sb-library-* classes from 2 SanBar EXPress Sheet's supplier modal, since this plugin writes to 3 the same taxonomy (sbs_supplier) and should present the same UI. */ 1 4 2 5 3 .sb-library-overlay-backdrop { … … 170 168 .sb-library-filter:hover { background: #eef2ff !important; color: #4338ca; } 171 169 172 /* Suppliers Library groups: active note / registered-with-catalog / bare. */173 170 .sb-library-section-head { 174 171 padding: 8px 12px 4px; … … 214 211 } 215 212 .sb-library-sup-field--wide { grid-column: 1 / -1; } 216 /* Nickname field — "Show nickname" checkbox and input on the same row. 217 The field keeps the standard label+content column layout with an 218 empty ( ) label so it inherits the same label+gap height as the 219 State field and stays vertically aligned with it. The checkbox+input 220 row itself lives in .sb-library-sup-nickname-row. */ 213 221 214 .sb-library-sup-nickname-row { 222 215 display: flex; … … 233 226 color: #374151; 234 227 } 235 /* :not(.sb-sup-f-nickname) excludes the nickname input, which has its 236 own fixed width defined below and would otherwise be overridden by 237 this generic width:100% rule (both use !important, so exclusion by 238 selector is needed rather than relying on specificity). */ 228 239 229 .sb-library-sup-field input:not([type="checkbox"]):not([type="radio"]):not(.sb-sup-f-nickname), 240 230 .sb-library-sup-field select, … … 247 237 width: 100% !important; 248 238 } 249 /* "Show nickname" checkbox — resets the generic field styling above 250 (width/padding/border), which would otherwise stretch it. */ 239 251 240 .sb-library-sup-field input[type="checkbox"] { 252 241 -webkit-appearance: checkbox !important; … … 306 295 } 307 296 308 /* "!" icon next to the supplier select on the main toolbar — specific309 to this plugin; the Sheet only edits suppliers from the Library. */310 297 .sbnfebr-supplier-info-btn { 311 298 all: unset; … … 337 324 .sbnfebr-supplier-info-btn--unregistered:hover { background: #fecaca; } 338 325 339 /* "i" note info icon — same skeleton as the supplier "!" icon above,340 but stateless (purely informational, never turns red/green). */341 326 .sbnfebr-note-info-btn { 342 327 all: unset; -
sanbar-express-nfe-xml-import-br/trunk/assets/css/price-history.css
r3725460 r3782421 1 /* Price history modal table (nfebr-price-history.js). */ 1 2 2 .sbnfebr-ph-table { 3 3 width: 100%; -
sanbar-express-nfe-xml-import-br/trunk/assets/css/sheet-bridge.css
r3725460 r3782421 1 /* Iframe modal injected into the Sheet screen (nfebr-sheet-bridge.js). 2 .sbnfebr-bridge-* namespace avoids colliding with Sheet's own classes. */ 1 3 2 .sbnfebr-bridge-overlay { 4 3 position: fixed; … … 26 25 display: block; 27 26 } 28 /* Standard close button style, duplicated from .sbnfebr-close-btn in 29 core.css because this screen only loads sheet-bridge.css. */ 27 30 28 .sbnfebr-bridge-close { 31 29 position: absolute; … … 49 47 } 50 48 51 /* Plus edition indicator — amber outline on the standard button, no52 text/icon change. Inset border via box-shadow, not an outer outline. */53 49 #sbnfebr-bridge-btn.sbnfebr-bridge-btn--plus { 54 50 box-shadow: inset 0 0 0 2px #f59e0b; -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-core.js
r3725460 r3782421 1 /* ================================================================2 nfebr-core.js — global namespace (window.SBNFEBR), i18n, REST API3 helper. Each module is an IIFE that exports into it.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 12 8 : function ( s ) { return s; }; 13 9 14 /**15 * Builds the final URL for a plugin REST endpoint, appending16 * querystring parameters. Separator can't be hardcoded '?' — plain17 * permalinks already put `?rest_route=` in CFG.rest_url.18 *19 * @param {string} endpoint Relative path (e.g. 'items').20 * @param {Object|URLSearchParams} [params] Querystring parameters.21 * @return {string}22 */23 10 function buildUrl( endpoint, params ) { 24 11 var base = CFG.rest_url + endpoint; … … 30 17 } 31 18 32 /** 33 * Fetch helper against the plugin's REST API (sbnfebr/v1 namespace). 34 * 35 * @param {string} endpoint Relative path (e.g. 'suppliers'). 36 * @param {Object} [params] Querystring parameters (optional). 37 * @param {Object} [opts] Extra fetch options (method, body...). 38 * @return {Promise<any>} 39 */ 19 function announceSent( endpoint, opts, data ) { 20 if ( 'POST' !== String( opts.method || '' ).toUpperCase() || 0 !== String( endpoint ).indexOf( 'workflow/' ) ) { return; } 21 var detail = { ids: [], sourceIds: [] }; 22 var item = /^workflow\/items\/(\d+)\/(send-new|sync-existing|update-\w+|transition)$/.exec( endpoint ); 23 var source = /^workflow\/source-items\/(\d+)\/review$/.exec( endpoint ); 24 if ( item ) { 25 var stage = ''; 26 try { stage = JSON.parse( opts.body || '{}' ).stage || ''; } catch ( error ) {} 27 if ( 'transition' !== item[ 2 ] || ( stage && 'entry' !== stage ) ) { detail.ids.push( Number( item[ 1 ] ) ); } 28 } else if ( source ) { 29 detail.sourceIds.push( Number( source[ 1 ] ) ); 30 } else if ( data && Array.isArray( data.workflow_ids ) ) { 31 detail.ids = data.workflow_ids.map( Number ); 32 } else if ( data && Array.isArray( data.applied ) ) { 33 detail.ids = data.applied.map( function ( row ) { return Number( row.workflow_id ); } ).filter( Boolean ); 34 } 35 if ( detail.ids.length || detail.sourceIds.length ) { 36 document.dispatchEvent( new CustomEvent( 'sbnfebr:workflow-sent', { detail: detail } ) ); 37 } 38 } 39 40 40 function api( endpoint, params, opts ) { 41 41 opts = opts || {}; 42 var headers = Object.assign( 43 { 'Content-Type': 'application/json', 'X-WP-Nonce': CFG.rest_nonce },44 opts.headers || {}45 );42 var headers = Object.assign( { 'X-WP-Nonce': CFG.rest_nonce }, opts.headers || {} ); 43 if ( ! ( opts.body instanceof FormData ) ) { 44 headers['Content-Type'] = 'application/json'; 45 } 46 46 return fetch( buildUrl( endpoint, params ), Object.assign( {}, opts, { headers: headers } ) ) 47 47 .then( function ( res ) { … … 51 51 // Preserves WP_Error's code/data — some endpoints 52 52 // (e.g. /link, /price-source) send an extra payload 53 // in `data.conflict` the UI needs beyond the message.54 53 err.code = body.code || null; 55 54 err.data = body.data || null; … … 57 56 } ); 58 57 } 59 return res.json(); 58 return res.json().then( function ( data ) { 59 announceSent( endpoint, opts, data ); 60 return data; 61 } ); 60 62 } ); 61 63 } 62 64 63 /**64 * Basic escaping for safe text insertion into innerHTML.65 *66 * @param {*} s Value to escape.67 * @return {string}68 */69 65 function esc( s ) { 70 66 var div = document.createElement( 'div' ); … … 73 69 } 74 70 75 /**76 * Formats a 'YYYY-MM-DD...' date (as returned by the DB/REST) into77 * Brazilian dd/mm/yyyy. Empty/unrecognized input is returned as-is.78 *79 * @param {string} isoDate Date in 'YYYY-MM-DD' format (optionally with time).80 * @return {string}81 */82 71 function formatDateBR( isoDate ) { 83 72 var m = /^(\d{4})-(\d{2})-(\d{2})/.exec( String( isoDate || '' ) ); … … 85 74 } 86 75 87 /**88 * Plugin's standard confirmation modal — replaces window.confirm()89 * for destructive/important actions.90 *91 * @param {string} message Question text.92 * @param {Object} [opts] { title, confirmLabel, danger, list, checkbox, out } —93 * danger:true colors the confirm button red;94 * list (string[], optional) renders bullets95 * below the message.96 * checkbox { label, checked } (optional) —97 * when present, `out` (a mutable object98 * passed by the caller) receives99 * `out.checked` BEFORE the Promise resolves;100 * the Promise itself still resolves only101 * `true`/`false` (compatible with callers102 * using `SB.confirm` without a checkbox).103 * extraHtml (string, optional) — free HTML104 * inserted before the actions, for content105 * checkbox/list can't express (e.g. radios).106 * readExtra(rootEl) (optional) runs BEFORE107 * resolving with `true`, populating `out` —108 * same contract as the checkbox.109 * @return {Promise<boolean>}110 */111 76 function confirmDialog( message, opts ) { 112 77 opts = opts || {}; … … 164 129 } 165 130 166 /**167 * Standardized alert card — title ("what happened") separate from an168 * optional detail ("why"). Color is the only severity signal.169 *170 * @param {string} variant 'danger'|'warn'|'info'|'good'.171 * @param {string} icon Emoji, literal (not escaped — caller provides it as-is).172 * @param {string} title Title HTML — caller must escape dynamic parts.173 * @param {string} [detail] Technical detail HTML — same, optional.174 * @return {string}175 */176 131 function alertCard( variant, icon, title, detail ) { 177 132 return '<div class="sbnfebr-alert sbnfebr-alert--' + variant + '">' + … … 179 134 ( detail ? '<div class="sbnfebr-alert-detail">' + detail + '</div>' : '' ) + 180 135 '</div>'; 136 } 137 138 function handleProductsSent( results, options ) { 139 var rows = Array.isArray( results ) ? results : [ results ]; 140 var indexes = {}; 141 var products = []; 142 rows.forEach( function ( row ) { 143 var productId = Number( row && row.product_id ); 144 if ( ! Number.isInteger( productId ) || productId <= 0 ) { 145 return; 146 } 147 var editUrl = row && row.edit_url ? String( row.edit_url ) : ''; 148 if ( Object.prototype.hasOwnProperty.call( indexes, productId ) ) { 149 if ( ! products[ indexes[ productId ] ].edit_url && editUrl ) { 150 products[ indexes[ productId ] ].edit_url = editUrl; 151 } 152 return; 153 } 154 indexes[ productId ] = products.length; 155 products.push( { product_id: productId, edit_url: editUrl } ); 156 } ); 157 158 if ( ! products.length ) { 159 return products; 160 } 161 162 var productIds = products.map( function ( product ) { return product.product_id; } ); 163 if ( window.parent !== window ) { 164 window.parent.postMessage( 165 { type: 'sbnfebr:products-created', product_ids: productIds }, 166 window.location.origin 167 ); 168 return products; 169 } 170 171 document.dispatchEvent( new CustomEvent( 'sbnfebr:products-sent', { 172 detail: { 173 products: products, 174 productIds: productIds, 175 message: options && options.message ? String( options.message ) : '' 176 } 177 } ) ); 178 return products; 179 } 180 181 function openProduct( productId, editUrl ) { 182 productId = Number( productId ) || 0; 183 if ( CFG.sm_admin_url && productId ) { 184 if ( window.parent !== window ) { 185 window.parent.postMessage( { type: 'sbnfebr:products-created', product_ids: [ productId ] }, window.location.origin ); 186 return; 187 } 188 window.open( CFG.sm_admin_url + ( -1 !== CFG.sm_admin_url.indexOf( '?' ) ? '&' : '?' ) + 'sbesfw_ids=' + productId, '_blank' ); 189 return; 190 } 191 if ( editUrl ) { window.open( editUrl, '_blank', 'noopener' ); } 192 } 193 194 function productButtons( productId, editUrl, options ) { 195 options = options || {}; 196 productId = Number( productId ) || 0; 197 var attrs = ' data-product-id="' + productId + '" data-edit-url="' + esc( editUrl || '' ) + '"'; 198 var wide = options.labels ? ' is-wide' : ''; 199 var editLabel = __( 'Abrir no editor do WooCommerce', 'sanbar-express-nfe-xml-import-br' ); 200 var sm = ''; 201 if ( CFG.sm_admin_url && options.single ) { 202 return '<button type="button" class="sbnfebr-btn sbnfebr-open-sm is-wide" data-open-sm' + attrs + ' title="' + esc( __( 'Abrir na Store Manager', 'sanbar-express-nfe-xml-import-br' ) ) + '">' + esc( options.single ) + ' ↗</button>'; 203 } 204 if ( CFG.sm_admin_url ) { 205 sm = '<button type="button" class="sbnfebr-btn sbnfebr-open-sm' + wide + '" data-open-sm' + attrs + ' title="' + esc( __( 'Abrir na Store Manager', 'sanbar-express-nfe-xml-import-br' ) ) + '">↗ ' + esc( options.labels ? __( 'Abrir na SM', 'sanbar-express-nfe-xml-import-br' ) : 'SM' ) + '</button>'; 206 } else if ( false !== options.placeholder && ! options.labels ) { 207 sm = '<span class="sbnfebr-open-sm is-empty" aria-hidden="true"></span>'; 208 } 209 if ( options.single ) { 210 return '<button type="button" class="sbnfebr-btn sbnfebr-open-editor is-wide" data-open-editor' + attrs + ' title="' + esc( editLabel ) + '" aria-label="' + esc( editLabel ) + '">' + esc( options.single ) + ' ↗</button>'; 211 } 212 return sm + '<button type="button" class="sbnfebr-btn sbnfebr-open-editor' + wide + '" data-open-editor' + attrs + ' title="' + esc( editLabel ) + '" aria-label="' + esc( editLabel ) + '">' + ( options.labels ? esc( __( 'Abrir no editor', 'sanbar-express-nfe-xml-import-br' ) ) : '↗' ) + '</button>'; 213 } 214 215 document.addEventListener( 'click', function ( event ) { 216 var target = event.target.closest ? event.target.closest( '[data-open-sm],[data-open-editor],[data-open-product]' ) : null; 217 if ( ! target ) { return; } 218 var editUrl = target.dataset.editUrl || target.getAttribute( 'href' ) || ''; 219 if ( target.hasAttribute( 'data-open-editor' ) ) { 220 if ( editUrl ) { window.open( editUrl, '_blank', 'noopener' ); } 221 } else if ( CFG.sm_admin_url || target.hasAttribute( 'data-open-sm' ) ) { 222 openProduct( target.dataset.productId, editUrl ); 223 } else { 224 return; 225 } 226 event.preventDefault(); 227 } ); 228 229 if ( window.MutationObserver && document.body ) { 230 var lockFrame = 0; 231 var lockSelector = '.sbnfebr-danger-backdrop, .sb-library-overlay-backdrop.open'; 232 var syncScrollLock = function () { 233 lockFrame = 0; 234 var open = Array.prototype.some.call( document.querySelectorAll( lockSelector ), function ( node ) { return node.getClientRects().length > 0; } ); 235 document.body.classList.toggle( 'sbnfebr-scroll-locked', open ); 236 }; 237 new MutationObserver( function () { 238 if ( ! lockFrame ) { lockFrame = window.requestAnimationFrame( syncScrollLock ); } 239 } ).observe( document.body, { childList: true, subtree: true, attributes: true, attributeFilter: [ 'class', 'style', 'hidden' ] } ); 181 240 } 182 241 … … 189 248 confirm: confirmDialog, 190 249 alertCard: alertCard, 250 handleProductsSent: handleProductsSent, 251 openProduct: openProduct, 252 productButtons: productButtons, 191 253 } ); 192 254 })(); -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-diff-card.js
r3725460 r3782421 1 /* ================================================================2 nfebr-diff-card.js — reusable "diff row" component (current value3 → new value). Rendering only, no network calls.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 13 9 var __ = SB.__; 14 10 15 /**16 * One divergent-field row with an opt-in checkbox (checked by17 * default), for batch review where each field can be accepted or18 * rejected independently.19 *20 * @param {Object} field { key, label, current, incoming } — `current`/`incoming` already formatted as strings.21 * @param {boolean} [checked=true]22 * @return {string}23 */24 11 function fieldRow( field, checked ) { 25 12 checked = false !== checked; … … 33 20 } 34 21 35 /**36 * Reads which fields are checked within a container.37 *38 * @param {HTMLElement} root39 * @return {string[]} Checked field keys.40 */41 22 function readCheckedFields( root ) { 42 23 return Array.prototype.map.call( … … 46 27 } 47 28 48 /**49 * Compact row for the source selector — one occurrence of the same50 * GTIN in another note/supplier.51 *52 * @param {Object} source { id, note_number, series, emission_date, supplier_name, supplier_cnpj, unit_value, ncm }.53 * @param {boolean} isSelected54 * @param {Object} baseline Currently active source, used to compute the price delta and the supplier/NCM-changed flag.55 * @return {string}56 */57 29 function sourceRow( source, isSelected, baseline ) { 58 30 var supplierChanged = baseline && source.supplier_cnpj !== baseline.supplier_cnpj; … … 72 44 } 73 45 74 return '<button type="button" class="sbnfebr-diffcard-source' + ( isSelected ? ' sbnfebr-diffcard-source--selected' : '' ) + '" data-source-id="' + source.id + '">' + 46 var workflowId = Number( source.workflow_id ) || 0; 47 var stage = String( source.workflow_stage || 'entry' ); 48 var action = isSelected 49 ? '✓ ' + __( 'Em uso', 'sanbar-express-nfe-xml-import-br' ) 50 : ( 'sync' === stage ? __( 'Já sincronizada', 'sanbar-express-nfe-xml-import-br' ) : ( workflowId ? __( 'Usar esta nota', 'sanbar-express-nfe-xml-import-br' ) : __( 'Indisponível', 'sanbar-express-nfe-xml-import-br' ) ) ); 51 52 return '<button type="button" class="sbnfebr-diffcard-source' + ( isSelected ? ' sbnfebr-diffcard-source--selected' : '' ) + '" data-source-id="' + source.id + '" data-workflow-id="' + workflowId + '" data-workflow-stage="' + SB.esc( stage ) + '"' + ( isSelected || ! workflowId || 'sync' === stage ? ' disabled' : '' ) + '>' + 75 53 '<span class="sbnfebr-diffcard-source-main">' + 76 54 '<span class="sbnfebr-diffcard-source-note">' + SB.esc( source.note_number + '/' + source.series + ' · ' + dateBR ) + '</span>' + … … 81 59 ( supplierChanged ? '<i class="sbnfebr-diffcard-flag sbnfebr-diffcard-flag--supplier" title="' + SB.esc( __( 'Fornecedor diferente', 'sanbar-express-nfe-xml-import-br' ) ) + '">🏬</i>' : '' ) + 82 60 ( ncmChanged ? '<i class="sbnfebr-diffcard-flag sbnfebr-diffcard-flag--ncm" title="' + SB.esc( __( 'NCM diferente', 'sanbar-express-nfe-xml-import-br' ) ) + '">⚠</i>' : '' ) + 61 '<em class="sbnfebr-diffcard-source-action">' + SB.esc( action ) + '</em>' + 83 62 '</span>' + 84 63 '</button>'; -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-error-log.js
r3725460 r3782421 1 /* ================================================================2 nfebr-error-log.js — internal error log overlay. Toolbar icon3 highlights on unseen errors; opening marks them seen.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 20 16 } 21 17 22 /* ============================================================23 * Ícone — estado normal/destacado24 * ========================================================== */25 18 26 19 function refreshIcon() { … … 37 30 } 38 31 39 /**40 * Called externally (e.g. after a failed upload/import) to re-check41 * status; whether the error was actually logged depends on the42 * configured log level.43 */44 32 var _notifyTimer = null; 45 33 function notifyApiError() { … … 48 36 } 49 37 50 /* ============================================================51 * Overlay52 * ========================================================== */53 38 54 39 function ensureOverlay() { … … 190 175 } 191 176 192 /* ============================================================193 * "Clear log" — simple confirm dialog.194 * ========================================================== */195 177 196 178 function confirmClearLog() { -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-grid.js
r3725460 r3782421 1 /* ================================================================2 nfebr-grid.js — column definitions (DANFE order) + table3 rendering; fiscal columns auto-hide when no loaded item has data.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 13 9 var __ = SB.__; 14 10 15 // Same order as the DANFE. 'structural: true' = navigation column 16 // (Supplier/Note), never hidden by auto-hide, visibility decided by 17 // the active filter, not by the data. 11 // active filter, not by the data. 18 12 var COLS = [ 19 // Selection checkbox — always the first column, never hidden.20 // Feeds the "Create Draft+" bulk button in the toolbar, but is a21 // base for any future bulk action.22 { key: 'select', label: '', structural: true, isSelect: true },23 // Action column — always first, never hidden (by auto-hide or24 // filter). Not data, it's a button; rendered separately in25 13 // render() (see isAction). 26 14 { key: 'actions', label: '', structural: true, isAction: true }, 15 { key: 'description', label: __( 'Descrição', 'sanbar-express-nfe-xml-import-br' ), mobileLabel: __( 'Nome', 'sanbar-express-nfe-xml-import-br' ), sortable: true }, 16 { key: 'gtin', label: __( 'GTIN', 'sanbar-express-nfe-xml-import-br' ) }, 27 17 { key: 'supplier_name', label: __( 'Fornecedor', 'sanbar-express-nfe-xml-import-br' ), structural: true, sortable: true }, 28 18 { key: 'note_ref', label: __( 'Nota', 'sanbar-express-nfe-xml-import-br' ), structural: true }, 29 19 { key: 'product_code', label: __( 'Código', 'sanbar-express-nfe-xml-import-br' ) }, 30 { key: 'gtin', label: __( 'GTIN', 'sanbar-express-nfe-xml-import-br' ) },31 { key: 'description', label: __( 'Descrição', 'sanbar-express-nfe-xml-import-br' ), sortable: true },32 20 { key: 'ncm', label: __( 'NCM/SH', 'sanbar-express-nfe-xml-import-br' ) }, 33 21 { key: 'cest', label: __( 'CEST', 'sanbar-express-nfe-xml-import-br' ) }, … … 36 24 { key: 'unit', label: __( 'Unidade', 'sanbar-express-nfe-xml-import-br' ) }, 37 25 { key: 'quantity', label: __( 'Qtd', 'sanbar-express-nfe-xml-import-br' ), numeric: true, decimals: 4 }, 38 { key: 'unit_value', label: __( 'Valor unitário', 'sanbar-express-nfe-xml-import-br' ), numeric: true, decimals: 2 },26 { key: 'unit_value', label: __( 'Valor unitário', 'sanbar-express-nfe-xml-import-br' ), mobileLabel: __( 'Preço', 'sanbar-express-nfe-xml-import-br' ), numeric: true, decimals: 2 }, 39 27 { key: 'total_value', label: __( 'Valor total', 'sanbar-express-nfe-xml-import-br' ), numeric: true, decimals: 2 }, 40 28 { key: 'discount_value', label: __( 'Desconto', 'sanbar-express-nfe-xml-import-br' ), numeric: true, decimals: 2 }, … … 48 36 ]; 49 37 50 // "Per-product" view: 1 row per identity (GTIN, or supplier+code),51 // not per note line item. Fixed columns, no auto-hide.52 38 var PRODUCT_COLS = [ 53 { key: 'select', label: '', structural: true, isSelect: true },54 39 { key: 'actions', label: '', structural: true, isAction: true }, 55 40 { key: 'description', label: __( 'Nome', 'sanbar-express-nfe-xml-import-br' ), sortable: true }, 56 41 { key: 'gtin', label: __( 'GTIN', 'sanbar-express-nfe-xml-import-br' ) }, 57 42 { key: 'product_code', label: __( 'Código', 'sanbar-express-nfe-xml-import-br' ) }, 58 // Badges — cell rendered separately (see isBadge in render()),59 43 // not plain text formatted by formatCell(). 60 44 { key: 'last_price', label: __( 'Preço', 'sanbar-express-nfe-xml-import-br' ), isBadge: true }, … … 65 49 ]; 66 50 67 /** 68 * A value counts as "present" for column auto-hide purposes: not 69 * null/undefined/empty string, and not numeric zero. 70 */ 51 // checkboxes or expose the bulk interaction surface. 52 if ( SB.is_plus ) { 53 COLS.unshift( { key: 'select', label: '', structural: true, isSelect: true } ); 54 PRODUCT_COLS.unshift( { key: 'select', label: '', structural: true, isSelect: true } ); 55 } 56 71 57 function hasValue( v ) { 72 58 if ( v === null || v === undefined || v === '' ) { … … 80 66 } 81 67 82 /**83 * Soft-colored rectangular badge — per-product view. Color is fixed84 * per column, decorative, not state; "no data" is always neutral gray.85 * Warning signal (price varied / stock zero) is a ⚠ inside the badge.86 *87 * @param {string} text88 * @param {string} variant 'neutral'|'price'|'stock'|'date'.89 * @param {string} [warnTitle] When present, adds "⚠" with this title.90 * @return {string}91 */92 68 function badgeHTML( text, variant, warnTitle ) { 93 69 if ( ! text ) { … … 100 76 } 101 77 102 /**103 * Most recent price (unit_value of the representative row). Column104 * always blue; ⚠ when the price has varied between notes for this105 * supplier+code (price_variants, same criterion as the per-note view).106 */107 78 function priceBadgeCell( item ) { 108 79 if ( ! hasValue( item.unit_value ) ) { … … 115 86 } 116 87 117 /**118 * Current stock (WooCommerce, only when linked). Green with a value,119 * ⚠ at zero; neutral gray with no linked/managed stock.120 */121 88 function stockBadgeCell( item ) { 122 89 if ( ! item.wc_product_id ) { … … 131 98 } 132 99 133 /**134 * Most recent note date where this product appeared — column always135 * purple, no state indicator (informational only).136 */137 100 function lastDateBadgeCell( item ) { 138 101 if ( ! item.product_last_date ) { … … 172 135 } 173 136 174 /**175 * Decides which columns to show for the loaded set of items.176 *177 * @param {Array} items Items returned by the REST API.178 * @param {Object} visibility { showSupplier, showNote } — forces179 * structural columns per the active180 * toolbar filter.181 * @param {string} [mode] 'note' (default) | 'product'.182 * @return {Array} Subset of COLS to render.183 */184 137 function visibleColumns( items, visibility, mode ) { 185 138 if ( 'product' === mode ) { … … 203 156 } 204 157 205 /**206 * Renders the grid's thead + tbody.207 *208 * @param {Array} items Items to display.209 * @param {Object} elements { thead, tbody, table, empty }.210 * @param {Object} visibility { showSupplier, showNote }.211 * @param {Set} [selected] Selected item IDs — optional, no212 * selection if omitted.213 * @param {string} [mode] 'note' (default) | 'product'.214 * @param {Object} [sortState] { by, dir } — active column/direction215 * (dir: 'asc'|'desc'), or {} for no sort.216 */217 158 function render( items, elements, visibility, selected, mode, sortState ) { 218 159 var cols = visibleColumns( items, visibility, mode ); … … 231 172 var dir = sortState.by === col.key ? sortState.dir : null; 232 173 var arrow = 'asc' === dir ? '▲' : ( 'desc' === dir ? '▼' : '⇅' ); 233 return '<th class="sbnfebr-col-' + col.key + '" ><button type="button" class="sbnfebr-sort-btn' + ( dir ? ' sbnfebr-sort-btn--active' : '' ) + '" data-sort-key="' + col.key + '">'234 + SB.esc( col.label) + ' <span class="sbnfebr-sort-arrow">' + arrow + '</span></button></th>';235 } 236 return '<th class="sbnfebr-col-' + col.key + ( col.isAction ? ' sbnfebr-col-actions' : '' ) + '" >' + SB.esc( col.label ) + '</th>';174 return '<th class="sbnfebr-col-' + col.key + '"' + ( col.mobileLabel ? ' data-mobile-label="' + SB.esc( col.mobileLabel ) + '"' : '' ) + '><button type="button" class="sbnfebr-sort-btn' + ( dir ? ' sbnfebr-sort-btn--active' : '' ) + '" data-sort-key="' + col.key + '">' 175 + '<span class="sbnfebr-label-wide">' + SB.esc( col.label ) + '</span>' + ( col.mobileLabel ? '<span class="sbnfebr-label-mobile">' + SB.esc( col.mobileLabel ) + '</span>' : '' ) + ' <span class="sbnfebr-sort-arrow">' + arrow + '</span></button></th>'; 176 } 177 return '<th class="sbnfebr-col-' + col.key + ( col.isAction ? ' sbnfebr-col-actions' : '' ) + '"' + ( col.mobileLabel ? ' data-mobile-label="' + SB.esc( col.mobileLabel ) + '"' : '' ) + '>' + SB.esc( col.label ) + '</th>'; 237 178 } ).join( '' ); 238 179 … … 249 190 return '<td class="sbnfebr-col-' + col.key + '">' + badgeCellHTML( col, item ) + '</td>'; 250 191 } 251 return '<td class="sbnfebr-col-' + col.key + '">' + SB.esc( formatCell( col, item ) ) + '</td>'; 192 var value = formatCell( col, item ); 193 var title = [ 'supplier_name', 'note_ref' ].indexOf( col.key ) !== -1 && value 194 ? ' title="' + SB.esc( value ) + '"' 195 : ''; 196 return '<td class="sbnfebr-col-' + col.key + '"' + title + '>' + SB.esc( value ) + '</td>'; 252 197 } ).join( '' ); 253 return '<tr' + ( selected.has( String( item.id ) ) ? ' class="sbnfebr-row-selected"' : '' ) + '>' + cells + '</tr>'; 198 var rowClasses = []; 199 if ( selected.has( String( item.id ) ) ) { rowClasses.push( 'sbnfebr-row-selected' ); } 200 if ( Number( item.ignored ) ) { rowClasses.push( 'sbnfebr-row--ignored' ); } 201 return '<tr' + ( rowClasses.length ? ' class="' + rowClasses.join( ' ' ) + '"' : '' ) + '>' + cells + '</tr>'; 254 202 } ).join( '' ); 203 elements.table.classList.toggle( 'sbnfebr-mobile-selection-active', selected.size > 0 ); 255 204 256 205 var hasItems = items.length > 0; … … 259 208 } 260 209 261 /** 262 * 5 icons in the action cell: "⋯" opens the full Action Modal, the 263 * other 4 open a popup via `SB.itemActions.quickAction()`. States 264 * are approximated from grid data; the popup fetches the real snapshot. 265 * 266 * @param {Object} item 267 * @return {string} 268 */ 210 /** Builds the workflow actions for one row. */ 269 211 function quickActionIconsHTML( item ) { 270 var hasProduct = !! Number( item.wc_product_id ); 271 var hasMatch = ! hasProduct && !! item.match_product_id && !! SB.is_plus; 272 var targetId = hasProduct ? Number( item.wc_product_id ) : ( hasMatch ? Number( item.match_product_id ) : 0 ); 273 var matchBySupplierKey = hasMatch && 'supplier_key' === item.match_source; 274 var matchByBoxGtin = hasMatch && 'gtin' === item.match_source && 'box' === item.match_field; 275 var matchBySku = hasMatch && 'gtin' === item.match_source && 'sku' === item.match_field; 276 var hasFullData = hasProduct && !! item.linked_ncm; 277 // Presence alone (hasFullData) only says "Plus fiscal was applied 278 // at some point" — used for the 🔀 done/done-plus color. The 🧾 279 // icon needs to know if it's actually in sync with THIS note, so 280 // it also compares against the note's own NCM (item.ncm). 281 var fiscalInSync = hasFullData && String( item.linked_ncm ) === String( item.ncm || '' ); 282 283 function icon( key, glyph, state, title ) { 284 return '<button type="button" class="sbnfebr-ac-gicon sbnfebr-ac-gicon--' + state + '" data-item-id="' + item.id + '" data-key="' + key + '" title="' + SB.esc( title ) + '">' + glyph + '</button>'; 285 } 286 287 // Draft/Link — done (green/gold) when already linked, alert 288 // otherwise (there's always a decision to make). 289 var rState = hasProduct ? ( hasFullData ? 'done-plus' : 'done' ) : 'alert'; 290 var rTitle = hasProduct 291 ? ( hasFullData 292 ? __( 'Produto criado/vinculado com dado completo (Plus) — clique para abrir', 'sanbar-express-nfe-xml-import-br' ) 293 : __( 'Produto criado/vinculado (só identidade) — clique para abrir', 'sanbar-express-nfe-xml-import-br' ) ) 294 : ( matchBySupplierKey 295 ? __( 'Produto correspondente encontrado por fornecedor + código — clique pra revisar', 'sanbar-express-nfe-xml-import-br' ) 296 : ( matchBySku 297 ? __( 'Produto compatível encontrado por SKU = GTIN — confira antes de vincular', 'sanbar-express-nfe-xml-import-br' ) 298 : ( matchByBoxGtin 299 ? __( 'Produto correspondente encontrado pelo GTIN de caixa — clique pra revisar', 'sanbar-express-nfe-xml-import-br' ) 300 : ( hasMatch 301 ? __( 'Produto correspondente achado por GTIN — clique para vincular', 'sanbar-express-nfe-xml-import-br' ) 302 : __( 'Criar produto / vincular a um existente', 'sanbar-express-nfe-xml-import-br' ) ) ) ) ); 303 // 🔗 for a match found (GTIN, unit or box), ❗ for a weaker signal 304 // (supplier+code, or SKU = GTIN — could coincide by chance), ➕ for 305 // "nothing yet, needs creating". 📦 is exclusive to the Stock card. 306 var rGlyph = hasProduct ? '🔀' : ( ( matchBySupplierKey || matchBySku ) ? '❗' : ( hasMatch ? '🔗' : '➕' ) ); 307 308 var overview = icon( 'overview', '⋯', 'neutral', __( 'Abrir modal de ação', 'sanbar-express-nfe-xml-import-br' ) ); 309 310 var staleTitle = 'missing' === item.stale_reason 311 ? __( 'O produto vinculado não existe mais — clique para vincular outro', 'sanbar-express-nfe-xml-import-br' ) 312 : __( 'O GTIN do produto mudou desde que este vínculo foi feito — clique para revisar', 'sanbar-express-nfe-xml-import-br' ); 313 var staleBadge = item.stale 314 ? '<span class="sbnfebr-stale-badge" title="' + SB.esc( staleTitle ) + '">⚠️</span>' 315 : ''; 316 var rascunho = '<span class="sbnfebr-ac-gicon-wrap">' + icon( 'rascunho', rGlyph, rState, rTitle ) + staleBadge + '</span>'; 317 318 var estoque; 319 if ( ! SB.is_plus ) { 320 estoque = icon( 'estoque', '📦', 'locked', __( 'Estoque (recurso Plus)', 'sanbar-express-nfe-xml-import-br' ) ); 321 } else if ( ! targetId ) { 322 estoque = icon( 'estoque', '📦', 'quiet', __( 'Estoque — crie ou vincule um produto primeiro', 'sanbar-express-nfe-xml-import-br' ) ); 323 } else { 324 estoque = icon( 'estoque', '📦', Number( item.quantity ) > 0 ? 'alert' : 'quiet', __( 'Estoque', 'sanbar-express-nfe-xml-import-br' ) ); 325 } 326 327 // Numbered badge attached to the 🏷️ icon specifically — the icon 328 // most related to "price varied between notes". 329 var priceVariants = Number( item.price_variants ) || 0; 330 var priceBadge = priceVariants > 1 331 ? '<span class="sbnfebr-price-variant-badge" title="' + SB.esc( __( 'Preço varia entre notas', 'sanbar-express-nfe-xml-import-br' ) ) + '">' + ( Number( item.note_occurrence_count ) || 0 ) + '</span>' 332 : ''; 333 var precoTitle = ( targetId ? __( 'Preço / Fonte', 'sanbar-express-nfe-xml-import-br' ) : __( 'Preço / Fonte — crie ou vincule um produto primeiro', 'sanbar-express-nfe-xml-import-br' ) ) 334 + ( priceVariants > 1 ? ' — ' + __( 'preço varia entre notas', 'sanbar-express-nfe-xml-import-br' ) : '' ); 335 var preco = '<span class="sbnfebr-ac-gicon-wrap">' + 336 icon( 'preco', '🏷️', targetId ? 'alert' : 'quiet', precoTitle ) + 337 priceBadge + 338 '</span>'; 339 340 var fiscal; 341 if ( ! SB.is_plus ) { 342 fiscal = icon( 'fiscal', '🧾', 'locked', __( 'Dados fiscais (recurso Plus)', 'sanbar-express-nfe-xml-import-br' ) ); 343 } else if ( ! targetId ) { 344 fiscal = icon( 'fiscal', '🧾', 'quiet', __( 'Dados fiscais — crie ou vincule um produto primeiro', 'sanbar-express-nfe-xml-import-br' ) ); 345 } else { 346 fiscal = icon( 347 'fiscal', '🧾', fiscalInSync ? 'done' : 'alert', 348 fiscalInSync 349 ? __( 'Dados fiscais — em dia com esta nota', 'sanbar-express-nfe-xml-import-br' ) 350 : __( 'Dados fiscais — desatualizados em relação a esta nota (NCM diferente ou nunca sincronizado)', 'sanbar-express-nfe-xml-import-br' ) 351 ); 352 } 353 354 return '<span class="sbnfebr-ac-gicon-group">' + overview + rascunho + estoque + preco + fiscal + '</span>'; 355 } 356 357 /** 358 * Action button HTML for one row. State (red/amber/gray) is computed 359 * from the backend's price_variants / gtin_supplier_count fields. 360 * 361 * @param {Object} item Row (needs item.id, price_variants, gtin_supplier_count). 362 * @return {string} 363 */ 212 var indicators = 'function' === typeof SB.rowIndicators ? SB.rowIndicators( item ) : ''; 213 var overview = '<button type="button" class="sbnfebr-ac-gicon sbnfebr-ac-gicon--neutral" data-item-id="' + item.id + '" data-key="overview" title="' + SB.esc( __( 'Abrir ações do produto', 'sanbar-express-nfe-xml-import-br' ) ) + '">⋯</button>'; 214 var stage = String( item.workflow_stage || 'entry' ); 215 var workflowState = 'entry'; 216 var workflowGlyph = '→'; 217 var workflowTitle = __( 'Enviar para Conferência', 'sanbar-express-nfe-xml-import-br' ); 218 if ( 'sync' === stage || 'synced' === item.workflow_sync_status ) { 219 workflowState = 'synced'; workflowGlyph = '✓'; workflowTitle = __( 'Sincronizado', 'sanbar-express-nfe-xml-import-br' ); 220 } else if ( 'error' === item.workflow_sync_status || 'error' === item.workflow_check_status || 'stale' === item.workflow_fiscal_status ) { 221 workflowState = 'error'; workflowGlyph = '✓'; workflowTitle = 'stale' === item.workflow_fiscal_status ? __( 'Enviado; a Conferência precisa ser refeita', 'sanbar-express-nfe-xml-import-br' ) : __( 'Enviado; Conferência com correções pendentes', 'sanbar-express-nfe-xml-import-br' ); 222 } else if ( 'warning' === item.workflow_check_status ) { 223 workflowState = 'warning'; workflowGlyph = '✓'; workflowTitle = __( 'Enviado; Conferência com avisos', 'sanbar-express-nfe-xml-import-br' ); 224 } else if ( 'approved' === item.workflow_fiscal_status ) { 225 workflowState = 'approved'; workflowGlyph = '✓'; workflowTitle = __( 'Conferência aprovada', 'sanbar-express-nfe-xml-import-br' ); 226 } else if ( 'ok' === item.workflow_check_status ) { 227 workflowState = 'checked'; workflowGlyph = '✓'; workflowTitle = __( 'Dados conferidos; aguardando aprovação', 'sanbar-express-nfe-xml-import-br' ); 228 } else if ( 'review' === stage ) { 229 workflowState = 'sent'; workflowGlyph = '✓'; workflowTitle = __( 'Enviado para Conferência', 'sanbar-express-nfe-xml-import-br' ); 230 } 231 var review = '<button type="button" class="sbnfebr-workflow-review-btn is-' + workflowState + '" data-item-id="' + item.id + '" title="' + SB.esc( workflowTitle ) + '"' + ( 'entry' === stage ? '' : ' disabled' ) + '>' + workflowGlyph + '</button>'; 232 return '<span class="sbnfebr-ac-gicon-group is-workflow">' + overview + indicators + review + '</span>'; 233 } 234 364 235 function actionButtonsHTML( item ) { 365 236 var stateClass = ''; … … 379 250 var draftBtn = quickActionIconsHTML( item ); 380 251 381 // "Ignored" icon — only appears when the item is already ignored382 // (clean row otherwise), click undoes it. Right of the price383 252 // history icon, same cell. 384 253 var ignoredBtn = Number( item.ignored ) -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-item-actions.js
r3725460 r3782421 1 /* ================================================================ 2 nfebr-item-actions.js — item action modal/popups: Draft/Link, 3 Stock, Price/Source, Fiscal data. Click delegation on document. 4 ================================================================ */ 1 /* Ação única da Entrada para o workflow. */ 5 2 (function () { 6 3 'use strict'; 7 4 8 5 var SB = window.SBNFEBR; 9 if ( ! SB ) { 10 return; 6 if ( ! SB ) { return; } 7 var __ = SB.__; 8 9 function openWorkflowItem( item ) { 10 if ( ! Number( item.workflow_id ) ) { 11 SB.toast.error( __( 'Este item ainda não foi migrado para o catálogo de Conferência.', 'sanbar-express-nfe-xml-import-br' ) ); 12 return; 13 } 14 document.dispatchEvent( new CustomEvent( 'sbnfebr:workflow-context-action', { detail: { 15 sourceItemId: Number( item.id ), 16 workflowId: Number( item.workflow_id ), 17 stage: String( item.workflow_stage || 'entry' ), 18 search: String( item.gtin || item.product_code || item.description || '' ) 19 } } ) ); 11 20 } 12 21 13 var __ = SB.__; 14 var backdrop = null; 15 // Action popups live outside `backdrop`, so closeModal() must track 16 // the last opened one to avoid leaving it orphaned. 17 var openPopup = null; 18 19 function closeModal() { 20 if ( openPopup ) { 21 openPopup.close(); 22 openPopup = null; 23 } 24 if ( backdrop ) { 25 backdrop.remove(); 26 backdrop = null; 27 } 22 function requestItem( itemId ) { 23 document.dispatchEvent( new CustomEvent( 'sbnfebr:open-item-action', { detail: { itemId: itemId } } ) ); 28 24 } 29 25 30 /** 31 * Tells nfebr-main.js this item's product link changed, so it can 32 * update state.lastItems and re-render without a REST reload. The 33 * backend propagates the link to the whole GTIN/supplier+code family. 34 * 35 * @param {Object} item 36 * @param {number} productId 37 * @param {boolean} [identityOnly] Force identity-only even on Plus. 38 * @param {string} [toastMessage] Toast text to show on success. 39 */ 40 function notifyLinked( item, productId, identityOnly, toastMessage ) { 41 SB.toast.success( toastMessage || __( 'Produto vinculado', 'sanbar-express-nfe-xml-import-br' ) ); 42 document.dispatchEvent( new CustomEvent( 'sbnfebr:item-linked', { 43 // hasFiscal: true only when SB.is_plus and not identityOnly — 44 // full fiscal data is sent only on Plus link/draft/sync paths. 45 detail: { 46 itemId: item.id, 47 productId: productId, 48 hasFiscal: !! SB.is_plus && ! identityOnly, 49 gtin: item.gtin, 50 supplierCnpj: item.supplier_cnpj, 51 productCode: item.product_code 52 } 53 } ) ); 54 } 55 56 /** 57 * Tells nfebr-main.js this item lost its link — clears 58 * `wc_product_id`/`linked_ncm` locally and re-renders without a 59 * REST reload. Sends the same identity data as notifyLinked(). 60 * 61 * @param {Object} item 62 */ 63 function notifyUnlinked( item ) { 64 SB.toast.success( __( 'Produto desvinculado', 'sanbar-express-nfe-xml-import-br' ) ); 65 document.dispatchEvent( new CustomEvent( 'sbnfebr:item-unlinked', { 66 detail: { 67 itemId: item.id, 68 gtin: item.gtin, 69 supplierCnpj: item.supplier_cnpj, 70 productCode: item.product_code 71 } 72 } ) ); 73 } 74 75 /** 76 * @param {*} e Rejection from SB.api(). 77 * @return {boolean} True when the backend answered "product not found". 78 */ 79 function isMissingProductError( e ) { 80 return !! e && 'sbnfebr_product_not_found' === e.code; 81 } 82 83 /** 84 * The backend says a product this item still pointed to (link or match 85 * candidate) no longer exists — it already cleared the link on its side. 86 * Drops the dead reference from the UI (grid + Registry check via the 87 * event) and, when a modal is open, redraws it so Draft/Link is offered 88 * again instead of actions over a product that isn't there. 89 * 90 * @param {Object} item 91 * @param {number} productId 92 * @param {HTMLElement|null} [modal] 93 */ 94 function handleMissingProduct( item, productId, modal ) { 95 var pid = String( productId ); 96 if ( String( item.wc_product_id ) === pid ) { 97 item.wc_product_id = null; 98 item.linked_ncm = null; 99 item.stale = false; 100 item.stale_reason = ''; 101 } 102 if ( String( item.match_product_id ) === pid ) { 103 item.match_product_id = null; 104 item.match_product_name = null; 105 item.match_source = null; 106 } 107 document.dispatchEvent( new CustomEvent( 'sbnfebr:product-missing', { detail: { productId: productId } } ) ); 108 SB.toast.error( __( 'Este produto não existe mais — o vínculo foi removido. Crie um novo ou vincule outro.', 'sanbar-express-nfe-xml-import-br' ) ); 109 if ( modal ) { 110 renderActionPanels( modal, item ); 111 } 112 } 113 114 /** 115 * Enforces "1 registered product = 1 NFE identity": on a link 116 * conflict (`e.data.conflict`) confirms with the user, then retries 117 * `callFn` with reassign=true and dispatches sbnfebr:item-unlinked. 118 * 119 * @param {Function} callFn (reassign:boolean) => Promise 120 * @return {Promise} 121 */ 122 function callWithReassign( callFn ) { 123 return callFn( false ).catch( function ( e ) { 124 var conflict = e && e.data && e.data.conflict; 125 if ( ! conflict ) { 126 throw e; 127 } 128 var noteLabel = conflict.note_number ? ( conflict.note_number + ( conflict.series ? '/' + conflict.series : '' ) ) : ''; 129 return SB.confirm( 130 __( 'Este produto já está vinculado a um item diferente do catálogo desta nota:', 'sanbar-express-nfe-xml-import-br' ) + ' "' + conflict.description + '"' + ( noteLabel ? ' (' + noteLabel + ')' : '' ) + '. ' 131 + __( 'Só um item pode ficar vinculado a ele. Vincular aqui e desvincular o outro?', 'sanbar-express-nfe-xml-import-br' ), 132 { danger: true, title: '⚠ ' + __( 'Atenção', 'sanbar-express-nfe-xml-import-br' ), confirmLabel: __( 'Vincular e desvincular o outro', 'sanbar-express-nfe-xml-import-br' ) } 133 ).then( function ( ok ) { 134 if ( ! ok ) { 135 throw e; 136 } 137 return callFn( true ).then( function ( res ) { 138 document.dispatchEvent( new CustomEvent( 'sbnfebr:item-unlinked', { 139 detail: { 140 itemId: conflict.item_id, 141 gtin: conflict.gtin, 142 supplierCnpj: conflict.supplier_cnpj, 143 productCode: conflict.product_code 144 } 145 } ) ); 146 return res; 147 } ); 148 } ); 149 } ); 150 } 151 152 /** 153 * Notifies the main screen when the GTIN couldn't become the SKU 154 * because it already belongs to another product. 155 * 156 * @param {Object} res Response from /draft, /link, /link-update etc. — may have `sku_status`. 157 */ 158 function maybeWarnSkuConflict( res ) { 159 if ( res && 'conflict' === res.sku_status ) { 160 document.dispatchEvent( new CustomEvent( 'sbnfebr:sku-conflict', { detail: {} } ) ); 161 } 162 } 163 164 function setBusy( root, busy ) { 165 // `root` is optional — actions triggered directly from a grid 166 // icon, without the Action Modal open, pass null. 167 if ( root ) { 168 root.querySelectorAll( 'button' ).forEach( function ( b ) { b.disabled = busy; } ); 169 } 170 } 171 172 /** 173 * Surfaces the price variance between notes at action time. Fetches 174 * full history to compare against the prior note's value; the 175 * action always uses THIS note's value regardless — warning only. 176 * 177 * @param {Object} item 178 * @return {Promise<string|null>} Warning text, or null if none. 179 */ 180 function priceVarianceNote( item ) { 181 if ( ! ( Number( item.price_variants ) > 1 ) ) { 182 return Promise.resolve( null ); 183 } 184 return SB.api( 'items/' + item.id + '/price-history' ) 185 .then( function ( res ) { 186 var history = res.history || []; 187 var prior = history.filter( function ( h ) { 188 return ! ( String( h.note_number ) === String( item.note_number ) && String( h.series ) === String( item.series ) ); 189 } ); 190 if ( ! prior.length ) { 191 return null; 192 } 193 var last = prior[ prior.length - 1 ]; // history comes ASC by date — the last one is the most recent before this note. 194 var prevValue = Number( last.unit_value ); 195 var thisValue = Number( item.unit_value ); 196 if ( Math.abs( prevValue - thisValue ) < 0.001 ) { 197 return null; // same value — price_variants>1 is from other notes, doesn't affect this comparison 198 } 199 return __( 'Preço varia entre notas para este produto:', 'sanbar-express-nfe-xml-import-br' ) + ' ' 200 + fmtMoney( prevValue ) + ' (' + last.note_number + '/' + last.series + ') → ' 201 + fmtMoney( thisValue ) + ' (' + __( 'esta nota', 'sanbar-express-nfe-xml-import-br' ) + ').'; 202 } ) 203 .catch( function () { return null; } ); 204 } 205 206 /** 207 * Shows the error inline near `.sbnfebr-danger-actions` when present, 208 * falls back to an error toast otherwise (e.g. `root` is null for 209 * actions triggered directly from a grid icon, with no modal open). 210 * 211 * @param {HTMLElement|null} root 212 * @param {string} message 213 */ 214 function showError( root, message ) { 215 var actions = root ? root.querySelector( '.sbnfebr-danger-actions' ) : null; 216 if ( actions ) { 217 var existing = root.querySelector( '.sbnfebr-danger-error' ); 218 if ( existing ) { 219 existing.remove(); 220 } 221 var err = document.createElement( 'div' ); 222 err.className = 'sbnfebr-danger-error'; 223 err.textContent = message; 224 actions.insertAdjacentElement( 'beforebegin', err ); 225 return; 226 } 227 SB.toast.error( message ); 228 } 229 230 function fmtMoney( v ) { 231 return 'R$ ' + ( Number( v ) || 0 ).toLocaleString( 'pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 } ); 232 } 233 234 /** 235 * Unit vs box/case heuristic: 14-digit GTIN is always GTIN-14 (box), 236 * shorter is unit. Mirrors resolve_gtin_kind() in PHP; user can 237 * correct via radio. 238 * 239 * @param {Object} item 240 * @return {string} 'unit'|'box' 241 */ 242 function defaultGtinKind( item ) { 243 var digits = String( item.gtin || '' ).replace( /\D/g, '' ); 244 return 14 === digits.length ? 'box' : 'unit'; 245 } 246 247 /** 248 * HTML for the "This GTIN is: Unit/Box" and "Fill SKU with:" radios. 249 * Without a real GTIN, disables (not hides) the Unit/Box row and the 250 * GTIN SKU option; "Product code" stays valid either way. 251 * 252 * @param {Object} item 253 * @return {string} 254 */ 255 function gtinKindRadioHtml( item ) { 256 var gtin = String( item.gtin || '' ).trim().toUpperCase(); 257 var hasGtin = gtin && 'SEM GTIN' !== gtin; 258 var def = hasGtin ? defaultGtinKind( item ) : null; 259 var kindDisabled = hasGtin ? '' : ' disabled'; 260 var skuDefault = hasGtin ? 'gtin' : 'product_code'; 261 return '<div class="sbnfebr-ia-gtinkind-row">' + 262 '<span class="sbnfebr-ia-gtinkind-label">' + SB.esc( __( 'Este GTIN é:', 'sanbar-express-nfe-xml-import-br' ) ) + '</span>' + 263 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ia-gtin-kind" value="unit"' + ( 'unit' === def ? ' checked' : '' ) + kindDisabled + '> ' + SB.esc( __( 'Unidade', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 264 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ia-gtin-kind" value="box"' + ( 'box' === def ? ' checked' : '' ) + kindDisabled + '> ' + SB.esc( __( 'Caixa', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 265 '</div>' + 266 // 3-option radio, not a checkbox. Same row as the unit/box radio, 267 // grouped since both decide what to do with the GTIN. 268 '<div class="sbnfebr-ia-gtinkind-row sbnfebr-ia-sku-row">' + 269 '<span class="sbnfebr-ia-gtinkind-label">' + SB.esc( __( 'Preencher SKU com:', 'sanbar-express-nfe-xml-import-br' ) ) + '</span>' + 270 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ia-sku-source" value="none"' + ( 'none' === skuDefault ? ' checked' : '' ) + '> ' + SB.esc( __( "Não alterar", 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 271 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ia-sku-source" value="gtin"' + ( 'gtin' === skuDefault ? ' checked' : '' ) + kindDisabled + '> ' + SB.esc( __( 'GTIN', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 272 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ia-sku-source" value="product_code"' + ( 'product_code' === skuDefault ? ' checked' : '' ) + '> ' + SB.esc( __( 'Código do produto', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 273 '</div>'; 274 } 275 276 /** 277 * Reads the gtin_kind radio inside a container — null when it 278 * doesn't exist (item without GTIN, radio never rendered). 279 * 280 * @param {HTMLElement} root 281 * @return {string|null} 282 */ 283 function readGtinKind( root ) { 284 var checked = root.querySelector( 'input[name="sbnfebr-ia-gtin-kind"]:checked' ); 285 return checked ? checked.value : null; 286 } 287 288 /** 289 * Reads the "Fill SKU with" radio — 'gtin' when it wasn't even 290 * rendered (item without GTIN, same default as the backend). 291 * 292 * @param {HTMLElement} root 293 * @return {string} 'none'|'gtin'|'product_code'. 294 */ 295 function readSkuSource( root ) { 296 var checked = root.querySelector( 'input[name="sbnfebr-ia-sku-source"]:checked' ); 297 return checked ? checked.value : 'gtin'; 298 } 299 300 301 /** 302 * Wires the manual link toggle (Plus only) — reveals a product 303 * search; picking a result calls /items/{id}/link-plus. No-op if 304 * the toggle isn't in the modal (Lite, or product/match already set). 305 * 306 * @param {HTMLElement} modal 307 * @param {Object} item 308 */ 309 function wireManualLink( modal, item ) { 310 var toggle = modal.querySelector( '.sbnfebr-ia-manual-link-toggle' ); 311 if ( ! toggle ) { 312 return; 313 } 314 315 toggle.addEventListener( 'click', function () { 316 openManualLinkPopup( modal, item ); 317 } ); 318 } 319 320 /** 321 * Search popup for manual link — its own popup layered over the main 322 * modal, using the same visual pattern (.sbnfebr-danger-*). Shows a 323 * thumbnail for each result to help identify the right product. 324 * 325 * @param {HTMLElement} parentModal Item-action modal (stays underneath). 326 * @param {Object} item Note item being linked. 327 */ 328 function openManualLinkPopup( parentModal, item ) { 329 var backdrop = document.createElement( 'div' ); 330 backdrop.className = 'sbnfebr-danger-backdrop'; 331 backdrop.innerHTML = 332 '<div class="sbnfebr-danger-modal sbnfebr-ia-manual-link-popup" role="dialog" aria-modal="true">' + 333 '<div class="sbnfebr-itemaction-header">' + 334 '<div class="sbnfebr-danger-title" style="margin:0">' + SB.esc( __( 'Vincular a um produto existente', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>' + 335 '<button type="button" class="sbnfebr-close-btn sbnfebr-ia-manual-link-close">' + SB.esc( __( 'FECHAR', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 336 '</div>' + 337 '<input type="text" class="sbnfebr-danger-input sbnfebr-ia-manual-link-search" placeholder="' + SB.esc( __( 'Buscar por nome ou SKU…', 'sanbar-express-nfe-xml-import-br' ) ) + '" autocomplete="off">' + 338 gtinKindRadioHtml( item ) + 339 '<div class="sbnfebr-ia-manual-link-results"></div>' + 340 '</div>'; 341 document.body.appendChild( backdrop ); 342 343 var searchInput = backdrop.querySelector( '.sbnfebr-ia-manual-link-search' ); 344 var resultsEl = backdrop.querySelector( '.sbnfebr-ia-manual-link-results' ); 345 var searchTimer = null; 346 347 function close() { 348 backdrop.remove(); 349 } 350 351 backdrop.querySelector( '.sbnfebr-ia-manual-link-close' ).addEventListener( 'click', close ); 352 backdrop.addEventListener( 'click', function ( e ) { 353 if ( e.target === backdrop ) { 354 close(); 355 } 356 } ); 357 358 searchInput.addEventListener( 'input', function () { 359 var q = searchInput.value.trim(); 360 window.clearTimeout( searchTimer ); 361 if ( q.length < 2 ) { 362 resultsEl.innerHTML = ''; 363 return; 364 } 365 searchTimer = window.setTimeout( function () { 366 SB.api( 'products-search', { q: q, exclude_item_id: item.id } ) 367 .then( function ( results ) { 368 renderManualLinkResults( results || [] ); 369 } ) 370 .catch( function () { 371 resultsEl.innerHTML = '<div class="sbnfebr-ia-diff-loading">' + SB.esc( __( 'Falha na busca.', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>'; 372 } ); 373 }, 300 ); 374 } ); 375 376 function renderManualLinkResults( results ) { 377 if ( ! results.length ) { 378 resultsEl.innerHTML = '<div class="sbnfebr-ia-diff-loading">' + SB.esc( __( 'Nenhum produto encontrado.', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>'; 379 return; 380 } 381 resultsEl.innerHTML = results.map( function ( p ) { 382 var thumb = p.thumbnail_url 383 ? '<img class="sbnfebr-ia-manual-link-thumb" src="' + SB.esc( p.thumbnail_url ) + '" alt="">' 384 : '<span class="sbnfebr-ia-manual-link-thumb sbnfebr-ia-manual-link-thumb--empty">🖼</span>'; 385 // Shown before the click, not only after in the confirmation 386 // — doesn't block the choice (could be intentional). 387 var inUse = p.used_by_other_item 388 ? '<span class="sbnfebr-ia-manual-link-inuse">⚠ ' + SB.esc( __( 'Já vinculado a outro item', 'sanbar-express-nfe-xml-import-br' ) ) + '</span>' 389 : ''; 390 return '<button type="button" class="sbnfebr-ia-manual-link-item' + ( p.used_by_other_item ? ' sbnfebr-ia-manual-link-item--inuse' : '' ) + '" data-product-id="' + p.id + '">' + 391 thumb + 392 '<span class="sbnfebr-ia-manual-link-item-text"><strong>' + SB.esc( p.name ) + '</strong>' + 393 ( p.sku ? '<span class="sbnfebr-ia-manual-link-sku">SKU: ' + SB.esc( p.sku ) + '</span>' : '' ) + 394 inUse + 395 '</span>' + 396 '</button>'; 397 } ).join( '' ); 398 399 resultsEl.querySelectorAll( '.sbnfebr-ia-manual-link-item' ).forEach( function ( btn, idx ) { 400 btn.addEventListener( 'click', function () { 401 var productId = parseInt( btn.dataset.productId, 10 ); 402 confirmAndLinkManual( productId, results[ idx ].name, results[ idx ].used_by_other_item ); 403 } ); 404 } ); 405 } 406 407 /** 408 * Manual link writes the note's GTIN onto the chosen product — 409 * checks /match-gtin first so linking doesn't create 2 products 410 * with the same GTIN. 411 * 412 * @param {number} productId Product chosen in the popup. 413 * @param {string} productName Product name for display. 414 * @param {Object|null} usedByOther From the search result already. 415 */ 416 function confirmAndLinkManual( productId, productName, usedByOther ) { 417 var gtin = String( item.gtin || '' ).trim().toUpperCase(); 418 var hasGtin = gtin && 'SEM GTIN' !== gtin; 419 420 var check = hasGtin 421 ? SB.api( 'match-gtin', null, { method: 'POST', body: JSON.stringify( { gtins: [ item.gtin ] } ) } ) 422 : Promise.resolve( {} ); 423 424 check.then( function ( matches ) { 425 var conflict = matches && matches[ gtin ]; 426 var warnings = []; 427 if ( conflict && conflict.product_id !== productId ) { 428 warnings.push( 429 __( 'O GTIN deste item já está cadastrado em outro produto:', 'sanbar-express-nfe-xml-import-br' ) + ' "' + conflict.name + '". ' 430 + __( 'Vincular mesmo assim vai gravar o mesmo GTIN neste produto também, criando uma duplicata.', 'sanbar-express-nfe-xml-import-br' ) 431 ); 432 } 433 if ( usedByOther ) { 434 var otherNote = usedByOther.note_number + '/' + usedByOther.series; 435 warnings.push( 436 __( 'Este produto TAMBÉM está vinculado a outro item:', 'sanbar-express-nfe-xml-import-br' ) + ' "' + usedByOther.description + '" (' + otherNote + ') — ' 437 + __( 'esta ação vai sobrescrevê-lo com o dado deste item.', 'sanbar-express-nfe-xml-import-br' ) 438 ); 439 } 440 if ( warnings.length ) { 441 return SB.confirm( 442 warnings.join( ' ' ) + ' ' + __( 'Continuar mesmo assim?', 'sanbar-express-nfe-xml-import-br' ), 443 { danger: true, title: '⚠ ' + __( 'Atenção', 'sanbar-express-nfe-xml-import-br' ), confirmLabel: __( 'Continuar mesmo assim', 'sanbar-express-nfe-xml-import-br' ) } 444 ); 445 } 446 // Confirms even without a conflict — a wrong click on the 447 // search list would otherwise link immediately with no 448 // chance to undo it. 449 return SB.confirm( 450 __( 'Vincular este item ao produto selecionado?', 'sanbar-express-nfe-xml-import-br' ), 451 { confirmLabel: __( 'Vincular', 'sanbar-express-nfe-xml-import-br' ), list: [ productName ] } 452 ); 453 } ).then( function ( ok ) { 454 if ( ! ok ) { 455 return; 456 } 457 var gtinKind = readGtinKind( backdrop ); 458 var skuSource = readSkuSource( backdrop ); 459 close(); 460 // Manual link only sends identity+fiscal (link-plus always 461 // applies both together); the modal's cards refresh on 462 // their own. 463 setBusy( parentModal, true ); 464 callWithReassign( function ( reassign ) { 465 return SB.api( 'items/' + item.id + '/link-plus', null, { method: 'POST', body: JSON.stringify( { product_id: productId, gtin_kind: gtinKind, sku_source: skuSource, reassign: reassign } ) } ); 466 } ) 467 .then( function ( res ) { 468 maybeWarnSkuConflict( res ); 469 notifyLinked( item, res.product_id, false, __( 'Vinculado e atualizado', 'sanbar-express-nfe-xml-import-br' ) ); 470 item.wc_product_id = res.product_id; 471 item.match_product_id = null; 472 setBusy( parentModal, false ); 473 if ( parentModal ) { 474 renderActionPanels( parentModal, item ); 475 } 476 } ) 477 .catch( function ( e2 ) { 478 setBusy( parentModal, false ); 479 showError( parentModal, ( e2 && e2.message ) || __( 'Falha ao vincular.', 'sanbar-express-nfe-xml-import-br' ) ); 480 } ); 481 } ); 482 } 483 484 searchInput.focus(); 485 } 486 487 /** 488 * Fills a match/link card with the product's SKU/GTIN/price so the 489 * user can confirm it's the right product without opening the editor. 490 * 491 * @param {HTMLElement} container 492 * @param {number} productId 493 * @param {Function} [onMissing] Called when the product no longer exists. 494 */ 495 function loadProductInfo( container, productId, onMissing ) { 496 var slot = container.querySelector( '.sbnfebr-ia-product-info' ); 497 var scopeSlot = container.querySelector( '.sbnfebr-ia-identity-scope' ); 498 if ( ( ! slot && ! scopeSlot ) || ! productId ) { 499 return; 500 } 501 SB.api( 'products/' + productId + '/snapshot' ) 502 .then( function ( snap ) { 503 if ( slot ) { 504 var codeBits = []; 505 if ( snap.sku ) { 506 codeBits.push( 'SKU: ' + SB.esc( snap.sku ) ); 507 } 508 if ( snap.gtin ) { 509 codeBits.push( 'GTIN: ' + SB.esc( snap.gtin ) ); 510 } 511 var priceBits = []; 512 if ( snap.price ) { 513 priceBits.push( SB.esc( fmtMoney( snap.price ) ) ); 514 } 515 if ( snap.created_at ) { 516 priceBits.push( SB.esc( __( 'criado', 'sanbar-express-nfe-xml-import-br' ) + ' ' + SB.formatDateBR( snap.created_at ) ) ); 517 } 518 slot.innerHTML = 519 ( snap.name ? '<div class="sbnfebr-ia-product-info-name">' + SB.esc( snap.name ) + '</div>' : '' ) + 520 ( codeBits.length ? '<div class="sbnfebr-ia-product-info-line">' + codeBits.join( ' · ' ) + '</div>' : '' ) + 521 ( priceBits.length ? '<div class="sbnfebr-ia-product-info-line">' + priceBits.join( ' · ' ) + '</div>' : '' ); 522 } 523 if ( scopeSlot && snap.gtin ) { 524 renderIdentityScope( scopeSlot, productId, snap.identity_scope ); 525 } 526 } ) 527 .catch( function ( e ) { 528 // Any other failure stays silent — card keeps whatever it already had. 529 if ( onMissing && isMissingProductError( e ) ) { 530 onMissing(); 531 } 532 } ); 533 } 534 535 /** 536 * Identity-scope indicator + toggle — only relevant for a product 537 * with a GTIN (without one identity is always supplier-restricted). 538 * 539 * @param {HTMLElement} slot 540 * @param {number} productId 541 * @param {string} scope 'supplier_only'|''. 542 */ 543 function renderIdentityScope( slot, productId, scope ) { 544 var restricted = 'supplier_only' === scope; 545 slot.innerHTML = ( restricted 546 ? '🔒 ' + SB.esc( __( 'Identidade restrita a este fornecedor.', 'sanbar-express-nfe-xml-import-br' ) ) 547 : '🔓 ' + SB.esc( __( 'Identidade aberta a qualquer fornecedor com este GTIN.', 'sanbar-express-nfe-xml-import-br' ) ) ) + 548 ' <button type="button" class="sbnfebr-ia-identity-scope-toggle">' + SB.esc( __( 'Alterar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>'; 549 550 slot.querySelector( '.sbnfebr-ia-identity-scope-toggle' ).addEventListener( 'click', function ( e ) { 551 var btn = e.currentTarget; 552 var decision = restricted ? 'expand' : 'restrict'; 553 btn.disabled = true; 554 // Saves without confirmation; the toast is the only sign 555 // that something is running. 556 var toast = SB.toast.start( __( 'Salvando', 'sanbar-express-nfe-xml-import-br' ) ); 557 SB.api( 'products/' + productId + '/identity-scope', null, { method: 'POST', body: JSON.stringify( { decision: decision } ) } ) 558 .then( function () { 559 renderIdentityScope( slot, productId, restricted ? '' : 'supplier_only' ); 560 } ) 561 .catch( function () { 562 btn.disabled = false; 563 } ) 564 .finally( function () { 565 toast.done(); 566 } ); 567 } ); 568 } 569 570 571 /** 572 * Creation form fields — name/Title Case/GTIN radio/SKU. 573 * 574 * @param {Object} item 575 * @return {string} 576 */ 577 function buildCreateFormFieldsHtml( item ) { 578 var draftPlusHint = SB.is_plus 579 ? '<div class="sbnfebr-import-hint">✚ ' + SB.esc( __( 'Plus: já cria com dado fiscal, custo, Calculadora de Preço e impostos inclusos.', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>' 580 : ''; 581 return '<label class="sbnfebr-radio-line" style="display:flex;margin-bottom:6px">' + 582 '<input type="radio" name="sbnfebr-ia-name-src" value="note" checked> ' + 583 SB.esc( __( 'Usar o nome da nota', 'sanbar-express-nfe-xml-import-br' ) ) + 584 '</label>' + 585 '<label class="sbnfebr-radio-line" style="display:flex;margin-bottom:4px">' + 586 '<input type="radio" name="sbnfebr-ia-name-src" value="custom"> ' + 587 SB.esc( __( 'Usar outro nome', 'sanbar-express-nfe-xml-import-br' ) ) + 588 '</label>' + 589 '<input type="text" class="sbnfebr-itemaction-name-input sbnfebr-ia-name-input" value="' + SB.esc( item.description ) + '" disabled>' + 590 '<label class="sbnfebr-radio-line" style="display:flex;margin-top:4px;margin-bottom:2px">' + 591 '<input type="checkbox" class="sbnfebr-ia-capitalize-chk" checked> ' + 592 SB.esc( __( 'Capitalizar (Iniciais Maiúsculas)', 'sanbar-express-nfe-xml-import-br' ) ) + 593 '</label>' + 594 gtinKindRadioHtml( item ) + 595 draftPlusHint; 596 } 597 598 /** 599 * "Create draft+"/"Create draft" button — 2 lines, line 1 is the 600 * verb, line 2 differentiates Lite ("simple") from Plus ("with 601 * fiscal data"). Reused in buildCreateDraftHtml(). 602 * 603 * @return {string} 604 */ 605 function draftBtnLabelHtml() { 606 var line1 = SB.esc( SB.is_plus ? __( 'Criar rascunho+', 'sanbar-express-nfe-xml-import-br' ) : __( 'Criar rascunho', 'sanbar-express-nfe-xml-import-br' ) ); 607 var line2 = SB.esc( SB.is_plus ? __( 'com dados fiscais', 'sanbar-express-nfe-xml-import-br' ) : __( 'simples', 'sanbar-express-nfe-xml-import-br' ) ); 608 return line1 + '<br>' + line2; 609 } 610 611 function buildCreateDraftHtml( item ) { 612 var draftBtnLabel = draftBtnLabelHtml(); 613 // Neutral white on purpose — not the primary action (blue) nor 614 // the manual link (amber). 615 var identityOnlyToggle = SB.is_plus 616 ? '<button type="button" class="sbnfebr-btn sbnfebr-ia-identity-only-btn sbnfebr-ia-identity-only-btn--narrow">' + 617 SB.esc( __( 'Ou criar', 'sanbar-express-nfe-xml-import-br' ) ) + '<br>' + SB.esc( __( 'rascunho simples', 'sanbar-express-nfe-xml-import-br' ) ) + 618 '</button>' 619 : ''; 620 var manualLinkBtnPlus = '<button type="button" class="sbnfebr-btn sbnfebr-btn--amber sbnfebr-ia-manual-link-toggle">' + 621 SB.esc( __( 'Vincular a', 'sanbar-express-nfe-xml-import-br' ) ) + '<br>' + SB.esc( __( 'produto existente', 'sanbar-express-nfe-xml-import-br' ) ) + 622 '</button>'; 623 var manualLinkInfoLite = '<div class="sbnfebr-sync-card sbnfebr-ia-manual-link-toggle--spaced">' + 624 '<span class="sbnfebr-sync-card__ribbon">PLUS</span>' + 625 '<div class="sbnfebr-ia-sync-status sbnfebr-ia-sync-status--neutral">ℹ ' + 626 SB.esc( __( 'O Plus também permite vincular este item a um produto existente em vez de criar um novo.', 'sanbar-express-nfe-xml-import-br' ) ) + 627 '</div>' + 628 '</div>'; 629 630 // identityOnlyToggle sits on the same row as "Link", next to it. 631 var draftRow = SB.is_plus 632 ? '<div class="sbnfebr-ia-draft-row">' + 633 '<button type="button" class="sbnfebr-btn sbnfebr-btn--blue sbnfebr-ia-draft-btn">' + draftBtnLabel + '</button>' + 634 manualLinkBtnPlus + 635 identityOnlyToggle + 636 '</div>' 637 : '<button type="button" class="sbnfebr-btn sbnfebr-btn--blue sbnfebr-ia-draft-btn" style="margin-top:10px">' + draftBtnLabel + '</button>'; 638 639 return buildCreateFormFieldsHtml( item ) + 640 draftRow + 641 ( SB.is_plus ? '' : manualLinkInfoLite ); 642 } 643 644 /** 645 * Wires the form built by buildCreateDraftHtml(); elements must 646 * already be in the DOM inside `modal`. 647 * 648 * @param {HTMLElement} modal 649 * @param {Object} item 650 */ 651 function wireCreateDraftMode( modal, item ) { 652 var nameInput = modal.querySelector( '.sbnfebr-ia-name-input' ); 653 var capitalizeChk = modal.querySelector( '.sbnfebr-ia-capitalize-chk' ); 654 modal.querySelectorAll( 'input[name="sbnfebr-ia-name-src"]' ).forEach( function ( radio ) { 655 radio.addEventListener( 'change', function () { 656 var useCustomName = 'custom' === radio.value && radio.checked; 657 nameInput.disabled = ! useCustomName; 658 if ( useCustomName ) { 659 nameInput.focus(); 660 } 661 if ( capitalizeChk ) { 662 capitalizeChk.disabled = useCustomName; 663 } 664 } ); 665 } ); 666 667 /** 668 * Creates the product — confirms first with a clear list of what 669 * will be written. identityOnly forces identity only even on Plus. 670 * 671 * @param {boolean} identityOnly 672 */ 673 function runCreateDraft( identityOnly ) { 674 var useCustom = modal.querySelector( 'input[name="sbnfebr-ia-name-src"]:checked' ).value === 'custom'; 675 var name = useCustom ? nameInput.value.trim() : ''; 676 var capitalize = ! useCustom && !! ( capitalizeChk && capitalizeChk.checked ); 677 var fullData = SB.is_plus && ! identityOnly; 678 679 var list = fullData 680 ? [ 681 __( 'Identidade (GTIN, código do fornecedor, vínculo com fornecedor)', 'sanbar-express-nfe-xml-import-br' ), 682 __( 'Dado fiscal (NCM, CEST, CST/CSOSN…)', 'sanbar-express-nfe-xml-import-br' ), 683 __( 'Custo pago', 'sanbar-express-nfe-xml-import-br' ), 684 __( 'Campos da Calculadora de Preço', 'sanbar-express-nfe-xml-import-br' ), 685 __( 'Lista de impostos', 'sanbar-express-nfe-xml-import-br' ) 686 ] 687 : [ __( 'Identidade (GTIN, código do fornecedor, vínculo com fornecedor)', 'sanbar-express-nfe-xml-import-br' ) ]; 688 689 priceVarianceNote( item ).then( function ( priceNote ) { 690 var msg = __( 'Criar um novo produto a partir deste item da nota?', 'sanbar-express-nfe-xml-import-br' ); 691 if ( priceNote ) { 692 msg += ' ⚠ ' + priceNote; 693 } 694 return SB.confirm( msg, { confirmLabel: __( 'Criar', 'sanbar-express-nfe-xml-import-br' ), list: list } ); 695 } ).then( function ( ok ) { 696 if ( ! ok ) { 697 return; 698 } 699 setBusy( modal, true ); 700 SB.api( 'items/' + item.id + '/draft', null, { method: 'POST', body: JSON.stringify( { name: name, identity_only: identityOnly, capitalize: capitalize, gtin_kind: readGtinKind( modal ), sku_source: readSkuSource( modal ) } ) } ) 701 .then( function ( res ) { 702 maybeWarnSkuConflict( res ); 703 // res.created: identity may already resolve to an 704 // existing product, so the toast reflects that instead. 705 notifyLinked( item, res.product_id, identityOnly, res.created ? __( 'Rascunho criado', 'sanbar-express-nfe-xml-import-br' ) : __( 'Produto vinculado', 'sanbar-express-nfe-xml-import-br' ) ); 706 closeModal(); 707 document.dispatchEvent( new CustomEvent( 'sbnfebr:product-created', { 708 detail: { productId: res.product_id, editUrl: res.edit_url } 709 } ) ); 710 } ) 711 .catch( function ( e2 ) { 712 setBusy( modal, false ); 713 showError( modal, ( e2 && e2.message ) || __( 'Falha ao criar o produto.', 'sanbar-express-nfe-xml-import-br' ) ); 714 } ); 715 } ); 716 } 717 718 modal.querySelector( '.sbnfebr-ia-draft-btn' ).addEventListener( 'click', function () { 719 runCreateDraft( false ); 720 } ); 721 722 var identityOnlyBtn = modal.querySelector( '.sbnfebr-ia-identity-only-btn' ); 723 if ( identityOnlyBtn ) { 724 identityOnlyBtn.addEventListener( 'click', function () { 725 runCreateDraft( true ); 726 } ); 727 } 728 729 wireManualLink( modal, item ); 730 } 731 732 /** 733 * Source selector — other occurrences of the same GTIN. Choosing a 734 * row re-renders the panels targeted at it, reusing renderActionPanels() 735 * instead of swapping state underneath. Hidden without a real GTIN. 736 * 737 * @param {HTMLElement} modal 738 * @param {Object} item 739 */ 740 function loadSourceSelector( modal, item ) { 741 var section = modal.querySelector( '.sbnfebr-ia-source-section' ); 742 var rowsEl = modal.querySelector( '.sbnfebr-ia-source-rows' ); 743 var gtin = String( item.gtin || '' ).trim().toUpperCase(); 744 if ( ! section || ! rowsEl || ! gtin || 'SEM GTIN' === gtin ) { 745 return; 746 } 747 748 SB.api( 'items/' + item.id + '/gtin-family' ) 749 .then( function ( family ) { 750 if ( ! family || ! family.length ) { 751 return; 752 } 753 section.style.display = ''; 754 modal.classList.add( 'sbnfebr-itemaction-modal--has-source' ); 755 756 // Combined list, most recent date first; order is fixed 757 // after building it, even as selection changes. 758 var all = [ item ].concat( family ).sort( function ( a, b ) { 759 return String( b.emission_date ) < String( a.emission_date ) ? -1 : 1; 760 } ); 761 var baseline = item; 762 var selectedId = String( item.id ); 763 764 // If ANY occurrence in the family is already linked, the 765 // whole family IS that product (mirrors backend propagation). 766 var familyProductId = 0; 767 all.forEach( function ( s ) { 768 if ( ! familyProductId && Number( s.wc_product_id ) ) { 769 familyProductId = Number( s.wc_product_id ); 770 } 771 } ); 772 773 function render() { 774 rowsEl.innerHTML = all.map( function ( source ) { 775 return SB.diffCard.sourceRow( source, String( source.id ) === selectedId, baseline ); 776 } ).join( '' ); 777 778 rowsEl.querySelectorAll( '.sbnfebr-diffcard-source' ).forEach( function ( btn ) { 779 btn.addEventListener( 'click', function () { 780 // id comes as a string from the REST API (raw wpdb 781 // row, no cast) — always compare as strings. 782 var chosenId = String( btn.dataset.sourceId ); 783 if ( chosenId === selectedId ) { 784 return; 785 } 786 var chosen = all.filter( function ( s ) { return String( s.id ) === chosenId; } )[ 0 ]; 787 if ( ! chosen ) { 788 return; 789 } 790 selectedId = chosenId; 791 render(); 792 var merged = Object.assign( {}, item, chosen, { id: parseInt( chosen.id, 10 ) } ); 793 if ( familyProductId ) { 794 // Identity already resolved for the family — 795 // never offer "create new" for any row in it. 796 merged.wc_product_id = familyProductId; 797 merged.match_product_id = null; 798 merged.match_product_name = null; 799 merged.match_source = null; 800 } else { 801 merged.match_product_id = null; 802 merged.match_product_name = null; 803 merged.match_source = null; 804 } 805 renderActionPanels( modal, merged ); 806 } ); 807 } ); 808 } 809 810 render(); 811 } ) 812 .catch( function () {} ); 813 } 814 815 /** 816 * Metadata line in the modal header — GTIN, supplier, unit, to 817 * visually confirm this is the right item before any action. 818 * 819 * @param {Object} item 820 * @return {string} 821 */ 822 function buildHeaderMetaHtml( item ) { 823 var gtin = String( item.gtin || '' ).trim(); 824 var hasGtin = gtin && 'SEM GTIN' !== gtin.toUpperCase(); 825 var bits = []; 826 bits.push( 'GTIN: ' + ( hasGtin ? gtin : __( 'nenhum', 'sanbar-express-nfe-xml-import-br' ) ) ); 827 if ( item.supplier_name ) { 828 bits.push( item.supplier_name ); 829 } 830 if ( item.unit ) { 831 bits.push( item.unit ); 832 } 833 return '<div class="sbnfebr-itemaction-meta">' + SB.esc( bits.join( ' · ' ) ) + '</div>'; 834 } 835 836 /** 837 * Opens the unified modal for one grid item. Draft/Link block has 838 * 3 states: already linked, GTIN match found, or neither. Sync 839 * card always appears — re-syncing an already-linked item is valid. 840 * 841 * @param {Object} item Grid row (id, product_code, description, wc_product_id, match_product_id, match_product_name). 842 */ 843 function openModal( item ) { 844 closeModal(); 845 846 backdrop = document.createElement( 'div' ); 847 backdrop.className = 'sbnfebr-danger-backdrop'; 848 backdrop.innerHTML = 849 '<div class="sbnfebr-danger-modal sbnfebr-itemaction-modal" role="dialog" aria-modal="true">' + 850 '<div class="sbnfebr-itemaction-header">' + 851 '<div>' + 852 '<div class="sbnfebr-itemaction-code">' + SB.esc( item.product_code || item.gtin || '' ) + '</div>' + 853 '<div class="sbnfebr-itemaction-desc">' + SB.esc( item.description ) + '</div>' + 854 buildHeaderMetaHtml( item ) + 855 '</div>' + 856 '<button type="button" class="sbnfebr-close-btn sbnfebr-danger-cancel">' + SB.esc( __( 'FECHAR', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 857 '</div>' + 858 '<div class="sbnfebr-itemaction-body">' + 859 '<div class="sbnfebr-configure-section sbnfebr-ia-source-section sbnfebr-itemaction-source-col" style="display:none">' + 860 '<div class="sbnfebr-configure-section-title">' + SB.esc( __( 'Fonte', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>' + 861 '<div class="sbnfebr-ia-source-rows"></div>' + 862 '</div>' + 863 '<div class="sbnfebr-itemaction-main-col">' + 864 '<div class="sbnfebr-ia-top-alert"></div>' + 865 '<div class="sbnfebr-ac-cards"></div>' + 866 '</div>' + 867 '</div>' + 868 '</div>'; 869 document.body.appendChild( backdrop ); 870 871 var modal = backdrop.querySelector( '.sbnfebr-itemaction-modal' ); 872 873 loadSourceSelector( modal, item ); 874 renderActionPanels( modal, item ); 875 876 backdrop.querySelectorAll( '.sbnfebr-danger-cancel' ).forEach( function ( b ) { b.addEventListener( 'click', closeModal ); } ); 877 backdrop.addEventListener( 'click', function ( e ) { 878 if ( e.target === backdrop ) { 879 closeModal(); 880 } 881 } ); 882 } 883 884 /** 885 * Renders the 4 atomic action cards (Draft/Link, Stock, Price/Source, 886 * Fiscal data) — always available, never disabled; only the state 887 * (alert/quiet) signals whether there's something new to apply. 888 * 889 * @param {HTMLElement} modal 890 * @param {Object} item Active item (may not be the one that opened the modal, if the source was switched). 891 */ 892 function renderActionPanels( modal, item ) { 893 var hasProduct = !! Number( item.wc_product_id ); 894 var hasMatch = ! hasProduct && !! item.match_product_id; 895 var targetId = hasProduct ? Number( item.wc_product_id ) : ( hasMatch ? Number( item.match_product_id ) : 0 ); 896 897 var topAlert = modal.querySelector( '.sbnfebr-ia-top-alert' ); 898 if ( topAlert ) { 899 topAlert.innerHTML = '<span class="sbnfebr-ia-product-info-slot"></span>'; 900 } 901 902 renderActionCards( modal, item, hasProduct, hasMatch, targetId, null ); 903 904 if ( targetId ) { 905 SB.api( 'products/' + targetId + '/snapshot', { exclude_item_id: item.id } ) 906 .then( function ( snap ) { 907 if ( snap.used_by_other_item && topAlert ) { 908 var otherNoteSK = snap.used_by_other_item.note_number + '/' + snap.used_by_other_item.series; 909 topAlert.innerHTML = SB.alertCard( 910 'warn', '⚠', 911 SB.esc( __( 'Este produto já está ligado a outro item', 'sanbar-express-nfe-xml-import-br' ) ), 912 '"' + SB.esc( snap.used_by_other_item.description ) + '" — ' + SB.esc( __( 'nota', 'sanbar-express-nfe-xml-import-br' ) ) + ' <code>' + SB.esc( otherNoteSK ) + '</code>. ' + 913 SB.esc( __( 'Vincular aqui não desfaz esse outro vínculo.', 'sanbar-express-nfe-xml-import-br' ) ) 914 ); 915 } 916 renderActionCards( modal, item, hasProduct, hasMatch, targetId, snap ); 917 } ) 918 .catch( function ( e ) { 919 if ( isMissingProductError( e ) ) { 920 handleMissingProduct( item, targetId, modal ); 921 } 922 } ); 923 } 924 } 925 926 /** 927 * Builds the HTML for one action card — never `disabled`, the visual 928 * state is what communicates whether there's something to do. 929 * 930 * @param {string} key 'rascunho'|'estoque'|'preco'|'fiscal'. 931 * @param {string} icon Card emoji. 932 * @param {string} state 'alert'|'quiet'|'done'|'locked'. 933 * @param {string} title 934 * @param {string} detail Already-escaped HTML where needed. 935 * @param {string} btnLabel 936 * @return {string} 937 */ 938 function cardHtml( key, icon, state, title, detail, btnLabel ) { 939 var ribbon = 'locked' === state ? '<span class="sbnfebr-sync-card__ribbon sbnfebr-ac-ribbon">PLUS</span>' : ''; 940 return '<div class="sbnfebr-ac-card sbnfebr-ac-card--' + state + '" data-card="' + key + '">' + 941 ribbon + 942 '<div class="sbnfebr-ac-icon">' + icon + '</div>' + 943 '<div class="sbnfebr-ac-body">' + 944 '<div class="sbnfebr-ac-title">' + SB.esc( title ) + '</div>' + 945 '<div class="sbnfebr-ac-detail">' + detail + '</div>' + 946 '</div>' + 947 '<button type="button" class="sbnfebr-btn sbnfebr-ac-btn" data-card="' + key + '">' + SB.esc( btnLabel ) + '</button>' + 948 '</div>'; 949 } 950 951 /** 952 * Computes and draws the state of the 4 cards — called twice (before 953 * and after the snapshot arrives), always rewiring the buttons. 954 * 955 * @param {HTMLElement} modal 956 * @param {Object} item 957 * @param {boolean} hasProduct 958 * @param {boolean} hasMatch 959 * @param {number} targetId Product to consider (already linked, or the match — 0 if none). 960 * @param {Object|null} snap Product snapshot (get_snapshot()) — null while loading. 961 */ 962 function renderActionCards( modal, item, hasProduct, hasMatch, targetId, snap ) { 963 var container = modal.querySelector( '.sbnfebr-ac-cards' ); 964 if ( ! container ) { 965 return; 966 } 967 968 var noProductYetHint = __( 'Crie ou vincule um produto primeiro', 'sanbar-express-nfe-xml-import-br' ); 969 970 // ---- Draft / Link — never locked, Lite only creates. ---- 971 var rState, rDetail, rBtn; 972 if ( hasProduct ) { 973 rState = 'done'; 974 rDetail = SB.esc( __( 'Já vinculado', 'sanbar-express-nfe-xml-import-br' ) ) + ( snap && snap.created_at ? ' — ' + SB.esc( SB.formatDateBR( snap.created_at ) ) : '' ); 975 rBtn = __( 'Abrir', 'sanbar-express-nfe-xml-import-br' ); 976 } else if ( hasMatch ) { 977 rState = 'alert'; 978 rDetail = SB.esc( __( 'Match encontrado:', 'sanbar-express-nfe-xml-import-br' ) ) + ' <strong>' + SB.esc( item.match_product_name || ( '#' + item.match_product_id ) ) + '</strong>'; 979 rBtn = __( 'Escolher', 'sanbar-express-nfe-xml-import-br' ); 980 } else { 981 rState = 'alert'; 982 rDetail = SB.esc( __( 'Nenhum produto vinculado ainda', 'sanbar-express-nfe-xml-import-br' ) ); 983 rBtn = __( 'Criar', 'sanbar-express-nfe-xml-import-br' ); 984 } 985 986 // ---- Stock — Plus only, always part of linking. ---- 987 var eState, eDetail, eBtn = __( 'Aplicar', 'sanbar-express-nfe-xml-import-br' ); 988 if ( ! SB.is_plus ) { 989 eState = 'locked'; 990 eDetail = SB.esc( __( 'Soma ou define o estoque a partir desta nota', 'sanbar-express-nfe-xml-import-br' ) ); 991 eBtn = __( 'Saiba mais', 'sanbar-express-nfe-xml-import-br' ); 992 } else if ( ! targetId ) { 993 eState = 'quiet'; 994 eDetail = SB.esc( noProductYetHint ); 995 } else { 996 var noteQty = Number( item.quantity ) || 0; 997 eState = noteQty > 0 ? 'alert' : 'quiet'; 998 var stockKnown = !! snap && null !== snap.stock && undefined !== snap.stock; 999 var currentStock = stockKnown ? Number( snap.stock ) : 0; 1000 eDetail = stockKnown 1001 ? SB.esc( __( 'Atual:', 'sanbar-express-nfe-xml-import-br' ) ) + ' ' + currentStock + ' — ' + SB.esc( __( 'esta nota traz', 'sanbar-express-nfe-xml-import-br' ) ) + ' ' + noteQty + ' ' + SB.esc( __( 'unidades', 'sanbar-express-nfe-xml-import-br' ) ) 1002 : SB.esc( __( 'Não gerenciado', 'sanbar-express-nfe-xml-import-br' ) ) + ' — ' + SB.esc( __( 'esta nota traz', 'sanbar-express-nfe-xml-import-br' ) ) + ' ' + noteQty + ' ' + SB.esc( __( 'unidades', 'sanbar-express-nfe-xml-import-br' ) ); 1003 } 1004 1005 // ---- Price / Source — Lite and Plus. ---- 1006 var pState, pDetail, pBtn = __( 'Aplicar', 'sanbar-express-nfe-xml-import-br' ); 1007 if ( ! targetId ) { 1008 pState = 'quiet'; 1009 pDetail = SB.esc( noProductYetHint ); 1010 } else { 1011 var costKnown = !! snap && 'unit' === snap.sale_type && null !== snap.cost_paid && undefined !== snap.cost_paid; 1012 var costChanged = costKnown && Math.abs( Number( snap.cost_paid ) - ( Number( item.unit_value ) || 0 ) ) > 0.001; 1013 pState = ( ! snap ) ? 'quiet' : ( ( costChanged || ! costKnown ) ? 'alert' : 'quiet' ); 1014 pDetail = ! snap 1015 ? SB.esc( __( 'Checando…', 'sanbar-express-nfe-xml-import-br' ) ) 1016 : ( costKnown 1017 ? SB.esc( __( 'Custo:', 'sanbar-express-nfe-xml-import-br' ) ) + ' ' + SB.esc( fmtMoney( snap.cost_paid ) ) + ' → ' + SB.esc( fmtMoney( item.unit_value ) ) 1018 : SB.esc( __( 'Nenhum custo registrado ainda', 'sanbar-express-nfe-xml-import-br' ) ) ); 1019 } 1020 1021 // ---- Fiscal data — Plus only, always was. ---- 1022 var fState, fDetail, fBtn = __( 'Aplicar', 'sanbar-express-nfe-xml-import-br' ); 1023 if ( ! SB.is_plus ) { 1024 fState = 'locked'; 1025 fDetail = SB.esc( __( 'NCM, CEST, unidades e impostos a partir desta nota', 'sanbar-express-nfe-xml-import-br' ) ); 1026 fBtn = __( 'Saiba mais', 'sanbar-express-nfe-xml-import-br' ); 1027 } else if ( ! targetId ) { 1028 fState = 'quiet'; 1029 fDetail = SB.esc( noProductYetHint ); 1030 } else if ( ! snap ) { 1031 fState = 'quiet'; 1032 fDetail = SB.esc( __( 'Checando…', 'sanbar-express-nfe-xml-import-br' ) ); 1033 } else { 1034 var fieldDiffs = FISCAL_FIELD_MAP.filter( function ( f ) { 1035 return !! item[ f.item ] && String( snap[ f.snap ] || '' ) !== String( item[ f.item ] ); 1036 } ); 1037 var offeredFields = FISCAL_FIELD_MAP.filter( function ( f ) { return !! item[ f.item ]; } ); 1038 var neverSynced = offeredFields.length > 0 && offeredFields.every( function ( f ) { return ! snap[ f.snap ]; } ); 1039 if ( neverSynced ) { 1040 fState = 'alert'; 1041 fDetail = SB.esc( __( 'Este produto ainda não tem dado fiscal', 'sanbar-express-nfe-xml-import-br' ) ); 1042 } else if ( fieldDiffs.length ) { 1043 fState = 'alert'; 1044 fDetail = fieldDiffs.length + ' ' + SB.esc( __( 'campo(s) fiscal(is) desatualizado(s)', 'sanbar-express-nfe-xml-import-br' ) ); 1045 } else { 1046 fState = 'quiet'; 1047 fDetail = SB.esc( __( 'Em dia', 'sanbar-express-nfe-xml-import-br' ) ); 1048 } 1049 } 1050 1051 container.innerHTML = 1052 cardHtml( 'rascunho', '🔀', rState, __( 'Rascunho / Vínculo', 'sanbar-express-nfe-xml-import-br' ), rDetail, rBtn ) + 1053 cardHtml( 'estoque', '📦', eState, __( 'Estoque', 'sanbar-express-nfe-xml-import-br' ), eDetail, eBtn ) + 1054 cardHtml( 'preco', '🏷️', pState, __( 'Preço / Fonte', 'sanbar-express-nfe-xml-import-br' ), pDetail, pBtn ) + 1055 cardHtml( 'fiscal', '🧾', fState, __( 'Dados fiscais', 'sanbar-express-nfe-xml-import-br' ), fDetail, fBtn ); 1056 1057 wireCardButtons( modal, item, hasProduct, hasMatch, targetId, snap ); 1058 } 1059 1060 /** 1061 * Standard popup reused by all 4 actions — same backdrop/modal 1062 * skeleton as the manual link popup. 1063 * 1064 * @param {string} icon 1065 * @param {string} iconClass 'sbnfebr-ac-popup-icon--blue'|'--amber'. 1066 * @param {string} title 1067 * @param {string} bodyHtml 1068 * @param {string} [footerHtml] 1069 * @return {{el: HTMLElement, close: Function}} 1070 */ 1071 function openActionPopup( icon, iconClass, title, bodyHtml, footerHtml, subtitle ) { 1072 var pop = document.createElement( 'div' ); 1073 pop.className = 'sbnfebr-danger-backdrop'; 1074 pop.innerHTML = 1075 '<div class="sbnfebr-danger-modal sbnfebr-ac-popup" role="dialog" aria-modal="true">' + 1076 '<div class="sbnfebr-ac-popup-head">' + 1077 '<span class="sbnfebr-ac-popup-icon ' + iconClass + '">' + icon + '</span>' + 1078 '<span class="sbnfebr-ac-popup-headtext">' + 1079 '<span class="sbnfebr-ac-popup-title">' + SB.esc( title ) + '</span>' + 1080 ( subtitle ? '<span class="sbnfebr-ac-popup-subtitle">' + SB.esc( subtitle ) + '</span>' : '' ) + 1081 '</span>' + 1082 '<button type="button" class="sbnfebr-close-btn sbnfebr-ac-popup-close">' + SB.esc( __( 'FECHAR', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1083 '</div>' + 1084 '<div class="sbnfebr-ac-popup-body">' + bodyHtml + '</div>' + 1085 ( footerHtml ? '<div class="sbnfebr-ac-popup-actions">' + footerHtml + '</div>' : '' ) + 1086 '</div>'; 1087 document.body.appendChild( pop ); 1088 1089 function close() { 1090 pop.remove(); 1091 if ( openPopup && openPopup.el === pop ) { 1092 openPopup = null; 1093 } 1094 } 1095 1096 pop.querySelector( '.sbnfebr-ac-popup-close' ).addEventListener( 'click', close ); 1097 pop.addEventListener( 'click', function ( e ) { 1098 if ( e.target === pop ) { 1099 close(); 1100 } 1101 } ); 1102 1103 openPopup = { el: pop, close: close }; 1104 return openPopup; 1105 } 1106 1107 /** 1108 * Locked card (Plus, shown on Lite) — static text only, no Plus 1109 * logic/calls (WordPress.org disallows Plus code in the Lite build). 1110 * 1111 * @param {string} text 1112 */ 1113 function openLockedInfo( text ) { 1114 var popup = openActionPopup( 1115 '🔒', 'sbnfebr-ac-popup-icon--amber', 1116 __( 'Recurso Plus', 'sanbar-express-nfe-xml-import-br' ), 1117 '<div class="sbnfebr-ia-sync-status sbnfebr-ia-sync-status--neutral">ℹ ' + SB.esc( text ) + '</div>' 1118 ); 1119 var modalEl = popup.el.querySelector( '.sbnfebr-ac-popup' ); 1120 if ( modalEl ) { 1121 modalEl.insertAdjacentHTML( 'afterbegin', '<span class="sbnfebr-sync-card__ribbon sbnfebr-ac-ribbon">PLUS</span>' ); 1122 } 1123 return popup; 1124 } 1125 1126 /** 1127 * Card with no product/match yet (Stock/Price/Fiscal before any 1128 * link) — same warning the Sync card already showed. 1129 * 1130 * @param {HTMLElement} modal 1131 * @param {Object} item 1132 */ 1133 function showNeedProductHint( modal, item ) { 1134 openActionPopup( 1135 'ℹ️', 'sbnfebr-ac-popup-icon--blue', 1136 __( 'Ainda sem produto', 'sanbar-express-nfe-xml-import-br' ), 1137 '<div class="sbnfebr-ia-sync-status sbnfebr-ia-sync-status--neutral">ℹ ' + 1138 SB.esc( __( 'Crie ou vincule um produto primeiro (card Rascunho/Vínculo) — esta ação só atualiza um produto que já existe.', 'sanbar-express-nfe-xml-import-br' ) ) + 1139 '</div>', 1140 null, item && item.description 1141 ); 1142 } 1143 1144 /** 1145 * Wires the click of the 4 card buttons — each decides on its own 1146 * whether to open the real popup or a warning (Plus locked / no 1147 * product). 1148 * 1149 * @param {HTMLElement} modal 1150 * @param {Object} item 1151 * @param {boolean} hasProduct 1152 * @param {boolean} hasMatch 1153 * @param {number} targetId 1154 * @param {Object|null} snap 1155 */ 1156 function wireCardButtons( modal, item, hasProduct, hasMatch, targetId, snap ) { 1157 modal.querySelectorAll( '.sbnfebr-ac-btn' ).forEach( function ( btn ) { 1158 btn.addEventListener( 'click', function () { 1159 var key = btn.dataset.card; 1160 if ( 'rascunho' === key ) { 1161 openRascunhoPopup( modal, item, hasProduct, hasMatch, targetId, snap ); 1162 } else if ( 'estoque' === key ) { 1163 if ( ! SB.is_plus ) { 1164 openLockedInfo( __( 'Plus permite somar ou definir o estoque direto a partir desta nota, mantendo o controle do que você já tem.', 'sanbar-express-nfe-xml-import-br' ) ); 1165 return; 1166 } 1167 if ( ! targetId ) { 1168 showNeedProductHint( modal, item ); 1169 return; 1170 } 1171 openEstoquePopup( modal, item, targetId, snap ); 1172 } else if ( 'preco' === key ) { 1173 if ( ! targetId ) { 1174 showNeedProductHint( modal, item ); 1175 return; 1176 } 1177 openPrecoPopup( modal, item, targetId, snap ); 1178 } else if ( 'fiscal' === key ) { 1179 if ( ! SB.is_plus ) { 1180 openLockedInfo( __( 'Plus preenche NCM, CEST, unidades, os campos da Calculadora de Preço e a lista de impostos automaticamente a partir desta nota.', 'sanbar-express-nfe-xml-import-br' ) ); 1181 return; 1182 } 1183 if ( ! targetId ) { 1184 showNeedProductHint( modal, item ); 1185 return; 1186 } 1187 openFiscalPopup( modal, item, targetId, snap ); 1188 } 1189 } ); 1190 } ); 1191 } 1192 1193 /** 1194 * "Draft / Link" popup — content varies with the item's state: 1195 * already linked (info + actions), match found (3 choices), or 1196 * neither (2 choices, no "link to found"). 1197 * 1198 * @param {HTMLElement} modal 1199 * @param {Object} item 1200 * @param {boolean} hasProduct 1201 * @param {boolean} hasMatch 1202 * @param {number} targetId 1203 * @param {Object|null} snap 1204 */ 1205 function openRascunhoPopup( modal, item, hasProduct, hasMatch, targetId, snap ) { 1206 if ( hasProduct ) { 1207 var gtinChanged = 'gtin_changed' === item.stale_reason; 1208 var staleCard = item.stale 1209 ? SB.alertCard( 'warn', '⚠️', SB.esc( gtinChanged 1210 ? __( 'O GTIN deste produto mudou desde o vínculo. Aceite o novo GTIN para remover este aviso, ou vincule outro produto.', 'sanbar-express-nfe-xml-import-br' ) 1211 : __( 'Este produto mudou desde que foi vinculado — o GTIN não bate mais, ou o produto foi removido', 'sanbar-express-nfe-xml-import-br' ) ) ) 1212 : ''; 1213 var body = 1214 staleCard + 1215 SB.alertCard( 'good', '🔀', SB.esc( __( 'Este item já tem um produto vinculado', 'sanbar-express-nfe-xml-import-br' ) ), '<div class="sbnfebr-ia-product-info"></div>' ) + 1216 '<div class="sbnfebr-ia-identity-scope" style="margin-top:8px"></div>' + 1217 '<div class="sbnfebr-ac-popup-btnrow">' + 1218 ( SB.sm_admin_url 1219 ? '<button type="button" class="sbnfebr-btn sbnfebr-ac-open-sm-btn">' + SB.esc( __( 'Abrir no Store Manager', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' 1220 : '' ) + 1221 '<button type="button" class="sbnfebr-btn sbnfebr-ac-open-btn">' + SB.esc( __( 'Abrir no editor', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1222 ( gtinChanged 1223 ? '<button type="button" class="sbnfebr-btn sbnfebr-btn--blue sbnfebr-ac-accept-btn">' + SB.esc( __( 'Aceitar novo GTIN', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' 1224 : '' ) + 1225 ( item.stale 1226 ? '<button type="button" class="sbnfebr-btn sbnfebr-ac-relink-btn">' + SB.esc( __( 'Buscar outro produto', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' 1227 : '' ) + 1228 '<button type="button" class="sbnfebr-btn sbnfebr-ac-unlink-btn">' + SB.esc( __( 'Desvincular', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1229 '</div>'; 1230 var popup = openActionPopup( '🔀', 'sbnfebr-ac-popup-icon--blue', __( 'Rascunho / Vínculo', 'sanbar-express-nfe-xml-import-br' ), body, null, item.description ); 1231 loadProductInfo( popup.el, targetId, function () { 1232 popup.close(); 1233 handleMissingProduct( item, targetId, modal ); 1234 openRascunhoPopup( modal, item, false, false, 0, null ); 1235 } ); 1236 popup.el.querySelector( '.sbnfebr-ac-open-btn' ).addEventListener( 'click', function () { 1237 window.open( SB.adminUrl + 'post.php?post=' + targetId + '&action=edit', '_blank' ); 1238 } ); 1239 var acceptBtn = popup.el.querySelector( '.sbnfebr-ac-accept-btn' ); 1240 if ( acceptBtn ) { 1241 acceptBtn.addEventListener( 'click', function () { 1242 acceptBtn.disabled = true; 1243 SB.api( 'items/' + item.id + '/accept-link-snapshot', null, { method: 'POST' } ) 1244 .then( function () { 1245 item.stale = false; 1246 item.stale_reason = ''; 1247 document.dispatchEvent( new CustomEvent( 'sbnfebr:link-snapshot-accepted', { detail: { productId: targetId } } ) ); 1248 SB.toast.success( __( 'Novo GTIN aceito', 'sanbar-express-nfe-xml-import-br' ) ); 1249 popup.close(); 1250 } ) 1251 .catch( function ( e2 ) { 1252 acceptBtn.disabled = false; 1253 if ( isMissingProductError( e2 ) ) { 1254 popup.close(); 1255 handleMissingProduct( item, targetId, modal ); 1256 openRascunhoPopup( modal, item, false, false, 0, null ); 1257 return; 1258 } 1259 SB.toast.error( ( e2 && e2.message ) || __( 'Falha ao aceitar o novo GTIN.', 'sanbar-express-nfe-xml-import-br' ) ); 1260 } ); 1261 } ); 1262 } 1263 var relinkBtn = popup.el.querySelector( '.sbnfebr-ac-relink-btn' ); 1264 if ( relinkBtn ) { 1265 relinkBtn.addEventListener( 'click', function () { 1266 openManualLinkPopup( popup.el, item ); 1267 } ); 1268 } 1269 var openSmBtn = popup.el.querySelector( '.sbnfebr-ac-open-sm-btn' ); 1270 if ( openSmBtn ) { 1271 openSmBtn.addEventListener( 'click', function () { 1272 var inIframe = window.parent !== window; 1273 if ( inIframe ) { 1274 window.parent.postMessage( { type: 'sbnfebr:products-created', product_ids: [ targetId ] }, window.location.origin ); 1275 } else if ( SB.sm_admin_url ) { 1276 var sep = SB.sm_admin_url.indexOf( '?' ) !== -1 ? '&' : '?'; 1277 window.open( SB.sm_admin_url + sep + 'sbesfw_ids=' + targetId, '_blank' ); 1278 } 1279 } ); 1280 } 1281 popup.el.querySelector( '.sbnfebr-ac-unlink-btn' ).addEventListener( 'click', function () { 1282 SB.confirm( 1283 __( 'Desvincular este item do produto? O produto em si não é alterado nem excluído — só o vínculo deste item é removido.', 'sanbar-express-nfe-xml-import-br' ), 1284 { confirmLabel: __( 'Desvincular', 'sanbar-express-nfe-xml-import-br' ) } 1285 ).then( function ( ok ) { 1286 if ( ! ok ) { 1287 return; 1288 } 1289 SB.api( 'items/' + item.id + '/unlink', null, { method: 'POST' } ) 1290 .then( function () { 1291 notifyUnlinked( item ); 1292 popup.close(); 1293 closeModal(); 1294 } ) 1295 .catch( function ( e2 ) { 1296 showError( modal, ( e2 && e2.message ) || __( 'Falha ao desvincular.', 'sanbar-express-nfe-xml-import-br' ) ); 1297 } ); 1298 } ); 1299 } ); 1300 return; 1301 } 1302 1303 var choices = ''; 1304 choices += '<div class="sbnfebr-ac-choose-opt" data-choice="create">' + 1305 '<div><div class="sbnfebr-ac-choose-label">' + SB.esc( SB.is_plus ? __( 'Criar rascunho+', 'sanbar-express-nfe-xml-import-br' ) : __( 'Criar rascunho', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>' + 1306 '<div class="sbnfebr-ac-choose-sub">' + SB.esc( hasMatch ? __( 'Ignora o match, produto novo do zero', 'sanbar-express-nfe-xml-import-br' ) : ( SB.is_plus ? __( 'Produto novo, com dados fiscais', 'sanbar-express-nfe-xml-import-br' ) : __( 'Produto novo, só identidade', 'sanbar-express-nfe-xml-import-br' ) ) ) + '</div></div>' + 1307 '<button type="button" class="sbnfebr-btn sbnfebr-btn--blue sbnfebr-ac-choose-btn" data-choice="create">' + SB.esc( __( 'Criar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1308 '</div>'; 1309 if ( hasMatch ) { 1310 choices += '<div class="sbnfebr-ac-choose-opt" data-choice="link">' + 1311 '<div><div class="sbnfebr-ac-choose-label">' + SB.esc( __( 'Vincular ao match encontrado', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>' + 1312 '<div class="sbnfebr-ac-choose-sub">' + SB.esc( item.match_product_name || ( '#' + item.match_product_id ) ) + '</div></div>' + 1313 '<button type="button" class="sbnfebr-btn sbnfebr-btn--amber sbnfebr-ac-choose-btn" data-choice="link">' + SB.esc( __( 'Vincular', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1314 '</div>'; 1315 } 1316 if ( SB.is_plus ) { 1317 choices += '<div class="sbnfebr-ac-choose-opt" data-choice="search">' + 1318 '<div><div class="sbnfebr-ac-choose-label">' + SB.esc( __( 'Buscar outro produto', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>' + 1319 '<div class="sbnfebr-ac-choose-sub">' + SB.esc( __( 'Se o match automático não for o certo', 'sanbar-express-nfe-xml-import-br' ) ) + '</div></div>' + 1320 '<button type="button" class="sbnfebr-btn sbnfebr-ac-choose-btn" data-choice="search">' + SB.esc( __( 'Buscar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1321 '</div>'; 1322 } 1323 1324 var choosePopup = openActionPopup( 1325 '🔀', 'sbnfebr-ac-popup-icon--blue', __( 'Rascunho / Vínculo', 'sanbar-express-nfe-xml-import-br' ), 1326 '<div class="sbnfebr-ac-choose-list">' + choices + '</div>', 1327 null, item.description 1328 ); 1329 1330 choosePopup.el.querySelectorAll( '.sbnfebr-ac-choose-btn' ).forEach( function ( btn ) { 1331 btn.addEventListener( 'click', function () { 1332 var choice = btn.dataset.choice; 1333 if ( 'create' === choice ) { 1334 choosePopup.el.querySelector( '.sbnfebr-ac-popup-body' ).innerHTML = buildCreateDraftHtml( item ); 1335 wireCreateDraftMode( choosePopup.el, item ); 1336 } else if ( 'link' === choice ) { 1337 SB.confirm( 1338 __( 'Vincular este item ao produto encontrado?', 'sanbar-express-nfe-xml-import-br' ), 1339 { confirmLabel: __( 'Vincular', 'sanbar-express-nfe-xml-import-br' ), list: [ item.match_product_name || ( '#' + item.match_product_id ) ] } 1340 ).then( function ( ok ) { 1341 if ( ! ok ) { 1342 return; 1343 } 1344 choosePopup.close(); 1345 setBusy( modal, true ); 1346 callWithReassign( function ( reassign ) { 1347 return SB.api( 'items/' + item.id + '/link', null, { method: 'POST', body: JSON.stringify( { product_id: item.match_product_id, reassign: reassign } ) } ); 1348 } ) 1349 .then( function ( res ) { 1350 maybeWarnSkuConflict( res ); 1351 notifyLinked( item, res.product_id, false, __( 'Produto vinculado', 'sanbar-express-nfe-xml-import-br' ) ); 1352 item.wc_product_id = res.product_id; 1353 item.match_product_id = null; 1354 setBusy( modal, false ); 1355 if ( modal ) { renderActionPanels( modal, item ); } 1356 } ) 1357 .catch( function ( e2 ) { 1358 setBusy( modal, false ); 1359 if ( isMissingProductError( e2 ) ) { 1360 handleMissingProduct( item, item.match_product_id, modal ); 1361 openRascunhoPopup( modal, item, false, false, 0, null ); 1362 return; 1363 } 1364 showError( modal, ( e2 && e2.message ) || __( 'Falha ao vincular.', 'sanbar-express-nfe-xml-import-br' ) ); 1365 } ); 1366 } ); 1367 } else if ( 'search' === choice ) { 1368 choosePopup.close(); 1369 openManualLinkPopup( modal, item ); 1370 } 1371 } ); 1372 } ); 1373 } 1374 1375 /** 1376 * Compact "source note" selector (same GTIN family) for quick-action 1377 * popups — reuses loadSourceSelector()'s gtin-family endpoint, with 1378 * a select instead of a row column. 1379 * 1380 * @param {Object} popup Return value of openActionPopup(). 1381 * @param {Object} item Current item (baseline). 1382 * @param {Function} onChange Receives the merged item for the chosen row. 1383 */ 1384 function wireSourceSelector( popup, item, onChange ) { 1385 var slot = popup.el.querySelector( '.sbnfebr-ac-source-slot' ); 1386 var gtin = String( item.gtin || '' ).trim().toUpperCase(); 1387 if ( ! slot || ! gtin || 'SEM GTIN' === gtin ) { 1388 return; 1389 } 1390 1391 SB.api( 'items/' + item.id + '/gtin-family' ) 1392 .then( function ( family ) { 1393 if ( ! family || ! family.length ) { 1394 return; 1395 } 1396 var all = [ item ].concat( family ).sort( function ( a, b ) { 1397 return String( b.emission_date ) < String( a.emission_date ) ? -1 : 1; 1398 } ); 1399 var selectedId = String( item.id ); 1400 1401 slot.innerHTML = 1402 '<span class="sbnfebr-ac-source-label">' + SB.esc( __( 'Nota de origem', 'sanbar-express-nfe-xml-import-br' ) ) + '</span>' + 1403 '<select class="sbnfebr-danger-input sbnfebr-ac-source-select">' + 1404 all.map( function ( s ) { 1405 var noteLabel = s.note_number ? ( s.note_number + ( s.series ? '/' + s.series : '' ) ) : ''; 1406 var dateBR = SB.formatDateBR ? SB.formatDateBR( s.emission_date ) : String( s.emission_date || '' ); 1407 var label = fmtMoney( s.unit_value ) + ' · ' + noteLabel + ' · ' + dateBR; 1408 return '<option value="' + SB.esc( String( s.id ) ) + '"' + ( String( s.id ) === selectedId ? ' selected' : '' ) + '>' + SB.esc( label ) + '</option>'; 1409 } ).join( '' ) + 1410 '</select>'; 1411 slot.style.display = ''; 1412 1413 slot.querySelector( '.sbnfebr-ac-source-select' ).addEventListener( 'change', function ( e ) { 1414 var chosenId = String( e.target.value ); 1415 var chosen = all.filter( function ( s ) { return String( s.id ) === chosenId; } )[ 0 ]; 1416 if ( ! chosen ) { 1417 return; 1418 } 1419 onChange( Object.assign( {}, item, chosen, { id: parseInt( chosen.id, 10 ) } ) ); 1420 } ); 1421 } ) 1422 .catch( function () {} ); 1423 } 1424 1425 /** 1426 * "Stock" popup — Plus only (caller already guaranteed this). 1427 * 1428 * @param {HTMLElement} modal 1429 * @param {Object} item 1430 * @param {number} targetId 1431 * @param {Object|null} snap 1432 */ 1433 function openEstoquePopup( modal, item, targetId, snap ) { 1434 var state = { item: item }; 1435 1436 function dynamicHtml( it ) { 1437 var noteQty = Number( it.quantity ) || 0; 1438 var stockKnown = !! snap && null !== snap.stock && undefined !== snap.stock; 1439 var currentStock = stockKnown ? Number( snap.stock ) : 0; 1440 var sumDefault = stockKnown ? ( currentStock + noteQty ) : noteQty; 1441 var remembered = ( snap && snap.remembered ) || {}; 1442 var rememberedStock = remembered.stock_action || 'sum'; 1443 var startValue = 'replace' === rememberedStock ? noteQty : sumDefault; 1444 1445 var linkNote = targetId === Number( it.wc_product_id ) 1446 ? '' 1447 : '<div class="sbnfebr-ac-popup-note">' + SB.esc( __( 'Isso vincula este item ao produto encontrado antes de aplicar (ainda não estava vinculado).', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>'; 1448 1449 return linkNote + 1450 '<div class="sbnfebr-radio-group">' + 1451 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ac-stock-action" value="none" data-value="' + currentStock + '"' + ( 'none' === rememberedStock ? ' checked' : '' ) + '> ' + SB.esc( __( "Não alterar", 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 1452 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ac-stock-action" value="sum" data-value="' + sumDefault + '"' + ( 'sum' === rememberedStock ? ' checked' : '' ) + '> ' + SB.esc( __( 'Somar', 'sanbar-express-nfe-xml-import-br' ) ) + ' (' + currentStock + ' + ' + noteQty + ' = ' + sumDefault + ')</label>' + 1453 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-ac-stock-action" value="replace" data-value="' + noteQty + '"' + ( 'replace' === rememberedStock ? ' checked' : '' ) + '> ' + SB.esc( __( 'Definir como', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 1454 '</div>' + 1455 '<input type="number" step="1" class="sbnfebr-danger-input sbnfebr-ac-stock-value" style="width:100px;height:30px;padding:2px 8px;margin-top:6px;font-family:inherit" value="' + startValue + '"' + ( 'none' === rememberedStock ? ' disabled' : '' ) + '>' + 1456 '<label class="sbnfebr-radio-line" style="margin-top:8px"><input type="checkbox" class="sbnfebr-ac-remember-chk"> ' + SB.esc( __( 'Lembrar esta escolha como padrão da próxima vez', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>'; 1457 } 1458 1459 function wireDynamic() { 1460 var valueInput = popup.el.querySelector( '.sbnfebr-ac-stock-value' ); 1461 popup.el.querySelectorAll( 'input[name="sbnfebr-ac-stock-action"]' ).forEach( function ( radio ) { 1462 radio.addEventListener( 'change', function () { 1463 valueInput.disabled = 'none' === radio.value; 1464 valueInput.value = radio.dataset.value; 1465 } ); 1466 } ); 1467 } 1468 1469 function renderDynamic( it ) { 1470 state.item = it; 1471 popup.el.querySelector( '.sbnfebr-ac-dynamic' ).innerHTML = dynamicHtml( it ); 1472 wireDynamic(); 1473 } 1474 1475 var body = '<div class="sbnfebr-ac-source-slot" style="display:none"></div>' + 1476 '<div class="sbnfebr-ac-dynamic"></div>'; 1477 var footer = '<button type="button" class="sbnfebr-btn sbnfebr-ac-popup-cancel">' + SB.esc( __( 'Cancelar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1478 '<button type="button" class="sbnfebr-btn sbnfebr-btn--amber sbnfebr-ac-popup-submit">' + SB.esc( __( 'Aplicar estoque', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>'; 1479 1480 var popup = openActionPopup( '📦', 'sbnfebr-ac-popup-icon--amber', __( 'Atualizar estoque', 'sanbar-express-nfe-xml-import-br' ), body, footer, item.description ); 1481 1482 renderDynamic( item ); 1483 wireSourceSelector( popup, item, renderDynamic ); 1484 1485 popup.el.querySelector( '.sbnfebr-ac-popup-cancel' ).addEventListener( 'click', popup.close ); 1486 popup.el.querySelector( '.sbnfebr-ac-popup-submit' ).addEventListener( 'click', function () { 1487 var it = state.item; 1488 var stockRadio = popup.el.querySelector( 'input[name="sbnfebr-ac-stock-action"]:checked' ); 1489 var stockAction = stockRadio ? stockRadio.value : 'none'; 1490 var valueInput = popup.el.querySelector( '.sbnfebr-ac-stock-value' ); 1491 var remember = popup.el.querySelector( '.sbnfebr-ac-remember-chk' ).checked; 1492 1493 var actionLabel = 'sum' === stockAction 1494 ? __( 'Somar', 'sanbar-express-nfe-xml-import-br' ) 1495 : ( 'replace' === stockAction ? __( 'Definir como', 'sanbar-express-nfe-xml-import-br' ) : __( "Não alterar", 'sanbar-express-nfe-xml-import-br' ) ); 1496 var summary = 'none' === stockAction ? actionLabel : ( actionLabel + ': ' + valueInput.value ); 1497 1498 SB.confirm( 1499 __( 'Aplicar esta alteração de estoque?', 'sanbar-express-nfe-xml-import-br' ), 1500 { confirmLabel: __( 'Aplicar estoque', 'sanbar-express-nfe-xml-import-br' ), list: [ summary ] } 1501 ).then( function ( ok ) { 1502 if ( ! ok ) { 1503 return; 1504 } 1505 popup.close(); 1506 setBusy( modal, true ); 1507 callWithReassign( function ( reassign ) { 1508 return SB.api( 'items/' + it.id + '/stock', null, { method: 'POST', body: JSON.stringify( { 1509 product_id: targetId, 1510 stock_action: stockAction, 1511 stock_value: 'none' !== stockAction ? Number( valueInput.value ) : null, 1512 remember: remember, 1513 reassign: reassign 1514 } ) } ); 1515 } ) 1516 .then( function ( res ) { 1517 // identityOnly=true: stock never sends fiscal data — 1518 // keeps the icon from "upgrading" to gold by mistake. 1519 notifyLinked( item, res.product_id, true, __( 'Estoque atualizado', 'sanbar-express-nfe-xml-import-br' ) ); 1520 item.wc_product_id = res.product_id; 1521 item.match_product_id = null; 1522 setBusy( modal, false ); 1523 if ( modal ) { renderActionPanels( modal, item ); } 1524 } ) 1525 .catch( function ( e2 ) { 1526 setBusy( modal, false ); 1527 showError( modal, ( e2 && e2.message ) || __( 'Falha ao atualizar estoque.', 'sanbar-express-nfe-xml-import-br' ) ); 1528 } ); 1529 } ); 1530 } ); 1531 } 1532 1533 /** 1534 * "Price / Source" popup — Lite and Plus. 1535 * 1536 * @param {HTMLElement} modal 1537 * @param {Object} item 1538 * @param {number} targetId 1539 * @param {Object|null} snap 1540 */ 1541 function openPrecoPopup( modal, item, targetId, snap ) { 1542 var state = { item: item }; 1543 1544 function dynamicHtml( it ) { 1545 var costKnown = !! snap && 'unit' === snap.sale_type && null !== snap.cost_paid && undefined !== snap.cost_paid; 1546 var costChanged = costKnown && Math.abs( Number( snap.cost_paid ) - ( Number( it.unit_value ) || 0 ) ) > 0.001; 1547 1548 var linkNote = targetId === Number( it.wc_product_id ) 1549 ? '' 1550 : '<div class="sbnfebr-ac-popup-note">' + SB.esc( __( 'Isso vincula este item ao produto encontrado antes de aplicar (ainda não estava vinculado).', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>'; 1551 1552 var priceLine = costKnown 1553 ? '<label class="sbnfebr-radio-line"><input type="checkbox" class="sbnfebr-ac-price-chk"' + ( costChanged ? ' checked' : '' ) + '> ' + SB.esc( __( 'Atualizar custo:', 'sanbar-express-nfe-xml-import-br' ) ) + ' ' + SB.esc( fmtMoney( snap.cost_paid ) ) + ' → ' + SB.esc( fmtMoney( it.unit_value ) ) + '</label>' 1554 : '<label class="sbnfebr-radio-line"><input type="checkbox" class="sbnfebr-ac-price-chk" checked> ' + SB.esc( __( 'Definir custo:', 'sanbar-express-nfe-xml-import-br' ) ) + ' ' + SB.esc( fmtMoney( it.unit_value ) ) + '</label>'; 1555 1556 return linkNote + priceLine + gtinKindRadioHtml( it ); 1557 } 1558 1559 function renderDynamic( it ) { 1560 state.item = it; 1561 popup.el.querySelector( '.sbnfebr-ac-dynamic' ).innerHTML = dynamicHtml( it ); 1562 } 1563 1564 var body = '<div class="sbnfebr-ac-source-slot" style="display:none"></div>' + 1565 '<div class="sbnfebr-ac-dynamic"></div>'; 1566 var footer = '<button type="button" class="sbnfebr-btn sbnfebr-ac-popup-cancel">' + SB.esc( __( 'Cancelar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1567 '<button type="button" class="sbnfebr-btn sbnfebr-btn--amber sbnfebr-ac-popup-submit">' + SB.esc( __( 'Aplicar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>'; 1568 1569 var popup = openActionPopup( '🏷️', 'sbnfebr-ac-popup-icon--amber', __( 'Preço e fonte', 'sanbar-express-nfe-xml-import-br' ), body, footer, item.description ); 1570 1571 renderDynamic( item ); 1572 wireSourceSelector( popup, item, renderDynamic ); 1573 1574 popup.el.querySelector( '.sbnfebr-ac-popup-cancel' ).addEventListener( 'click', popup.close ); 1575 popup.el.querySelector( '.sbnfebr-ac-popup-submit' ).addEventListener( 'click', function () { 1576 var it = state.item; 1577 var applyPrice = popup.el.querySelector( '.sbnfebr-ac-price-chk' ).checked; 1578 var gtinKind = readGtinKind( popup.el ); 1579 var skuSource = readSkuSource( popup.el ); 1580 1581 var list = []; 1582 if ( applyPrice ) { 1583 list.push( __( 'Custo:', 'sanbar-express-nfe-xml-import-br' ) + ' ' + fmtMoney( it.unit_value ) ); 1584 } 1585 if ( gtinKind ) { 1586 list.push( __( 'Este GTIN é:', 'sanbar-express-nfe-xml-import-br' ) + ' ' + ( 'unit' === gtinKind ? __( 'Unidade', 'sanbar-express-nfe-xml-import-br' ) : __( 'Caixa', 'sanbar-express-nfe-xml-import-br' ) ) ); 1587 } 1588 1589 SB.confirm( 1590 __( 'Aplicar esta alteração de preço/fonte?', 'sanbar-express-nfe-xml-import-br' ), 1591 { confirmLabel: __( 'Aplicar', 'sanbar-express-nfe-xml-import-br' ), list: list } 1592 ).then( function ( ok ) { 1593 if ( ! ok ) { 1594 return; 1595 } 1596 popup.close(); 1597 setBusy( modal, true ); 1598 callWithReassign( function ( reassign ) { 1599 return SB.api( 'items/' + it.id + '/price-source', null, { method: 'POST', body: JSON.stringify( { 1600 product_id: targetId, 1601 apply_price: applyPrice, 1602 gtin_kind: gtinKind, 1603 sku_source: skuSource, 1604 reassign: reassign 1605 } ) } ); 1606 } ) 1607 .then( function ( res ) { 1608 maybeWarnSkuConflict( res ); 1609 // identityOnly=true: price/source never sends fiscal 1610 // data — keeps the icon from "upgrading" to gold by 1611 // mistake. 1612 notifyLinked( item, res.product_id, true, __( 'Preço/fonte atualizado', 'sanbar-express-nfe-xml-import-br' ) ); 1613 item.wc_product_id = res.product_id; 1614 item.match_product_id = null; 1615 setBusy( modal, false ); 1616 if ( modal ) { renderActionPanels( modal, item ); } 1617 } ) 1618 .catch( function ( e2 ) { 1619 setBusy( modal, false ); 1620 showError( modal, ( e2 && e2.message ) || __( 'Falha ao atualizar preço/fonte.', 'sanbar-express-nfe-xml-import-br' ) ); 1621 } ); 1622 } ); 1623 } ); 1624 } 1625 1626 /** 1627 * "Fiscal data" popup — Plus only. Field by field (note × product): 1628 * only checked fields are sent; product fields still empty come 1629 * pre-checked, so nothing already filled is overwritten by default. 1630 * CFOP/CSOSN/cBenef are the supplier's — shown as reference only. 1631 * 1632 * @param {HTMLElement} modal 1633 * @param {Object} item 1634 * @param {number} targetId 1635 * @param {Object|null} snap 1636 */ 1637 function openFiscalPopup( modal, item, targetId, snap ) { 1638 // Without the snapshot every product field would look empty and come pre-checked. 1639 if ( ! snap ) { 1640 SB.api( 'products/' + targetId + '/snapshot', { exclude_item_id: item.id } ) 1641 .then( function ( s ) { openFiscalPopup( modal, item, targetId, s ); } ) 1642 .catch( function () { SB.toast.error( __( 'Falha ao carregar dados do produto.', 'sanbar-express-nfe-xml-import-br' ) ); } ); 1643 return; 1644 } 1645 1646 var noteVals = snap.note_fiscal || {}; 1647 1648 function yesNo( v ) { 1649 if ( '1' === v ) { 1650 return __( 'Sim', 'sanbar-express-nfe-xml-import-br' ); 1651 } 1652 if ( '0' === v ) { 1653 return __( 'Não', 'sanbar-express-nfe-xml-import-br' ); 1654 } 1655 return v; 1656 } 1657 1658 var fields = FISCAL_FIELD_MAP.map( function ( f ) { 1659 return { key: f.snap, label: f.label, note: String( item[ f.item ] || '' ), current: String( ( snap && snap[ f.snap ] ) || '' ), fmt: String }; 1660 } ); 1661 fields.push( { 1662 key: 'fornecedor_st', 1663 label: __( 'Mercadoria com ICMS-ST', 'sanbar-express-nfe-xml-import-br' ), 1664 note: String( noteVals.fornecedor_st || '' ), 1665 current: String( ( snap && snap.fornecedor_st ) || '' ), 1666 fmt: yesNo 1667 } ); 1668 fields = fields.filter( function ( f ) { return '' !== f.note; } ); 1669 1670 var rows = fields.map( function ( f ) { 1671 var equal = f.note === f.current; 1672 var cell = equal 1673 ? '<span class="sbnfebr-ac-fiscal-eq" title="' + SB.esc( __( 'Igual ao cadastro', 'sanbar-express-nfe-xml-import-br' ) ) + '">=</span>' 1674 : '<input type="checkbox" class="sbnfebr-ac-fiscal-chk" value="' + SB.esc( f.key ) + '"' + ( '' === f.current ? ' checked' : '' ) + '>'; 1675 return '<tr' + ( equal ? ' class="is-equal"' : '' ) + '>' + 1676 '<td class="sbnfebr-ac-fiscal-pick">' + cell + '</td>' + 1677 '<td>' + SB.esc( f.label ) + '</td>' + 1678 '<td>' + SB.esc( f.fmt( f.note ) ) + '</td>' + 1679 '<td>' + ( '' === f.current ? '<span class="sbnfebr-ac-fiscal-empty">' + SB.esc( __( '(vazio)', 'sanbar-express-nfe-xml-import-br' ) ) + '</span>' : SB.esc( f.fmt( f.current ) ) ) + '</td>' + 1680 '</tr>'; 1681 } ); 1682 1683 var refs = []; 1684 if ( item.cfop ) { 1685 refs.push( 'CFOP ' + item.cfop ); 1686 } 1687 if ( item.cst_csosn ) { 1688 refs.push( 'CSOSN/CST ' + item.cst_csosn ); 1689 } 1690 if ( item.cbenef ) { 1691 refs.push( 'cBenef ' + item.cbenef ); 1692 } 1693 1694 var linkNote = targetId === Number( item.wc_product_id ) 1695 ? '' 1696 : '<div class="sbnfebr-ac-popup-note">' + SB.esc( __( 'Isso vincula este item ao produto encontrado antes de aplicar (ainda não estava vinculado).', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>'; 1697 1698 var body = linkNote + 1699 ( rows.length 1700 ? '<table class="sbnfebr-ac-fiscal-table">' + 1701 '<thead><tr><th></th>' + 1702 '<th>' + SB.esc( __( 'Campo', 'sanbar-express-nfe-xml-import-br' ) ) + '</th>' + 1703 '<th>' + SB.esc( __( 'Na nota', 'sanbar-express-nfe-xml-import-br' ) ) + '</th>' + 1704 '<th>' + SB.esc( __( 'No cadastro', 'sanbar-express-nfe-xml-import-br' ) ) + '</th>' + 1705 '</tr></thead>' + 1706 '<tbody>' + rows.join( '' ) + '</tbody>' + 1707 '</table>' 1708 : '<div class="sbnfebr-ac-popup-note">' + SB.esc( __( 'Esta nota não traz dado fiscal para enviar.', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>' ) + 1709 ( refs.length 1710 ? '<div class="sbnfebr-ac-popup-fields">' + SB.esc( __( 'Do fornecedor, só referência (não vão para o cadastro):', 'sanbar-express-nfe-xml-import-br' ) ) + ' ' + SB.esc( refs.join( ' · ' ) ) + '</div>' 1711 : '' ) + 1712 '<label class="sbnfebr-radio-line"><input type="checkbox" class="sbnfebr-ac-fiscal-prices-chk"> ' + SB.esc( __( 'Atualizar também custo, Calculadora de Preço e impostos', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 1713 '<div class="sbnfebr-ac-popup-warn sbnfebr-ac-fiscal-prices-warn" style="display:none">⚠ ' + SB.esc( __( 'A lista de impostos do produto será SUBSTITUÍDA pela desta nota — imposto adicionado à mão que não está nesta nota será perdido.', 'sanbar-express-nfe-xml-import-br' ) ) + '</div>'; 1714 1715 var footer = '<button type="button" class="sbnfebr-btn sbnfebr-ac-popup-cancel">' + SB.esc( __( 'Cancelar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1716 '<button type="button" class="sbnfebr-btn sbnfebr-btn--amber sbnfebr-ac-popup-submit">' + SB.esc( __( 'Enviar selecionados', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>'; 1717 1718 var popup = openActionPopup( '🧾', 'sbnfebr-ac-popup-icon--amber', __( 'Dados fiscais', 'sanbar-express-nfe-xml-import-br' ), body, footer, item.description ); 1719 popup.el.querySelector( '.sbnfebr-ac-popup' ).classList.add( 'sbnfebr-ac-popup--wide' ); 1720 1721 var pricesChk = popup.el.querySelector( '.sbnfebr-ac-fiscal-prices-chk' ); 1722 pricesChk.addEventListener( 'change', function () { 1723 popup.el.querySelector( '.sbnfebr-ac-fiscal-prices-warn' ).style.display = pricesChk.checked ? '' : 'none'; 1724 } ); 1725 1726 popup.el.querySelector( '.sbnfebr-ac-popup-cancel' ).addEventListener( 'click', popup.close ); 1727 popup.el.querySelector( '.sbnfebr-ac-popup-submit' ).addEventListener( 'click', function () { 1728 var chosen = Array.prototype.map.call( popup.el.querySelectorAll( '.sbnfebr-ac-fiscal-chk:checked' ), function ( c ) { return c.value; } ); 1729 var withPrices = pricesChk.checked; 1730 1731 if ( ! chosen.length && ! withPrices ) { 1732 SB.toast.error( __( 'Marque ao menos um campo para enviar.', 'sanbar-express-nfe-xml-import-br' ) ); 1733 return; 1734 } 1735 1736 var list = fields.filter( function ( f ) { return chosen.indexOf( f.key ) !== -1; } ).map( function ( f ) { 1737 return f.label + ': ' + ( '' === f.current ? '' : f.fmt( f.current ) + ' → ' ) + f.fmt( f.note ); 1738 } ); 1739 if ( withPrices ) { 1740 list.push( __( 'Custo, Calculadora de Preço e impostos', 'sanbar-express-nfe-xml-import-br' ) ); 1741 } 1742 1743 SB.confirm( 1744 __( 'Enviar estes dados para o cadastro do produto?', 'sanbar-express-nfe-xml-import-br' ), 1745 { danger: withPrices, confirmLabel: __( 'Enviar selecionados', 'sanbar-express-nfe-xml-import-br' ), list: list } 1746 ).then( function ( ok ) { 1747 if ( ! ok ) { 1748 return; 1749 } 1750 popup.close(); 1751 setBusy( modal, true ); 1752 callWithReassign( function ( reassign ) { 1753 return SB.api( 'items/' + item.id + '/sync', null, { method: 'POST', body: JSON.stringify( { product_id: targetId, reassign: reassign, fields: chosen, with_prices: withPrices } ) } ); 1754 } ) 1755 .then( function ( res ) { 1756 notifyLinked( item, res.product_id, false, __( 'Dados fiscais sincronizados', 'sanbar-express-nfe-xml-import-br' ) ); 1757 item.wc_product_id = res.product_id; 1758 item.match_product_id = null; 1759 setBusy( modal, false ); 1760 if ( modal ) { renderActionPanels( modal, item ); } 1761 } ) 1762 .catch( function ( e2 ) { 1763 setBusy( modal, false ); 1764 showError( modal, ( e2 && e2.message ) || __( 'Falha ao sincronizar dados fiscais.', 'sanbar-express-nfe-xml-import-br' ) ); 1765 } ); 1766 } ); 1767 } ); 1768 } 1769 1770 /** 1771 * Opens one of the 4 popups directly from a grid icon, bypassing the 1772 * full Action Modal. Passes `modal = null` — callees already handle 1773 * that (toast fallback, skip renderActionPanels). 1774 * 1775 * @param {Object} item 1776 * @param {string} key 'rascunho'|'estoque'|'preco'|'fiscal'. 1777 */ 1778 function quickAction( item, key ) { 1779 var hasProduct = !! Number( item.wc_product_id ); 1780 var hasMatch = ! hasProduct && !! item.match_product_id; 1781 var targetId = hasProduct ? Number( item.wc_product_id ) : ( hasMatch ? Number( item.match_product_id ) : 0 ); 1782 1783 if ( 'rascunho' === key ) { 1784 openRascunhoPopup( null, item, hasProduct, hasMatch, targetId, null ); 1785 return; 1786 } 1787 if ( 'estoque' === key && ! SB.is_plus ) { 1788 openLockedInfo( __( 'Plus permite somar ou definir o estoque direto a partir desta nota, mantendo o controle do que você já tem.', 'sanbar-express-nfe-xml-import-br' ) ); 1789 return; 1790 } 1791 if ( 'fiscal' === key && ! SB.is_plus ) { 1792 openLockedInfo( __( 'Plus preenche NCM, CEST, unidades, os campos da Calculadora de Preço e a lista de impostos automaticamente a partir desta nota.', 'sanbar-express-nfe-xml-import-br' ) ); 1793 return; 1794 } 1795 if ( ! targetId ) { 1796 showNeedProductHint( null, item ); 1797 return; 1798 } 1799 SB.api( 'products/' + targetId + '/snapshot', { exclude_item_id: item.id } ) 1800 .then( function ( snap ) { 1801 if ( 'estoque' === key ) { 1802 openEstoquePopup( null, item, targetId, snap ); 1803 } else if ( 'preco' === key ) { 1804 openPrecoPopup( null, item, targetId, snap ); 1805 } else if ( 'fiscal' === key ) { 1806 openFiscalPopup( null, item, targetId, snap ); 1807 } 1808 } ) 1809 .catch( function ( e ) { 1810 if ( isMissingProductError( e ) ) { 1811 handleMissingProduct( item, targetId, null ); 1812 openRascunhoPopup( null, item, false, false, 0, null ); 1813 return; 1814 } 1815 SB.toast.error( __( 'Falha ao carregar dados do produto.', 'sanbar-express-nfe-xml-import-br' ) ); 1816 } ); 1817 } 1818 1819 1820 // Snapshot key / item key / label, mirrors SYNC_FIELD_KEYS in PHP. 1821 // CSOSN/CST, CFOP and cBenef excluded on purpose — they belong to the 1822 // supplier's operation, so there is no valid "note vs product" comparison. 1823 var FISCAL_FIELD_MAP = [ 1824 { snap: 'ncm', item: 'ncm', label: 'NCM' }, 1825 { snap: 'cest', item: 'cest', label: 'CEST' }, 1826 { snap: 'origem', item: 'origem', label: __( 'Origem', 'sanbar-express-nfe-xml-import-br' ) }, 1827 { snap: 'u_com', item: 'unit', label: __( 'Unidade comercial', 'sanbar-express-nfe-xml-import-br' ) }, 1828 { snap: 'u_trib', item: 'unit_taxable', label: __( 'Unidade tributável', 'sanbar-express-nfe-xml-import-br' ) }, 1829 { snap: 'cclasstrib', item: 'cclasstrib', label: 'cClassTrib' }, 1830 { snap: 'ind_escala', item: 'ind_escala', label: __( 'Indicador de escala', 'sanbar-express-nfe-xml-import-br' ) }, 1831 { snap: 'cnpj_fabricante', item: 'cnpj_fabricante', label: __( 'CNPJ do fabricante', 'sanbar-express-nfe-xml-import-br' ) }, 1832 { snap: 'nfci', item: 'nfci', label: 'NFCI' } 1833 ]; 1834 1835 document.addEventListener( 'click', function ( e ) { 1836 // Grid action cell has 5 icons: "⋯" opens the full Action Modal, 1837 // the other 4 open the matching popup directly. 1838 var gicon = e.target.closest( '.sbnfebr-ac-gicon' ); 1839 if ( gicon ) { 1840 if ( 'overview' === gicon.dataset.key ) { 1841 document.dispatchEvent( new CustomEvent( 'sbnfebr:open-item-action', { detail: { itemId: gicon.dataset.itemId } } ) ); 1842 } else { 1843 SB.itemActions.quickAction( gicon.dataset.itemId, gicon.dataset.key ); 1844 } 1845 return; 1846 } 1847 1848 var btn = e.target.closest( '.sbnfebr-action-btn--draft' ); 1849 if ( ! btn ) { 1850 return; 1851 } 1852 1853 // Always opens the modal, even if already created (the "Open in 1854 // editor" button is inside it) — a direct click on the green icon 1855 // never jumps to the editor without going through the modal. 1856 document.dispatchEvent( new CustomEvent( 'sbnfebr:open-item-action', { detail: { itemId: btn.dataset.itemId } } ) ); 26 document.addEventListener( 'click', function ( event ) { 27 var action = event.target.closest( '.sbnfebr-ac-gicon, .sbnfebr-action-btn--draft' ); 28 if ( action ) { requestItem( action.dataset.itemId ); } 1857 29 } ); 1858 30 1859 // nfebr-main.js holds the full item (state.lastItems) — asks it to 1860 // resolve the item and hand it back to open the modal, instead of 1861 // duplicating state here. 1862 document.addEventListener( 'sbnfebr:resolve-item-action', function ( e ) { 1863 openModal( e.detail.item ); 31 document.addEventListener( 'sbnfebr:resolve-item-action', function ( event ) { 32 openWorkflowItem( event.detail.item ); 1864 33 } ); 1865 34 1866 // Same resolution pattern as above, for one of the 4 row icons (grid 1867 // or Registry Check) instead of the single icon that opens the full 1868 // modal. 1869 document.addEventListener( 'sbnfebr:resolve-quick-action', function ( e ) { 1870 quickAction( e.detail.item, e.detail.key ); 35 document.addEventListener( 'sbnfebr:resolve-quick-action', function ( event ) { 36 openWorkflowItem( event.detail.item ); 1871 37 } ); 1872 38 1873 document.addEventListener( 'keydown', function ( e ) { 1874 if ( 'Escape' === e.key ) { 1875 closeModal(); 1876 } 1877 } ); 1878 1879 window.SBNFEBR = Object.assign( SB, { 1880 itemActions: { 1881 // Dispatched by nfebr-grid.js/nfebr-registry-check.js; item 1882 // lives in state.lastItems (nfebr-main.js), so resolve there first. 1883 quickAction: function ( itemId, key ) { 1884 document.dispatchEvent( new CustomEvent( 'sbnfebr:quick-action', { detail: { itemId: itemId, key: key } } ) ); 1885 }, 1886 // Exposed for nfebr-registry-check.js to compute the same 1887 // "fiscal data outdated" signal without duplicating the 1888 // field list. 1889 FISCAL_FIELD_MAP: FISCAL_FIELD_MAP 1890 } 1891 } ); 39 SB.itemActions = { 40 quickAction: function ( itemId ) { requestItem( itemId ); } 41 }; 1892 42 })(); -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-library-notes.js
r3725460 r3782421 1 /* ================================================================2 nfebr-library-notes.js — "Manage Notes" modal (Supplier → Notes,3 deletion). Deleting a note never touches products already created.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 14 10 var _overlay = null; 15 11 var _notes = []; 16 // CNPJs of expanded supplier groups. Empty by default (all17 // collapsed); an active search forces everything open (see18 // renderList()) without touching this Set, so manual state19 12 // returns once the search is cleared. 20 13 var _expandedSuppliers = new Set(); … … 40 33 } 41 34 42 /**43 * Authorization protocol status badge (note's cStat). Empty when the44 * XML was a standalone <NFe> instead of a full <nfeProc> — expected,45 * not an error.46 *47 * @param {string} status cStat (e.g. '100', '101', '110').48 * @param {string} message xMotivo, used as the title for detail.49 * @return {string} Badge HTML, or an empty string if no protocol.50 */51 35 function protocolBadge( status, message ) { 52 36 if ( ! status ) { … … 68 52 } 69 53 70 /* ============================================================71 * Overlay principal — construção (uma vez)72 * ========================================================== */73 54 74 55 function ensureOverlay() { … … 120 101 } 121 102 122 /* ============================================================123 * Carregamento / lista, agrupada por fornecedor124 * ========================================================== */125 103 126 104 function loadNotes() { … … 165 143 166 144 var groups = groupBySupplier( filtered ); 167 // An active search forces all groups open so filtered results168 // aren't hidden inside a collapsed one; doesn't touch the169 // manual expansion state, just ignores it while `q` is set.170 145 var forceOpen = !! q; 171 146 … … 215 190 } 216 191 217 /* ============================================================218 * Destructive confirm — type "DELETE" to proceed.219 * ========================================================== */220 192 221 193 function openDeleteNote( noteId, noteLabel ) { -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-library-supplier.js
r3725460 r3782421 1 /* ================================================================2 nfebr-library-supplier.js — "Suppliers Library" modal, own REST3 endpoint (sbnfebr/v1/library/suppliers).4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 23 19 } 24 20 25 /* ============================================================26 * Overlay — construção (uma vez)27 * ========================================================== */28 21 29 22 function ensureOverlay() { … … 64 57 } 65 58 66 /**67 * Opens the Suppliers Library.68 *69 * @param {Object} [opts] {70 * focusId: number — jump directly to editing this supplier (by term ID).71 * focusDocument: string — focus the supplier with this CNPJ (resolved from72 * loaded data, since the grid only knows CNPJ, not73 * term ID). If none is registered yet, opens the74 * creation form with the document pre-filled.75 * }76 */77 59 function openLibrary( opts ) { 78 60 ensureOverlay(); … … 92 74 return; 93 75 } 94 // Supplier not registered yet — pulls the latest snapshot95 // captured from an imported note with this CNPJ (name, IE,96 // phone, address) so the user doesn't retype what the XML97 76 // already provided. 98 77 SB.api( 'suppliers/' + digits + '/snapshot' ) … … 115 94 } 116 95 117 /* ============================================================118 * Carregamento / lista119 * ========================================================== */120 96 121 97 function loadTerms() { … … 145 121 } 146 122 147 // Three groups: has an active note right now / registered with a WC148 // product catalog but no note (candidate for future GTIN match) /149 123 // registered with neither. 150 124 var withNote = []; … … 230 204 body.querySelectorAll( '.sb-library-row--filterable' ).forEach( function ( row ) { 231 205 row.addEventListener( 'click', function ( e ) { 232 // Name keeps its own dblclick-to-edit behavior — only the233 // row's empty space and its badge act as the filter target.234 206 if ( e.target.closest( '.sb-library-name, .sb-library-row-actions' ) ) { 235 207 return; … … 255 227 } 256 228 257 /* ============================================================258 * Formulário (compartilhado entre editar e criar)259 * ========================================================== */260 229 261 230 function field( cls, label, value, type, placeholder ) { … … 282 251 + field( 'sb-sup-f-city', __( 'Cidade', 'sanbar-express-nfe-xml-import-br' ), t.city ) 283 252 + field( 'sb-sup-f-state', __( 'Estado (UF)', 'sanbar-express-nfe-xml-import-br' ), t.state ) 284 // Nickname — alternative display name (e.g. note issued by a285 // legal entity name, product/brand commonly known by another286 // name). Deliberately not --wide: falls into the grid's right287 // column, same row as State. Keeps the same label+content288 // skeleton as the other fields (empty label of equal size) so289 // it inherits the same label+gap height as State, keeping the290 // checkbox+input row aligned with State's input. Input is291 // disabled when unchecked (toggled in the wire function, not292 253 // here — this only builds the initial HTML). 293 254 + '<div class="sb-library-sup-field sb-library-sup-field--nickname">' + … … 331 292 } 332 293 333 /**334 * Auto-suggests the Code field: 5 letters from the name + 5 digits335 * from the document. Stops updating once the user edits Code by hand.336 */337 294 function wireSupplierFormAutosuggest( container, initialCodeSuggested ) { 338 295 var nameInp = container.querySelector( '.sb-sup-f-name' ); … … 357 314 codeInp.addEventListener( 'input', function () { codeManuallyEdited = true; } ); 358 315 359 // Runs once on form open: pre-filled values are set directly via360 // HTML without firing "input", so without this Code would stay361 316 // empty until the user typed something. 362 317 updateSuggestion(); 363 318 } 364 319 365 /**366 * Ties the "Show nickname" checkbox to the nickname input's disabled367 * state — unchecked disables the input but keeps its saved value.368 */369 320 function wireNicknameToggle( container ) { 370 321 var checkbox = container.querySelector( '.sb-sup-f-use-nickname' ); -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-main.js
r3725460 r3782421 1 /* ================================================================2 nfebr-main.js — entry point: wires the toolbar to the grid.3 ================================================================ */4 1 (function () { 5 2 'use strict'; … … 34 31 lastItems: [], selected: new Set(), 35 32 page: 1, perPage: loadPerPage(), totalPages: 1, 36 // 'note' (default, 1 row per line item) | 'product' (1 row per37 33 // identity, aggregated — GET /items/by-product). 38 34 viewMode: 'note', 39 // Column sort (Supplier/Description only, see COLS/PRODUCT_COLS40 // in nfebr-grid.js). sortBy=null = default order (note date).41 35 sortBy: null, sortDir: 'asc' 42 36 }; 43 37 var searchTimer = null; 38 var ignoredCountRequest = 0; 44 39 45 40 function q( id ) { … … 50 45 var NOTICE_AUTOHIDE_MS = 5000; 51 46 52 /**53 * Icon glossary — icon + short phrase, grouped. "(Plus)" on lines54 * only active in Plus is informational text, not a feature switch.55 *56 * @return {Array} [{ group: string }|{ icon, text }]57 */58 47 function glossaryEntries() { 59 48 return [ 60 { group: __( 'Ícones de ação', 'sanbar-express-nfe-xml-import-br' ) }, 61 { icon: '⋯', text: __( 'Abre o painel de ação completo deste item.', 'sanbar-express-nfe-xml-import-br' ) }, 62 { icon: '🔀', text: __( 'Já vinculado a um produto.', 'sanbar-express-nfe-xml-import-br' ) }, 63 { icon: '🔗', text: __( 'Foi encontrado um produto compatível — vincule, ou crie um novo mesmo assim.', 'sanbar-express-nfe-xml-import-br' ) }, 64 { icon: '➕', text: __( 'Nenhuma correspondência encontrada — cria um novo produto.', 'sanbar-express-nfe-xml-import-br' ) }, 65 { icon: '❗', text: __( 'Correspondência encontrada por fornecedor + código (não por GTIN) — confira antes de vincular.', 'sanbar-express-nfe-xml-import-br' ) }, 66 { icon: '📦', text: __( 'Ação de estoque (Plus) — soma ou define a quantidade em estoque do produto.', 'sanbar-express-nfe-xml-import-br' ) }, 67 { icon: '🏷️', text: __( 'Ação de preço/fonte — atualiza o custo pago e/ou a fonte do GTIN·SKU.', 'sanbar-express-nfe-xml-import-br' ) }, 68 { icon: '🧾', text: __( 'Ação de dados fiscais (Plus) — sincroniza NCM, CEST, CST/CSOSN e impostos.', 'sanbar-express-nfe-xml-import-br' ) }, 49 { group: __( 'Botões da linha', 'sanbar-express-nfe-xml-import-br' ) }, 50 { icon: '⋯', text: __( 'Abre o painel do produto: preparar, conferir, enviar e ver o histórico.', 'sanbar-express-nfe-xml-import-br' ) }, 51 { icon: '→', text: __( 'Envia o item para a Conferência.', 'sanbar-express-nfe-xml-import-br' ) }, 52 { icon: '✓', text: __( 'Item já enviado. A cor mostra a situação: aprovado, com avisos, com correções ou sincronizado.', 'sanbar-express-nfe-xml-import-br' ) }, 53 { group: __( 'Vínculo com produto existente (Plus)', 'sanbar-express-nfe-xml-import-br' ) }, 54 { icon: '🔗', text: __( 'Produto vinculado ou possível vínculo encontrado. Abra para vincular, trocar ou desfazer.', 'sanbar-express-nfe-xml-import-br' ) }, 69 55 { icon: '🔒', text: __( 'Recurso exclusivo do Plus, não disponível nesta edição.', 'sanbar-express-nfe-xml-import-br' ) }, 70 { group: __( 'Estado do ícone', 'sanbar-express-nfe-xml-import-br' ) },71 { icon: '✳', text: __( 'Pulsando = há algo novo pra revisar ou aplicar.', 'sanbar-express-nfe-xml-import-br' ) },72 { icon: '◌', text: __( 'Apagado = nada novo no momento, mas continua clicável.', 'sanbar-express-nfe-xml-import-br' ) },73 56 { group: __( 'Histórico de preço', 'sanbar-express-nfe-xml-import-br' ) }, 74 57 { icon: '🕘', text: __( 'Cinza — sem variação de preço entre notas.', 'sanbar-express-nfe-xml-import-br' ) }, … … 115 98 els.notice.style.display = ''; 116 99 117 // Always auto-dismisses, even on error — same pattern as the118 // SanBar EXPress Sheet notification bar (sheet-notifications.js).119 100 noticeTimer = window.setTimeout( hideNotice, NOTICE_AUTOHIDE_MS ); 120 101 } 121 102 122 /**123 * Builds the "Open in Store Manager" action, if detectable — null124 * when the SM doesn't exist (SB.sm_admin_url empty), so the caller125 * simply doesn't offer the option.126 *127 * @param {number[]} productIds128 * @return {{label:string, onClick:Function}|null}129 */130 103 function buildOpenInSmAction( productIds ) { 131 var inIframe = window.parent !== window; 132 if ( ! inIframe && ! SB.sm_admin_url ) { 104 if ( ! SB.sm_admin_url ) { 133 105 return null; 134 106 } … … 136 108 label: __( 'Abrir no Store Manager', 'sanbar-express-nfe-xml-import-br' ), 137 109 onClick: function () { 138 if ( inIframe ) { 139 // The SM (iframe owner) listens for this and applies 140 // the ID filter on its own. 141 window.parent.postMessage( 142 { type: 'sbnfebr:products-created', product_ids: productIds }, 143 window.location.origin 144 ); 145 } else if ( SB.sm_admin_url ) { 146 // Standalone (outside the iframe) — new tab, with the 147 // ID filter already in the URL (the Sheet reads 148 // `sbesfw_ids` on load and applies it). 149 var sep = SB.sm_admin_url.indexOf( '?' ) !== -1 ? '&' : '?'; 150 window.open( SB.sm_admin_url + sep + 'sbesfw_ids=' + productIds.join( ',' ), '_blank' ); 151 } 110 var sep = SB.sm_admin_url.indexOf( '?' ) !== -1 ? '&' : '?'; 111 window.open( SB.sm_admin_url + sep + 'sbesfw_ids=' + productIds.join( ',' ), '_blank' ); 152 112 hideNotice(); 153 113 } … … 155 115 } 156 116 157 /** 158 * Fiscal Check tab (both Plus): opens it in the same tab (or the same Sheet modal), filtered to the products just created. 159 * 160 * @param {number[]} productIds 161 * @return {{label:string, onClick:Function}|null} 162 */ 163 function buildOpenInFcAction( productIds ) { 164 if ( ! SB.fc_url || ! productIds.length ) { 117 function buildOpenStandardEditorAction( products ) { 118 var urls = []; 119 ( products || [] ).forEach( function ( product ) { 120 var url = product && product.edit_url ? String( product.edit_url ) : ''; 121 if ( url && urls.indexOf( url ) === -1 ) { 122 urls.push( url ); 123 } 124 } ); 125 if ( ! urls.length ) { 165 126 return null; 166 127 } 167 128 return { 168 label: '🔎 ' + __( 'Conferir fiscal', 'sanbar-express-nfe-xml-import-br' ) + ' (' + productIds.length + ')', 129 label: 1 === urls.length 130 ? __( 'Abrir cadastro padrão', 'sanbar-express-nfe-xml-import-br' ) 131 : __( 'Abrir cadastros padrão', 'sanbar-express-nfe-xml-import-br' ) + ' (' + urls.length + ')', 169 132 onClick: function () { 170 window.location.href = SB.fc_url + '&sbfcbr_ids=' + productIds.join( ',' ); 133 urls.forEach( function ( url ) { window.open( url, '_blank' ); } ); 134 hideNotice(); 171 135 } 172 136 }; … … 178 142 } 179 143 180 /**181 * Notice with action buttons. Doesn't auto-dismiss — there's an182 * action to take, unlike the plain success/error notice.183 *184 * @param {string} message185 * @param {Array<{label:string, onClick:Function}>} actions186 */187 144 function showActionNotice( message, actions ) { 188 145 window.clearTimeout( noticeTimer ); … … 207 164 } 208 165 209 /**210 * Shows a progress bar inside the notice area — used during XML211 * upload (1 or several files).212 *213 * @param {number} current Current file (1-based).214 * @param {number} total Total files.215 */216 166 function showProgress( current, total ) { 217 167 window.clearTimeout( noticeTimer ); … … 224 174 } 225 175 226 /**227 * Reloads the grid with the current filter state.228 *229 * @param {boolean} [resetPage] Default true (resets page 1 + selection); pass false to preserve selection across pages.230 */231 176 function reloadItems( resetPage ) { 232 177 if ( false !== resetPage ) { … … 247 192 params.note_id = state.noteId; 248 193 } 249 // Mode/period also filter the per-product view; 'duplicates' and250 // 'ignored' are excluded (updateViewToggle() prevents selecting them).251 194 if ( state.mode ) { 252 195 params.mode = state.mode; … … 268 211 state.totalPages = res.total_pages || 1; 269 212 renderGrid(); 270 notifySelectionChanged(); 213 if ( SB.is_plus && 'function' === typeof notifySelectionChanged ) { 214 notifySelectionChanged(); 215 } 271 216 updatePaginationUI(); 272 273 // "Items" and "Unique products" always show their own true 274 // count, regardless of which view is active — neither stat 217 refreshIgnoredCount(); 218 275 219 // changes meaning when the view toggle changes. 276 220 var countParams = { count_only: 1 }; … … 313 257 314 258 if ( isProductView ) { 315 // get_items_by_product() doesn't compute price_variants/316 // gtin_supplier_count, so checkMatches() is skipped here.317 259 return; 318 260 } 319 261 320 // Runs on every page/filter change so a match against an321 // already-registered GTIN shows without a manual click.322 262 checkMatches(); 323 263 } ); 324 264 } 325 265 326 /**327 * Fetches ALL items matching the current filters, ignoring the328 * grid's page — caps at 500 and warns instead of locking up the329 * screen on a huge catalog.330 *331 * @return {Promise<{items: Array, truncated: boolean}>}332 */333 266 function fetchAllItemsForCheck() { 334 267 var CAP = 500; … … 373 306 } 374 307 375 /**376 * Updates the pagination controls' text/state — "◀ Page X of N ▶"377 * pattern.378 */379 308 function updatePaginationUI() { 380 309 if ( ! els.pageLabel ) { … … 386 315 } 387 316 388 /** 389 * Applies a product link/unlink to every item on screen sharing the 390 * same identity (GTIN crosses suppliers; supplier+code without GTIN 391 * doesn't). Local state sync only — the backend already wrote it. 392 * 393 * @param {Object} identity { gtin, supplierCnpj, productCode }. 394 * @param {number|null} productId Product to apply, or null to unlink. 395 * @param {boolean} hasFiscal See notifyLinked() in nfebr-item-actions.js. 396 * @param {Object[]} [list] Items to update; defaults to state.lastItems. 397 * The Registry check modal passes its own copy. 398 * @return {string[]} IDs of the updated items. 399 */ 317 function updateIgnoredDrawer( count ) { 318 var active = 'ignored' === state.mode; 319 if ( els.statIgnored && count !== undefined ) { 320 els.statIgnored.textContent = String( count ); 321 } 322 if ( ! els.btnIgnoredDrawer ) { 323 return; 324 } 325 els.btnIgnoredDrawer.classList.toggle( 'is-active', active ); 326 els.btnIgnoredDrawer.setAttribute( 'aria-pressed', active ? 'true' : 'false' ); 327 els.btnIgnoredDrawer.title = active 328 ? __( 'Voltar aos produtos visíveis', 'sanbar-express-nfe-xml-import-br' ) 329 : __( 'Ver produtos ocultos e restaurá-los individualmente', 'sanbar-express-nfe-xml-import-br' ); 330 } 331 332 function refreshIgnoredCount() { 333 if ( ! els.statIgnored ) { 334 return; 335 } 336 var request = ++ignoredCountRequest; 337 var params = { mode: 'ignored', count_only: 1 }; 338 if ( state.supplierCnpj ) { params.supplier_cnpj = state.supplierCnpj; } 339 if ( state.noteId ) { params.note_id = state.noteId; } 340 if ( state.search ) { params.search = state.search; } 341 updateIgnoredDrawer(); 342 SB.api( 'items', params ).then( function ( response ) { 343 if ( request === ignoredCountRequest ) { 344 updateIgnoredDrawer( Number( response.total || 0 ) ); 345 } 346 } ).catch( function () { 347 if ( request === ignoredCountRequest ) { 348 els.statIgnored.textContent = '—'; 349 } 350 } ); 351 } 352 400 353 function applyLinkToIdentity( identity, productId, hasFiscal, list ) { 401 354 var gtin = String( identity.gtin || '' ).trim().toUpperCase(); … … 415 368 it.match_product_name = null; 416 369 it.match_source = null; 417 // Only "upgrades" (never downgrades) — if the backend418 // already had fiscal data recorded, a link/sync without419 // fiscal (Lite) doesn't clear this local state. Mirrors the420 // item's own NCM (not just a truthy sentinel) so the grid's421 // stale-vs-synced comparison (linked_ncm === ncm) is correct422 370 // right after this sync, without a reload. 423 371 if ( hasFiscal ) { … … 435 383 SB.applyLinkToIdentity = applyLinkToIdentity; 436 384 437 /**438 * Clears every local reference (link or match candidate) to a product439 * that turned out not to exist anymore. Local state only — the backend440 * already cleared the link when it answered 404.441 *442 * @param {number} productId443 * @param {Object[]} [list] Defaults to state.lastItems.444 * @return {string[]} IDs of the updated items.445 */446 385 function clearMissingProduct( productId, list ) { 447 386 var touchedIds = []; … … 471 410 SB.clearMissingProduct = clearMissingProduct; 472 411 473 /**474 * Finds an item by id — first in the grid's current page475 * (state.lastItems), then in the Registry check modal, which loads up to476 * 500 items independently of the grid's pagination.477 *478 * @param {string|number} itemId479 * @return {Object|null}480 */481 412 function findItemById( itemId ) { 482 413 var id = String( itemId ); … … 488 419 } 489 420 490 /**491 * Temporary highlight (green, self-clearing) on the row(s) that492 * just changed (`.sbnfebr-row-just-linked`, see core.css).493 *494 * @param {string[]} itemIds495 */496 421 function flashRows( itemIds ) { 497 422 if ( ! itemIds || ! itemIds.length || ! els.tbody ) { … … 505 430 } 506 431 row.classList.remove( 'sbnfebr-row-just-linked' ); 507 // Force reflow — without this, removing+adding the class in508 432 // the same tick doesn't restart the CSS animation. 509 433 void row.offsetWidth; … … 515 439 } 516 440 517 /** 518 * Renders the grid from `state.lastItems` — separate from 519 * reloadItems() so it can re-render after merging checkMatches() 520 * results without hitting the REST /items endpoint again. 521 */ 441 var showOnlySelected = false; 442 522 443 function renderGrid() { 523 444 // "Show only selected" — local filter, doesn't touch 524 // state.lastItems itself (would otherwise lose the page's other525 445 // items when the filter is turned off). 526 446 var itemsToRender = showOnlySelected … … 537 457 } 538 458 539 /** 540 * Notifies the rest of the screen (toolbar) when the selection 541 * changes — listeners decide what to do (e.g. show/hide the bulk 542 * button). 543 */ 544 function notifySelectionChanged() { 545 document.dispatchEvent( new CustomEvent( 'sbnfebr:selection-changed', { 546 detail: { count: state.selected.size, ids: Array.from( state.selected ) } 547 } ) ); 548 } 549 550 /** 551 * Bulk "Create N as Draft(+)" button label adjusts to SB.is_plus. 552 */ 553 var bulkBtn = document.getElementById( 'sbnfebr-btn-bulk-draft-plus' ); 554 var bulkIgnoreBtn = document.getElementById( 'sbnfebr-btn-bulk-ignore' ); 555 var bulkShowSelBtn = document.getElementById( 'sbnfebr-btn-bulk-show-selected' ); 556 var bulkCopyBtn = document.getElementById( 'sbnfebr-btn-bulk-copy-codes' ); 557 var bulkClearBtn = document.getElementById( 'sbnfebr-btn-bulk-clear' ); 558 var showOnlySelected = false; 559 560 function updateBulkButton( count ) { 561 if ( bulkBtn ) { 562 if ( count > 0 ) { 563 var label = SB.is_plus 564 ? __( 'como Draft+', 'sanbar-express-nfe-xml-import-br' ) 565 : __( 'como Draft', 'sanbar-express-nfe-xml-import-br' ); 566 bulkBtn.textContent = '✓ ' + __( 'Criar', 'sanbar-express-nfe-xml-import-br' ) + ' ' + count + ' ' + label; 567 bulkBtn.style.display = ''; 568 } else { 569 bulkBtn.style.display = 'none'; 570 } 571 } 572 if ( bulkIgnoreBtn ) { 573 if ( count > 0 ) { 574 bulkIgnoreBtn.textContent = '👁 ' + __( 'Ignorar', 'sanbar-express-nfe-xml-import-br' ) + ' ' + count; 575 bulkIgnoreBtn.style.display = ''; 576 } else { 577 bulkIgnoreBtn.style.display = 'none'; 578 } 579 } 580 // "Show only selected" — instant local filter, no backend call. 581 // Only filters what's on the currently loaded page. 582 if ( bulkShowSelBtn ) { 583 if ( count > 0 ) { 584 bulkShowSelBtn.textContent = showOnlySelected 585 ? '↩ ' + __( 'Mostrar tudo', 'sanbar-express-nfe-xml-import-br' ) 586 : '👁 ' + __( 'Mostrar só selecionados', 'sanbar-express-nfe-xml-import-br' ); 587 bulkShowSelBtn.style.display = ''; 588 } else { 589 showOnlySelected = false; 590 bulkShowSelBtn.style.display = 'none'; 591 } 592 } 593 // "Copy codes" — code/GTIN of the checked items, plain text. 594 if ( bulkCopyBtn ) { 595 bulkCopyBtn.style.display = count > 0 ? '' : 'none'; 596 } 597 if ( bulkClearBtn ) { 598 bulkClearBtn.style.display = count > 0 ? '' : 'none'; 599 } 600 } 601 602 document.addEventListener( 'sbnfebr:selection-changed', function ( e ) { 603 updateBulkButton( e.detail.count ); 604 } ); 605 606 if ( bulkShowSelBtn ) { 607 bulkShowSelBtn.addEventListener( 'click', function () { 608 showOnlySelected = ! showOnlySelected; 609 updateBulkButton( state.selected.size ); 610 renderGrid(); 611 } ); 612 } 613 614 if ( bulkCopyBtn ) { 615 bulkCopyBtn.addEventListener( 'click', function () { 616 var ids = Array.from( state.selected ); 617 if ( ! ids.length ) { 459 460 if ( ! SB.is_plus ) { 461 document.addEventListener( 'click', function ( e ) { 462 var ignoredBtn = e.target.closest( '.sbnfebr-action-btn--ignored' ); 463 if ( ! ignoredBtn ) { 618 464 return; 619 465 } 620 621 function extractCodes( items ) { 622 // GTIN takes priority, falls back to product code. 623 // "SEM GTIN" is the sentinel for "no GTIN", treated as empty. 624 return items.map( function ( it ) { 625 var gtin = String( it.gtin || '' ).trim(); 626 var hasRealGtin = gtin && 'SEM GTIN' !== gtin.toUpperCase(); 627 return hasRealGtin ? gtin : ( it.product_code || '' ); 628 } ).filter( function ( c ) { return c; } ); 629 } 630 631 function copyText( text, count ) { 632 function done( ok ) { 633 if ( ok ) { 634 showNotice( count + ' ' + __( 'código(s) copiado(s) pra área de transferência.', 'sanbar-express-nfe-xml-import-br' ), 'success' ); 635 } else { 636 showNotice( __( 'Falha ao copiar — área de transferência indisponível.', 'sanbar-express-nfe-xml-import-br' ), 'error' ); 637 } 638 } 639 // Clipboard API requires a secure context (HTTPS/localhost); 640 // falls back to the legacy execCommand method otherwise. 641 if ( navigator.clipboard && navigator.clipboard.writeText && window.isSecureContext ) { 642 navigator.clipboard.writeText( text ).then( function () { done( true ); } ).catch( function () { done( false ); } ); 643 return; 644 } 645 var ta = document.createElement( 'textarea' ); 646 ta.value = text; 647 ta.style.position = 'fixed'; 648 ta.style.opacity = '0'; 649 document.body.appendChild( ta ); 650 ta.focus(); 651 ta.select(); 652 var copied = false; 653 try { 654 copied = document.execCommand( 'copy' ); 655 } catch ( e ) { /* copied fica false */ } 656 document.body.removeChild( ta ); 657 done( copied ); 658 } 659 660 // Fetches full data by ID — state.lastItems only holds the 661 // currently loaded page, so other-page selections need a fresh lookup. 662 bulkCopyBtn.disabled = true; 663 SB.api( 'items', { ids: ids.join( ',' ) } ) 664 .then( function ( res ) { 665 var codes = extractCodes( res.items || [] ); 666 copyText( codes.join( '\n' ), codes.length ); 667 } ) 668 .catch( function () { 669 showNotice( __( 'Falha ao carregar os itens selecionados.', 'sanbar-express-nfe-xml-import-br' ), 'error' ); 670 } ) 671 .finally( function () { 672 bulkCopyBtn.disabled = false; 466 var itemId = parseInt( ignoredBtn.dataset.itemId, 10 ); 467 SB.api( 'items/ignore', null, { method: 'POST', body: JSON.stringify( { item_ids: [ itemId ], ignored: false } ) } ) 468 .then( function () { reloadItems( false ); } ) 469 .catch( function ( e2 ) { 470 showNotice( ( e2 && e2.message ) || __( 'Falha ao reverter o item ignorado.', 'sanbar-express-nfe-xml-import-br' ), 'error' ); 673 471 } ); 674 472 } ); 675 473 } 676 474 677 if ( bulkIgnoreBtn ) {678 bulkIgnoreBtn.addEventListener( 'click', function () {679 var ids = Array.from( state.selected );680 if ( ! ids.length ) {681 return;682 }683 SB.confirm(684 __( 'Marcar', 'sanbar-express-nfe-xml-import-br' ) + ' ' + ids.length + ' '685 + __( 'item(ns) como ignorado(s)? Eles vão sumir da visão padrão (ainda acessíveis pelo filtro "Ignorados").', 'sanbar-express-nfe-xml-import-br' ),686 { confirmLabel: __( 'Ignorar', 'sanbar-express-nfe-xml-import-br' ) }687 ).then( function ( ok ) {688 if ( ! ok ) {689 return;690 }691 bulkIgnoreBtn.disabled = true;692 SB.api( 'items/ignore', null, { method: 'POST', body: JSON.stringify( { item_ids: ids, ignored: true } ) } )693 .then( function () {694 showNotice( ids.length + ' ' + __( 'item(ns) marcado(s) como ignorado(s).', 'sanbar-express-nfe-xml-import-br' ), 'success' );695 state.selected.clear();696 reloadItems( false );697 } )698 .catch( function ( e2 ) {699 showNotice( ( e2 && e2.message ) || __( 'Falha ao ignorar os itens.', 'sanbar-express-nfe-xml-import-br' ), 'error' );700 } )701 .finally( function () {702 bulkIgnoreBtn.disabled = false;703 } );704 } );705 } );706 }707 708 // Individual "👁" icon — only exists in the DOM when the item is709 // already ignored (see actionButtonsHTML in nfebr-grid.js), click undoes it.710 document.addEventListener( 'click', function ( e ) {711 var ignoredBtn = e.target.closest( '.sbnfebr-action-btn--ignored' );712 if ( ! ignoredBtn ) {713 return;714 }715 var itemId = parseInt( ignoredBtn.dataset.itemId, 10 );716 SB.api( 'items/ignore', null, { method: 'POST', body: JSON.stringify( { item_ids: [ itemId ], ignored: false } ) } )717 .then( function () {718 reloadItems( false );719 } )720 .catch( function ( e2 ) {721 showNotice( ( e2 && e2.message ) || __( 'Falha ao reverter o item ignorado.', 'sanbar-express-nfe-xml-import-br' ), 'error' );722 } );723 } );724 725 if ( bulkClearBtn ) {726 bulkClearBtn.addEventListener( 'click', function () {727 state.selected.clear();728 renderGrid();729 notifySelectionChanged();730 } );731 }732 733 if ( bulkBtn ) {734 bulkBtn.addEventListener( 'click', function () {735 var ids = Array.from( state.selected );736 if ( ! ids.length ) {737 return;738 }739 var msg = SB.is_plus740 ? __( 'Criar', 'sanbar-express-nfe-xml-import-br' ) + ' ' + ids.length + ' ' + __( 'produto(s) como Draft+ (identidade + fiscal + custo + impostos)?', 'sanbar-express-nfe-xml-import-br' )741 : __( 'Criar', 'sanbar-express-nfe-xml-import-br' ) + ' ' + ids.length + ' ' + __( 'produto(s) como Draft (só identidade)?', 'sanbar-express-nfe-xml-import-br' );742 var confirmOut = {};743 // Same 2 decisions as the individual modal (GTIN unit/box,744 // SKU source), applied to the whole batch at once instead of745 // each item's own default/heuristic.746 var bulkOptionsHtml =747 '<div class="sbnfebr-ia-gtinkind-row">' +748 '<span class="sbnfebr-ia-gtinkind-label">' + SB.esc( __( 'Este GTIN é:', 'sanbar-express-nfe-xml-import-br' ) ) + '</span>' +749 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-bulk-gtin-kind" value="unit" checked> ' + SB.esc( __( 'Unidade', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' +750 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-bulk-gtin-kind" value="box"> ' + SB.esc( __( 'Caixa', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' +751 '</div>' +752 '<div class="sbnfebr-ia-gtinkind-row sbnfebr-ia-sku-row">' +753 '<span class="sbnfebr-ia-gtinkind-label">' + SB.esc( __( 'Preencher SKU com:', 'sanbar-express-nfe-xml-import-br' ) ) + '</span>' +754 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-bulk-sku-source" value="none"> ' + SB.esc( __( "Não alterar", 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' +755 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-bulk-sku-source" value="gtin" checked> ' + SB.esc( __( 'GTIN', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' +756 '<label class="sbnfebr-radio-line"><input type="radio" name="sbnfebr-bulk-sku-source" value="product_code"> ' + SB.esc( __( 'Código do produto', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' +757 '</div>';758 SB.confirm( msg, {759 confirmLabel: __( 'Criar', 'sanbar-express-nfe-xml-import-br' ),760 checkbox: { label: __( 'Iniciais Maiúsculas (capitalizar nomes)', 'sanbar-express-nfe-xml-import-br' ), checked: true },761 extraHtml: bulkOptionsHtml,762 readExtra: function ( root, out ) {763 var gtinKindEl = root.querySelector( 'input[name="sbnfebr-bulk-gtin-kind"]:checked' );764 var skuSourceEl = root.querySelector( 'input[name="sbnfebr-bulk-sku-source"]:checked' );765 out.gtinKind = gtinKindEl ? gtinKindEl.value : 'unit';766 out.skuSource = skuSourceEl ? skuSourceEl.value : 'gtin';767 },768 out: confirmOut769 } ).then( function ( ok ) {770 if ( ! ok ) {771 return;772 }773 runBulkDraftPlus( ids, !! confirmOut.checked, confirmOut.gtinKind, confirmOut.skuSource );774 } );775 } );776 }777 778 function runBulkDraftPlus( ids, capitalize, gtinKind, skuSource ) {779 bulkBtn.disabled = true;780 // A single call processes the whole batch server-side, no real781 // per-item %; the toast stays indeterminate.782 var toast = SB.toast.start( __( 'Processando', 'sanbar-express-nfe-xml-import-br' ) );783 SB.api( 'items/draft-plus-bulk', null, { method: 'POST', body: JSON.stringify( { item_ids: ids, capitalize: !! capitalize, gtin_kind: gtinKind, sku_source: skuSource } ) } )784 .then( function ( res ) {785 var created = ( res.created || [] ).length;786 var failed = ( res.failed || [] ).length;787 state.selected.clear();788 reloadItems( false );789 790 var createdIds = ( res.created || [] ).map( function ( c ) { return c.product_id; } );791 792 // Inside the SM's iframe, applies the ID filter793 // automatically; outside it, offers it as a notice action instead.794 var inIframe = window.parent !== window;795 var fcAction = buildOpenInFcAction( createdIds );796 if ( inIframe && created > 0 && ! fcAction ) {797 window.parent.postMessage(798 { type: 'sbnfebr:products-created', product_ids: createdIds },799 window.location.origin800 );801 }802 803 // Surfaces when SKU=GTIN didn't apply for some items804 // (SKU already used by another product).805 var skuConflicts = ( res.created || [] ).filter( function ( c ) { return 'conflict' === c.sku_status; } ).length;806 807 var summary = created + ' ' + __( 'produto(s) criado(s).', 'sanbar-express-nfe-xml-import-br' )808 + ( failed ? ' ' + failed + ' ' + __( 'falhou(aram).', 'sanbar-express-nfe-xml-import-br' ) : '' )809 + ( skuConflicts ? ' ' + skuConflicts + ' ' + __( 'produto(s) não puderam usar o GTIN como SKU (já em uso).', 'sanbar-express-nfe-xml-import-br' ) : '' );810 811 if ( created > 0 && ( ! inIframe || fcAction ) ) {812 var noticeActions = [];813 if ( fcAction ) {814 noticeActions.push( fcAction );815 }816 var smAction = buildOpenInSmAction( createdIds );817 if ( smAction ) {818 noticeActions.push( smAction );819 }820 if ( noticeActions.length ) {821 showActionNotice( summary, noticeActions );822 return;823 }824 }825 showNotice( summary, ( failed || skuConflicts ) ? 'error' : 'success' );826 } )827 .catch( function ( e2 ) {828 showNotice( ( e2 && e2.message ) || __( 'Falha ao criar os produtos.', 'sanbar-express-nfe-xml-import-br' ), 'error' );829 } )830 .finally( function () {831 bulkBtn.disabled = false;832 toast.done();833 } );834 }835 836 document.addEventListener( 'change', function ( e ) {837 var rowCheck = e.target.closest( '.sbnfebr-row-check' );838 if ( rowCheck ) {839 // Always a string — item.id comes as a string from $wpdb;840 // mixed types would make Set has()/delete() silently fail.841 var id = String( rowCheck.dataset.itemId );842 if ( rowCheck.checked ) {843 state.selected.add( id );844 } else {845 state.selected.delete( id );846 }847 var checkedRow = rowCheck.closest( 'tr' );848 if ( checkedRow ) {849 checkedRow.classList.toggle( 'sbnfebr-row-selected', rowCheck.checked );850 }851 var selectAll = document.getElementById( 'sbnfebr-select-all' );852 if ( selectAll ) {853 selectAll.checked = state.lastItems.length > 0 && state.lastItems.every( function ( item ) {854 return state.selected.has( String( item.id ) );855 } );856 }857 notifySelectionChanged();858 return;859 }860 861 if ( 'sbnfebr-select-all' === e.target.id ) {862 if ( e.target.checked ) {863 state.lastItems.forEach( function ( item ) { state.selected.add( String( item.id ) ); } );864 } else {865 state.lastItems.forEach( function ( item ) { state.selected.delete( String( item.id ) ); } );866 }867 renderGrid();868 notifySelectionChanged();869 }870 } );871 872 /**873 * Checks unlinked items for a GTIN match (POST /match-gtin, both874 * editions), then a supplier+code fallback (POST /match-supplier-key,875 * Plus only — Lite has no UI to act on that match).876 */877 475 function checkMatches() { 878 476 var pending = state.lastItems.filter( function ( item ) { … … 892 490 item.match_product_name = match.name; 893 491 item.match_source = 'gtin'; 894 // 'unit'|'box' — which of the Sheet's GTIN fields matched.895 492 item.match_field = match.field || 'unit'; 896 493 } … … 932 529 } ) 933 530 .catch( function () { 934 // A check failure shouldn't lock up the screen — grid935 // stays in its previous state, no error notice (not an936 531 // explicit user action, just a silent refinement). 937 532 renderGrid(); … … 940 535 } 941 536 942 /**943 * Reloads the distinct supplier count (stat) — independent of the944 * active filter, it's a global count.945 */946 537 function reloadSupplierStat( suppliers ) { 947 538 els.statSuppliers.textContent = String( suppliers.length ); … … 963 554 } 964 555 965 /**966 * Populates the note select, filtered (or not) by supplier.967 */968 556 function reloadNotes() { 969 557 var params = state.supplierCnpj ? { supplier_cnpj: state.supplierCnpj } : {}; … … 977 565 } ).join( '' ); 978 566 979 // Preserves the selection if the note still exists, else980 // falls back to "All notes" — and keeps state.noteId in sync.981 567 var stillExists = notes.some( function ( n ) { return String( n.id ) === current; } ); 982 568 els.filterNote.value = stillExists ? current : ''; … … 992 578 } 993 579 994 /**995 * Uploads 1 XML file to the given endpoint (actual import or just a996 * preview) — same upload mechanics for both.997 *998 * @param {File} file .xml file.999 * @param {string} endpoint 'import' or 'import/preview'.1000 * @return {Promise<Object>} Resolves with the response body; rejects with an Error on failure.1001 */1002 580 function uploadTo( file, endpoint ) { 1003 581 var form = new FormData(); … … 1018 596 } 1019 597 1020 /**1021 * Uploads 1 XML file to the actual import endpoint (writes to the database).1022 *1023 * @param {File} file .xml file.1024 * @return {Promise<Object>} Resolves with { ok, fileName, result } or { ok:false, fileName, error }.1025 */1026 598 function uploadOne( file ) { 1027 599 return uploadTo( file, 'import' ) … … 1034 606 } 1035 607 1036 /**1037 * Toggles the "importing" visual state on the upload buttons —1038 * disables them (avoids a double click mid-processing) and swaps the1039 * text for a "n/total" counter when more than 1 file.1040 *1041 * @param {boolean} active true = importing, false = restore.1042 * @param {number} [current] Current file (1-based), only when active.1043 * @param {number} [total] Total files, only when active.1044 */1045 608 function setUploadingState( active, current, total ) { 1046 609 [ els.btnUpload, els.btnUploadEmpty ].forEach( function ( btn ) { … … 1065 628 } 1066 629 1067 /**1068 * Imports the files — called only after the user confirms the1069 * preview summary.1070 *1071 * @param {FileList|File[]} files Files already confirmed by the user.1072 */1073 630 function doImport( files ) { 1074 631 var list = Array.prototype.slice.call( files ); … … 1110 667 } 1111 668 1112 // Any failure shows in red, even with partial success —1113 // better to highlight what needs attention than hide it1114 669 // behind a green "all good" notice. 1115 670 showNotice( lines.join( ' ' ), errList.length ? 'error' : 'success' ); … … 1121 676 refreshAll(); 1122 677 1123 // Post-import review — nfebr-review-modal.js decides whether 1124 // to open; this only announces which notes just came in. 678 // Registry Check uses this to review new matches. 1125 679 var importedNoteIds = okList.map( function ( o ) { return o.result.note_id; } ).filter( Boolean ); 1126 680 if ( importedNoteIds.length ) { … … 1142 696 } 1143 697 1144 /**1145 * Shows the preview summary and only calls doImport() if the user1146 * explicitly confirms — never window.confirm(). The real warning is1147 * `owner_mismatch` (recipient vs. configured CNPJ, if set).1148 *1149 * @param {File} file File already validated by the preview.1150 * @param {Object} preview Response from POST import/preview.1151 */1152 698 function openImportConfirm( file, preview ) { 1153 699 var backdrop = document.createElement( 'div' ); 1154 700 backdrop.className = 'sbnfebr-danger-backdrop'; 1155 701 1156 // Same title+detail pattern as the item modal: SB.alertCard()1157 // instead of one sentence mixing everything together.1158 702 var warnings = ''; 1159 703 if ( preview.already_imported ) { … … 1175 719 + '</div>'; 1176 720 } 1177 // Doesn't block, just asks for an extra check before confirming1178 721 // (the actual blocking cap is much higher — see 1179 722 // SBNFEBR_Xml_Parser_Service::MAX_ITEMS). … … 1222 765 } 1223 766 1224 /**1225 * Upload entry point: always goes through the preview before writing1226 * anything — never imports directly on the first click.1227 *1228 * @param {File} file File selected in the input.1229 */1230 767 function startImportFlow( file ) { 1231 768 setUploadingState( true, 1, 1 ); … … 1247 784 } 1248 785 1249 /**1250 * One field of the "Company data" form — same visual layout as the1251 * Suppliers form (.sb-library-sup-field), reused here to stay1252 * visually identical.1253 *1254 * @param {string} cls Class to find the input later.1255 * @param {string} label Label.1256 * @param {string} value Current value.1257 * @return {string}1258 */1259 786 function companyField( cls, label, value ) { 1260 787 return '<div class="sb-library-sup-field"><label>' + SB.esc( label ) + '</label>' … … 1262 789 } 1263 790 1264 /**1265 * Small backdrop/modal skeleton shared by the settings sub-modals —1266 * same visual language as the rest of the plugin's popups.1267 *1268 * @param {string} titleText1269 * @param {string} bodyHtml1270 * @param {string} saveLabel1271 * @param {string} [extraClass] Extra class on the modal (e.g. narrower hub layout).1272 * @return {{backdrop: HTMLElement, close: Function}}1273 */1274 791 function openSettingsModal( titleText, bodyHtml, saveLabel, extraClass ) { 1275 792 var backdrop = document.createElement( 'div' ); … … 1285 802 '</div>'; 1286 803 document.body.appendChild( backdrop ); 804 document.body.classList.add( 'sbnfebr-settings-modal-open' ); 1287 805 1288 806 function close() { 1289 807 backdrop.remove(); 808 if ( ! document.querySelector( '.sbnfebr-configure-modal' ) ) { 809 document.body.classList.remove( 'sbnfebr-settings-modal-open' ); 810 } 1290 811 } 1291 812 backdrop.querySelector( '.sbnfebr-danger-cancel' ).addEventListener( 'click', close ); … … 1299 820 } 1300 821 1301 /**1302 * Shows a save error inline in a settings sub-modal, above the1303 * Cancel/Save row.1304 *1305 * @param {HTMLElement} backdrop1306 * @param {string} message1307 */1308 822 function showSettingsError( backdrop, message ) { 1309 823 var existing = backdrop.querySelector( '.sbnfebr-danger-error' ); … … 1317 831 } 1318 832 1319 /** 1320 * "Configure" — small hub with one button per settings group, so the 1321 * initial modal stays short as more settings groups get added. 1322 */ 833 function formatSettingsCnpj( value ) { 834 var digits = String( value || '' ).replace( /\D/g, '' ).slice( 0, 14 ); 835 return 14 === digits.length 836 ? digits.replace( /^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/, '$1.$2.$3/$4-$5' ) 837 : digits; 838 } 839 840 function settingsCertificateHtml( status ) { 841 status = status || {}; 842 if ( 'vault' === status.source ) { 843 var expired = !! status.expired; 844 return '<div class="sbnfebr-settings-block">' + 845 '<div class="sbnfebr-settings-block-head"><strong>' + SB.esc( __( 'Certificado digital A1', 'sanbar-express-nfe-xml-import-br' ) ) + '</strong><span class="sbnfebr-settings-tag ' + ( expired ? 'is-warning' : 'is-ok' ) + '">' + SB.esc( expired ? __( 'Vencido', 'sanbar-express-nfe-xml-import-br' ) : __( 'Disponível', 'sanbar-express-nfe-xml-import-br' ) ) + '</span></div>' + 846 '<div class="sbnfebr-settings-cert ' + ( expired ? 'is-warning' : 'is-ok' ) + '"><span class="dashicons dashicons-' + ( expired ? 'warning' : 'yes-alt' ) + '"></span><div><b>' + SB.esc( status.razao_social || status.cnpj || __( 'Certificado A1', 'sanbar-express-nfe-xml-import-br' ) ) + '</b><small>' + SB.esc( ( status.cnpj ? __( 'CNPJ', 'sanbar-express-nfe-xml-import-br' ) + ' ' + formatSettingsCnpj( status.cnpj ) + ' · ' : '' ) + ( status.valido_ate ? __( 'válido até', 'sanbar-express-nfe-xml-import-br' ) + ' ' + status.valido_ate : '' ) ) + '</small></div></div>' + 847 '<p class="sbnfebr-settings-note">' + SB.esc( __( 'Encontrado no cofre compartilhado. O mesmo certificado atende o XML Import-BR e o PDV.', 'sanbar-express-nfe-xml-import-br' ) ) + '</p>' + 848 '</div>'; 849 } 850 851 var reason = status.unreadable 852 ? __( 'O cofre existe, mas não pôde ser aberto. Envie o certificado novamente.', 'sanbar-express-nfe-xml-import-br' ) 853 : __( 'Se houver certificado no cofre do PDV, ele aparecerá aqui automaticamente.', 'sanbar-express-nfe-xml-import-br' ); 854 var missing = ( status.missing_ext || [] ).length 855 ? '<p class="sbnfebr-settings-warning">' + SB.esc( __( 'A hospedagem precisa ativar:', 'sanbar-express-nfe-xml-import-br' ) + ' ' + status.missing_ext.join( ', ' ) ) + '</p>' 856 : ''; 857 var upload = SB.can_manage && status.can_upload 858 ? '<label class="sbnfebr-settings-upload"><input type="file" accept=".pfx,.p12" data-settings-cert-file><span class="dashicons dashicons-media-archive"></span><span><b>' + SB.esc( __( 'Selecionar certificado', 'sanbar-express-nfe-xml-import-br' ) ) + '</b><small>' + SB.esc( __( 'Arquivo .pfx ou .p12', 'sanbar-express-nfe-xml-import-br' ) ) + '</small></span></label>' + 859 '<label class="sbnfebr-settings-field"><span>' + SB.esc( __( 'Senha do certificado', 'sanbar-express-nfe-xml-import-br' ) ) + '</span><input type="password" autocomplete="new-password" placeholder="' + SB.esc( __( 'Digite a senha', 'sanbar-express-nfe-xml-import-br' ) ) + '" data-settings-cert-pass></label>' + 860 '<button type="button" class="sbnfebr-btn sbnfebr-btn--blue" data-settings-cert-upload>' + SB.esc( __( 'Validar e guardar', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' 861 : ''; 862 863 return '<fieldset class="sbnfebr-settings-block sbnfebr-settings-fieldset"><legend><span>2</span>' + SB.esc( __( 'Adicione o certificado A1', 'sanbar-express-nfe-xml-import-br' ) ) + '</legend>' + 864 '<p class="sbnfebr-settings-note">' + SB.esc( reason ) + '</p>' + missing + upload + 865 '<p class="sbnfebr-settings-security"><span class="dashicons dashicons-lock"></span>' + SB.esc( __( 'Arquivo e senha ficam criptografados no cofre compartilhado e nunca são exibidos.', 'sanbar-express-nfe-xml-import-br' ) ) + '</p>' + 866 '</fieldset>'; 867 } 868 869 function settingsTablesHtml( tables ) { 870 var ncm = tables && tables.ncm; 871 var ncmText = ncm && ncm.count 872 ? ncm.count + ' ' + __( 'códigos disponíveis', 'sanbar-express-nfe-xml-import-br' ) 873 : __( 'Ainda não baixada', 'sanbar-express-nfe-xml-import-br' ); 874 var state = ncm ? 'is-ok' : 'is-warning'; 875 return '<div class="sbnfebr-settings-block">' + 876 '<div class="sbnfebr-settings-block-head"><strong>' + SB.esc( __( 'Tabelas fiscais', 'sanbar-express-nfe-xml-import-br' ) ) + '</strong><span class="sbnfebr-settings-tag ' + state + '">' + SB.esc( ncm ? __( 'Disponíveis', 'sanbar-express-nfe-xml-import-br' ) : __( 'Requer atualização', 'sanbar-express-nfe-xml-import-br' ) ) + '</span></div>' + 877 '<div class="sbnfebr-settings-table-status"><span><b>NCM</b><small>' + SB.esc( ncmText ) + '</small></span><span><b>CEST</b><small>' + SB.esc( ( tables && tables.cest_count ? tables.cest_count + ' ' + __( 'códigos incluídos', 'sanbar-express-nfe-xml-import-br' ) : __( 'Incluída no plugin', 'sanbar-express-nfe-xml-import-br' ) ) ) + '</small></span></div>' + 878 ( tables && tables.can_update ? '<button type="button" class="sbnfebr-btn" data-settings-update-ncm><span class="dashicons dashicons-update"></span>' + SB.esc( __( 'Atualizar NCM agora', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' : '' ) + 879 '</div>'; 880 } 881 1323 882 function openConfigure() { 1324 var modal = openSettingsModal( 1325 __( 'Configurar', 'sanbar-express-nfe-xml-import-br' ), 1326 '<div class="sbnfebr-configure-hub">' + 1327 '<button type="button" class="sbnfebr-btn sbnfebr-configure-hub-btn" data-target="company">🏢 ' + SB.esc( __( 'Dados da empresa', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1328 '<button type="button" class="sbnfebr-btn sbnfebr-configure-hub-btn" data-target="errorlog">🪵 ' + SB.esc( __( 'Log de erros', 'sanbar-express-nfe-xml-import-br' ) ) + '</button>' + 1329 '</div>', 1330 '', 1331 'sbnfebr-configure-modal--hub' 1332 ); 1333 // Hub has no Save button of its own — each option opens its own 1334 // modal with its own Save. 1335 modal.backdrop.querySelector( '.sbnfebr-settings-save' ).style.display = 'none'; 1336 1337 modal.backdrop.querySelectorAll( '.sbnfebr-configure-hub-btn' ).forEach( function ( btn ) { 1338 btn.addEventListener( 'click', function () { 1339 modal.close(); 1340 if ( 'company' === btn.dataset.target ) { 1341 openCompanyDataModal(); 1342 } else { 1343 openErrorLogSettingsModal(); 1344 } 1345 } ); 1346 } ); 1347 } 1348 1349 /** 1350 * Company data — only the CNPJ is actually used by this plugin (the 1351 * import mismatch warning). No tax regime field here — which taxes 1352 * count as cost is decided in the Sheet's Library → Taxes/Fees, 1353 * not by a regime setting on the profile. 1354 */ 1355 /** Regime tributário lido do NF-e PDV — HTML pro rodapé, só leitura. */ 883 Promise.all( [ 884 SB.api( 'settings' ), 885 SB.api( 'workflow/fiscal/regime' ), 886 SB.api( 'workflow/fiscal/tables' ), 887 SB.can_manage ? SB.api( 'workflow/certificate' ) : Promise.resolve( null ) 888 ] ).then( function ( response ) { 889 var settings = response[0] || {}; 890 var regime = response[1] || {}; 891 var tables = response[2] || {}; 892 var certificate = response[3] || {}; 893 var pdv = 'pdv' === regime.source; 894 var ready = regime.supported && 'vault' === certificate.source && ! certificate.expired && !! tables.ncm; 895 var regimeHtml = pdv 896 ? '<div class="sbnfebr-settings-block"><div class="sbnfebr-settings-block-head"><strong>' + SB.esc( __( 'Regime tributário', 'sanbar-express-nfe-xml-import-br' ) ) + '</strong><span class="sbnfebr-settings-tag is-linked">' + SB.esc( __( 'NF-e & PDV', 'sanbar-express-nfe-xml-import-br' ) ) + '</span></div><div class="sbnfebr-settings-value"><b>' + SB.esc( regime.label ) + '</b><span>' + SB.esc( __( 'Produtos conferidos para CRT', 'sanbar-express-nfe-xml-import-br' ) + ' ' + regime.crt + '.' ) + '</span></div><p class="sbnfebr-settings-note">' + SB.esc( __( 'O regime vem do PDV e fica somente para leitura aqui.', 'sanbar-express-nfe-xml-import-br' ) ) + '</p></div>' 897 : '<fieldset class="sbnfebr-settings-block sbnfebr-settings-fieldset"><legend><span>1</span>' + SB.esc( __( 'Qual é o regime da loja?', 'sanbar-express-nfe-xml-import-br' ) ) + '</legend><label class="sbnfebr-settings-choice"><input type="radio" name="sbnfebr-settings-regime" value="crt_4"' + ( 'crt_4' === regime.key ? ' checked' : '' ) + '><span><b>MEI</b><small>' + SB.esc( __( 'Microempreendedor Individual · CRT 4', 'sanbar-express-nfe-xml-import-br' ) ) + '</small></span></label><label class="sbnfebr-settings-choice"><input type="radio" name="sbnfebr-settings-regime" value="crt_1"' + ( 'crt_1' === regime.key ? ' checked' : '' ) + '><span><b>' + SB.esc( __( 'Simples Nacional', 'sanbar-express-nfe-xml-import-br' ) ) + '</b><small>' + SB.esc( __( 'Empresas optantes pelo Simples · CRT 1', 'sanbar-express-nfe-xml-import-br' ) ) + '</small></span></label></fieldset>'; 898 var body = '<div class="sbnfebr-settings-screen-body"><div class="sbnfebr-settings-heading"><div><h2>' + SB.esc( __( 'Configurações', 'sanbar-express-nfe-xml-import-br' ) ) + '</h2><p>' + SB.esc( __( 'O necessário para conferir notas e consultar dados oficiais.', 'sanbar-express-nfe-xml-import-br' ) ) + '</p></div><span class="sbnfebr-settings-summary ' + ( ready ? 'is-ok' : 'is-warning' ) + '"><span class="dashicons dashicons-' + ( ready ? 'yes-alt' : 'warning' ) + '"></span>' + SB.esc( ready ? __( 'Tudo pronto', 'sanbar-express-nfe-xml-import-br' ) : __( 'Requer atenção', 'sanbar-express-nfe-xml-import-br' ) ) + '</span></div><div class="sbnfebr-settings-layout"><section class="sbnfebr-settings-section"><div class="sbnfebr-settings-section-title"><span class="dashicons dashicons-shield"></span><div><h3>' + SB.esc( __( 'Fiscal e consulta oficial', 'sanbar-express-nfe-xml-import-br' ) ) + '</h3><p>' + SB.esc( pdv ? __( 'Regime, certificado e tabelas usadas na conferência.', 'sanbar-express-nfe-xml-import-br' ) : __( 'Sem PDV configurado, estas escolhas ficam salvas no XML Import-BR.', 'sanbar-express-nfe-xml-import-br' ) ) + '</p></div></div>' + regimeHtml + settingsCertificateHtml( certificate ) + settingsTablesHtml( tables ) + '</section><section class="sbnfebr-settings-section"><div class="sbnfebr-settings-section-title"><span class="dashicons dashicons-building"></span><div><h3>' + SB.esc( __( 'Identificação da loja', 'sanbar-express-nfe-xml-import-br' ) ) + '</h3><p>' + SB.esc( __( 'Evita importar por engano uma nota emitida para outro CNPJ.', 'sanbar-express-nfe-xml-import-br' ) ) + '</p></div></div><label class="sbnfebr-settings-field"><span>' + SB.esc( __( 'CNPJ da loja', 'sanbar-express-nfe-xml-import-br' ) ) + '</span><input type="text" inputmode="numeric" maxlength="18" value="' + SB.esc( formatSettingsCnpj( settings.company && settings.company.document ) ) + '" placeholder="00.000.000/0000-00" data-settings-cnpj></label><div class="sbnfebr-settings-shared"><span class="dashicons dashicons-info"></span><span>' + SB.esc( __( 'Nome, endereço e contato continuam compartilhados com o Store Manager, mas não precisam ser editados nesta tela.', 'sanbar-express-nfe-xml-import-br' ) ) + '</span></div></section></div></div>'; 899 var modal = openSettingsModal( __( 'XML Import-BR', 'sanbar-express-nfe-xml-import-br' ), body, __( 'Salvar alterações', 'sanbar-express-nfe-xml-import-br' ), 'sbnfebr-settings-screen' ); 900 var backdrop = modal.backdrop; 901 backdrop.querySelector( '.sbnfebr-danger-cancel' ).textContent = __( 'Fechar', 'sanbar-express-nfe-xml-import-br' ); 902 903 var cnpjInput = backdrop.querySelector( '[data-settings-cnpj]' ); 904 cnpjInput.addEventListener( 'input', function () { 905 cnpjInput.value = formatSettingsCnpj( cnpjInput.value ); 906 } ); 907 908 var updateNcm = backdrop.querySelector( '[data-settings-update-ncm]' ); 909 if ( updateNcm ) { 910 updateNcm.addEventListener( 'click', function () { 911 updateNcm.disabled = true; 912 updateNcm.textContent = __( 'Atualizando…', 'sanbar-express-nfe-xml-import-br' ); 913 SB.api( 'workflow/fiscal/tables', null, { method: 'POST', body: '{}' } ).then( function () { 914 modal.close(); 915 showNotice( __( 'Tabela NCM atualizada.', 'sanbar-express-nfe-xml-import-br' ), 'success' ); 916 openConfigure(); 917 } ).catch( function ( error ) { 918 updateNcm.disabled = false; 919 updateNcm.textContent = __( 'Atualizar NCM agora', 'sanbar-express-nfe-xml-import-br' ); 920 showSettingsError( backdrop, error.message ); 921 } ); 922 } ); 923 } 924 925 var certUpload = backdrop.querySelector( '[data-settings-cert-upload]' ); 926 if ( certUpload ) { 927 certUpload.addEventListener( 'click', function () { 928 var file = backdrop.querySelector( '[data-settings-cert-file]' ).files[0]; 929 var password = backdrop.querySelector( '[data-settings-cert-pass]' ).value; 930 if ( ! file || ! password ) { 931 showSettingsError( backdrop, __( 'Selecione o certificado e informe a senha.', 'sanbar-express-nfe-xml-import-br' ) ); 932 return; 933 } 934 var form = new FormData(); 935 form.append( 'arquivo', file ); 936 form.append( 'senha', password ); 937 certUpload.disabled = true; 938 SB.api( 'workflow/certificate', null, { method: 'POST', body: form } ).then( function () { 939 modal.close(); 940 showNotice( __( 'Certificado salvo no cofre compartilhado.', 'sanbar-express-nfe-xml-import-br' ), 'success' ); 941 openConfigure(); 942 } ).catch( function ( error ) { 943 certUpload.disabled = false; 944 showSettingsError( backdrop, error.message ); 945 } ); 946 } ); 947 } 948 949 backdrop.querySelector( '.sbnfebr-settings-save' ).addEventListener( 'click', function ( event ) { 950 var documentDigits = cnpjInput.value.replace( /\D/g, '' ); 951 if ( documentDigits && 14 !== documentDigits.length ) { 952 showSettingsError( backdrop, __( 'O CNPJ precisa ter 14 dígitos.', 'sanbar-express-nfe-xml-import-br' ) ); 953 return; 954 } 955 var selectedRegime = backdrop.querySelector( '[name="sbnfebr-settings-regime"]:checked' ); 956 if ( ! pdv ) { 957 if ( ! selectedRegime ) { 958 showSettingsError( backdrop, __( 'Selecione MEI ou Simples Nacional.', 'sanbar-express-nfe-xml-import-br' ) ); 959 return; 960 } 961 } 962 var company = Object.assign( {}, settings.company || {}, { document: documentDigits } ); 963 var requests = [ SB.api( 'settings', null, { method: 'POST', body: JSON.stringify( { company: company } ) } ) ]; 964 if ( ! pdv ) { 965 requests.push( SB.api( 'workflow/fiscal/regime', null, { method: 'POST', body: JSON.stringify( { regime: selectedRegime.value } ) } ) ); 966 } 967 event.currentTarget.disabled = true; 968 Promise.all( requests ).then( function () { 969 modal.close(); 970 showNotice( __( 'Configurações salvas.', 'sanbar-express-nfe-xml-import-br' ), 'success' ); 971 } ).catch( function ( error ) { 972 event.currentTarget.disabled = false; 973 showSettingsError( backdrop, error.message ); 974 } ); 975 } ); 976 } ).catch( function ( error ) { 977 showNotice( ( error && error.message ) || __( 'Não foi possível abrir as configurações.', 'sanbar-express-nfe-xml-import-br' ), 'error' ); 978 } ); 979 } 980 1356 981 function companyRegimeBadgeHtml( taxRegime ) { 1357 982 var tr = taxRegime || { configured: false, label: '' }; … … 1363 988 } 1364 989 1365 function openCompanyDataModal() {1366 SB.api( 'settings' ).then( function ( settings ) {1367 var company = ( settings && settings.company ) || {};1368 1369 var body =1370 '<p class="sbnfebr-configure-hint">' + SB.esc( __( 'Usado pra avisar quando uma nota importada não foi emitida pra você.', 'sanbar-express-nfe-xml-import-br' ) ) + '</p>' +1371 '<div class="sb-library-sup-panel sbnfebr-configure-grid">' +1372 companyField( 'sbnfebr-cf-name', __( 'Razão social', 'sanbar-express-nfe-xml-import-br' ), company.name ) +1373 companyField( 'sbnfebr-cf-fantasy', __( 'Nome fantasia', 'sanbar-express-nfe-xml-import-br' ), company.fantasy_name ) +1374 companyField( 'sbnfebr-cf-document', __( 'CNPJ', 'sanbar-express-nfe-xml-import-br' ), company.document ) +1375 companyField( 'sbnfebr-cf-ie', __( 'Inscrição Estadual (IE)', 'sanbar-express-nfe-xml-import-br' ), company.ie ) +1376 companyField( 'sbnfebr-cf-phone', __( 'Telefone', 'sanbar-express-nfe-xml-import-br' ), company.phone ) +1377 companyField( 'sbnfebr-cf-email', __( 'E-mail', 'sanbar-express-nfe-xml-import-br' ), company.email ) +1378 companyField( 'sbnfebr-cf-site', __( 'Site', 'sanbar-express-nfe-xml-import-br' ), company.site ) +1379 companyField( 'sbnfebr-cf-cep', __( 'CEP', 'sanbar-express-nfe-xml-import-br' ), company.cep ) +1380 companyField( 'sbnfebr-cf-street', __( 'Logradouro', 'sanbar-express-nfe-xml-import-br' ), company.street ) +1381 companyField( 'sbnfebr-cf-number', __( 'Número', 'sanbar-express-nfe-xml-import-br' ), company.number ) +1382 companyField( 'sbnfebr-cf-complement', __( 'Complemento', 'sanbar-express-nfe-xml-import-br' ), company.complement ) +1383 companyField( 'sbnfebr-cf-district', __( 'Bairro', 'sanbar-express-nfe-xml-import-br' ), company.district ) +1384 companyField( 'sbnfebr-cf-city', __( 'Cidade', 'sanbar-express-nfe-xml-import-br' ), company.city ) +1385 companyField( 'sbnfebr-cf-state', __( 'Estado (UF)', 'sanbar-express-nfe-xml-import-br' ), company.state ) +1386 '</div>' +1387 companyRegimeBadgeHtml( settings && settings.tax_regime );1388 1389 var modal = openSettingsModal( __( 'Dados da empresa', 'sanbar-express-nfe-xml-import-br' ), body, __( 'Salvar', 'sanbar-express-nfe-xml-import-br' ) );1390 var backdrop = modal.backdrop;1391 1392 backdrop.querySelector( '.sbnfebr-settings-save' ).addEventListener( 'click', function () {1393 var get = function ( cls ) {1394 var el = backdrop.querySelector( cls );1395 return el ? el.value.trim() : '';1396 };1397 1398 var payload = {1399 company: {1400 name: get( '.sbnfebr-cf-name' ),1401 fantasy_name: get( '.sbnfebr-cf-fantasy' ),1402 document: get( '.sbnfebr-cf-document' ),1403 ie: get( '.sbnfebr-cf-ie' ),1404 phone: get( '.sbnfebr-cf-phone' ),1405 email: get( '.sbnfebr-cf-email' ),1406 site: get( '.sbnfebr-cf-site' ),1407 cep: get( '.sbnfebr-cf-cep' ),1408 street: get( '.sbnfebr-cf-street' ),1409 number: get( '.sbnfebr-cf-number' ),1410 complement: get( '.sbnfebr-cf-complement' ),1411 district: get( '.sbnfebr-cf-district' ),1412 city: get( '.sbnfebr-cf-city' ),1413 state: get( '.sbnfebr-cf-state' )1414 }1415 };1416 1417 SB.api( 'settings', null, { method: 'POST', body: JSON.stringify( payload ) } )1418 .then( function () {1419 modal.close();1420 showNotice( __( 'Configurações salvas.', 'sanbar-express-nfe-xml-import-br' ), 'success' );1421 } )1422 .catch( function ( e ) {1423 showSettingsError( backdrop, ( e && e.message ) || __( 'Falha ao salvar as configurações.', 'sanbar-express-nfe-xml-import-br' ) );1424 } );1425 } );1426 } );1427 }1428 1429 990 /** 1430 991 * Error log verbosity level. 1431 992 */ 1432 function openErrorLogSettingsModal() { 1433 SB.api( 'settings' ).then( function ( settings ) { 1434 var body = 1435 '<div class="sbnfebr-danger-confirm">' + 1436 '<label>' + SB.esc( __( 'Nível:', 'sanbar-express-nfe-xml-import-br' ) ) + '</label>' + 1437 '<select class="sbnfebr-settings-loglevel">' + 1438 '<option value="all">' + SB.esc( __( 'Todos os erros (recomendado em teste)', 'sanbar-express-nfe-xml-import-br' ) ) + '</option>' + 1439 '<option value="errors_only">' + SB.esc( __( 'Só falhas reais (recomendado em uso normal)', 'sanbar-express-nfe-xml-import-br' ) ) + '</option>' + 1440 '</select>' + 1441 '</div>'; 1442 1443 var modal = openSettingsModal( __( 'Log de erros', 'sanbar-express-nfe-xml-import-br' ), body, __( 'Salvar', 'sanbar-express-nfe-xml-import-br' ) ); 1444 var backdrop = modal.backdrop; 1445 1446 var levelSelect = backdrop.querySelector( '.sbnfebr-settings-loglevel' ); 1447 levelSelect.value = settings && 'errors_only' === settings.error_log_level ? 'errors_only' : 'all'; 1448 1449 backdrop.querySelector( '.sbnfebr-settings-save' ).addEventListener( 'click', function () { 1450 SB.api( 'settings', null, { method: 'POST', body: JSON.stringify( { error_log_level: levelSelect.value } ) } ) 1451 .then( function () { 1452 modal.close(); 1453 showNotice( __( 'Configurações salvas.', 'sanbar-express-nfe-xml-import-br' ), 'success' ); 1454 } ) 1455 .catch( function ( e ) { 1456 showSettingsError( backdrop, ( e && e.message ) || __( 'Falha ao salvar as configurações.', 'sanbar-express-nfe-xml-import-br' ) ); 1457 } ); 1458 } ); 1459 } ); 1460 } 1461 1462 /** 1463 * Checks whether the selected supplier is registered in the Library 1464 * and paints the icon accordingly: green = registered, red = not yet. 1465 */ 993 1466 994 function refreshSupplierInfoBtn() { 1467 995 if ( ! els.btnSupplierInfo ) { … … 1502 1030 } 1503 1031 1504 // After creating/editing/removing in the modal, the "!" icon's1505 1032 // status may have changed — rechecks on close. 1506 1033 document.addEventListener( 'sbnfebr:library-closed', refreshSupplierInfoBtn ); 1507 1034 1508 // "🔎" in the Suppliers Library — jumps the main grid to this1509 // supplier's items. Only offered for suppliers with an active note,1510 // so the CNPJ is always present in the filter's own options.1511 1035 document.addEventListener( 'sbnfebr:library-filter-supplier', function ( e ) { 1512 1036 var digits = ( ( e.detail && e.detail.document ) || '' ).replace( /\D/g, '' ); … … 1537 1061 } 1538 1062 1539 if ( els.btn Configure) {1540 els.btn Configure.addEventListener( 'click', openConfigure );1063 if ( els.btnSettings ) { 1064 els.btnSettings.addEventListener( 'click', openConfigure ); 1541 1065 } 1542 1066 … … 1546 1070 } 1547 1071 1548 // Delegated on the header <tr> (recreated on every renderGrid()).1549 // 3 states per click: no sort -> asc -> desc -> no sort again.1550 1072 if ( els.theadRow ) { 1551 1073 els.theadRow.addEventListener( 'click', function ( e ) { … … 1569 1091 } 1570 1092 1571 // Fetches all items matching current filters, ignoring pagination, capped at 500.1572 1093 if ( els.btnCheckMatch && SB.registryCheck ) { 1573 1094 els.btnCheckMatch.addEventListener( 'click', function () { 1095 if ( SB.importPrompt && state.noteId ) { 1096 SB.importPrompt.open( state.noteId ); 1097 return; 1098 } 1574 1099 els.btnCheckMatch.disabled = true; 1575 1100 fetchAllItemsForCheck().then( function ( result ) { … … 1582 1107 } 1583 1108 // Explicit subtitle='' — clears any "note N/S" left 1584 // over from a previous post-import auto-open in the same session.1585 1109 SB.registryCheck.open( result.items, '' ); 1586 1110 } ).catch( function () { … … 1590 1114 } 1591 1115 1592 // After creating 1 product, offers "Open in editor" + "Open in1593 // Store Manager" (if detectable) instead of opening on its own.1594 1116 document.addEventListener( 'sbnfebr:product-created', function ( e ) { 1595 var productId = e.detail.productId; 1596 var editUrl = e.detail.editUrl; 1117 SB.handleProductsSent( { 1118 product_id: e.detail.productId, 1119 edit_url: e.detail.editUrl 1120 }, { message: __( 'Produto criado.', 'sanbar-express-nfe-xml-import-br' ) } ); 1121 } ); 1122 1123 // by the adapter and never reach this event. 1124 document.addEventListener( 'sbnfebr:products-sent', function ( e ) { 1125 var detail = e.detail || {}; 1126 var productIds = detail.productIds || []; 1597 1127 var actions = []; 1598 var fcAction = buildOpenInFcAction( [ productId ] ); 1599 if ( fcAction ) { 1600 actions.push( fcAction ); 1601 } 1602 if ( editUrl ) { 1603 actions.push( { 1604 label: __( 'Abrir no editor', 'sanbar-express-nfe-xml-import-br' ), 1605 onClick: function () { window.open( editUrl, '_blank' ); hideNotice(); } 1606 } ); 1607 } 1608 var smAction = buildOpenInSmAction( [ productId ] ); 1128 var editorAction = buildOpenStandardEditorAction( detail.products || [] ); 1129 if ( editorAction ) { actions.push( editorAction ); } 1130 var smAction = buildOpenInSmAction( productIds ); 1609 1131 if ( smAction ) { 1610 1132 actions.push( smAction ); 1611 1133 } 1612 1134 if ( actions.length ) { 1613 showActionNotice( __( 'Produto criado.', 'sanbar-express-nfe-xml-import-br' ), actions ); 1614 } 1615 } ); 1616 1617 // Note deleted in the manager — reloads suppliers/notes/items on 1618 // the main screen, same pattern as the post-import refresh. 1135 showActionNotice( 1136 detail.message || ( 1 === productIds.length 1137 ? __( 'Produto enviado com sucesso.', 'sanbar-express-nfe-xml-import-br' ) 1138 : productIds.length + ' ' + __( 'produtos enviados com sucesso.', 'sanbar-express-nfe-xml-import-br' ) ), 1139 actions 1140 ); 1141 } 1142 } ); 1143 1619 1144 document.addEventListener( 'sbnfebr:notes-changed', refreshAll ); 1620 1145 1621 // Auto-opens the Registry Check right after importing, filtered1622 // to this note's items — only if there's at least 1 match.1623 1146 document.addEventListener( 'sbnfebr:notes-imported', function ( e ) { 1624 if ( ! SB.registryCheck ) {1147 if ( ! SB.registryCheck || SB.importPrompt ) { 1625 1148 return; 1626 1149 } 1627 1150 ( e.detail.noteIds || [] ).forEach( function ( noteId ) { 1628 // per_page caps at 100 (get_items()) — a note with more1629 1151 // items only has its 1st page checked here. 1630 1152 SB.api( 'items', { note_id: noteId, per_page: 100 } ).then( function ( res ) { … … 1670 1192 } ); 1671 1193 1672 // nfebr-item-actions.js doesn't store the items (main.js holds1673 // state.lastItems) — resolves the requested item and hands it1674 1194 // back to open the modal. 1675 1195 document.addEventListener( 'sbnfebr:open-item-action', function ( e ) { … … 1682 1202 } ); 1683 1203 1684 // Same pattern as above, for the group of 4 quick-action icons1685 // (stock/price/fiscal/draft-link) in the grid row itself,1686 1204 // without opening the full modal. 1687 1205 document.addEventListener( 'sbnfebr:quick-action', function ( e ) { … … 1694 1212 } ); 1695 1213 1696 // Item gained (or changed) a linked product via Make Draft/Link/1697 // Sync — updates local state without reloading from the REST API.1698 1214 document.addEventListener( 'sbnfebr:item-linked', function ( e ) { 1699 // Identity comes in the event itself — doesn't depend on1700 // finding the clicked row in state.lastItems first (it might1701 // not be in the current view, filtered by supplier/note).1702 1215 var touchedIds = applyLinkToIdentity( e.detail, e.detail.productId, !! e.detail.hasFiscal ); 1703 1216 renderGrid(); … … 1705 1218 } ); 1706 1219 1707 // "Unlink" — clears the item's local state, without reloading1708 // from the REST API. Reappears as pending (📦) or a match (if1709 // checkMatches() runs again — doesn't run on its own here, the1710 1220 // user can click "Check registry"). 1711 1221 document.addEventListener( 'sbnfebr:item-unlinked', function ( e ) { … … 1715 1225 } ); 1716 1226 1717 // A product the UI still had linked/matched turned out not to exist1718 // anymore (deleted elsewhere while this screen stayed open).1719 1227 document.addEventListener( 'sbnfebr:product-missing', function ( e ) { 1720 1228 var touchedIds = clearMissingProduct( e.detail.productId ); … … 1723 1231 } ); 1724 1232 1725 // "Accept new GTIN": every item linked to that product stops being1726 // flagged as changed (the backend rewrote all their baselines).1727 1233 document.addEventListener( 'sbnfebr:link-snapshot-accepted', function ( e ) { 1728 1234 var pid = String( e.detail.productId ); … … 1736 1242 } ); 1737 1243 1738 // GTIN couldn't become the SKU because another product already uses that value.1739 1244 document.addEventListener( 'sbnfebr:sku-conflict', function () { 1740 1245 showNotice( __( 'O GTIN não pôde virar SKU — outro produto já usa esse SKU.', 'sanbar-express-nfe-xml-import-br' ), 'error' ); 1741 1246 } ); 1742 1247 1743 // Generic — other modules that don't have access to showNotice1744 // (local to this file, not exposed on SB) fire this to request1745 1248 // an error notice without duplicating the notice UI. 1746 1249 document.addEventListener( 'sbnfebr:api-error', function ( e ) { 1747 1250 showNotice( ( e.detail && e.detail.message ) || __( 'Algo deu errado.', 'sanbar-express-nfe-xml-import-br' ), 'error' ); 1251 } ); 1252 1253 document.addEventListener( 'sbnfebr:entry-refresh', function () { 1254 reloadItems( false ); 1748 1255 } ); 1749 1256 … … 1764 1271 } 1765 1272 1766 if ( els.filterMode ) { 1767 els.filterMode.addEventListener( 'change', function () { 1768 state.mode = els.filterMode.value; 1273 var applyEntryMode = function ( mode ) { 1274 state.mode = mode; 1275 if ( els.filterMode ) { 1276 els.filterMode.value = mode; 1277 } 1278 if ( els.filterDates ) { 1769 1279 var needsDates = 'price_period' === state.mode || 'notes_period' === state.mode; 1770 1280 els.filterDates.style.display = needsDates ? '' : 'none'; … … 1775 1285 els.filterDateTo.value = ''; 1776 1286 } 1777 reloadItems(); 1287 } 1288 updateIgnoredDrawer(); 1289 reloadItems(); 1290 }; 1291 1292 if ( els.filterMode ) { 1293 els.filterMode.addEventListener( 'change', function () { 1294 applyEntryMode( els.filterMode.value ); 1778 1295 } ); 1779 1296 } … … 1828 1345 } ); 1829 1346 1830 /**1831 * Toggles the active view-mode segment and swaps the <table>1832 * class for the product-mode layout. 'duplicates'/'ignored'1833 * modes are disabled and reset in the per-product view.1834 */1835 1347 function updateViewToggle() { 1836 1348 var isProductView = 'product' === state.viewMode; … … 1876 1388 } 1877 1389 1390 if ( els.btnIgnoredDrawer ) { 1391 els.btnIgnoredDrawer.addEventListener( 'click', function () { 1392 if ( 'product' === state.viewMode ) { 1393 state.viewMode = 'note'; 1394 updateViewToggle(); 1395 reloadNotes(); 1396 } 1397 applyEntryMode( 'ignored' === state.mode ? '' : 'ignored' ); 1398 } ); 1399 } 1400 1878 1401 if ( els.btnViewNote || els.btnViewProduct ) { 1879 1402 updateViewToggle(); … … 1888 1411 var triggerUpload = function () { els.fileInput.click(); }; 1889 1412 els.btnUpload.addEventListener( 'click', triggerUpload ); 1413 var uploadQuery = window.matchMedia( '(min-width: 721px)' ); 1414 var placeUpload = function () { 1415 var nav = document.getElementById( 'sbnfebr-workflow-tabs' ); 1416 var box = els.btnUpload.closest( '.sbnfebr-row1__actions' ) || document.querySelector( '.sbnfebr-row1__actions' ); 1417 if ( ! nav || ! box ) { return; } 1418 if ( uploadQuery.matches ) { 1419 nav.insertBefore( els.btnUpload, nav.firstChild ); 1420 } else { 1421 box.insertBefore( els.btnUpload, box.querySelector( '.sbnfebr-bulk-toolbar' ) ); 1422 } 1423 }; 1424 placeUpload(); 1425 uploadQuery.addEventListener( 'change', placeUpload ); 1426 var backupBtn = document.getElementById( 'sbnfebr-btn-backup' ); 1427 var backupMenu = document.getElementById( 'sbnfebr-backup-menu' ); 1428 if ( backupBtn && backupMenu ) { 1429 var setBackup = function ( open ) { 1430 backupMenu.hidden = ! open; 1431 backupBtn.setAttribute( 'aria-expanded', open ? 'true' : 'false' ); 1432 }; 1433 backupBtn.addEventListener( 'click', function ( event ) { 1434 event.stopPropagation(); 1435 setBackup( backupMenu.hidden ); 1436 } ); 1437 backupMenu.addEventListener( 'click', function ( event ) { 1438 if ( event.target.closest( 'button' ) ) { setBackup( false ); } 1439 } ); 1440 document.addEventListener( 'click', function ( event ) { 1441 if ( ! backupMenu.hidden && ! backupMenu.contains( event.target ) ) { setBackup( false ); } 1442 } ); 1443 document.addEventListener( 'keydown', function ( event ) { 1444 if ( 'Escape' === event.key && ! backupMenu.hidden ) { setBackup( false ); backupBtn.focus(); } 1445 } ); 1446 } 1890 1447 if ( els.btnUploadEmpty ) { 1891 1448 els.btnUploadEmpty.addEventListener( 'click', triggerUpload ); … … 1909 1466 btnNotesManager: q( 'sbnfebr-btn-notes-manager' ), 1910 1467 btnCheckMatch: q( 'sbnfebr-btn-check-match' ), 1911 btn Configure: q( 'sbnfebr-btn-cols' ),1468 btnSettings: q( 'sbnfebr-btn-settings' ), 1912 1469 btnClearFilters: q( 'sbnfebr-btn-clear-filters' ), 1913 1470 btnViewNote: q( 'sbnfebr-btn-view-note' ), … … 1930 1487 statNotes: q( 'sbnfebr-stat-notes' ), 1931 1488 statSuppliers: q( 'sbnfebr-stat-suppliers' ), 1489 btnIgnoredDrawer: q( 'sbnfebr-btn-ignored-drawer' ), 1490 statIgnored: q( 'sbnfebr-stat-ignored' ), 1932 1491 pagePrev: q( 'sbnfebr-page-prev' ), 1933 1492 pageNext: q( 'sbnfebr-page-next' ), -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-note-info.js
r3725460 r3782421 1 /* ================================================================2 nfebr-note-info.js — read-only "note details" modal.3 ================================================================ */4 1 (function () { 5 2 'use strict'; … … 20 17 } 21 18 22 // modFrete — standard XML code, 0-4 and 9 (layout 4.00).23 19 function freightByLabel( code ) { 24 20 var map = { … … 133 129 } 134 130 135 // Payment method — can have more than one (split payment), same136 131 // table layout as installments. 137 132 var paymentsHtml = ''; … … 158 153 } 159 154 160 // Additional information — free text from the supplier, can be long.161 155 var additionalInfoHtml = ''; 162 156 if ( n.additional_info ) { … … 167 161 } 168 162 169 // Purpose only shown when different from Normal, to avoid170 163 // cluttering the header in the common case. 171 164 var purposeHtml = ( n.nfe_purpose && '1' !== String( n.nfe_purpose ) ) … … 194 187 } 195 188 196 /**197 * Opens the modal for a specific note.198 *199 * @param {number} noteId200 * @return {void}201 */202 189 function open( noteId ) { 203 190 if ( ! noteId ) { … … 226 213 } ); 227 214 } ).catch( function ( e ) { 228 // showNotice isn't exposed on the SB namespace, so dispatch229 // an event that nfebr-main.js listens for and renders.230 215 document.dispatchEvent( new CustomEvent( 'sbnfebr:api-error', { 231 216 detail: { message: ( e && e.message ) || __( 'Falha ao carregar os detalhes da nota.', 'sanbar-express-nfe-xml-import-br' ) } -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-price-history.js
r3725460 r3782421 1 /* ================================================================2 nfebr-price-history.js — price history modal, product code across3 notes from the same supplier, sorted by date.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 43 39 } 44 40 45 /**46 * Rounds to 2 decimals — trend must compare the displayed value,47 * not raw XML precision, or equal-looking prices could show a48 * false trend arrow.49 */50 41 function round2( v ) { 51 42 return Math.round( Number( v ) * 100 ) / 100; 52 43 } 53 44 54 /**55 * Builds one history table. `rows` must be ASC by date so the trend56 * arrow compares each row to its true predecessor; display order is57 * reversed only after the trend is computed.58 *59 * @param {Array} rows History rows, ASC by date.60 * @param {boolean} withSupplier Include the "Supplier" column.61 * @return {string}62 */63 45 function buildTableHTML( rows, withSupplier ) { 64 46 var trs = rows.map( function ( h, index ) { -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-registry-check.js
r3725460 r3782421 1 /* ================================================================2 nfebr-registry-check.js — "Registry cross-check" modal: pending3 items matched against the WooCommerce catalog by GTIN.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 15 11 var _lastItems = null; 16 12 var _lastSubtitle = ''; 17 // Client-side sort (Supplier/Name) — data is already fully loaded,18 // no need to re-query the backend. _lastCandidates/_lastMatches19 // hold the last render() so re-sorting skips the catalog search.20 13 var _sortBy = null; 21 14 var _sortDir = 'asc'; … … 57 50 58 51 ov.querySelector( '.sb-library-close' ).addEventListener( 'click', close ); 59 // Delegated once (overlay is created only on first open, see60 // _overlay cache above), so it covers the sort buttons even61 52 // after render() recreates the innerHTML. 62 53 ov.addEventListener( 'click', function ( e ) { … … 98 89 } 99 90 100 /**101 * Opens the modal and runs the cross-check over `items` (same shape102 * as state.lastItems — whatever is already loaded in the grid at103 * click time, not a fresh full fetch from the DB).104 *105 * @param {Array} items106 * @param {string} [subtitle] "note N/S · SUPPLIER" on the post-import107 * auto-open; empty when opened manually.108 */109 91 function open( items, subtitle ) { 110 92 _lastItems = items; 111 // undefined (not passed) preserves the active subtitle — this is112 // how maybeRefresh() calls back in after an action applies,113 // without losing the "note N/S · SUPPLIER" from the auto-open.114 93 _lastSubtitle = undefined === subtitle ? _lastSubtitle : subtitle; 115 94 ensureOverlay(); … … 121 100 var body = document.getElementById( 'sbnfebr-regcheck-body' ); 122 101 123 // Only pending items (no product yet) with a real GTIN —124 // nothing to match without one (supplier+code out of scope).125 102 var candidates = ( items || [] ).filter( function ( it ) { 126 103 var gtin = String( it.gtin || '' ).trim().toUpperCase(); … … 146 123 } 147 124 148 /**149 * Sort button matching the main grid's (▲/▼/⇅), reused for the150 * "Name"/"Supplier" headers.151 *152 * @param {string} key 'description'|'supplier_name'.153 * @param {string} label154 * @return {string}155 */156 125 function sortHeaderHtml( key, label ) { 157 126 var dir = _sortBy === key ? _sortDir : null; … … 221 190 } 222 191 223 /** 224 * Same 5-icon group as the grid, but with precise state: `m` carries 225 * the matched product's snapshot fields (registry_check() reuses 226 * get_snapshot()), so real diffs are computed here. 227 * 228 * @param {Object} item Note item. 229 * @param {Object} m Match — includes get_snapshot() fields. 230 * @return {string} 231 */ 232 function quickIconsForRow( item, m ) { 233 var FM = ( SB.itemActions && SB.itemActions.FISCAL_FIELD_MAP ) || []; 234 var isPlus = !! SB.is_plus; 235 236 function icon( key, glyph, state, title ) { 237 return '<button type="button" class="sbnfebr-ac-gicon sbnfebr-ac-gicon--' + state + '" data-item-id="' + item.id + '" data-key="' + key + '" title="' + esc( title ) + '">' + glyph + '</button>'; 238 } 239 240 var overview = icon( 'overview', '⋯', 'neutral', __( 'Abrir modal de ação', 'sanbar-express-nfe-xml-import-br' ) ); 241 // 🔗 for a found match (same glyph as the grid, unit or box — the 242 // badge next to the GTIN already distinguishes that in text). 243 // 📦 stays exclusive to the Stock card. 244 var rascunho = icon( 'rascunho', '🔗', 'alert', __( 'Rascunho / Vínculo', 'sanbar-express-nfe-xml-import-br' ) ); 245 246 var estoque; 247 if ( ! isPlus ) { 248 estoque = icon( 'estoque', '📦', 'locked', __( 'Estoque (recurso Plus)', 'sanbar-express-nfe-xml-import-br' ) ); 249 } else { 250 estoque = icon( 'estoque', '📦', Number( item.quantity ) > 0 ? 'alert' : 'quiet', __( 'Estoque', 'sanbar-express-nfe-xml-import-br' ) ); 251 } 252 253 var costKnown = 'unit' === m.sale_type && null !== m.cost_paid && undefined !== m.cost_paid; 254 var costChanged = costKnown && Math.abs( Number( m.cost_paid ) - ( Number( item.unit_value ) || 0 ) ) > 0.001; 255 var preco = icon( 'preco', '🏷️', ( costChanged || ! costKnown ) ? 'alert' : 'quiet', __( 'Preço / Fonte', 'sanbar-express-nfe-xml-import-br' ) ); 256 257 var fiscal; 258 if ( ! isPlus ) { 259 fiscal = icon( 'fiscal', '🧾', 'locked', __( 'Dados fiscais (recurso Plus)', 'sanbar-express-nfe-xml-import-br' ) ); 260 } else { 261 var fieldDiffs = FM.filter( function ( f ) { return !! item[ f.item ] && String( m[ f.snap ] || '' ) !== String( item[ f.item ] ); } ); 262 var offeredFields = FM.filter( function ( f ) { return !! item[ f.item ]; } ); 263 var neverSynced = offeredFields.length > 0 && offeredFields.every( function ( f ) { return ! m[ f.snap ]; } ); 264 fiscal = icon( 'fiscal', '🧾', ( neverSynced || fieldDiffs.length ) ? 'alert' : 'quiet', __( 'Dados fiscais', 'sanbar-express-nfe-xml-import-br' ) ); 265 } 266 267 return '<span class="sbnfebr-ac-gicon-group">' + overview + rascunho + estoque + preco + fiscal + '</span>'; 192 function workflowActionForRow( item ) { 193 if ( ! Number( item.workflow_id ) ) { 194 return '<button type="button" class="sbnfebr-btn sbnfebr-row-action" disabled title="' + esc( __( 'Migração para o catálogo de conferência pendente.', 'sanbar-express-nfe-xml-import-br' ) ) + '">!</button>'; 195 } 196 var stage = String( item.workflow_stage || 'entry' ); 197 var label = __( 'Enviar', 'sanbar-express-nfe-xml-import-br' ); 198 var title = __( 'Enviar para Conferência', 'sanbar-express-nfe-xml-import-br' ); 199 var state = 'entry'; 200 if ( 'sync' === stage || 'synced' === item.workflow_sync_status ) { 201 state = 'sync'; 202 label = __( 'Ver Sync', 'sanbar-express-nfe-xml-import-br' ); 203 title = label; 204 } else if ( 'review' === stage ) { 205 var broken = 'error' === item.workflow_check_status || 'stale' === item.workflow_fiscal_status; 206 state = broken ? 'error' : 'review'; 207 label = broken ? __( 'Corrigir', 'sanbar-express-nfe-xml-import-br' ) : __( 'Conferir', 'sanbar-express-nfe-xml-import-br' ); 208 title = label; 209 } 210 return '<button type="button" class="sbnfebr-btn sbnfebr-row-action is-' + state + '" title="' + esc( title ) + '" data-registry-workflow-action data-source-item-id="' + Number( item.id ) + '" data-workflow-id="' + Number( item.workflow_id ) + '" data-workflow-stage="' + esc( stage ) + '" data-workflow-search="' + esc( item.gtin || item.product_code || item.description || '' ) + '">' + esc( label ) + '</button>'; 268 211 } 269 212 … … 277 220 return '<div class="sbnfebr-regcheck-row">' + 278 221 '<div class="sbnfebr-regcheck-grp sbnfebr-regcheck-grp--note">' + 279 '<div class="sbnfebr-regcheck-name" title="' + esc( item.description || '' ) + '">' + esc( item.description || '' ) + '</div>' +280 '<div class="sbnfebr-regcheck-money" >' + esc( fmtMoney( item.unit_value ) ) + '</div>' +281 '<div class="sbnfebr-regcheck-mono" >' + esc( item.gtin || '' ) + '</div>' +282 '<div class="sbnfebr-regcheck-muted" >' + esc( item.product_code || '' ) + '</div>' +283 '<div class="sbnfebr-regcheck-muted" >' + esc( item.supplier_name || '' ) + '</div>' +222 '<div class="sbnfebr-regcheck-name" data-label="' + esc( __( 'Nome na nota', 'sanbar-express-nfe-xml-import-br' ) ) + '" title="' + esc( item.description || '' ) + '">' + esc( item.description || '' ) + '</div>' + 223 '<div class="sbnfebr-regcheck-money" data-label="' + esc( __( 'Valor', 'sanbar-express-nfe-xml-import-br' ) ) + '">' + esc( fmtMoney( item.unit_value ) ) + '</div>' + 224 '<div class="sbnfebr-regcheck-mono" data-label="GTIN">' + esc( item.gtin || '' ) + '</div>' + 225 '<div class="sbnfebr-regcheck-muted" data-label="' + esc( __( 'Cód. forn.', 'sanbar-express-nfe-xml-import-br' ) ) + '">' + esc( item.product_code || '' ) + '</div>' + 226 '<div class="sbnfebr-regcheck-muted" data-label="' + esc( __( 'Fornecedor', 'sanbar-express-nfe-xml-import-br' ) ) + '">' + esc( item.supplier_name || '' ) + '</div>' + 284 227 '</div>' + 285 228 '<div class="sbnfebr-regcheck-divider">→</div>' + 286 229 '<div class="sbnfebr-regcheck-grp sbnfebr-regcheck-grp--wc">' + 287 '<div class="sbnfebr-regcheck-name" title="' + esc( m.name || '' ) + '">' + esc( m.name || '' ) + '</div>' +288 '<div class="sbnfebr-regcheck-money" >' + esc( fmtMoney( m.price ) ) + '</div>' +289 '<div class="sbnfebr-regcheck-muted" title="' + esc( m.category || '' ) + '">' + esc( m.category || '—' ) + '</div>' +290 '<div class="sbnfebr-regcheck-muted" title="' + esc( m.brand || '' ) + '">' + esc( m.brand || '—' ) + '</div>' +291 '<div class="sbnfebr-regcheck-gtin-cell" ><span class="sbnfebr-regcheck-mono">' + esc( item.gtin || '' ) + '</span>' + fieldBadge + '</div>' +230 '<div class="sbnfebr-regcheck-name" data-label="' + esc( __( 'Nome no cadastro', 'sanbar-express-nfe-xml-import-br' ) ) + '" title="' + esc( m.name || '' ) + '">' + esc( m.name || '' ) + '</div>' + 231 '<div class="sbnfebr-regcheck-money" data-label="' + esc( __( 'Preço', 'sanbar-express-nfe-xml-import-br' ) ) + '">' + esc( fmtMoney( m.price ) ) + '</div>' + 232 '<div class="sbnfebr-regcheck-muted" data-label="' + esc( __( 'Categoria', 'sanbar-express-nfe-xml-import-br' ) ) + '" title="' + esc( m.category || '' ) + '">' + esc( m.category || '—' ) + '</div>' + 233 '<div class="sbnfebr-regcheck-muted" data-label="' + esc( __( 'Marca', 'sanbar-express-nfe-xml-import-br' ) ) + '" title="' + esc( m.brand || '' ) + '">' + esc( m.brand || '—' ) + '</div>' + 234 '<div class="sbnfebr-regcheck-gtin-cell" data-label="GTIN"><span class="sbnfebr-regcheck-mono">' + esc( item.gtin || '' ) + '</span>' + fieldBadge + '</div>' + 292 235 '</div>' + 293 236 '<div class="sbnfebr-regcheck-actions">' + 294 quickIconsForRow( item, m ) + 295 '<button type="button" class="sbnfebr-btn sbnfebr-regcheck-open-editor-btn" data-edit-url="' + esc( m.edit_url || '' ) + '" title="' + esc( __( 'Abrir produto no editor', 'sanbar-express-nfe-xml-import-br' ) ) + '">↗</button>' + 296 // Same pattern as the SM button in the action modal: only 297 // rendered if the Sheet is installed (SB.sm_admin_url). 298 ( SB.sm_admin_url 299 ? '<button type="button" class="sbnfebr-btn sbnfebr-regcheck-open-sm-btn" data-product-id="' + m.product_id + '" title="' + esc( __( 'Abrir no Store Manager', 'sanbar-express-nfe-xml-import-br' ) ) + '">↗ SM</button>' 300 : '' ) + 237 workflowActionForRow( item ) + 238 SB.productButtons( m.product_id, m.edit_url ) + 301 239 '</div>' + 302 240 '</div>'; … … 304 242 305 243 function wireRowActions( body ) { 306 // .sbnfebr-ac-gicon clicks are NOT rewired here: nfebr-item-actions.js 307 // already has a delegated listener on `document` for that selector; 308 // rewiring here would fire the same action twice per click. 309 body.querySelectorAll( '.sbnfebr-regcheck-open-editor-btn' ).forEach( function ( btn ) { 244 body.querySelectorAll( '[data-registry-workflow-action]' ).forEach( function ( btn ) { 310 245 btn.addEventListener( 'click', function () { 311 var url = this.dataset.editUrl; 312 if ( url ) { 313 window.open( url, '_blank' ); 314 } 246 close(); 247 document.dispatchEvent( new CustomEvent( 'sbnfebr:workflow-context-action', { detail: { 248 sourceItemId: Number( this.dataset.sourceItemId ), 249 workflowId: Number( this.dataset.workflowId ), 250 stage: String( this.dataset.workflowStage || 'entry' ), 251 search: String( this.dataset.workflowSearch || '' ) 252 } } ) ); 315 253 } ); 316 254 } ); 317 // Inside the Sheet's iframe, notify the parent via postMessage; 318 // outside it, open Store Manager in a new tab. 319 body.querySelectorAll( '.sbnfebr-regcheck-open-sm-btn' ).forEach( function ( btn ) { 320 btn.addEventListener( 'click', function () { 321 var productId = this.dataset.productId; 322 var inIframe = window.parent !== window; 323 if ( inIframe ) { 324 window.parent.postMessage( 325 { type: 'sbnfebr:products-created', product_ids: [ productId ] }, 326 window.location.origin 327 ); 328 } else if ( SB.sm_admin_url ) { 329 var sep = SB.sm_admin_url.indexOf( '?' ) !== -1 ? '&' : '?'; 330 window.open( SB.sm_admin_url + sep + 'sbesfw_ids=' + productId, '_blank' ); 331 } 332 } ); 333 } ); 334 } 335 336 // Re-runs the cross-check when an action applies (item-linked/-unlinked), 337 // so linked items drop off and the rest get fresh data. Only while open. 255 } 256 338 257 function maybeRefresh() { 339 258 if ( _overlay && _overlay.classList.contains( 'open' ) && _lastItems ) { … … 342 261 } 343 262 344 /**345 * Item lookup for nfebr-main.js — this modal loads up to 500 items346 * independently of the grid's pagination, so its items are often347 * outside state.lastItems.348 *349 * @param {string|number} itemId350 * @return {Object|null}351 */352 263 function getItem( itemId ) { 353 264 var id = String( itemId ); … … 355 266 } 356 267 357 // _lastItems is a separate copy from the grid's state.lastItems, so link358 // changes applied there (nfebr-main.js) never reach it — without this,359 268 // a just-linked item stayed listed as pending here. 360 269 function syncLink( e ) { -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-sheet-bridge.js
r3725460 r3782421 1 /* ================================================================2 nfebr-sheet-bridge.js — enqueued only on the Sheet plugin's own3 screen; opens this plugin in an isolated iframe modal.4 ================================================================ */5 1 (function () { 6 2 'use strict'; … … 12 8 if (!window.SBNFEBR_BRIDGE || !window.SBNFEBR_BRIDGE.modal_url) return; 13 9 14 // Appends the NF-e plugin's version next to the Sheet's own version15 // tag (e.g. "v<sheet> / NF-e v<own>"). Retried independently of the button.16 10 function injectVersionTag() { 17 11 if (document.getElementById('sbnfebr-version-tag')) return true; // already injected … … 36 30 btn.title = __( 'Importar XML de NF-e', 'sanbar-express-nfe-xml-import-br' ); 37 31 btn.textContent = '📄 ' + __( 'XML Import', 'sanbar-express-nfe-xml-import-br' ); 38 // Amber outline just signals the installed edition (Plus) —39 32 // same button, text, and icon otherwise. 40 33 if (window.SBNFEBR_BRIDGE.is_plus) { … … 58 51 document.body.appendChild(overlay); 59 52 60 // Closing is deliberately X-only — clicking outside or pressing61 // Esc does NOT close, to avoid losing in-progress import work62 53 // to an accidental click/keypress. 63 54 overlay.querySelector('.sbnfebr-bridge-close').addEventListener('click', function () { … … 66 57 } 67 58 68 // The iframe notifies this page of new product IDs via postMessage;69 // e.origin is checked to only accept same-origin messages.70 59 window.addEventListener('message', function (e) { 71 60 if (e.origin !== window.location.origin) return; … … 84 73 }); 85 74 86 // Execution order between plugins' scripts isn't guaranteed —87 75 // retries up to 20x (4s) before giving up silently. 88 76 var attempts = 0; -
sanbar-express-nfe-xml-import-br/trunk/assets/js/nfebr-toast.js
r3725460 r3782421 1 /* ================================================================2 nfebr-toast.js — progress toast, bottom-right corner.3 ================================================================ */4 1 (function () { 5 2 'use strict'; … … 24 21 } 25 22 26 /**27 * Starts a progress toast, visible only if still running after28 * SHOW_DELAY_MS. Without update() it stays indeterminate ("Label…");29 * with it, shows "Label… N%".30 *31 * @param {string} label Text without ellipsis (added here).32 * @return {{update:function(number):void, done:function():void}}33 */34 23 function start( label ) { 35 24 var id = 'sbnfebr-toast-' + ( ++seq ); … … 81 70 } 82 71 83 /**84 * Confirmation toast — unlike start(), always appears immediately85 * (no 300ms delay, since this is a deliberate confirmation rather86 * than a progress indicator) and auto-dismisses.87 *88 * @param {string} message Ready to display (no ellipsis).89 * @param {number} [durationMs] Default 2500.90 * @return {void}91 */92 72 function success( message, durationMs ) { 93 73 var el = document.createElement( 'div' ); … … 107 87 } 108 88 109 /**110 * Error toast — same pattern as success(), red, longer on screen.111 * Fallback used by showError() when there's no modal to anchor112 * an inline error to.113 *114 * @param {string} message Ready to display.115 * @param {number} [durationMs] Default 4000.116 */117 89 function error( message, durationMs ) { 118 90 var el = document.createElement( 'div' ); -
sanbar-express-nfe-xml-import-br/trunk/includes/class-sbnfebr-admin.php
r3725460 r3782421 1 1 <?php 2 /**3 * Admin page renderer + asset enqueuer for SanBar EXPress NF-e for WooCommerce.4 *5 * Responsibilities:6 * - Register the plugin menu (submenu of "SB Softwares" if the SB7 * Softwares Hub is active, own top-level menu otherwise)8 * - Enqueue CSS + JS9 * - Render the screen's HTML shell (supplier -> notes -> grid)10 *11 * @package SBNFEBR12 * @since 0.1.013 */14 2 15 3 defined( 'ABSPATH' ) || exit; 16 4 17 5 if ( ! function_exists( 'sbnfebr_sb_parent_menu_exists' ) ) { 18 /**19 * Checks whether the "sb-softwares" parent menu is already registered20 * (typically by the SB Softwares Hub plugin).21 *22 * @return bool23 */24 6 function sbnfebr_sb_parent_menu_exists() { 25 7 global $menu; … … 53 35 } 54 36 55 /**56 * Adds a dedicated body class on this plugin's screen, so shell CSS can57 * neutralize WP chrome without affecting the rest of admin.58 *59 * @param string $classes Existing classes.60 * @return string61 */62 37 public static function body_class( $classes ) { 63 38 $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null; 64 if ( $screen && false !== strpos( (string) $screen->id, 'sbnfebr' ) ) {39 if ( $screen && false !== strpos( (string) $screen->id, 'sbnfebr' ) && self::is_plugin_page() ) { 65 40 $classes .= ' sbnfebr-fullscreen'; 66 41 } … … 68 43 } 69 44 70 /* =========================================================== 71 * MENU 72 * ========================================================= */ 73 74 /** 75 * Registers the plugin menu: submenu of "SB Softwares" if the Hub is 76 * active, its own top-level menu otherwise. 77 * 78 * @return void 79 */ 45 protected static function plus_cta() { 46 if ( sbnfebr_is_plus() ) { 47 return array( 'url' => '', 'trial' => false ); 48 } 49 if ( function_exists( 'sbnfebr_fs' ) ) { 50 $trial = ! sbnfebr_fs()->is_trial_utilized(); 51 return array( 52 'url' => $trial ? sbnfebr_fs()->get_trial_url() : sbnfebr_fs()->get_upgrade_url(), 53 'trial' => $trial, 54 ); 55 } 56 return array( 'url' => 'https://software.sanbazar.com.br', 'trial' => false ); 57 } 58 59 protected static function license_info() { 60 if ( ! function_exists( 'sbnfebr_fs' ) ) { 61 return null; 62 } 63 $fs = sbnfebr_fs(); 64 $registered = $fs->is_registered(); 65 $license = $registered ? $fs->_get_license() : null; 66 $site = $registered ? $fs->get_site() : null; 67 $date_fmt = get_option( 'date_format' ); 68 69 if ( ! $registered ) { 70 $status = __( 'Ainda não conectado. Conecte para iniciar o teste grátis ou ativar uma licença Plus.', 'sanbar-express-nfe-xml-import-br' ); 71 } elseif ( $fs->is_trial() ) { 72 $ends = ( $site && ! empty( $site->trial_ends ) ) ? date_i18n( $date_fmt, strtotime( $site->trial_ends ) ) : ''; 73 /* translators: %s: trial end date. */ 74 $status = $ends ? sprintf( __( 'Teste grátis do Plus, até %s.', 'sanbar-express-nfe-xml-import-br' ), $ends ) : __( 'Teste grátis do Plus.', 'sanbar-express-nfe-xml-import-br' ); 75 } elseif ( $fs->is_paying() && $license ) { 76 if ( $license->is_lifetime() ) { 77 $status = __( 'Plus ativo (vitalício).', 'sanbar-express-nfe-xml-import-br' ); 78 } else { 79 /* translators: %s: license expiration date. */ 80 $status = sprintf( __( 'Plus ativo, válido até %s.', 'sanbar-express-nfe-xml-import-br' ), date_i18n( $date_fmt, strtotime( $license->expiration ) ) ); 81 } 82 } elseif ( $license && $license->is_expired() ) { 83 $status = __( 'Licença Plus vencida. O plugin está funcionando como Lite.', 'sanbar-express-nfe-xml-import-br' ); 84 } else { 85 $status = __( 'Lite (grátis).', 'sanbar-express-nfe-xml-import-br' ); 86 } 87 88 $buttons = array(); 89 if ( ! $registered ) { 90 $buttons[] = array( 'url' => $fs->get_activation_url(), 'label' => __( 'Conectar', 'sanbar-express-nfe-xml-import-br' ), 'primary' => true ); 91 } else { 92 $buttons[] = array( 'url' => $fs->get_account_url(), 'label' => __( 'Minha conta / licença', 'sanbar-express-nfe-xml-import-br' ), 'primary' => false ); 93 } 94 if ( ! $fs->is_paying() ) { 95 if ( ! $fs->is_trial() && ! $fs->is_trial_utilized() ) { 96 $buttons[] = array( 'url' => $fs->get_trial_url(), 'label' => __( 'Iniciar teste grátis de 3 dias', 'sanbar-express-nfe-xml-import-br' ), 'primary' => true ); 97 } 98 $buttons[] = array( 'url' => $fs->get_upgrade_url(), 'label' => __( 'Assinar o Plus', 'sanbar-express-nfe-xml-import-br' ), 'primary' => true ); 99 } 100 $buttons[] = array( 'url' => $fs->contact_url(), 'label' => __( 'Contato', 'sanbar-express-nfe-xml-import-br' ), 'primary' => false ); 101 $buttons[] = array( 'url' => 'https://wordpress.org/support/plugin/sanbar-express-nfe-xml-import-br/', 'label' => __( 'Fórum de suporte', 'sanbar-express-nfe-xml-import-br' ), 'primary' => false ); 102 103 foreach ( $buttons as $i => $btn ) { 104 $buttons[ $i ]['url'] = esc_url_raw( $btn['url'] ); 105 } 106 107 return array( 108 'status' => $status, 109 'buttons' => $buttons, 110 ); 111 } 112 113 private static function is_plugin_page() { 114 return isset( $_GET['page'] ) && 'sbnfebr' === $_GET['page']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended 115 } 116 80 117 public static function register_menu() { 81 118 if ( sbnfebr_sb_parent_menu_exists() ) { 82 // Dentro do hub "SB Softwares" o "SB" já é redundante (o próprio83 // hub já agrupa por isso) — rótulo mais curto só pra esse caso.84 119 add_submenu_page( 85 120 'sb-softwares', … … 104 139 } 105 140 106 /* ===========================================================107 * ENQUEUE108 * ========================================================= */109 110 /**111 * admin_enqueue_scripts hook callback — only runs on this plugin's screen.112 *113 * @param string $hook Current admin screen hook.114 * @return void115 */116 141 public static function enqueue( $hook ) { 117 if ( false === strpos( $hook, 'sbnfebr' ) ) {142 if ( false === strpos( $hook, 'sbnfebr' ) || ! self::is_plugin_page() ) { 118 143 return; 119 144 } … … 126 151 file_exists( $css_path ) ? filemtime( $css_path ) : SBNFEBR_VERSION 127 152 ); 153 if ( sbnfebr_is_plus() ) { 154 $workflow_plus_css_path = SBNFEBR_DIR . 'plus/assets/css/nfebr-workflow-plus.css'; 155 wp_enqueue_style( 156 'sbnfebr-style-workflow-plus', 157 SBNFEBR_URL . 'plus/assets/css/nfebr-workflow-plus.css', 158 array( 'sbnfebr-style-core' ), 159 file_exists( $workflow_plus_css_path ) ? filemtime( $workflow_plus_css_path ) : SBNFEBR_VERSION 160 ); 161 } 128 162 self::maybe_add_embed_inline_style(); 129 163 … … 152 186 ); 153 187 188 $tokens_path = SBNFEBR_DIR . 'assets/css/design-tokens.css'; 189 $tokens_dependencies = array( 190 'sbnfebr-style-core', 191 'sbnfebr-style-library-supplier', 192 'sbnfebr-style-library-notes', 193 'sbnfebr-style-price-history', 194 ); 195 if ( sbnfebr_is_plus() ) { 196 $tokens_dependencies[] = 'sbnfebr-style-workflow-plus'; 197 } 198 wp_enqueue_style( 199 'sbnfebr-style-design-tokens', 200 SBNFEBR_URL . 'assets/css/design-tokens.css', 201 $tokens_dependencies, 202 file_exists( $tokens_path ) ? filemtime( $tokens_path ) : SBNFEBR_VERSION 203 ); 204 154 205 wp_enqueue_script( 'wp-i18n' ); 155 206 … … 235 286 ); 236 287 237 $ia_js_path = SBNFEBR_DIR . 'assets/js/nfebr-item-actions.js'; 288 $ia_js_rel = 'assets/js/nfebr-item-actions.js'; 289 $ia_js_path = SBNFEBR_DIR . $ia_js_rel; 238 290 wp_enqueue_script( 239 291 'sbnfebr-item-actions', 240 SBNFEBR_URL . 'assets/js/nfebr-item-actions.js',292 SBNFEBR_URL . $ia_js_rel, 241 293 array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-diff-card' ), 242 294 file_exists( $ia_js_path ) ? filemtime( $ia_js_path ) : SBNFEBR_VERSION, … … 244 296 ); 245 297 246 $review_js_path = SBNFEBR_DIR . 'assets/js/nfebr-review-modal.js';247 wp_enqueue_script(248 'sbnfebr-review-modal',249 SBNFEBR_URL . 'assets/js/nfebr-review-modal.js',250 array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-diff-card' ),251 file_exists( $review_js_path ) ? filemtime( $review_js_path ) : SBNFEBR_VERSION,252 true253 );254 255 298 $regcheck_js_path = SBNFEBR_DIR . 'assets/js/nfebr-registry-check.js'; 256 299 wp_enqueue_script( 257 300 'sbnfebr-registry-check', 258 301 SBNFEBR_URL . 'assets/js/nfebr-registry-check.js', 259 // Uses SB.itemActions.* (shared icon/popup group), hence the dependency.260 302 array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-item-actions' ), 261 303 file_exists( $regcheck_js_path ) ? filemtime( $regcheck_js_path ) : SBNFEBR_VERSION, … … 263 305 ); 264 306 307 $main_dependencies = array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-grid', 'sbnfebr-library-supplier', 'sbnfebr-library-notes', 'sbnfebr-note-info', 'sbnfebr-error-log', 'sbnfebr-price-history', 'sbnfebr-item-actions', 'sbnfebr-registry-check' ); 308 265 309 $main_path = SBNFEBR_DIR . 'assets/js/nfebr-main.js'; 266 310 wp_enqueue_script( 267 311 'sbnfebr-main', 268 312 SBNFEBR_URL . 'assets/js/nfebr-main.js', 269 array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-grid', 'sbnfebr-library-supplier', 'sbnfebr-library-notes', 'sbnfebr-note-info', 'sbnfebr-error-log', 'sbnfebr-price-history', 'sbnfebr-item-actions', 'sbnfebr-review-modal', 'sbnfebr-registry-check' ),313 $main_dependencies, 270 314 file_exists( $main_path ) ? filemtime( $main_path ) : SBNFEBR_VERSION, 271 315 true 272 316 ); 273 317 274 // One call per handle: each loads its own translation JSON, named 318 $workflow_path = SBNFEBR_DIR . 'assets/js/nfebr-workflow.js'; 319 wp_enqueue_script( 320 'sbnfebr-workflow', 321 SBNFEBR_URL . 'assets/js/nfebr-workflow.js', 322 array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-main' ), 323 file_exists( $workflow_path ) ? filemtime( $workflow_path ) : SBNFEBR_VERSION, 324 true 325 ); 326 $sefaz_path = SBNFEBR_DIR . 'assets/js/nfebr-sefaz.js'; 327 wp_enqueue_script( 328 'sbnfebr-sefaz', 329 SBNFEBR_URL . 'assets/js/nfebr-sefaz.js', 330 array( 'sbnfebr-workflow' ), 331 file_exists( $sefaz_path ) ? filemtime( $sefaz_path ) : SBNFEBR_VERSION, 332 true 333 ); 334 $welcome_css_path = SBNFEBR_DIR . 'assets/css/nfebr-welcome.css'; 335 wp_enqueue_style( 336 'sbnfebr-style-welcome', 337 SBNFEBR_URL . 'assets/css/nfebr-welcome.css', 338 array( 'sbnfebr-style-core' ), 339 file_exists( $welcome_css_path ) ? filemtime( $welcome_css_path ) : SBNFEBR_VERSION 340 ); 341 $welcome_path = SBNFEBR_DIR . 'assets/js/nfebr-welcome.js'; 342 wp_enqueue_script( 343 'sbnfebr-welcome', 344 SBNFEBR_URL . 'assets/js/nfebr-welcome.js', 345 array( 'sbnfebr-core', 'sbnfebr-workflow' ), 346 file_exists( $welcome_path ) ? filemtime( $welcome_path ) : SBNFEBR_VERSION, 347 true 348 ); 349 if ( sbnfebr_is_plus() ) { 350 $workflow_plus_path = SBNFEBR_DIR . 'plus/assets/js/nfebr-workflow-plus.js'; 351 wp_enqueue_script( 352 'sbnfebr-workflow-plus', 353 SBNFEBR_URL . 'plus/assets/js/nfebr-workflow-plus.js', 354 array( 'sbnfebr-sefaz' ), 355 file_exists( $workflow_plus_path ) ? filemtime( $workflow_plus_path ) : SBNFEBR_VERSION, 356 true 357 ); 358 $link_plus_path = SBNFEBR_DIR . 'plus/assets/js/nfebr-link-plus.js'; 359 wp_enqueue_script( 360 'sbnfebr-link-plus', 361 SBNFEBR_URL . 'plus/assets/js/nfebr-link-plus.js', 362 array( 'sbnfebr-workflow-plus' ), 363 file_exists( $link_plus_path ) ? filemtime( $link_plus_path ) : SBNFEBR_VERSION, 364 true 365 ); 366 $audit_plus_path = SBNFEBR_DIR . 'plus/assets/js/nfebr-bulk-audit-plus.js'; 367 wp_enqueue_script( 368 'sbnfebr-bulk-audit-plus', 369 SBNFEBR_URL . 'plus/assets/js/nfebr-bulk-audit-plus.js', 370 array( 'sbnfebr-link-plus' ), 371 file_exists( $audit_plus_path ) ? filemtime( $audit_plus_path ) : SBNFEBR_VERSION, 372 true 373 ); 374 $prompt_plus_path = SBNFEBR_DIR . 'plus/assets/js/nfebr-import-prompt-plus.js'; 375 wp_enqueue_script( 376 'sbnfebr-import-prompt-plus', 377 SBNFEBR_URL . 'plus/assets/js/nfebr-import-prompt-plus.js', 378 array( 'sbnfebr-link-plus' ), 379 file_exists( $prompt_plus_path ) ? filemtime( $prompt_plus_path ) : SBNFEBR_VERSION, 380 true 381 ); 382 } 383 275 384 // after the handle (see languages/). 276 foreach (array(385 $translation_handles = array( 277 386 'sbnfebr-core', 278 387 'sbnfebr-grid', … … 280 389 'sbnfebr-item-actions', 281 390 'sbnfebr-diff-card', 282 'sbnfebr-review-modal',283 391 'sbnfebr-library-notes', 284 392 'sbnfebr-library-supplier', … … 287 395 'sbnfebr-price-history', 288 396 'sbnfebr-registry-check', 289 ) as $handle ) { 397 'sbnfebr-workflow', 398 'sbnfebr-sefaz', 399 'sbnfebr-welcome', 400 ); 401 if ( sbnfebr_is_plus() ) { 402 $translation_handles[] = 'sbnfebr-workflow-plus'; 403 $translation_handles[] = 'sbnfebr-link-plus'; 404 $translation_handles[] = 'sbnfebr-import-prompt-plus'; 405 $translation_handles[] = 'sbnfebr-bulk-audit-plus'; 406 } 407 foreach ( $translation_handles as $handle ) { 290 408 wp_set_script_translations( 291 409 $handle, … … 301 419 'rest_nonce' => wp_create_nonce( 'wp_rest' ), 302 420 'is_plus' => sbnfebr_is_plus(), 421 'can_manage' => current_user_can( 'manage_woocommerce' ), 303 422 'adminUrl' => esc_url_raw( admin_url() ), 304 // Sheet screen URL, only when the Sheet plugin is active in305 // the same PHP process. Empty means not installed, and the306 423 // client hides the option. 307 424 'sm_admin_url' => class_exists( 'SBESFW_Admin' ) ? esc_url_raw( admin_url( 'admin.php?page=sbesfw' ) ) : '', 308 'fc_url' => self::fiscal_check_tab() ? esc_url_raw( self::fiscal_check_url() ) : '', 425 'fc_url' => '', 426 'plus_cta' => self::plus_cta(), 427 'license' => self::license_info(), 428 'welcome' => array( 429 'show' => current_user_can( 'edit_products' ) && get_user_meta( get_current_user_id(), SBNFEBR_Settings_Controller::WELCOME_META, true ) !== SBNFEBR_VERSION, 430 'version' => SBNFEBR_VERSION, 431 ), 309 432 ) 310 433 ); 311 434 } 312 435 313 /**314 * Fiscal Check tab: only when both plugins are Plus.315 *316 * @return bool317 */318 public static function fiscal_check_tab() {319 return sbnfebr_is_plus() && function_exists( 'sbfcbr_is_plus' ) && sbfcbr_is_plus();320 }321 322 /**323 * Fiscal Check screen URL; keeps ?embed=1 inside the Sheet modal.324 *325 * @return string326 */327 public static function fiscal_check_url() {328 $embedded = isset( $_GET['embed'] ) && '1' === $_GET['embed']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended329 return admin_url( 'admin.php?page=sbfcbr' . ( $embedded ? '&embed=1' : '' ) );330 }331 332 /* ===========================================================333 * SHEET INTEGRATION — a button on the Sheet's toolbar opens SBNFEBR334 * in a modal. The Sheet exposes #sb-row1-extensions as an anchor335 * point; each extension injects its own button there via JS. Does336 * not modify anything on the Sheet's side.337 * ========================================================= */338 339 /**340 * Enqueues the bridge script only on the Sheet's screen341 * (admin.php?page=sbesfw), never on this plugin's own screen or any other.342 *343 * @param string $hook Current admin screen hook (unused — the real check344 * is the 'page' query param, like enqueue() does via345 * strpos($hook,'sbnfebr')).346 * @return void347 */348 436 public static function enqueue_sheet_bridge( $hook ) { 349 437 if ( ! isset( $_GET['page'] ) || 'sbesfw' !== $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended … … 378 466 array( 379 467 'modal_url' => esc_url_raw( admin_url( 'admin.php?page=sbnfebr&embed=1' ) ), 380 // The "Import from NF-e" button only appears when SBNFEBR is381 // running the Plus edition — Lite has no Make Draft+ to offer.382 468 'is_plus' => sbnfebr_is_plus(), 383 // Installed NF-e version, shown next to the Sheet's own384 469 // version tag (.sb-version-tag). 385 470 'version' => SBNFEBR_VERSION, … … 388 473 } 389 474 390 /**391 * When this screen is opened with ?embed=1 (inside the Sheet's modal392 * iframe), hides WP-admin chrome (side menu, admin bar, footer) so393 * only the plugin content fills the iframe. CSS only — added as an394 * inline block on the already-enqueued 'sbnfebr-style-core' handle395 * (must run inside enqueue(), on admin_enqueue_scripts: admin_head396 * fires after styles are already printed, too late for397 * wp_add_inline_style() to have any effect).398 *399 * @return void400 */401 475 protected static function maybe_add_embed_inline_style() { 402 476 if ( ! isset( $_GET['page'] ) || 'sbnfebr' !== $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended … … 415 489 } 416 490 417 /* ===========================================================418 * RENDER PAGE (HTML scaffold)419 * ========================================================= */420 421 491 /** 422 492 * Renders the plugin's main page. … … 425 495 */ 426 496 public static function render_page() { 497 $sbnfebr_migration_error = get_option( SBNFEBR_Workflow_Service::MIGRATION_ERROR_OPTION, '' ); 498 $sbnfebr_has_pre_migration_backup = is_array( get_option( SBNFEBR_Workflow_Service::PRE_MIGRATION_BACKUP_OPTION, false ) ); 427 499 ?> 428 <div class="wrap " id="sbnfebr-wrap">500 <div class="wrap <?php echo sbnfebr_is_plus() ? 'sbnfebr-edition--plus' : 'sbnfebr-edition--lite'; ?>" id="sbnfebr-wrap"> 429 501 <div id="sbnfebr-header-area"> 502 <?php if ( $sbnfebr_migration_error ) : ?> 503 <div class="sbnfebr-notice sbnfebr-notice--error" role="alert"><?php echo esc_html( $sbnfebr_migration_error ); ?></div> 504 <?php endif; ?> 430 505 431 506 <div class="sbnfebr-row1"> … … 433 508 <a href="https://software.sanbazar.com.br" target="_blank" rel="noopener" class="sb-pro-link sb-pro-link--compact" title="<?php esc_attr_e( 'Conheça a suíte de softwares SanBar', 'sanbar-express-nfe-xml-import-br' ); ?>"><?php esc_html_e( 'Conheça nossa Suíte SanBar', 'sanbar-express-nfe-xml-import-br' ); ?></a> 434 509 <span class="sb-brand"> 510 <span class="sb-brand__mobile"><?php esc_html_e( 'XML Import-BR', 'sanbar-express-nfe-xml-import-br' ); ?></span> 435 511 <span class="sb-brand__prefix"><?php esc_html_e( 'SanBar', 'sanbar-express-nfe-xml-import-br' ); ?></span> 436 512 <span class="sb-brand__main"><?php esc_html_e( 'EXPress NF-e XML', 'sanbar-express-nfe-xml-import-br' ); ?></span> 437 <span class="sb-brand__suffix"><?php esc_html_e( ' for WooCommerce', 'sanbar-express-nfe-xml-import-br' ); ?></span>513 <span class="sb-brand__suffix"><?php esc_html_e( 'Gestão de produtos', 'sanbar-express-nfe-xml-import-br' ); ?></span> 438 514 </span> 439 515 <?php if ( sbnfebr_is_plus() ) : ?> … … 442 518 <span class="sb-edition-lite">Lite</span> 443 519 <?php endif; ?> 520 <?php $sbnfebr_cta = self::plus_cta(); ?> 521 <?php if ( '' !== $sbnfebr_cta['url'] ) : ?> 522 <a id="sbnfebr-btn-upgrade" class="sbnfebr-btn sbnfebr-btn--amber" href="<?php echo esc_url( $sbnfebr_cta['url'] ); ?>"><?php echo $sbnfebr_cta['trial'] ? esc_html__( '✦ Testar Plus grátis', 'sanbar-express-nfe-xml-import-br' ) : esc_html__( '✦ Conhecer o Plus', 'sanbar-express-nfe-xml-import-br' ); ?></a> 523 <?php endif; ?> 444 524 <span class="sb-version-tag" title="<?php esc_attr_e( 'Versão instalada do plugin', 'sanbar-express-nfe-xml-import-br' ); ?>">v<?php echo esc_html( SBNFEBR_VERSION ); ?></span> 525 </h1> 526 <div class="sbnfebr-row1__actions"> 445 527 <input type="file" id="sbnfebr-file-input" accept=".xml" style="display:none"> 446 528 <?php 447 // Tooltip surfaces upload limits (size/items/frequency)448 529 // directly on the button. 449 530 $sbnfebr_upload_tooltip = sprintf( 450 /* translators: 1: max file size in MB, 2: max item count, 3: max uploadsper minute. */531 /* translators: 1: MB, 2: items, 3: per minute. */ 451 532 __( 'Aceita .xml de até %1$dMB, %2$d itens, %3$d envios por minuto.', 'sanbar-express-nfe-xml-import-br' ), 452 533 10, … … 456 537 ?> 457 538 <button id="sbnfebr-btn-upload" class="sbnfebr-btn sbnfebr-btn--blue" title="<?php echo esc_attr( $sbnfebr_upload_tooltip ); ?>"><?php esc_html_e( '⬆ Importar XML', 'sanbar-express-nfe-xml-import-br' ); ?></button> 458 <?php /* Amber (Plus, full product) or blue (Lite, identity only) — set in JS. */ ?> 459 <button type="button" id="sbnfebr-btn-bulk-draft-plus" class="sbnfebr-btn<?php echo sbnfebr_is_plus() ? ' sbnfebr-btn--amber' : ' sbnfebr-btn--blue'; ?>" style="display:none"></button> 460 <button type="button" id="sbnfebr-btn-bulk-ignore" class="sbnfebr-btn" style="display:none"></button> 461 <button type="button" id="sbnfebr-btn-bulk-show-selected" class="sbnfebr-btn" style="display:none"></button> 462 <button type="button" id="sbnfebr-btn-bulk-copy-codes" class="sbnfebr-btn" title="<?php esc_attr_e( 'Copiar código/GTIN dos itens selecionados', 'sanbar-express-nfe-xml-import-br' ); ?>" style="display:none">📋</button> 463 <button type="button" id="sbnfebr-btn-bulk-clear" title="<?php esc_attr_e( 'Limpar seleção', 'sanbar-express-nfe-xml-import-br' ); ?>" style="display:none">✕</button> 464 </h1> 539 <?php if ( sbnfebr_is_plus() ) : ?> 540 <span class="sbnfebr-bulk-toolbar" aria-label="<?php esc_attr_e( 'Ações dos itens selecionados', 'sanbar-express-nfe-xml-import-br' ); ?>"> 541 <button type="button" id="sbnfebr-btn-bulk-draft-plus" class="sbnfebr-btn sbnfebr-btn--amber" style="display:none"></button> 542 <button type="button" id="sbnfebr-btn-bulk-ignore" class="sbnfebr-btn" style="display:none"></button> 543 <button type="button" id="sbnfebr-btn-bulk-show-selected" class="sbnfebr-btn" style="display:none"></button> 544 <button type="button" id="sbnfebr-btn-bulk-copy-codes" class="sbnfebr-btn" title="<?php esc_attr_e( 'Copiar código/GTIN dos itens selecionados', 'sanbar-express-nfe-xml-import-br' ); ?>" style="display:none">📋</button> 545 <button type="button" id="sbnfebr-btn-bulk-clear" title="<?php esc_attr_e( 'Limpar seleção', 'sanbar-express-nfe-xml-import-br' ); ?>" style="display:none">✕</button> 546 </span> 547 <?php endif; ?> 548 </div> 465 549 <div class="sbnfebr-row1__right"> 466 <?php if ( self::fiscal_check_tab() ) : ?>467 <nav class="sb-suite-tabs" aria-label="<?php esc_attr_e( 'Telas da suíte', 'sanbar-express-nfe-xml-import-br' ); ?>">468 <span class="sb-suite-tab sb-suite-tab--active" aria-current="page">📄 <?php esc_html_e( 'XML Import', 'sanbar-express-nfe-xml-import-br' ); ?></span>469 <a class="sb-suite-tab" href="<?php echo esc_url( self::fiscal_check_url() ); ?>">🔎 <?php esc_html_e( 'Fiscal Check', 'sanbar-express-nfe-xml-import-br' ); ?></a>470 </nav>471 <?php endif; ?>472 550 <button type="button" id="sbnfebr-btn-glossary" class="sbnfebr-errorlog-btn" title="<?php esc_attr_e( 'O que os ícones significam', 'sanbar-express-nfe-xml-import-br' ); ?>">?</button> 473 <button type="button" id="sbnfebr-btn-errorlog" class="sbnfebr-errorlog-btn" title="<?php esc_attr_e( 'Log interno de erros', 'sanbar-express-nfe-xml-import-br' ); ?>">!</button> 551 <button type="button" id="sbnfebr-btn-errorlog" class="sbnfebr-errorlog-btn" title="<?php esc_attr_e( 'Log interno de erros', 'sanbar-express-nfe-xml-import-br' ); ?>" aria-label="<?php esc_attr_e( 'Abrir log interno de erros', 'sanbar-express-nfe-xml-import-br' ); ?>"><span class="dashicons dashicons-media-text" aria-hidden="true"></span></button> 552 <div class="sbnfebr-backup" id="sbnfebr-backup"> 553 <button type="button" id="sbnfebr-btn-backup" class="sbnfebr-errorlog-btn" aria-haspopup="true" aria-expanded="false" aria-controls="sbnfebr-backup-menu" title="<?php esc_attr_e( 'Backup da Conferência', 'sanbar-express-nfe-xml-import-br' ); ?>" aria-label="<?php esc_attr_e( 'Abrir opções de backup', 'sanbar-express-nfe-xml-import-br' ); ?>"><span class="dashicons dashicons-backup" aria-hidden="true"></span></button> 554 <div class="sbnfebr-backup__menu" id="sbnfebr-backup-menu" hidden> 555 <button type="button" class="sbnfebr-btn" id="sbnfebr-workflow-export"><?php esc_html_e( 'Baixar backup', 'sanbar-express-nfe-xml-import-br' ); ?></button> 556 <?php if ( $sbnfebr_has_pre_migration_backup ) : ?><button type="button" class="sbnfebr-btn" id="sbnfebr-workflow-export-pre-migration"><?php esc_html_e( 'Backup pré-migração', 'sanbar-express-nfe-xml-import-br' ); ?></button><?php endif; ?> 557 <button type="button" class="sbnfebr-btn" id="sbnfebr-workflow-import"><?php esc_html_e( 'Restaurar backup', 'sanbar-express-nfe-xml-import-br' ); ?></button> 558 <input type="file" id="sbnfebr-workflow-import-file" accept="application/json,.json" hidden> 559 </div> 560 </div> 561 <button type="button" id="sbnfebr-btn-settings" class="sbnfebr-errorlog-btn" title="<?php esc_attr_e( 'Configurações do plugin', 'sanbar-express-nfe-xml-import-br' ); ?>" aria-label="<?php esc_attr_e( 'Abrir configurações do plugin', 'sanbar-express-nfe-xml-import-br' ); ?>"><span class="dashicons dashicons-admin-generic" aria-hidden="true"></span></button> 474 562 </div> 475 563 </div> 476 564 565 <nav class="sbnfebr-workflow-tabs" id="sbnfebr-workflow-tabs" aria-label="<?php esc_attr_e( 'Etapas do processamento', 'sanbar-express-nfe-xml-import-br' ); ?>"> 566 <button type="button" class="sbnfebr-workflow-tab is-active" data-stage="entry" aria-current="step"><span class="sbnfebr-workflow-tab__index">1</span><?php esc_html_e( 'Entrada', 'sanbar-express-nfe-xml-import-br' ); ?></button> 567 <button type="button" class="sbnfebr-workflow-tab" data-stage="catalog"><span class="sbnfebr-workflow-tab__index">2</span><?php esc_html_e( 'Cadastro e atualização', 'sanbar-express-nfe-xml-import-br' ); ?></button> 568 </nav> 569 570 <button type="button" class="sbnfebr-mobile-drawer-toggle" data-mobile-drawer-toggle="sbnfebr-entry-tools" aria-controls="sbnfebr-entry-tools" aria-expanded="false"><span><?php esc_html_e( 'Filtros e visualização', 'sanbar-express-nfe-xml-import-br' ); ?></span><i aria-hidden="true">⌄</i></button> 571 <div class="sbnfebr-mobile-drawer" id="sbnfebr-entry-tools"> 477 572 <div class="sbnfebr-row2"> 478 573 <label for="sbnfebr-filter-supplier" class="screen-reader-text"><?php esc_html_e( 'Filtrar por fornecedor', 'sanbar-express-nfe-xml-import-br' ); ?></label> … … 486 581 <option value=""><?php esc_html_e( 'Todas as notas', 'sanbar-express-nfe-xml-import-br' ); ?></option> 487 582 </select> 488 <?php /* Info-only counterpart to the supplier "!": full note data present only in the XML (freight, tax basis, receivables). Enabled only when one specific note is selected. */?>583 <?php ?> 489 584 <button type="button" id="sbnfebr-btn-note-info" class="sbnfebr-note-info-btn" title="<?php esc_attr_e( 'Ver detalhes completos da nota', 'sanbar-express-nfe-xml-import-br' ); ?>" disabled>i</button> 490 585 … … 492 587 <select id="sbnfebr-filter-mode" title="<?php esc_attr_e( 'Filtro especial', 'sanbar-express-nfe-xml-import-br' ); ?>"> 493 588 <option value=""><?php esc_html_e( 'Todos os itens', 'sanbar-express-nfe-xml-import-br' ); ?></option> 494 <option value="linked">🔀 <?php esc_html_e( 'Já criado / vinculado', 'sanbar-express-nfe-xml-import-br' ); ?></option> 495 <option value="pending">➕ <?php esc_html_e( 'Pendente (ainda sem produto)', 'sanbar-express-nfe-xml-import-br' ); ?></option> 496 <option value="stale">⚠️ <?php esc_html_e( 'Vínculo desatualizado', 'sanbar-express-nfe-xml-import-br' ); ?></option> 497 <option value="price_warn">🟡 <?php esc_html_e( 'Preço variou entre notas', 'sanbar-express-nfe-xml-import-br' ); ?></option> 498 <?php if ( sbnfebr_is_plus() ) : ?> 499 <option value="supplier_match">❗ <?php esc_html_e( 'Correspondência achada por fornecedor + código', 'sanbar-express-nfe-xml-import-br' ); ?></option> 500 <option value="sync_pending">⚠ <?php esc_html_e( 'Sync pendente / desatualizado', 'sanbar-express-nfe-xml-import-br' ); ?></option> 501 <option value="has_fiscal">🧾 <?php esc_html_e( 'Vinculado, com dados fiscais', 'sanbar-express-nfe-xml-import-br' ); ?></option> 502 <?php endif; ?> 503 <option value="duplicates">🔴 <?php esc_html_e( 'Duplicado / mesmo GTIN', 'sanbar-express-nfe-xml-import-br' ); ?></option> 504 <option value="price_period">📅 <?php esc_html_e( 'Preço variou no período', 'sanbar-express-nfe-xml-import-br' ); ?></option> 505 <option value="notes_period">📅 <?php esc_html_e( 'Notas no período', 'sanbar-express-nfe-xml-import-br' ); ?></option> 506 <option value="ignored">👁 <?php esc_html_e( 'Ignorados', 'sanbar-express-nfe-xml-import-br' ); ?></option> 589 <optgroup label="<?php esc_attr_e( 'Cadastro', 'sanbar-express-nfe-xml-import-br' ); ?>"> 590 <option value="linked"><?php esc_html_e( 'Vinculado a um produto', 'sanbar-express-nfe-xml-import-br' ); ?></option> 591 <option value="pending"><?php esc_html_e( 'Sem vínculo com produto', 'sanbar-express-nfe-xml-import-br' ); ?></option> 592 <option value="lvl_prep"><?php esc_html_e( 'Em preparação', 'sanbar-express-nfe-xml-import-br' ); ?></option> 593 <option value="lvl_simple"><?php esc_html_e( 'Cadastro simples', 'sanbar-express-nfe-xml-import-br' ); ?></option> 594 <option value="lvl_invoice"><?php esc_html_e( 'Dados da nota', 'sanbar-express-nfe-xml-import-br' ); ?></option> 595 <option value="lvl_regime"><?php esc_html_e( 'Regime completo', 'sanbar-express-nfe-xml-import-br' ); ?></option> 596 <option value="lvl_issues"><?php esc_html_e( 'Enviado com pendências', 'sanbar-express-nfe-xml-import-br' ); ?></option> 597 </optgroup> 598 <optgroup label="<?php echo esc_attr( sbnfebr_is_plus() ? __( 'Vínculo', 'sanbar-express-nfe-xml-import-br' ) : __( 'Vínculo (Plus)', 'sanbar-express-nfe-xml-import-br' ) ); ?>"> 599 <?php $sbnfebr_lock = sbnfebr_is_plus() ? '' : ' disabled'; ?> 600 <option value="supplier_match"<?php echo $sbnfebr_lock; // phpcs:ignore WordPress.Security.EscapeOutput ?>><?php echo ( sbnfebr_is_plus() ? '' : '🔒 ' ) . esc_html__( 'Possível vínculo (fornecedor + código)', 'sanbar-express-nfe-xml-import-br' ); ?></option> 601 <option value="sync_pending"<?php echo $sbnfebr_lock; // phpcs:ignore WordPress.Security.EscapeOutput ?>><?php echo ( sbnfebr_is_plus() ? '' : '🔒 ' ) . esc_html__( 'Atualização pendente', 'sanbar-express-nfe-xml-import-br' ); ?></option> 602 <option value="has_fiscal"<?php echo $sbnfebr_lock; // phpcs:ignore WordPress.Security.EscapeOutput ?>><?php echo ( sbnfebr_is_plus() ? '' : '🔒 ' ) . esc_html__( 'Vinculado, fiscal em dia', 'sanbar-express-nfe-xml-import-br' ); ?></option> 603 </optgroup> 604 <optgroup label="<?php esc_attr_e( 'Alertas', 'sanbar-express-nfe-xml-import-br' ); ?>"> 605 <option value="stale"><?php esc_html_e( 'Vínculo desatualizado', 'sanbar-express-nfe-xml-import-br' ); ?></option> 606 <option value="duplicates"><?php esc_html_e( 'Duplicado / mesmo GTIN', 'sanbar-express-nfe-xml-import-br' ); ?></option> 607 <option value="price_warn"><?php esc_html_e( 'Preço variou entre notas', 'sanbar-express-nfe-xml-import-br' ); ?></option> 608 <option value="price_period"><?php esc_html_e( 'Preço variou no período', 'sanbar-express-nfe-xml-import-br' ); ?></option> 609 <option value="notes_period"><?php esc_html_e( 'Notas no período', 'sanbar-express-nfe-xml-import-br' ); ?></option> 610 <option value="ignored"><?php esc_html_e( 'Ignorados', 'sanbar-express-nfe-xml-import-br' ); ?></option> 611 </optgroup> 507 612 </select> 508 613 <span id="sbnfebr-filter-dates" style="display:none"> … … 514 619 515 620 <button type="button" id="sbnfebr-btn-clear-filters" class="sbnfebr-btn" title="<?php esc_attr_e( 'Limpar todos os filtros', 'sanbar-express-nfe-xml-import-br' ); ?>">✕ <?php esc_html_e( 'Limpar filtros', 'sanbar-express-nfe-xml-import-br' ); ?></button> 516 <input type="text" id="sbnfebr-search" placeholder="<?php esc_attr_e( ' Buscar descrição, código, GTIN…', 'sanbar-express-nfe-xml-import-br' ); ?>" autocomplete="off">621 <input type="text" id="sbnfebr-search" placeholder="<?php esc_attr_e( 'Produto, código, GTIN ou fornecedor', 'sanbar-express-nfe-xml-import-br' ); ?>" autocomplete="off"> 517 622 </div> 518 623 … … 523 628 <span class="sbnfebr-stat__val" id="sbnfebr-stat-total">—</span> 524 629 </div> 525 <?php /* Counts product identity (GTIN, or supplier+code when no GTIN), visible in both view modes. */?>630 <?php ?> 526 631 <div class="sbnfebr-stat"> 527 632 <span class="sbnfebr-stat__label"><?php esc_html_e( 'Produtos únicos', 'sanbar-express-nfe-xml-import-br' ); ?></span> … … 544 649 <span class="sbnfebr-stat__val">🔎</span> 545 650 </button> 651 <button type="button" id="sbnfebr-btn-ignored-drawer" class="sbnfebr-stat sbnfebr-stat--link sbnfebr-ignored-drawer" aria-pressed="false" title="<?php esc_attr_e( 'Ver produtos ocultos e restaurá-los individualmente', 'sanbar-express-nfe-xml-import-br' ); ?>"> 652 <span class="sbnfebr-stat__label"><?php esc_html_e( 'Ocultos', 'sanbar-express-nfe-xml-import-br' ); ?></span> 653 <span class="sbnfebr-stat__val" id="sbnfebr-stat-ignored">—</span> 654 </button> 546 655 </div> 547 656 <div class="sbnfebr-stats__right"> 548 <?php /* Toggles the grid between "per note line" (default) and "per product" (grouped by GTIN/supplier+code); both segments stay visible with the active one highlighted. */?>657 <?php ?> 549 658 <span class="sbnfebr-view-toggle" id="sbnfebr-view-toggle"> 550 659 <button type="button" id="sbnfebr-btn-view-note" class="sbnfebr-view-toggle__btn" data-mode="note" title="<?php esc_attr_e( 'Visão por nota (1 linha por lançamento de nota)', 'sanbar-express-nfe-xml-import-br' ); ?>">🗒 <?php esc_html_e( 'Por nota', 'sanbar-express-nfe-xml-import-br' ); ?></button> … … 556 665 <button type="button" id="sbnfebr-page-next" class="sbnfebr-btn" title="<?php esc_attr_e( 'Próxima página', 'sanbar-express-nfe-xml-import-br' ); ?>">▶</button> 557 666 <label for="sbnfebr-per-page" class="screen-reader-text"><?php esc_html_e( 'Itens por página', 'sanbar-express-nfe-xml-import-br' ); ?></label> 667 <span class="sbnfebr-pagination__per-page" aria-hidden="true"><?php esc_html_e( 'por página', 'sanbar-express-nfe-xml-import-br' ); ?></span> 558 668 <select id="sbnfebr-per-page" title="<?php esc_attr_e( 'Itens por página', 'sanbar-express-nfe-xml-import-br' ); ?>"> 559 669 <option value="25">25</option> … … 563 673 </select> 564 674 </span> 565 <span id="sbnfebr-col-panel-wrap">566 <button id="sbnfebr-btn-cols" class="sbnfebr-btn" title="<?php esc_attr_e( 'Mostrar/ocultar colunas', 'sanbar-express-nfe-xml-import-br' ); ?>"><?php esc_html_e( '⚙ Configurar', 'sanbar-express-nfe-xml-import-br' ); ?></button>567 </span>568 675 </div> 676 </div> 569 677 </div> 570 678 </div> … … 584 692 </table> 585 693 </div> 694 695 <div class="sbnfebr-catalog-area" id="sbnfebr-workflow-catalog" hidden> 696 <div class="sbnfebr-catalog-head"> 697 <div><strong><?php esc_html_e( 'Cadastro e atualização', 'sanbar-express-nfe-xml-import-br' ); ?></strong><span><?php esc_html_e( 'Produtos preparados, aguardando envio ou já sincronizados.', 'sanbar-express-nfe-xml-import-br' ); ?></span></div> 698 <div class="sbnfebr-catalog-head__controls"> 699 <div class="sbnfebr-catalog-views" role="group" aria-label="<?php esc_attr_e( 'Modo de visualização', 'sanbar-express-nfe-xml-import-br' ); ?>"> 700 <button type="button" data-catalog-view="sheet"><?php esc_html_e( 'Planilha', 'sanbar-express-nfe-xml-import-br' ); ?></button> 701 <button type="button" data-catalog-view="grouped"><?php esc_html_e( 'Agrupado', 'sanbar-express-nfe-xml-import-br' ); ?></button> 702 </div> 703 <div class="sbnfebr-catalog-filters" role="group" aria-label="<?php esc_attr_e( 'Filtrar por situação', 'sanbar-express-nfe-xml-import-br' ); ?>"> 704 <button type="button" class="sbnfebr-catalog-filter is-active" data-catalog-stage="review"><span class="sbnfebr-label-wide"><?php esc_html_e( 'Aguardando preparação', 'sanbar-express-nfe-xml-import-br' ); ?></span><span class="sbnfebr-label-mobile"><?php esc_html_e( 'Em preparação', 'sanbar-express-nfe-xml-import-br' ); ?></span></button> 705 <button type="button" class="sbnfebr-catalog-filter" data-catalog-stage="sync"><span class="sbnfebr-label-wide"><?php esc_html_e( 'Cadastrados e sincronizados', 'sanbar-express-nfe-xml-import-br' ); ?></span><span class="sbnfebr-label-mobile"><?php esc_html_e( 'Sincronizados', 'sanbar-express-nfe-xml-import-br' ); ?></span></button> 706 </div> 707 </div> 708 </div> 709 710 <section class="sbnfebr-workflow-panel" id="sbnfebr-workflow-review" data-stage="review" hidden> 711 <div class="sbnfebr-workflow-toolbar"> 712 <div><strong><?php esc_html_e( 'Conferência fiscal', 'sanbar-express-nfe-xml-import-br' ); ?></strong><span><?php esc_html_e( 'Revise os dados e aprove antes de enviar ao cadastro.', 'sanbar-express-nfe-xml-import-br' ); ?></span></div> 713 <button type="button" class="sbnfebr-mobile-drawer-toggle" data-mobile-drawer-toggle="sbnfebr-review-tools" aria-controls="sbnfebr-review-tools" aria-expanded="false"><span><?php esc_html_e( 'Filtros e ações', 'sanbar-express-nfe-xml-import-br' ); ?></span><i aria-hidden="true">⌄</i></button> 714 <div class="sbnfebr-workflow-toolbar__actions sbnfebr-mobile-drawer" id="sbnfebr-review-tools"> 715 <div class="sbnfebr-workflow-filters"><input type="search" id="sbnfebr-workflow-review-search" placeholder="<?php esc_attr_e( 'Produto, código, GTIN ou fornecedor', 'sanbar-express-nfe-xml-import-br' ); ?>"><select id="sbnfebr-workflow-review-status"><option value=""><?php esc_html_e( 'Todas as situações', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="error"><?php esc_html_e( 'Corrigir', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="warning"><?php esc_html_e( 'Revisar avisos', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="ok"><?php esc_html_e( 'Fiscal OK', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="approved"><?php esc_html_e( 'Aprovados', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="pending"><?php esc_html_e( 'Não aprovados', 'sanbar-express-nfe-xml-import-br' ); ?></option><optgroup label="<?php esc_attr_e( 'Nível de cadastro', 'sanbar-express-nfe-xml-import-br' ); ?>"><option value="lvl_none"><?php esc_html_e( 'A preparar', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="lvl_simple"><?php esc_html_e( 'Cadastro simples', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="lvl_invoice"><?php esc_html_e( 'Dados da nota', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="lvl_regime"><?php esc_html_e( 'Regime completo', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="lvl_issues"><?php esc_html_e( 'Enviado com pendências', 'sanbar-express-nfe-xml-import-br' ); ?></option></optgroup></select><button type="button" class="sbnfebr-btn sbnfebr-sort-cycle" id="sbnfebr-workflow-review-sort" data-sort="recent" title="<?php esc_attr_e( 'Mudar a ordem da lista', 'sanbar-express-nfe-xml-import-br' ); ?>"><span data-sort-label><?php esc_html_e( '↓ Mais recentes', 'sanbar-express-nfe-xml-import-br' ); ?></span></button><button type="button" class="sbnfebr-btn sbnfebr-filter-clear" id="sbnfebr-workflow-review-clear" title="<?php esc_attr_e( 'Limpar filtros', 'sanbar-express-nfe-xml-import-br' ); ?>" aria-label="<?php esc_attr_e( 'Limpar filtros', 'sanbar-express-nfe-xml-import-br' ); ?>" hidden>✕</button></div> 716 </div> 717 </div> 718 <div class="sbnfebr-workflow-tablewrap"><table class="sbnfebr-workflow-grid"><colgroup><col class="sbnfebr-wcol-action"><col class="sbnfebr-wcol-status"><col class="sbnfebr-wcol-product"><col class="sbnfebr-wcol-gtin"><col class="sbnfebr-wcol-cost"><col class="sbnfebr-wcol-ncm"><col class="sbnfebr-wcol-cest"><col class="sbnfebr-wcol-csosn"><col class="sbnfebr-wcol-cfop"><col class="sbnfebr-wcol-regime"></colgroup><thead><tr><th class="sbnfebr-workflow-head--action"></th><th class="sbnfebr-workflow-head--status"><?php esc_html_e( 'Situação', 'sanbar-express-nfe-xml-import-br' ); ?></th><th class="sbnfebr-workflow-head--product"><?php esc_html_e( 'Produto', 'sanbar-express-nfe-xml-import-br' ); ?></th><th class="sbnfebr-workflow-head--gtin">GTIN</th><th class="sbnfebr-workflow-head--cost"><span class="sbnfebr-label-wide"><?php esc_html_e( 'Custo', 'sanbar-express-nfe-xml-import-br' ); ?></span><span class="sbnfebr-label-mobile"><?php esc_html_e( 'Preço', 'sanbar-express-nfe-xml-import-br' ); ?></span></th><th>NCM</th><th>CEST</th><th><?php esc_html_e( 'CSOSN venda', 'sanbar-express-nfe-xml-import-br' ); ?></th><th><?php esc_html_e( 'CFOP venda', 'sanbar-express-nfe-xml-import-br' ); ?></th><th><?php esc_html_e( 'Regime', 'sanbar-express-nfe-xml-import-br' ); ?></th></tr></thead><tbody id="sbnfebr-workflow-review-body"></tbody></table></div> 719 <div class="sbnfebr-workflow-empty" id="sbnfebr-workflow-review-empty" hidden><?php esc_html_e( 'Nenhum produto aguardando conferência.', 'sanbar-express-nfe-xml-import-br' ); ?></div> 720 <div class="sbnfebr-workflow-pager" data-workflow-pager="review"><button type="button" class="sbnfebr-btn" data-page-prev>‹</button><span data-page-label></span><button type="button" class="sbnfebr-btn" data-page-next>›</button></div> 721 </section> 722 723 <section class="sbnfebr-workflow-panel" id="sbnfebr-workflow-sync" data-stage="sync" hidden> 724 <div class="sbnfebr-workflow-toolbar"><div><strong><?php esc_html_e( 'Produtos sincronizados', 'sanbar-express-nfe-xml-import-br' ); ?></strong><span><?php esc_html_e( 'Envios confirmados, com tentativas e histórico auditável.', 'sanbar-express-nfe-xml-import-br' ); ?></span></div><button type="button" class="sbnfebr-mobile-drawer-toggle" data-mobile-drawer-toggle="sbnfebr-sync-tools" aria-controls="sbnfebr-sync-tools" aria-expanded="false"><span><?php esc_html_e( 'Filtros e ações', 'sanbar-express-nfe-xml-import-br' ); ?></span><i aria-hidden="true">⌄</i></button><div class="sbnfebr-workflow-toolbar__actions sbnfebr-mobile-drawer" id="sbnfebr-sync-tools"><div class="sbnfebr-workflow-filters"><input type="search" id="sbnfebr-workflow-sync-search" placeholder="<?php esc_attr_e( 'Produto, código, GTIN ou fornecedor', 'sanbar-express-nfe-xml-import-br' ); ?>"><select id="sbnfebr-workflow-sync-status"><option value=""><?php esc_html_e( 'Todos os resultados', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="first_try"><?php esc_html_e( 'Na primeira tentativa', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="retried"><?php esc_html_e( 'Após nova tentativa', 'sanbar-express-nfe-xml-import-br' ); ?></option><optgroup label="<?php esc_attr_e( 'Nível de cadastro', 'sanbar-express-nfe-xml-import-br' ); ?>"><option value="lvl_simple"><?php esc_html_e( 'Cadastro simples', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="lvl_invoice"><?php esc_html_e( 'Dados da nota', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="lvl_regime"><?php esc_html_e( 'Regime completo', 'sanbar-express-nfe-xml-import-br' ); ?></option><option value="lvl_issues"><?php esc_html_e( 'Enviado com pendências', 'sanbar-express-nfe-xml-import-br' ); ?></option></optgroup></select><button type="button" class="sbnfebr-btn sbnfebr-sort-cycle" id="sbnfebr-workflow-sync-sort" data-sort="recent" title="<?php esc_attr_e( 'Mudar a ordem da lista', 'sanbar-express-nfe-xml-import-br' ); ?>"><span data-sort-label><?php esc_html_e( '↓ Mais recentes', 'sanbar-express-nfe-xml-import-br' ); ?></span></button><button type="button" class="sbnfebr-btn sbnfebr-filter-clear" id="sbnfebr-workflow-sync-clear" title="<?php esc_attr_e( 'Limpar filtros', 'sanbar-express-nfe-xml-import-br' ); ?>" aria-label="<?php esc_attr_e( 'Limpar filtros', 'sanbar-express-nfe-xml-import-br' ); ?>" hidden>✕</button></div></div></div> 725 <div class="sbnfebr-workflow-tablewrap"><table class="sbnfebr-workflow-grid sbnfebr-workflow-sync-grid"><colgroup><col class="sbnfebr-wcol-action"><col class="sbnfebr-wcol-product"><col class="sbnfebr-wcol-gtin"><col class="sbnfebr-wcol-cost"><col class="sbnfebr-wcol-ncm"><col class="sbnfebr-wcol-product-id"><col class="sbnfebr-wcol-result"><col class="sbnfebr-wcol-attempts"><col class="sbnfebr-wcol-activity"></colgroup><thead><tr><th class="sbnfebr-workflow-head--action"><?php esc_html_e( 'Ação', 'sanbar-express-nfe-xml-import-br' ); ?></th><th class="sbnfebr-workflow-head--product"><?php esc_html_e( 'Produto', 'sanbar-express-nfe-xml-import-br' ); ?></th><th class="sbnfebr-workflow-head--gtin">GTIN</th><th class="sbnfebr-workflow-head--cost"><span class="sbnfebr-label-wide"><?php esc_html_e( 'Custo', 'sanbar-express-nfe-xml-import-br' ); ?></span><span class="sbnfebr-label-mobile"><?php esc_html_e( 'Preço', 'sanbar-express-nfe-xml-import-br' ); ?></span></th><th>NCM</th><th><?php esc_html_e( 'Produto cadastrado', 'sanbar-express-nfe-xml-import-br' ); ?></th><th class="sbnfebr-workflow-head--result"><?php esc_html_e( 'Resultado', 'sanbar-express-nfe-xml-import-br' ); ?></th><th><?php esc_html_e( 'Tentativas', 'sanbar-express-nfe-xml-import-br' ); ?></th><th><?php esc_html_e( 'Última atividade', 'sanbar-express-nfe-xml-import-br' ); ?></th></tr></thead><tbody id="sbnfebr-workflow-sync-body"></tbody></table></div> 726 <div class="sbnfebr-workflow-empty" id="sbnfebr-workflow-sync-empty" hidden><?php esc_html_e( 'Nenhum produto sincronizado ainda.', 'sanbar-express-nfe-xml-import-br' ); ?></div> 727 <div class="sbnfebr-workflow-pager" data-workflow-pager="sync"><button type="button" class="sbnfebr-btn" data-page-prev>‹</button><span data-page-label></span><button type="button" class="sbnfebr-btn" data-page-next>›</button></div> 728 </section> 729 </div> 586 730 </div> 587 731 <?php -
sanbar-express-nfe-xml-import-br/trunk/includes/class-sbnfebr-rest.php
r3725460 r3782421 1 1 <?php 2 /**3 * Registers all of the plugin's REST routes (namespace sbnfebr/v1).4 *5 * @package SBNFEBR6 * @since 0.2.07 */8 2 9 3 defined( 'ABSPATH' ) || exit; … … 20 14 } 21 15 22 /**23 * Registers the routes for each controller.24 *25 * @return void26 */27 16 public static function register_routes() { 28 17 SBNFEBR_Import_Controller::register_routes(); 18 SBNFEBR_Workflow_Controller::register_routes(); 19 SBNFEBR_Full_Backup_Controller::register_routes(); 29 20 SBNFEBR_Items_Controller::register_routes(); 30 21 SBNFEBR_Suppliers_Library_Controller::register_routes(); … … 33 24 SBNFEBR_Error_Log_Controller::register_routes(); 34 25 SBNFEBR_Match_Controller::register_routes(); 26 SBNFEBR_Fiscal_Controller::register_routes(); 35 27 36 // Plus routes (/sync, /link-update, /link-plus) only exist when the37 // plus/ tree is loaded (see sbnfebr_load_modules() in38 28 // sanbar-express-nfe-xml-import-br.php). 39 29 if ( class_exists( 'SBNFEBR_Draft_Controller_Plus' ) ) { -
sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-draft-controller.php
r3725460 r3782421 1 1 <?php 2 /**3 * REST controller for the item action modal: Make Draft, Link, Sync4 * (Plus), Price/Source, Unlink.5 *6 * @package SBNFEBR7 * @since 0.4.08 */9 2 10 3 defined( 'ABSPATH' ) || exit; … … 12 5 class SBNFEBR_Draft_Controller { 13 6 14 /**15 * Registers the routes.16 *17 * @return void18 */19 7 public static function register_routes() { 20 register_rest_route(21 'sbnfebr/v1',22 '/items/review-apply',23 array(24 'methods' => 'POST',25 'callback' => array( __CLASS__, 'review_apply' ),26 'permission_callback' => array( __CLASS__, 'permission' ),27 )28 );29 30 8 register_rest_route( 31 9 'sbnfebr/v1', … … 37 15 ) 38 16 ); 17 } 39 18 40 register_rest_route( 41 'sbnfebr/v1', 42 '/items/(?P<id>\d+)/link', 19 public static function permission() { 20 return current_user_can( 'edit_products' ) && current_user_can( 'publish_products' ); 21 } 22 23 public static function permission_plus() { 24 return self::permission() && sbnfebr_is_plus(); 25 } 26 27 protected static function legacy_workflow_adapter( WP_REST_Request $request, $canonical_route, $intent ) { 28 $source_item_id = (int) $request->get_param( 'id' ); 29 $workflow = SBNFEBR_Workflow_Service::get_by_source_item_id( $source_item_id ); 30 if ( ! $workflow ) { 31 return new WP_Error( 32 'sbnfebr_workflow_migration_required', 33 __( 'Este item ainda não possui registro no catálogo de Conferência. Conclua a migração antes de continuar.', 'sanbar-express-nfe-xml-import-br' ), 34 array( 'status' => 409, 'source_item_id' => $source_item_id, 'intent' => sanitize_key( $intent ) ) 35 ); 36 } 37 $data = self::legacy_adapter_data( $workflow, $canonical_route, $intent ); 38 if ( SBNFEBR_Workflow_Service::STAGE_REVIEW !== $workflow['stage'] || SBNFEBR_Workflow_Service::FISCAL_APPROVED !== $workflow['fiscal_status'] ) { 39 return new WP_Error( 40 'sbnfebr_workflow_approval_required', 41 __( 'A rota antiga não pode gravar este item. Abra a Conferência e aprove os dados antes do Sync.', 'sanbar-express-nfe-xml-import-br' ), 42 $data 43 ); 44 } 45 return self::legacy_route_moved( $data ); 46 } 47 48 protected static function legacy_bulk_adapter( array $source_item_ids, $canonical_route, $intent ) { 49 $items = array(); 50 foreach ( array_values( array_unique( array_filter( array_map( 'intval', $source_item_ids ) ) ) ) as $source_item_id ) { 51 $workflow = SBNFEBR_Workflow_Service::get_by_source_item_id( $source_item_id ); 52 $items[] = $workflow 53 ? self::legacy_adapter_data( $workflow, $canonical_route, $intent ) 54 : array( 'source_item_id' => $source_item_id, 'workflow_id' => null, 'ready' => false ); 55 } 56 return new WP_Error( 57 'sbnfebr_legacy_route_moved', 58 __( 'Esta rota em lote foi substituída pelo processamento aprovado do workflow.', 'sanbar-express-nfe-xml-import-br' ), 43 59 array( 44 'methods' => 'POST', 45 'callback' => array( __CLASS__, 'link_existing' ), 46 'permission_callback' => array( __CLASS__, 'permission' ), 47 ) 48 ); 49 50 // /sync, /link-plus are Plus-only, registered via 51 // SBNFEBR_Draft_Controller_Plus::register_routes(). 52 53 register_rest_route( 54 'sbnfebr/v1', 55 '/items/(?P<id>\d+)/price-source', 56 array( 57 'methods' => 'POST', 58 'callback' => array( __CLASS__, 'update_price_source' ), 59 'permission_callback' => array( __CLASS__, 'permission' ), 60 ) 61 ); 62 63 // Unlink: clears only the item's product link, not the product itself. 64 register_rest_route( 65 'sbnfebr/v1', 66 '/items/(?P<id>\d+)/unlink', 67 array( 68 'methods' => 'POST', 69 'callback' => array( __CLASS__, 'unlink_item' ), 70 'permission_callback' => array( __CLASS__, 'permission' ), 71 ) 72 ); 73 74 // Accept the product's current GTIN as the new baseline of the link, 75 // clearing the "changed since linked" warning without relinking. 76 register_rest_route( 77 'sbnfebr/v1', 78 '/items/(?P<id>\d+)/accept-link-snapshot', 79 array( 80 'methods' => 'POST', 81 'callback' => array( __CLASS__, 'accept_link_snapshot' ), 82 'permission_callback' => array( __CLASS__, 'permission' ), 83 ) 84 ); 85 86 // Bulk Draft+: same per-item logic as the single action. A failing 87 // item does not block the rest. 88 register_rest_route( 89 'sbnfebr/v1', 90 '/items/draft-plus-bulk', 91 array( 92 'methods' => 'POST', 93 'callback' => array( __CLASS__, 'create_draft_plus_bulk' ), 94 'permission_callback' => array( __CLASS__, 'permission' ), 60 'status' => 409, 61 'intent' => sanitize_key( $intent ), 62 'canonical_route' => $canonical_route, 63 'items' => $items, 64 'requires_approved_snapshot' => true, 95 65 ) 96 66 ); 97 67 } 98 68 99 /** 100 * Permission: creating/linking a product requires WooCommerce's own 101 * publish capability in addition to edit_products. 102 * 103 * @return bool 104 */ 105 public static function permission() { 106 return current_user_can( 'edit_products' ) && current_user_can( 'publish_products' ); 107 } 108 109 /** 110 * POST /items/review-apply. Post-import review "Apply selected". Body: 111 * { items: [ { item_id, product_id, stock_action, stock_value } ] }. 112 * A failing item does not block the rest. 113 * 114 * @param WP_REST_Request $request REST request. 115 * @return WP_REST_Response|WP_Error 116 */ 117 public static function review_apply( WP_REST_Request $request ) { 118 $body = $request->get_json_params(); 119 $items = ( is_array( $body ) && isset( $body['items'] ) && is_array( $body['items'] ) ) ? $body['items'] : array(); 120 if ( ! $items ) { 121 return new WP_Error( 'sbnfebr_missing_items', __( 'item_ids é obrigatório.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 400 ) ); 122 } 123 124 $applied = array(); 125 $failed = array(); 126 127 foreach ( $items as $row ) { 128 $item_id = isset( $row['item_id'] ) ? (int) $row['item_id'] : 0; 129 $product_id = isset( $row['product_id'] ) ? (int) $row['product_id'] : 0; 130 $stock_action = isset( $row['stock_action'] ) ? (string) $row['stock_action'] : 'none'; 131 $stock_value = isset( $row['stock_value'] ) && is_numeric( $row['stock_value'] ) ? (float) $row['stock_value'] : null; 132 133 $result = SBNFEBR_Draft_Service::apply_review_item( $item_id, $product_id, $stock_action, $stock_value ); 134 if ( is_wp_error( $result ) ) { 135 $failed[] = array( 'item_id' => $item_id, 'message' => $result->get_error_message() ); 136 continue; 137 } 138 $applied[] = array( 'item_id' => $item_id, 'product_id' => $result['product_id'], 'sku_status' => $result['sku_status'] ?? null ); 139 } 140 141 return rest_ensure_response( array( 'applied' => $applied, 'failed' => $failed ) ); 142 } 143 144 /** 145 * Draft+ / Sync is a Plus feature: base permission plus Plus edition. 146 * 147 * @return bool 148 */ 149 public static function permission_plus() { 150 return self::permission() && sbnfebr_is_plus(); 151 } 152 153 /** 154 * Sanitizes `gtin_kind` from the request body. Null lets 155 * SBNFEBR_Draft_Service::resolve_gtin_kind() decide on its own for 156 * callers with no explicit choice. 157 * 158 * @param mixed $raw 159 * @return string|null 160 */ 161 protected static function sanitize_gtin_kind( $raw ) { 162 return in_array( $raw, array( 'unit', 'box' ), true ) ? $raw : null; 163 } 164 165 /** 166 * `sku_source`: how to fill the SKU (leave as-is / GTIN / product code). 167 * Defaults to 'gtin' when the field is absent. 168 * 169 * @param array $body 170 * @return string 'none'|'gtin'|'product_code'. 171 */ 172 protected static function sanitize_sku_source( array $body ) { 173 $raw = isset( $body['sku_source'] ) ? (string) $body['sku_source'] : 'gtin'; 174 return in_array( $raw, array( 'none', 'gtin', 'product_code' ), true ) ? $raw : 'gtin'; 175 } 176 177 /** 178 * POST /items/{id}/draft. Optional body: { name, identity_only, 179 * capitalize }. In Plus, dispatches to create_draft_plus() unless 180 * `identity_only` is set. 181 * 182 * @param WP_REST_Request $request REST request. 183 * @return WP_REST_Response|WP_Error 184 */ 185 public static function create_draft( WP_REST_Request $request ) { 186 $body = $request->get_json_params(); 187 $body = is_array( $body ) ? $body : array(); 188 $name = isset( $body['name'] ) ? (string) $body['name'] : null; 189 $identity_only = ! empty( $body['identity_only'] ); 190 $capitalize = ! empty( $body['capitalize'] ); 191 $gtin_kind = self::sanitize_gtin_kind( $body['gtin_kind'] ?? null ); 192 $sku_source = self::sanitize_sku_source( $body ); 193 $id = (int) $request->get_param( 'id' ); 194 195 $result = ( sbnfebr_is_plus() && ! $identity_only && class_exists( 'SBNFEBR_Draft_Service_Plus' ) ) 196 ? SBNFEBR_Draft_Service_Plus::create_draft_plus( $id, $name, $capitalize, $gtin_kind, $sku_source ) 197 : SBNFEBR_Draft_Service::create_draft( $id, $name, $capitalize, $gtin_kind, $sku_source ); 198 199 if ( is_wp_error( $result ) ) { 200 return $result; 201 } 202 203 return rest_ensure_response( 69 protected static function legacy_product_adapter( WP_REST_Request $request, $intent ) { 70 return new WP_Error( 71 'sbnfebr_legacy_route_moved', 72 __( 'Esta configuração não pode mais ser gravada fora de um item aprovado. Abra o workflow correspondente.', 'sanbar-express-nfe-xml-import-br' ), 204 73 array( 205 'product_id' => $result['product_id'], 206 'created' => $result['created'], 207 'edit_url' => get_edit_post_link( $result['product_id'], 'raw' ), 208 'sku_status' => $result['sku_status'] ?? null, 74 'status' => 409, 75 'intent' => sanitize_key( $intent ), 76 'product_id' => (int) $request->get_param( 'id' ), 77 'canonical_route' => '/workflow/items', 78 'requires_workflow_selection' => true, 209 79 ) 210 80 ); 211 81 } 212 82 213 /** 214 * POST /items/{id}/link. Body: { product_id }. 215 * 216 * In Plus, dispatches to link_existing_plus(): every link/create 217 * action in Plus writes the full set (identity + fiscal + price + 218 * taxes) with no intermediate step, same as create_draft() above. 219 * 220 * @param WP_REST_Request $request REST request. 221 * @return WP_REST_Response|WP_Error 222 */ 223 public static function link_existing( WP_REST_Request $request ) { 224 $body = $request->get_json_params(); 225 $body = is_array( $body ) ? $body : array(); 226 $product_id = isset( $body['product_id'] ) ? (int) $body['product_id'] : 0; 227 if ( $product_id <= 0 ) { 228 return new WP_Error( 'sbnfebr_missing_product_id', __( 'product_id é obrigatório.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 400 ) ); 229 } 230 231 $gtin_kind = self::sanitize_gtin_kind( $body['gtin_kind'] ?? null ); 232 $sku_source = self::sanitize_sku_source( $body ); 233 $reassign = ! empty( $body['reassign'] ); 234 $item_id = (int) $request->get_param( 'id' ); 235 $result = ( sbnfebr_is_plus() && class_exists( 'SBNFEBR_Draft_Service_Plus' ) ) 236 ? SBNFEBR_Draft_Service_Plus::link_existing_plus( $item_id, $product_id, $gtin_kind, $sku_source, $reassign ) 237 : SBNFEBR_Draft_Service::link_existing( $item_id, $product_id, $gtin_kind, $sku_source, $reassign ); 238 if ( is_wp_error( $result ) ) { 239 return $result; 240 } 241 242 return rest_ensure_response( 243 array( 244 'product_id' => $result['product_id'], 245 'created' => $result['created'], 246 'edit_url' => get_edit_post_link( $result['product_id'], 'raw' ), 247 'sku_status' => $result['sku_status'] ?? null, 248 ) 83 private static function legacy_adapter_data( array $workflow, $canonical_route, $intent ) { 84 $workflow_id = (int) $workflow['id']; 85 return array( 86 'status' => 409, 87 'intent' => sanitize_key( $intent ), 88 'source_item_id' => (int) $workflow['source_item_id'], 89 'workflow_id' => $workflow_id, 90 'workflow_stage' => (string) $workflow['stage'], 91 'fiscal_status' => (string) $workflow['fiscal_status'], 92 'sync_status' => (string) $workflow['sync_status'], 93 'current_version' => (int) $workflow['version'], 94 'canonical_route' => str_replace( '{workflow_id}', (string) $workflow_id, $canonical_route ), 95 'requires_approved_snapshot' => true, 96 'ready' => SBNFEBR_Workflow_Service::STAGE_REVIEW === $workflow['stage'] && SBNFEBR_Workflow_Service::FISCAL_APPROVED === $workflow['fiscal_status'], 249 97 ); 250 98 } 251 99 252 /** 253 * POST /items/{id}/price-source. Body: 254 * { product_id, apply_price, gtin_kind, sku_source, reassign }. 255 * 256 * @param WP_REST_Request $request REST request. 257 * @return WP_REST_Response|WP_Error 258 */ 259 public static function update_price_source( WP_REST_Request $request ) { 260 $body = $request->get_json_params(); 261 $body = is_array( $body ) ? $body : array(); 262 $product_id = isset( $body['product_id'] ) ? (int) $body['product_id'] : 0; 263 if ( $product_id <= 0 ) { 264 return new WP_Error( 'sbnfebr_missing_product_id', __( 'product_id é obrigatório.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 400 ) ); 265 } 266 267 $apply_price = ! empty( $body['apply_price'] ); 268 $gtin_kind = self::sanitize_gtin_kind( $body['gtin_kind'] ?? null ); 269 $sku_source = self::sanitize_sku_source( $body ); 270 $reassign = ! empty( $body['reassign'] ); 271 $item_id = (int) $request->get_param( 'id' ); 272 273 $result = SBNFEBR_Draft_Service::update_price_source( $item_id, $product_id, $apply_price, $gtin_kind, $sku_source, $reassign ); 274 if ( is_wp_error( $result ) ) { 275 return $result; 276 } 277 278 return rest_ensure_response( 279 array( 280 'product_id' => $result['product_id'], 281 'sku_status' => $result['sku_status'] ?? null, 282 ) 100 private static function legacy_route_moved( array $data ) { 101 return new WP_Error( 102 'sbnfebr_legacy_route_moved', 103 __( 'Esta rota foi substituída. Use a operação canônica informada após revisar o plano de escrita.', 'sanbar-express-nfe-xml-import-br' ), 104 $data 283 105 ); 284 106 } 285 107 286 /** 287 * POST /items/{id}/unlink. Clears only this item's `wc_product_id`; 288 * does not touch the WooCommerce product or other items pointing to 289 * it. Idempotent: unlinking an already-unlinked item is a no-op. 290 * 291 * @param WP_REST_Request $request REST request. 292 * @return WP_REST_Response|WP_Error 293 */ 294 public static function unlink_item( WP_REST_Request $request ) { 295 $item_id = (int) $request->get_param( 'id' ); 296 $item = SBNFEBR_Notes_Service::get_item( $item_id ); 297 if ( ! $item ) { 298 return new WP_Error( 'sbnfebr_item_not_found', __( 'Item não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) ); 299 } 300 301 SBNFEBR_Notes_Service::unlink_item( $item_id ); 302 303 if ( class_exists( 'SBNFEBR_Audit_Service' ) ) { 304 SBNFEBR_Audit_Service::log( 305 SBNFEBR_Audit_Service::EVENT_PRODUCT_LINKED, 306 array( 307 'note_id' => (int) $item['note_id'], 308 'product_id' => (int) $item['wc_product_id'], 309 'detail' => $item['description'] . ' (Unlinked)', 310 ) 311 ); 312 } 313 314 return rest_ensure_response( array( 'unlinked' => true ) ); 315 } 316 317 /** 318 * POST /items/{id}/accept-link-snapshot. Rewrites the GTIN baseline of 319 * every item linked to this item's product, so the "changed since 320 * linked" warning goes away without touching the link or the product. 321 * 322 * @param WP_REST_Request $request REST request. 323 * @return WP_REST_Response|WP_Error 324 */ 325 public static function accept_link_snapshot( WP_REST_Request $request ) { 326 $item_id = (int) $request->get_param( 'id' ); 327 $item = SBNFEBR_Notes_Service::get_item( $item_id ); 328 if ( ! $item ) { 329 return new WP_Error( 'sbnfebr_item_not_found', __( 'Item não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) ); 330 } 331 332 $product_id = (int) $item['wc_product_id']; 333 if ( ! $product_id ) { 334 return new WP_Error( 'sbnfebr_item_not_linked', __( 'Este item não está vinculado a um produto.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 409 ) ); 335 } 336 337 $post = get_post( $product_id ); 338 if ( ! $post || 'trash' === $post->post_status ) { 339 SBNFEBR_Notes_Service::clear_product_link( $product_id ); 340 return new WP_Error( 341 'sbnfebr_product_not_found', 342 __( 'Produto não encontrado.', 'sanbar-express-nfe-xml-import-br' ), 343 array( 344 'status' => 404, 345 'product_id' => $product_id, 346 ) 347 ); 348 } 349 350 SBNFEBR_Notes_Service::refresh_link_snapshot( $product_id ); 351 352 if ( class_exists( 'SBNFEBR_Audit_Service' ) ) { 353 SBNFEBR_Audit_Service::log( 354 SBNFEBR_Audit_Service::EVENT_PRODUCT_LINKED, 355 array( 356 'note_id' => (int) $item['note_id'], 357 'product_id' => $product_id, 358 'detail' => $item['description'] . ' (GTIN change accepted)', 359 ) 360 ); 361 } 362 363 return rest_ensure_response( 364 array( 365 'accepted' => true, 366 'product_id' => $product_id, 367 ) 368 ); 369 } 370 371 /** 372 * POST /items/draft-plus-bulk. Body: { item_ids: [...], identity_only?, 373 * capitalize? }. Same per-item logic as create_draft(); a failing item 374 * does not block the rest. 375 * 376 * @param WP_REST_Request $request REST request. 377 * @return WP_REST_Response|WP_Error 378 */ 379 public static function create_draft_plus_bulk( WP_REST_Request $request ) { 380 $body = $request->get_json_params(); 381 $body = is_array( $body ) ? $body : array(); 382 $item_ids = ( isset( $body['item_ids'] ) && is_array( $body['item_ids'] ) ) 383 ? array_map( 'intval', $body['item_ids'] ) 384 : array(); 385 $identity_only = ! empty( $body['identity_only'] ); 386 $capitalize = ! empty( $body['capitalize'] ); 387 $gtin_kind = self::sanitize_gtin_kind( $body['gtin_kind'] ?? null ); 388 $sku_source = self::sanitize_sku_source( $body ); 389 390 if ( ! $item_ids ) { 391 return new WP_Error( 'sbnfebr_missing_item_ids', __( 'item_ids é obrigatório.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 400 ) ); 392 } 393 394 $created = array(); 395 $failed = array(); 396 397 foreach ( $item_ids as $item_id ) { 398 $result = ( sbnfebr_is_plus() && ! $identity_only && class_exists( 'SBNFEBR_Draft_Service_Plus' ) ) 399 ? SBNFEBR_Draft_Service_Plus::create_draft_plus( $item_id, null, $capitalize, $gtin_kind, $sku_source ) 400 : SBNFEBR_Draft_Service::create_draft( $item_id, null, $capitalize, $gtin_kind, $sku_source ); 401 if ( is_wp_error( $result ) ) { 402 $failed[] = array( 403 'item_id' => $item_id, 404 'message' => $result->get_error_message(), 405 ); 406 continue; 407 } 408 $created[] = array( 409 'item_id' => $item_id, 410 'product_id' => $result['product_id'], 411 'sku_status' => $result['sku_status'] ?? null, 412 ); 413 } 414 415 return rest_ensure_response( 416 array( 417 'created' => $created, 418 'failed' => $failed, 419 ) 420 ); 108 public static function create_draft( WP_REST_Request $request ) { 109 return self::legacy_workflow_adapter( $request, '/workflow/items/{workflow_id}/send-new', 'new_product' ); 421 110 } 422 111 } -
sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-error-log-controller.php
r3725460 r3782421 1 1 <?php 2 /**3 * REST controller for SBNFEBR's internal error log.4 *5 * GET /sbnfebr/v1/error-log Paginated list.6 * DELETE /sbnfebr/v1/error-log Clears everything.7 * GET /sbnfebr/v1/error-log/status {has_new, count} for the icon indicator.8 * POST /sbnfebr/v1/error-log/mark-seen Marks seen for the current user.9 *10 * Uses the `edit_products` capability consistently for every operation,11 * including clearing the log.12 *13 * @package SBNFEBR14 * @since 0.5.115 */16 2 17 3 defined( 'ABSPATH' ) || exit; … … 73 59 } 74 60 75 /**76 * Permission: same capability used across the plugin.77 *78 * @return bool79 */80 61 public static function permission() { 81 62 return current_user_can( 'edit_products' ); 82 63 } 83 64 84 /**85 * GET /error-log.86 *87 * @param WP_REST_Request $request REST request.88 * @return WP_REST_Response89 */90 65 public static function get_list( WP_REST_Request $request ) { 91 66 $page = (int) $request->get_param( 'page' ); … … 104 79 } 105 80 106 /**107 * POST /error-log/mark-seen.108 *109 * @return WP_REST_Response110 */111 81 public static function mark_seen() { 112 82 SBNFEBR_Error_Log_Service::mark_seen(); -
sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-import-controller.php
r3725460 r3782421 1 1 <?php 2 /**3 * REST controller for NF-e XML upload/import.4 *5 * POST /sbnfebr/v1/import/preview (multipart, field "file") — parses and6 * validates only, does not persist. Returns a summary for confirmation.7 * POST /sbnfebr/v1/import (multipart, field "file") — persists.8 * The client resends the same file after the user confirms the9 * preview summary; the server keeps no XML cache/state between calls.10 *11 * @package SBNFEBR12 * @since 0.2.013 */14 2 15 3 defined( 'ABSPATH' ) || exit; … … 17 5 class SBNFEBR_Import_Controller { 18 6 19 /**20 * Maximum accepted NF-e XML size in bytes. A real NF-e, even with many21 * items, stays within a few MB; generous enough for legitimate cases,22 * low enough to reject clearly malformed files before loading them.23 */24 7 const MAX_FILE_SIZE = 10485760; // 10 MB. 25 8 26 /**27 * Above this item count, the preview adds a non-blocking warning asking28 * for extra confirmation before import. The hard cap is much higher,29 * see SBNFEBR_Xml_Parser_Service::MAX_ITEMS.30 */31 9 const WARN_ITEMS_THRESHOLD = 100; 32 10 33 /**34 * Upload rate limit — a simple per-user transient counter, guarding35 * against resource abuse from unbounded sequential imports.36 */37 11 const RATE_LIMIT_MAX = 10; 38 12 const RATE_LIMIT_WINDOW = 60; // seconds. … … 65 39 } 66 40 67 /**68 * Permission: same capability used to edit WooCommerce products, since69 * importing an NF-e creates or updates a product.70 *71 * @return bool72 */73 41 public static function permission() { 74 42 return current_user_can( 'edit_products' ); 75 43 } 76 44 77 /**78 * Enforces the upload rate limit via a per-user transient counter.79 * A fixed window reset on each call, not a true sliding window, but80 * sufficient to block automated bursts. Shared by preview and import,81 * since both call validate_and_parse().82 *83 * @return true|WP_Error84 */85 45 protected static function check_rate_limit() { 86 46 $key = 'sbnfebr_import_rate_' . get_current_user_id(); … … 99 59 } 100 60 101 // TTL resets on each call: window is fixed from the last attempt,102 // not the first, which is sufficient to block automated bursts.103 61 set_transient( $key, $count + 1, self::RATE_LIMIT_WINDOW ); 104 62 return true; 105 63 } 106 64 107 /**108 * Validates the upload (presence, transport error, extension, size),109 * reads and parses it. Shared by preview and actual import so both110 * agree on what counts as an acceptable XML.111 *112 * @param WP_REST_Request $request REST request.113 * @return array|WP_Error Structure from SBNFEBR_Xml_Parser_Service::parse().114 */115 65 protected static function validate_and_parse( WP_REST_Request $request ) { 116 66 $rate_limited = self::check_rate_limit(); … … 144 94 } 145 95 146 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_get_contents147 96 $xml_string = file_get_contents( $file['tmp_name'] ); 148 97 if ( false === $xml_string ) { … … 153 102 } 154 103 155 /**156 * POST /import/preview. Validates and parses only, never persists.157 * Returns the summary shown before the user confirms the import.158 *159 * `tpNF` (Entrada/Saída) is not used to flag anything: it is always160 * "Saída" on a legitimate purchase note, since it reflects the161 * issuer's stock movement, not the recipient's — flagging it would162 * false-positive on every normal import.163 *164 * The real "wrong note" signal is comparing the note's recipient165 * against the configured company CNPJ (see Settings); `owner_mismatch`166 * is `null` when that is not configured yet.167 *168 * @param WP_REST_Request $request REST request.169 * @return WP_REST_Response|WP_Error170 */171 104 public static function handle_preview( WP_REST_Request $request ) { 172 105 $parsed = self::validate_and_parse( $request ); … … 203 136 } 204 137 205 /**206 * POST /import. Receives the upload, parses it, and persists the note.207 *208 * @param WP_REST_Request $request REST request.209 * @return WP_REST_Response|WP_Error210 */211 138 public static function handle_import( WP_REST_Request $request ) { 212 139 $parsed = self::validate_and_parse( $request ); -
sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-items-controller.php
r3725460 r3782421 1 1 <?php 2 /**3 * REST controller for reading already-imported items/suppliers/notes.4 *5 * GET /sbnfebr/v1/items?supplier_cnpj=¬e_id=&search=6 * GET /sbnfebr/v1/suppliers7 * GET /sbnfebr/v1/notes?supplier_cnpj=8 *9 * @package SBNFEBR10 * @since 0.2.011 */12 2 13 3 defined( 'ABSPATH' ) || exit; … … 63 53 register_rest_route( 64 54 'sbnfebr/v1', 65 '/notes/(?P<id>\d+)/review',66 array(67 'methods' => 'GET',68 'callback' => array( __CLASS__, 'get_note_review' ),69 'permission_callback' => array( __CLASS__, 'permission' ),70 )71 );72 73 register_rest_route(74 'sbnfebr/v1',75 '/products/(?P<id>\d+)/identity-scope',76 array(77 'methods' => 'POST',78 'callback' => array( __CLASS__, 'set_identity_scope' ),79 'permission_callback' => array( __CLASS__, 'permission' ),80 )81 );82 83 register_rest_route(84 'sbnfebr/v1',85 55 '/items/(?P<id>\d+)/gtin-family', 86 56 array( … … 152 122 } 153 123 154 /**155 * Permission: reading requires the same capability as editing products,156 * since this is sensitive fiscal data, not public.157 *158 * @return bool159 */160 124 public static function permission() { 161 125 return current_user_can( 'edit_products' ); 162 126 } 163 127 164 /**165 * GET /items.166 *167 * @param WP_REST_Request $request REST request.168 * @return WP_REST_Response169 */170 128 public static function get_items( WP_REST_Request $request ) { 171 // 'ids': CSV of IDs, to fetch full data for a selection spanning pages.172 129 $ids_param = (string) $request->get_param( 'ids' ); 173 130 $ids = '' !== $ids_param ? array_map( 'intval', explode( ',', $ids_param ) ) : array(); … … 189 146 ) 190 147 ); 148 if ( ! empty( $result['items'] ) ) { 149 $result['items'] = SBNFEBR_Workflow_Service::attach_source_states( $result['items'] ); 150 } 191 151 192 152 return rest_ensure_response( $result ); 193 153 } 194 154 195 /**196 * GET /items/by-product. Same listing as /items, aggregated by product197 * identity instead of per note entry. See198 * SBNFEBR_Notes_Service::get_items_by_product().199 *200 * @param WP_REST_Request $request REST request.201 * @return WP_REST_Response202 */203 155 public static function get_items_by_product( WP_REST_Request $request ) { 204 156 $result = SBNFEBR_Notes_Service::get_items_by_product( … … 217 169 ) 218 170 ); 171 if ( ! empty( $result['items'] ) ) { 172 $result['items'] = SBNFEBR_Workflow_Service::attach_source_states( $result['items'] ); 173 } 219 174 220 175 return rest_ensure_response( $result ); 221 176 } 222 177 223 /**224 * POST /items/ignore. Body: { item_ids: [...], ignored: bool }. Bulk225 * marks items that will never become a product.226 *227 * @param WP_REST_Request $request REST request.228 * @return WP_REST_Response|WP_Error229 */230 178 public static function set_ignored( WP_REST_Request $request ) { 231 179 $body = $request->get_json_params(); … … 242 190 } 243 191 244 /**245 * GET /items/{id}/price-history.246 *247 * @param WP_REST_Request $request REST request.248 * @return WP_REST_Response|WP_Error249 */250 192 public static function get_price_history( WP_REST_Request $request ) { 251 193 $item = SBNFEBR_Notes_Service::get_item( (int) $request->get_param( 'id' ) ); … … 267 209 } 268 210 269 /**270 * GET /notes/{id}/review. Post-import review: items already resolving271 * to an existing product, with a diff, plus candidates for "expand272 * identification".273 *274 * @param WP_REST_Request $request REST request.275 * @return WP_REST_Response276 */277 public static function get_note_review( WP_REST_Request $request ) {278 return rest_ensure_response( SBNFEBR_Notes_Service::get_post_import_review( (int) $request->get_param( 'id' ) ) );279 }280 281 /**282 * POST /products/{id}/identity-scope. Body: { decision: 'expand'|'restrict' }.283 *284 * @param WP_REST_Request $request REST request.285 * @return WP_REST_Response286 */287 public static function set_identity_scope( WP_REST_Request $request ) {288 $body = $request->get_json_params();289 $decision = ( is_array( $body ) && isset( $body['decision'] ) ) ? (string) $body['decision'] : '';290 SBNFEBR_Notes_Service::set_identity_scope( (int) $request->get_param( 'id' ), $decision );291 return rest_ensure_response( array( 'ok' => true ) );292 }293 294 /**295 * GET /items/{id}/gtin-family. All other occurrences of the same GTIN296 * (any note, any supplier), for the action modal's source selector to297 * pick which `item_id` becomes the Draft/Link/Sync target.298 *299 * @param WP_REST_Request $request REST request.300 * @return WP_REST_Response|WP_Error301 */302 211 public static function get_gtin_family( WP_REST_Request $request ) { 303 212 $item_id = (int) $request->get_param( 'id' ); … … 307 216 } 308 217 309 return rest_ensure_response( SBNFEBR_Notes_Service::get_gtin_family( $item['gtin'], $item_id ) ); 218 $rows = SBNFEBR_Notes_Service::get_gtin_family( 219 $item['gtin'], 220 $item_id, 221 $item['supplier_cnpj'], 222 $item['product_code'] 223 ); 224 return rest_ensure_response( SBNFEBR_Workflow_Service::attach_source_states( $rows ) ); 310 225 } 311 226 … … 319 234 } 320 235 321 /**322 * GET /suppliers/{cnpj}/snapshot.323 *324 * @param WP_REST_Request $request REST request.325 * @return WP_REST_Response326 */327 236 public static function get_supplier_snapshot( WP_REST_Request $request ) { 328 237 $cnpj = (string) $request->get_param( 'cnpj' ); … … 331 240 } 332 241 333 /**334 * GET /notes.335 *336 * @param WP_REST_Request $request REST request.337 * @return WP_REST_Response338 */339 242 public static function get_notes( WP_REST_Request $request ) { 340 243 $supplier_cnpj = (string) $request->get_param( 'supplier_cnpj' ); … … 342 245 } 343 246 344 /**345 * GET /audit-log?note_id=&page=&per_page=. Event history (note346 * imported/deleted, product created).347 *348 * @param WP_REST_Request $request REST request.349 * @return WP_REST_Response350 */351 247 public static function get_audit_log( WP_REST_Request $request ) { 352 248 return rest_ensure_response( … … 361 257 } 362 258 363 /**364 * DELETE /notes/{id}. Deletes the header and items; WooCommerce365 * products already created from this note's items are not affected.366 *367 * @param WP_REST_Request $request REST request.368 * @return WP_REST_Response|WP_Error369 */370 259 public static function delete_note( WP_REST_Request $request ) { 371 260 $result = SBNFEBR_Notes_Service::delete_note( (int) $request->get_param( 'id' ) ); … … 376 265 } 377 266 378 /**379 * GET /notes/{id}/detail. Full NF-e data (freight, tax basis,380 * receivables, transport) for the note detail icon.381 *382 * @param WP_REST_Request $request REST request.383 * @return WP_REST_Response|WP_Error384 */385 267 public static function get_note_detail( WP_REST_Request $request ) { 386 268 $detail = SBNFEBR_Notes_Service::get_note_detail( (int) $request->get_param( 'id' ) ); -
sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-match-controller.php
r3725460 r3782421 1 1 <?php 2 /**3 * REST controller for matching note items against existing WooCommerce4 * products, by GTIN first, then supplier+code as a fallback for notes5 * without a GTIN.6 *7 * POST /sbnfebr/v1/match-gtin8 * POST /sbnfebr/v1/match-supplier-key9 *10 * @package SBNFEBR11 * @since 0.5.512 */13 2 14 3 defined( 'ABSPATH' ) || exit; … … 73 62 } 74 63 75 /**76 * Permission: same capability used across the plugin.77 *78 * @return bool79 */80 64 public static function permission() { 81 65 return current_user_can( 'edit_products' ); 82 66 } 83 67 84 /**85 * POST /match-gtin. Body: { gtins: [...] }.86 *87 * @param WP_REST_Request $request REST request.88 * @return WP_REST_Response89 */90 68 public static function match_gtin( WP_REST_Request $request ) { 91 69 $body = $request->get_json_params(); … … 95 73 } 96 74 97 /**98 * POST /match-supplier-key. Body: { keys: [...] }, each key in99 * `CNPJ|code` format (matches `_sbnfebr_supplier_key`), built client-side.100 *101 * @param WP_REST_Request $request REST request.102 * @return WP_REST_Response103 */104 75 public static function match_supplier_key( WP_REST_Request $request ) { 105 76 $body = $request->get_json_params(); … … 109 80 } 110 81 111 /**112 * POST /registry-check. Body: { gtins: [...] }. Available in both Lite113 * and Plus; checks the given GTINs (grid items not yet linked to a114 * product) against the WooCommerce catalog.115 *116 * @param WP_REST_Request $request REST request.117 * @return WP_REST_Response118 */119 82 public static function registry_check( WP_REST_Request $request ) { 120 83 $body = $request->get_json_params(); … … 124 87 } 125 88 126 /**127 * GET /products/{id}/snapshot. Current stock/cost for the product,128 * used to build the diff shown for an already-registered product.129 * 404 (`sbnfebr_product_not_found`) when the product is gone/trashed.130 *131 * @param WP_REST_Request $request REST request.132 * @return WP_REST_Response|WP_Error133 */134 89 public static function get_snapshot( WP_REST_Request $request ) { 135 90 $product_id = (int) $request->get_param( 'id' ); … … 137 92 $post = get_post( $product_id ); 138 93 if ( ! $post || ! in_array( $post->post_type, array( 'product', 'product_variation' ), true ) || 'trash' === $post->post_status ) { 139 // Idempotent: same cleanup on_product_removed() does, for links140 // left pointing at a product that vanished without that hook.141 94 SBNFEBR_Notes_Service::clear_product_link( $product_id ); 142 95 return new WP_Error( … … 153 106 $snapshot = SBNFEBR_Match_Service::get_snapshot( $product_id, $item_id ); 154 107 155 // Plus: note-side values keyed like the product meta, for the selective fiscal sync popup.156 108 if ( $item_id && class_exists( 'SBNFEBR_Draft_Service_Plus' ) ) { 157 109 $item = SBNFEBR_Notes_Service::get_item( $item_id ); … … 164 116 } 165 117 166 /**167 * GET /products-search?q=...&exclude_item_id=... Product search for168 * manual linking when no automatic match is found. `exclude_item_id`169 * flags results already in use by another item.170 *171 * @param WP_REST_Request $request REST request.172 * @return WP_REST_Response173 */174 118 public static function search_products( WP_REST_Request $request ) { 175 119 return rest_ensure_response( 176 120 SBNFEBR_Match_Service::search_products( 177 121 (string) $request->get_param( 'q' ), 178 (int) $request->get_param( 'exclude_item_id' ) 122 (int) $request->get_param( 'exclude_item_id' ), 123 sanitize_key( (string) $request->get_param( 'field' ) ) 179 124 ) 180 125 ); -
sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-settings-controller.php
r3725460 r3782421 1 1 <?php 2 /**3 * REST controller for plugin settings: the own-company profile (same4 * fields as a supplier record) and error-log verbosity.5 *6 * The company profile's `document` (CNPJ) is compared against each7 * imported note's recipient in the preview, to flag notes not issued to8 * this company (see SBNFEBR_Import_Controller::handle_preview()).9 *10 * No editable tax regime field on the company profile — which taxes11 * count as cost is decided in the Sheet's Library → Taxes/Fees. The12 * response carries a read-only `tax_regime` block instead (see get_shared_tax_regime()).13 *14 * GET /sbnfebr/v1/settings15 * POST /sbnfebr/v1/settings16 *17 * @package SBNFEBR18 * @since 0.4.819 */20 2 21 3 defined( 'ABSPATH' ) || exit; … … 23 5 class SBNFEBR_Settings_Controller { 24 6 25 /** Option key — full company profile (serialized array). */26 7 const OPTION_COMPANY = 'sbnfebr_own_company'; 27 8 28 /** Legacy option key (CNPJ only), read as a migration fallback. */29 9 const OPTION_OWN_CNPJ_LEGACY = 'sbnfebr_own_cnpj'; 30 10 31 /**32 * Option compartilhada com a SM (class-sbsheet-settings.php,33 * COMPANY_OPTION) — perfil completo da empresa (nome, documento34 * fiscal, endereço, contato), editável dos dois lados. É a MESMA35 * option lida/gravada por ambos — não existe risco de duas verdades36 * desencontradas, só duas portas de entrada pro mesmo dado.37 * OPTION_COMPANY (abaixo) continua existindo só como fallback de38 * migração de instalações antigas (ver get_company()). Sem campo de39 * país/regime tributário — ver docblock da classe.40 */41 11 const SHARED_COMPANY_OPTION = 'sbesfw_company_data'; 42 12 43 /** Campos do perfil espelhados na option compartilhada — mesmos nomes dos dois lados. */44 13 const SHARED_FIELDS = array( 'name', 'fantasy_name', 'document', 'ie', 'phone', 'email', 'site', 'cep', 'street', 'number', 'complement', 'district', 'city', 'state' ); 45 14 46 /** Option do NF-e PDV (plugin irmão) — dono do regime tributário da loja. Leitura direta, sem class_exists(). */47 15 const PDV_FISCAL_CONFIG_OPTION = 'nfbr_config_fiscal'; 16 17 const WELCOME_META = 'sbnfebr_welcome_dismissed'; 48 18 49 19 /** … … 69 39 ) 70 40 ); 71 } 72 73 /** 74 * Permission: same capability used across the plugin. 75 * 76 * @return bool 77 */ 41 register_rest_route( 42 'sbnfebr/v1', 43 '/welcome/dismiss', 44 array( 45 'methods' => 'POST', 46 'callback' => array( __CLASS__, 'dismiss_welcome' ), 47 'permission_callback' => array( __CLASS__, 'permission' ), 48 ) 49 ); 50 } 51 52 public static function dismiss_welcome() { 53 update_user_meta( get_current_user_id(), self::WELCOME_META, SBNFEBR_VERSION ); 54 return rest_ensure_response( array( 'dismissed' => SBNFEBR_VERSION ) ); 55 } 56 78 57 public static function permission() { 79 58 return current_user_can( 'edit_products' ); 80 59 } 81 60 82 /**83 * Full company profile with defaults for every field. Falls back to84 * the legacy CNPJ-only option if the full profile was never saved.85 *86 * @return array87 */88 61 public static function get_company() { 89 62 $stored = get_option( self::OPTION_COMPANY, array() ); … … 111 84 $company = array_merge( $defaults, $stored ); 112 85 113 // Fall back to the legacy CNPJ option for reading only; it is not deleted.114 86 if ( '' === $company['document'] ) { 115 87 $legacy = preg_replace( '/\D/', '', (string) get_option( self::OPTION_OWN_CNPJ_LEGACY, '' ) ); … … 119 91 } 120 92 121 // A option compartilhada com a SM vence, campo a campo, quando já122 // tem algo salvo — fonte única entre os dois plugins (ver123 // SHARED_COMPANY_OPTION). Sem isso, editar qualquer campo pela SM124 93 // nunca refletiria aqui (e vice-versa). 125 94 $shared = get_option( self::SHARED_COMPANY_OPTION, array() ); … … 135 104 } 136 105 137 /**138 * Company CNPJ, digits only. Used by the import preview.139 *140 * @return string141 */142 106 public static function get_own_cnpj() { 143 107 return preg_replace( '/\D/', '', (string) self::get_company()['document'] ); 144 108 } 145 109 146 /**147 * CRT 1/4 (Simples/MEI) → 'simples', CRT 2/3 → 'normal'. "configured"148 * só é true se a option existir de verdade — o default do PDV é só em memória.149 *150 * @return array{configured:bool,crt:int|null,regime:string,label:string}151 */152 110 public static function get_shared_tax_regime() { 153 111 $raw = get_option( self::PDV_FISCAL_CONFIG_OPTION, null ); … … 193 151 } 194 152 195 /**196 * POST /settings. Each block (`company`, `error_log_level`) is optional.197 *198 * @param WP_REST_Request $request REST request.199 * @return WP_REST_Response|WP_Error200 */201 153 public static function update_settings( WP_REST_Request $request ) { 202 154 $body = $request->get_json_params(); … … 216 168 foreach ( self::SHARED_FIELDS as $key ) { 217 169 if ( 'document' === $key ) { 218 continue; // já setado acima (com a validação de 14 dígitos)170 continue; 219 171 } 220 172 $company[ $key ] = isset( $incoming[ $key ] ) ? sanitize_text_field( (string) $incoming[ $key ] ) : ''; … … 223 175 update_option( self::OPTION_COMPANY, $company, true ); 224 176 225 // Espelha o perfil inteiro na option compartilhada com a SM —226 177 // mesma fonte única dos dois lados. 227 178 $shared = get_option( self::SHARED_COMPANY_OPTION, array() ); -
sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-suppliers-library-controller.php
r3725460 r3782421 1 1 <?php 2 /**3 * REST controller for supplier CRUD (sbs_supplier taxonomy), used by the4 * Supplier Library modal.5 *6 * Route `/library/suppliers` is the editable full registry, separate from7 * `/suppliers`, which only lists CNPJs already seen on imported notes for8 * the grid filter.9 *10 * @package SBNFEBR11 * @since 0.3.012 */13 2 14 3 defined( 'ABSPATH' ) || exit; … … 67 56 } 68 57 69 /**70 * Permission: same capability used on the taxonomy (`edit_products`).71 *72 * @return bool73 */74 58 public static function permission() { 75 59 return current_user_can( 'edit_products' ); 76 60 } 77 61 78 /**79 * GET /library/suppliers?search=.80 *81 * @param WP_REST_Request $request REST request.82 * @return WP_REST_Response83 */84 62 public static function list_suppliers( WP_REST_Request $request ) { 85 63 $search = (string) $request->get_param( 'search' ); … … 87 65 } 88 66 89 /**90 * GET /library/suppliers/check?document=CNPJ. Lets the toolbar91 * indicator check registration status without loading the full list.92 *93 * @param WP_REST_Request $request REST request.94 * @return WP_REST_Response95 */96 67 public static function check_supplier( WP_REST_Request $request ) { 97 68 $document = (string) $request->get_param( 'document' ); … … 106 77 } 107 78 108 /**109 * Extracts the supplier field payload from the request body.110 *111 * @param WP_REST_Request $request REST request.112 * @return array113 */114 79 protected static function fields_from_request( WP_REST_Request $request ) { 115 80 $body = $request->get_json_params(); … … 126 91 } 127 92 128 /**129 * POST /library/suppliers.130 *131 * @param WP_REST_Request $request REST request.132 * @return WP_REST_Response|WP_Error133 */134 93 public static function create_supplier( WP_REST_Request $request ) { 135 94 $result = SBNFEBR_Supplier_Service::create( self::fields_from_request( $request ) ); … … 140 99 } 141 100 142 /**143 * PATCH /library/suppliers/{id}.144 *145 * @param WP_REST_Request $request REST request.146 * @return WP_REST_Response|WP_Error147 */148 101 public static function update_supplier( WP_REST_Request $request ) { 149 102 $term_id = (int) $request->get_param( 'id' ); … … 155 108 } 156 109 157 /**158 * DELETE /library/suppliers/{id}.159 *160 * @param WP_REST_Request $request REST request.161 * @return WP_REST_Response|WP_Error162 */163 110 public static function delete_supplier( WP_REST_Request $request ) { 164 111 $term_id = (int) $request->get_param( 'id' ); -
sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-audit-service.php
r3725460 r3782421 1 1 <?php 2 /**3 * Log de eventos (auditoria) do SBNFEBR — "quem fez o quê e quando":4 * nota importada, produto criado/linkado a partir de item, nota5 * excluída. Mesmo padrão estrutural de SBNFEBR_Error_Log_Service6 * (tabela própria, dbDelta versionado, poda mantendo só as mais7 * recentes) — mas grava evento por chamada explícita de cada8 * service/controller, não por um hook central (evento de negócio não9 * é "resposta HTTP com erro", não tem um ponto único pra interceptar).10 *11 * @package SBNFEBR12 * @since 0.5.213 */14 2 15 3 defined( 'ABSPATH' ) || exit; 16 4 17 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, PluginCheck.Security.DirectDB.UnescapedDBParameter18 // Tabela própria (sbnfebr_audit_log, fora do schema padrão do WP) — acesso direto via $wpdb é19 // inerente a esse modelo, não um descuido; não há cache de objeto porque o log é escrito a cada20 // evento e lido só sob demanda (sem tela de listagem de alto tráfego). Nome de tabela sempre vem21 // de self::table_name() ($wpdb->prefix . 'sbnfebr_audit_log', fixo — nunca input de usuário).22 // ReplacementsWrongNumber em list_entries() é falso positivo: $where/$params variam juntos23 // conforme o filtro é passado ou não, a contagem bate nos 2 casos em runtime.24 5 class SBNFEBR_Audit_Service { 25 6 26 /** Versão do schema — bump aqui força dbDelta rodar de novo em upgrade futuro. */27 7 const DB_VERSION = '1.0'; 28 8 29 /** Option key que guarda a versão do schema já aplicada. */30 9 const DB_VERSION_OPTION = 'sbnfebr_audit_db_version'; 31 10 32 /** Máximo de linhas mantidas no total (mais antigas são descartadas). */33 11 const MAX_ROWS = 1000; 34 12 … … 40 18 const EVENT_PRODUCT_SYNCED = 'product_synced'; 41 19 42 /**43 * Nome completo da tabela (com prefixo do WP).44 *45 * @return string46 */47 20 public static function table_name() { 48 21 global $wpdb; … … 50 23 } 51 24 52 /**53 * Cria a tabela se não existir, ou atualiza o schema se DB_VERSION54 * mudou. Idempotente.55 *56 * @return void57 */58 25 public static function create_table() { 59 26 $installed_version = get_option( self::DB_VERSION_OPTION ); … … 87 54 } 88 55 89 /**90 * Grava um evento e poda o excesso (mantém só as MAX_ROWS mais91 * recentes).92 *93 * @param string $event_type Um dos EVENT_* desta classe.94 * @param array $args { note_id, access_key, product_id, detail } — todos opcionais.95 * @return void96 */97 56 public static function log( $event_type, array $args = array() ) { 98 57 global $wpdb; … … 119 78 } 120 79 121 /**122 * Mantém no máximo MAX_ROWS linhas — apaga as mais antigas123 * quando ultrapassa.124 *125 * @return void126 */127 80 protected static function prune() { 128 81 global $wpdb; 129 82 $table = self::table_name(); 130 83 131 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName84 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); 132 85 if ( $total <= self::MAX_ROWS ) { 133 86 return; … … 137 90 $wpdb->query( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 138 91 $wpdb->prepare( 139 "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName92 "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d", 140 93 $excess 141 94 ) … … 143 96 } 144 97 145 /**146 * Lista paginada, mais recente primeiro — usada pelo Gerenciador de147 * Notas pra mostrar o histórico de uma nota específica, e por uma148 * futura tela de auditoria geral.149 *150 * @param array $args { note_id (opcional), page, per_page }.151 * @return array{entries:array,total:int,total_pages:int}152 */153 98 public static function list_entries( array $args = array() ) { 154 99 global $wpdb; … … 165 110 } 166 111 167 $count_sql = "SELECT COUNT(*) FROM {$table} WHERE {$where}"; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName112 $count_sql = "SELECT COUNT(*) FROM {$table} WHERE {$where}"; 168 113 $total = (int) ( $params ? $wpdb->get_var( $wpdb->prepare( $count_sql, $params ) ) : $wpdb->get_var( $count_sql ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 169 114 170 115 $list_params = array_merge( $params, array( $per_page, $offset ) ); 171 116 $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 172 $wpdb->prepare( 173 "SELECT * FROM {$table} WHERE {$where} ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName117 $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber 118 "SELECT * FROM {$table} WHERE {$where} ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", 174 119 $list_params 175 120 ), -
sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-draft-service.php
r3725460 r3782421 1 1 <?php 2 /**3 * Cria produtos WooCommerce (rascunho) a partir de itens de NF-e.4 * Campos fiscais usam as mesmas chaves de postmeta da SanBar EXPress5 * Sheet Plus (grupo `fiscal_brasil`). Nunca grava preço de venda.6 *7 * @package SBNFEBR8 * @since 0.4.09 */10 2 11 3 defined( 'ABSPATH' ) || exit; 12 4 13 5 class SBNFEBR_Draft_Service { 14 15 /** Postmeta privado — chave de matching durável (CNPJ + código), independente do SKU. */ 6 use SBNFEBR_Product_Data_Writers; 7 16 8 const META_SUPPLIER_KEY = '_sbnfebr_supplier_key'; 17 9 18 /**19 * Postmeta privado — 'unit'|'box', qual dos 2 campos de GTIN da Sheet20 * recebeu o código desta nota (`_global_unique_id` vs `sbs_gtin_box`).21 * Persistido no PRODUTO (não no item) pra um Sync/link-update22 * seguinte reaplicar o mesmo campo sem perguntar de novo — só o23 * Draft/Link inicial (com escolha explícita do usuário) grava aqui.24 */25 10 const META_GTIN_KIND = '_sbnfebr_gtin_kind'; 26 11 27 /**28 * Unidade comercial (uCom da NF-e, já capturada em $item['unit']) →29 * tipo de venda da Calculadora de Preço da Sheet Plus (sbs_price_sale_type).30 * Unidade não listada aqui: método inteiro não mexe em nada (mais31 * seguro deixar a Calculadora no padrão "unit" do que arriscar32 * classificar errado uma sigla desconhecida).33 *34 * @var array<string,string>35 */36 12 const UNIT_TO_SALE_TYPE = array( 37 13 'UN' => 'unit', … … 60 36 ); 61 37 62 /**63 * Classificação MAIS FINA que UNIT_TO_SALE_TYPE — unidade não listada64 * aqui usa só o `sale_type` genérico ('box'), sem gravar kind65 * nenhum. `sbs_price_sale_type` continua sempre 'box' pra tudo66 * nesta lista (nunca muda, formato inalterado) — o que muda é67 * `sbs_price_box_kind`, campo cosmético que a Calculadora usa só68 * pra trocar os RÓTULOS dos campos ("Quantidade por caixa" →69 * "Quantidade por dúzia" etc.), a fórmula de cálculo é idêntica70 * pra qualquer valor aqui (ver popup-pricecalc.js, BOX_KINDS/71 * updateBoxKindLabels()). Os valores aqui têm que bater exatamente72 * com as chaves de BOX_KINDS na Sheet.73 *74 * @var array<string,string>75 */76 38 const UNIT_TO_KIND = array( 77 39 'DZ' => 'dozen', … … 83 45 ); 84 46 47 const CSOSN_ST_FORNECEDOR = array( '201', '202', '203', '500' ); 48 49 const CST_ST_FORNECEDOR = array( '10', '30', '60', '70' ); 50 51 const SYNC_FIELD_KEYS = array( 52 'ncm', 'cest', 'origem', 'u_com', 'u_trib', 'cclasstrib', 53 'ind_escala', 'cnpj_fabricante', 'nfci', 'fornecedor_st', 54 'csosn_cst', 'cfop', 55 ); 56 85 57 /** 86 58 * Hook registration. … … 91 63 add_action( 'wp_trash_post', array( __CLASS__, 'on_product_removed' ) ); 92 64 add_action( 'before_delete_post', array( __CLASS__, 'on_product_removed' ) ); 93 // Integração opcional, sem dependência nenhuma da Sheet: se ela94 // estiver instalada (qualquer versão, Lite ou Plus) e disparar95 // este evento genérico (ex: conversão simples→variável recriando96 // o post_id de um produto), a gente re-vincula sozinho. Se a97 // Sheet não estiver instalada, ou for uma versão que nunca98 // dispara isto, o hook simplesmente nunca é chamado — sem erro,99 // sem checagem de classe/versão necessária dos dois lados.100 65 add_action( 'sbsheet_product_identity_moved', array( __CLASS__, 'on_product_identity_moved' ), 10, 2 ); 101 66 } 102 67 103 /** 104 * Limpa o link quando o produto vai pra lixeira ou é apagado — 105 * sem isso o ícone da grid ficava preso em "criado". 106 * 107 * @param int $post_id ID do post removido. 108 * @return void 109 */ 68 public static function build_write_plan( array $item, $note, array $options = array() ) { 69 $requested_sku = (string) ( $options['sku_source'] ?? 'gtin' ); 70 $sku_source = in_array( $requested_sku, array( 'none', 'gtin', 'product_code' ), true ) ? $requested_sku : 'gtin'; 71 $write_profile = in_array( $options['profile'] ?? '', array( 'simple', 'invoice' ), true ) ? $options['profile'] : 'complete'; 72 $include_calculator = 'simple' !== $write_profile || ! array_key_exists( 'include_calculator', $options ) || ! empty( $options['include_calculator'] ); 73 $gtin = trim( (string) ( $item['gtin'] ?? '' ) ); 74 $has_gtin = '' !== $gtin && 'SEM GTIN' !== strtoupper( $gtin ); 75 $requested_gtin_kind = (string) ( $options['gtin_kind'] ?? '' ); 76 $gtin_kind = in_array( $requested_gtin_kind, array( 'unit', 'box' ), true ) ? $requested_gtin_kind : ( 14 === strlen( preg_replace( '/\D/', '', $gtin ) ) ? 'box' : 'unit' ); 77 $fields = array(); 78 $add = static function ( &$target, $group, $key, $value, $mode = 'overwrite' ) { 79 if ( '' === (string) $value ) { return; } 80 $target[] = array( 'group' => $group, 'key' => $key, 'value' => $value, 'mode' => $mode ); 81 }; 82 $name = trim( (string) ( $options['name'] ?? '' ) ); 83 if ( '' === $name ) { 84 $name = ! empty( $options['capitalize'] ) ? self::title_case( (string) ( $item['description'] ?? '' ) ) : (string) ( $item['description'] ?? '' ); 85 } 86 $add( $fields, 'product', 'post_title', $name ); 87 $add( $fields, 'product', 'post_status', 'draft' ); 88 if ( $has_gtin ) { 89 $add( $fields, 'identity', 'box' === $gtin_kind ? 'sbs_gtin_box' : '_global_unique_id', $gtin ); 90 $add( $fields, 'identity', self::META_GTIN_KIND, $gtin_kind ); 91 } 92 if ( 'gtin' === $sku_source && $has_gtin ) { $add( $fields, 'identity', '_sku', $gtin, 'fill_if_empty' ); } 93 if ( 'product_code' === $sku_source ) { $add( $fields, 'identity', '_sku', (string) ( $item['product_code'] ?? '' ), 'fill_if_empty' ); } 94 $add( $fields, 'identity', 'sbs_supplier_product_code', (string) ( $item['product_code'] ?? '' ) ); 95 $add( $fields, 'identity', self::META_SUPPLIER_KEY, (string) ( $item['supplier_cnpj'] ?? '' ) . '|' . (string) ( $item['product_code'] ?? '' ) ); 96 if ( 'simple' !== $write_profile ) { 97 foreach ( self::note_fiscal_values( $item, $note ) as $key => $value ) { 98 if ( 'invoice' === $write_profile && in_array( $key, array( 'csosn_cst', 'cfop' ), true ) ) { continue; } 99 $add( $fields, 'fiscal', '_' . $key, $value ); 100 } 101 $add( $fields, 'reference', '_fornecedor_csosn_cst', (string) ( $item['cst_csosn'] ?? '' ) ); 102 $add( $fields, 'reference', '_fornecedor_cfop', (string) ( $item['cfop'] ?? '' ) ); 103 $add( $fields, 'reference', '_fornecedor_cbenef', (string) ( $item['cbenef'] ?? '' ) ); 104 $crt = (int) ( $item['fiscal_crt'] ?? 0 ); 105 $fiscal_profile = 4 === $crt ? 'mei' : 'sn'; 106 if ( 'complete' === $write_profile && in_array( $crt, array( 1, 4 ), true ) && ! empty( $item['sale_csosn'] ) && ! empty( $item['sale_cfop'] ) ) { 107 $add( $fields, 'fiscal_profile', '_sbfcbr_' . $fiscal_profile . '_csosn', (string) $item['sale_csosn'] ); 108 $add( $fields, 'fiscal_profile', '_sbfcbr_' . $fiscal_profile . '_cfop', (string) $item['sale_cfop'] ); 109 $add( $fields, 'fiscal_profile', '_sbfcbr_' . $fiscal_profile . '_modo', (string) ( $item['fiscal_profile_mode'] ?? 'auto' ) ); 110 $add( $fields, 'fiscal_profile', '_sbfcbr_applied', (string) $item['sale_csosn'] . '/' . (string) $item['sale_cfop'] ); 111 } 112 $add( $fields, 'fiscal', '_tipo_item', '00', 'fill_if_empty' ); 113 } 114 if ( $include_calculator ) { 115 foreach ( self::cost_meta_values( $item ) as $key => $value ) { $add( $fields, 'cost', $key, $value ); } 116 foreach ( self::price_calc_meta_values( $item ) as $key => $value ) { $add( $fields, 'calculator', $key, $value ); } 117 } 118 119 return array( 120 'profile' => $write_profile, 121 'destination' => array( 'type' => 'new_draft', 'product_id' => 0, 'label' => __( 'Novo produto em rascunho', 'sanbar-express-nfe-xml-import-br' ) ), 122 'fields' => $fields, 123 'operations' => array_merge( 124 array( array( 'key' => 'supplier_link', 'label' => __( 'Vincular fornecedor ao produto', 'sanbar-express-nfe-xml-import-br' ), 'edition' => 'base' ) ), 125 $include_calculator ? array( array( 'key' => 'taxes_if_available', 'label' => __( 'Aplicar impostos da nota se o catálogo da Calculadora estiver disponível', 'sanbar-express-nfe-xml-import-br' ), 'edition' => 'base' ) ) : array() 126 ), 127 ); 128 } 129 130 public static function verify_write_plan( $product_id, array $plan, array $skip = array() ) { 131 $post = get_post( (int) $product_id ); 132 if ( ! $post || 'trash' === (string) $post->post_status ) { 133 return new WP_Error( 'sbnfebr_sync_product_missing', __( 'O produto criado não está mais disponível para conferência.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 409 ) ); 134 } 135 $mismatches = array(); 136 foreach ( $plan['fields'] ?? array() as $field ) { 137 $key = (string) ( $field['key'] ?? '' ); 138 if ( '' === $key || in_array( $key, $skip, true ) ) { continue; } 139 if ( 'post_title' === $key ) { 140 $actual = (string) $post->post_title; 141 } elseif ( 'post_status' === $key ) { 142 $actual = (string) $post->post_status; 143 } else { 144 $actual = get_post_meta( (int) $product_id, $key, true ); 145 } 146 $expected = $field['value'] ?? ''; 147 if ( 'fill_if_empty' === ( $field['mode'] ?? '' ) && '' !== (string) $actual ) { continue; } 148 if ( (string) $actual !== (string) $expected ) { 149 $mismatches[] = array( 'field' => $key, 'expected' => $expected, 'actual' => $actual ); 150 } 151 } 152 if ( $mismatches ) { 153 return new WP_Error( 154 'sbnfebr_sync_write_mismatch', 155 __( 'O produto foi processado, mas alguns campos não foram confirmados. Tente novamente antes de marcar como sincronizado.', 'sanbar-express-nfe-xml-import-br' ), 156 array( 'status' => 409, 'product_id' => (int) $product_id, 'fields' => $mismatches ) 157 ); 158 } 159 return true; 160 } 161 110 162 public static function on_product_removed( $post_id ) { 111 163 if ( in_array( get_post_type( $post_id ), array( 'product', 'product_variation' ), true ) ) { 112 164 SBNFEBR_Notes_Service::clear_product_link( $post_id ); 113 } 114 } 115 116 /** 117 * Reage ao evento genérico 'sbsheet_product_identity_moved' (disparado 118 * por quem recriar o post_id de um produto e mover a identidade dele 119 * junto — hoje só a Sheet, na conversão simples→variável). Sem isto, 120 * o vínculo com a NF-e ficava preso no post_id antigo (virado 121 * pai/rascunho da variável), e o usuário precisava reclicar 122 * "Vincular" manualmente pra cada item, mesmo o matching já achando 123 * o candidato certo sozinho. 124 * 125 * @param int $old_product_id ID do post que deixou de representar o item. 126 * @param int $new_product_id ID do post novo que passou a representá-lo. 127 * @return void 128 */ 165 SBNFEBR_Workflow_Service::release_product( (int) $post_id ); 166 } 167 } 168 129 169 public static function on_product_identity_moved( $old_product_id, $new_product_id ) { 130 170 $old_product_id = (int) $old_product_id; … … 136 176 } 137 177 138 /** 139 * Cria (ou retorna o já existente) produto WooCommerce pra 1 item de 140 * nota. Idempotente enquanto o produto existir e não estiver na lixeira. 141 * Make Draft SIMPLES — não manda dado fiscal nenhum, só nome + 142 * identidade (GTIN/SKU/chave de matching). Dado fiscal/custo/impostos 143 * só entra via sync_full() (Plus). 144 * 145 * @param int $item_id ID da linha em sbnfebr_note_items. 146 * @param string|null $name_override Nome customizado (vazio/null = usa a descrição da nota). 147 * @param bool $capitalize Title Case em vez do texto cru da nota 148 * (geralmente TUDO MAIÚSCULO). Só se aplica 149 * quando NÃO há $name_override. 150 * @param string|null $gtin_kind 'unit'|'box' — null usa resolve_gtin_kind() 151 * (persistido ou heurística). 152 * @param string $sku_source 'none'|'gtin'|'product_code'. 153 * @return array|WP_Error { product_id, created (bool) } 154 */ 155 public static function create_draft( $item_id, $name_override = null, $capitalize = false, $gtin_kind = null, $sku_source = 'gtin' ) { 178 public static function create_draft( $item_id, $name_override = null, $capitalize = false, $gtin_kind = null, $sku_source = 'gtin', $item_override = null, array $options = array() ) { 156 179 $item = SBNFEBR_Notes_Service::get_item( $item_id ); 157 180 if ( ! $item ) { 158 181 return new WP_Error( 'sbnfebr_item_not_found', __( 'Item não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) ); 159 182 } 183 if ( is_array( $item_override ) ) { 184 $item = array_merge( $item, $item_override ); 185 $item['id'] = (int) $item_id; 186 } 187 if ( ! empty( $item['wc_product_id'] ) ) { 188 $already_created = get_post( (int) $item['wc_product_id'] ); 189 if ( $already_created && 'trash' !== $already_created->post_status ) { 190 $sku_status = 'not_applicable'; 191 if ( is_array( $item_override ) && 'draft' === (string) $already_created->post_status ) { 192 $product = wc_get_product( (int) $item['wc_product_id'] ); 193 if ( $product ) { 194 $name = trim( (string) $name_override ); 195 if ( '' === $name ) { $name = $capitalize ? self::title_case( $item['description'] ) : $item['description']; } 196 $product->set_name( $name ); 197 $product->set_status( 'draft' ); 198 $product->save(); 199 $note = SBNFEBR_Notes_Service::get_note( $item['note_id'] ); 200 $sku_status = self::apply_identity_meta( (int) $item['wc_product_id'], $item, $gtin_kind, $sku_source ); 201 self::apply_draft_profile( (int) $item['wc_product_id'], $item, $note, $options ); 202 } 203 } 204 return array( 'product_id' => (int) $item['wc_product_id'], 'created' => false, 'sku_status' => $sku_status ); 205 } 206 } 160 207 161 208 $existing_id = self::resolve_existing_product_id( $item ); 162 209 if ( $existing_id ) { 163 // Identidade (GTIN, ou fornecedor+código sem GTIN) já resolve 164 // pra um produto — mesmo que ESTA linha nunca tenha sido 165 // vinculada antes, criar de novo duplicaria o GTIN em 2 166 // produtos. Vincula à identidade em vez de criar. 167 $sku_status = self::apply_identity_meta( $existing_id, $item, $gtin_kind, $sku_source ); 168 SBNFEBR_Notes_Service::set_item_product_id( $item_id, $existing_id ); 169 SBNFEBR_Notes_Service::propagate_link( $item, $existing_id ); 170 return array( 'product_id' => $existing_id, 'created' => false, 'sku_status' => $sku_status ); 210 return new WP_Error( 211 'sbnfebr_existing_product_requires_plus', 212 __( 'Este item corresponde a um produto já cadastrado. A sincronização de produtos existentes está disponível na edição Plus.', 'sanbar-express-nfe-xml-import-br' ), 213 array( 'status' => 409, 'product_id' => $existing_id ) 214 ); 171 215 } 172 216 … … 180 224 $product->set_status( 'draft' ); 181 225 182 // O WordPress aplica a categoria padrão ("Sem categoria") sozinho183 // sempre que salva um produto sem nenhuma categoria — inclusive de184 // novo em qualquer ->save() subsequente (maybe_set_sku(), chamado185 // dentro de apply_identity_meta() logo abaixo, salva outra vez pro186 // SKU). Em vez de correr atrás disso a cada save, desligamos a187 // FONTE (a opção que registra o termo default da taxonomia) durante188 // toda a criação — mecanismo padrão do WordPress, não uma alteração189 // salva em lugar nenhum. Religa logo depois, então não afeta a190 // edição nativa nem outro plugin. Mesma técnica documentada em191 // SBSheet_Product_Service::create() (plugin irmão Sheet).192 226 add_filter( 'option_default_product_cat', '__return_zero' ); 193 227 … … 196 230 $product_id = $product->get_id(); 197 231 232 $note = SBNFEBR_Notes_Service::get_note( $item['note_id'] ); 198 233 $sku_status = self::apply_identity_meta( $product_id, $item, $gtin_kind, $sku_source ); 234 self::apply_draft_profile( $product_id, $item, $note, $options ); 199 235 200 236 remove_filter( 'option_default_product_cat', '__return_zero' ); 201 202 // IMPORTANTE: nenhum wp_set_object_terms($product_id, array(), 'product_cat')203 // aqui — WC_Post_Data::force_default_term() (hook nativo do WooCommerce)204 // reage a QUALQUER chamada de wp_set_post_terms com lista vazia pra205 // 'product_cat' reatribuindo a categoria padrão na hora, mesmo fora do206 // filtro acima. Com o filtro já tendo coberto os saves acima, o produto207 // já fica sem categoria — não precisa (e não pode) de mais nada aqui.208 237 209 238 SBNFEBR_Notes_Service::set_item_product_id( $item_id, $product_id ); … … 224 253 } 225 254 226 /** 227 * Identidade já resolve pra um produto vinculado? Checa primeiro a 228 * própria linha (idempotência de sempre), depois 229 * qualquer outra linha da mesma identidade (GTIN, ou fornecedor+ 230 * código quando não há GTIN) — impede criar produto duplicado pra 231 * um GTIN que outra nota já vinculou, mesmo que ESTA linha nunca 232 * tenha sido tocada antes. 233 * 234 * @param array $item Linha de sbnfebr_note_items. 235 * @return int ID do produto (não na lixeira), ou 0 se nenhum. 236 */ 255 private static function apply_draft_profile( $product_id, array $item, $note, array $options ) { 256 if ( 'invoice' === ( $options['profile'] ?? '' ) ) { 257 $plain = array_merge( $item, array( 'sale_csosn' => '', 'sale_cfop' => '', 'fiscal_crt' => '' ) ); 258 self::apply_fiscal_meta( $product_id, $plain, $note ); 259 self::apply_price_calc_meta( $product_id, $plain ); 260 self::apply_tax_meta( $product_id, $plain ); 261 return; 262 } 263 if ( 'simple' !== ( $options['profile'] ?? '' ) ) { 264 self::apply_fiscal_meta( $product_id, $item, $note ); 265 self::apply_price_calc_meta( $product_id, $item ); 266 self::apply_tax_meta( $product_id, $item ); 267 return; 268 } 269 if ( ! empty( $options['include_calculator'] ) ) { 270 self::apply_cost_meta( $product_id, $item ); 271 self::apply_price_calc_meta( $product_id, $item ); 272 self::apply_tax_meta( $product_id, $item ); 273 } 274 } 275 237 276 protected static function resolve_existing_product_id( array $item ) { 238 277 if ( ! empty( $item['wc_product_id'] ) ) { … … 255 294 } 256 295 257 /**258 * Title Case simples — primeira letra de cada palavra maiúscula,259 * resto minúsculo. Sem lista de exceção pra siglas/medidas ("220V",260 * "12X" etc), de propósito, pra não tentar adivinhar regra nenhuma.261 * `mb_convert_case` cobre acentuação (ç, ã, é...) corretamente.262 *263 * @param string $text Texto original (geralmente TUDO MAIÚSCULO, como vem do XML).264 * @return string265 */266 296 protected static function title_case( $text ) { 267 297 $text = (string) $text; … … 275 305 } 276 306 277 /**278 * Vincula o item a um produto WooCommerce JÁ EXISTENTE (achado pelo279 * "Checar cadastro" — matching de GTIN), em vez de criar um novo.280 * Não mexe no nome nem em nada além da identidade (mesmo critério281 * do Make Draft simples) — o produto já existe, não é este método282 * que decide como ele deve se chamar.283 *284 * @param int $item_id ID da linha em sbnfebr_note_items.285 * @param int $product_id ID do produto WooCommerce a vincular.286 * @param string|null $gtin_kind 'unit'|'box'.287 * @param string $sku_source 'none'|'gtin'|'product_code'.288 * @param bool $reassign Se o produto já está vinculado a outra289 * identidade, true resolve desvinculando a290 * antiga em vez de recusar (ver enforce_single_link()).291 * @return array|WP_Error { product_id, created: false }292 */293 public static function link_existing( $item_id, $product_id, $gtin_kind = null, $sku_source = 'gtin', $reassign = false ) {294 $item = SBNFEBR_Notes_Service::get_item( $item_id );295 if ( ! $item ) {296 return new WP_Error( 'sbnfebr_item_not_found', __( 'Item não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) );297 }298 299 $product = get_post( $product_id );300 if ( ! $product || ! in_array( $product->post_type, array( 'product', 'product_variation' ), true ) || 'trash' === $product->post_status ) {301 return new WP_Error( 'sbnfebr_product_not_found', __( 'Produto não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) );302 }303 304 $link_check = SBNFEBR_Notes_Service::enforce_single_link( $item, $product_id, $reassign );305 if ( is_wp_error( $link_check ) ) {306 return $link_check;307 }308 309 $sku_status = self::apply_identity_meta( $product_id, $item, $gtin_kind, $sku_source );310 SBNFEBR_Notes_Service::set_item_product_id( $item_id, $product_id );311 SBNFEBR_Notes_Service::propagate_link( $item, $product_id );312 313 if ( class_exists( 'SBNFEBR_Audit_Service' ) ) {314 SBNFEBR_Audit_Service::log(315 SBNFEBR_Audit_Service::EVENT_PRODUCT_LINKED,316 array(317 'note_id' => (int) $item['note_id'],318 'product_id' => (int) $product_id,319 'detail' => $item['description'],320 )321 );322 }323 324 return array( 'product_id' => (int) $product_id, 'created' => false, 'sku_status' => $sku_status );325 }326 327 328 /**329 * Vincula o item (se ainda não estiver) + grava GTIN kind/SKU source330 * + opcionalmente o custo desta nota. Nunca mexe em estoque nem em331 * dado fiscal.332 *333 * @param int $item_id ID da linha em sbnfebr_note_items.334 * @param int $product_id ID do produto WooCommerce a vincular/atualizar.335 * @param bool $apply_price Se true, grava `sbs_price_cost_paid` com o valor da nota.336 * @param string|null $gtin_kind 'unit'|'box'.337 * @param string $sku_source 'none'|'gtin'|'product_code'.338 * @param bool $reassign Ver link_existing().339 * @return array|WP_Error { product_id, sku_status }340 */341 public static function update_price_source( $item_id, $product_id, $apply_price, $gtin_kind = null, $sku_source = 'gtin', $reassign = false ) {342 $item = SBNFEBR_Notes_Service::get_item( $item_id );343 if ( ! $item ) {344 return new WP_Error( 'sbnfebr_item_not_found', __( 'Item não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) );345 }346 347 $product = wc_get_product( $product_id );348 if ( ! $product || 'trash' === $product->get_status() ) {349 return new WP_Error( 'sbnfebr_product_not_found', __( 'Produto não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) );350 }351 352 $link_check = SBNFEBR_Notes_Service::enforce_single_link( $item, $product_id, $reassign );353 if ( is_wp_error( $link_check ) ) {354 return $link_check;355 }356 357 $sku_status = self::apply_identity_meta( $product_id, $item, $gtin_kind, $sku_source );358 359 if ( $apply_price ) {360 // Mesma ressalva de apply_fiscal_meta()/link_and_update(): só361 // grava quando a unidade é reconhecida como peso/litro/metro/362 // caixa (não reconhecida usa fallback 'unit').363 $unit_raw = strtoupper( trim( (string) ( $item['unit'] ?? '' ) ) );364 $known_type = isset( self::UNIT_TO_SALE_TYPE[ $unit_raw ] ) ? self::UNIT_TO_SALE_TYPE[ $unit_raw ] : null;365 if ( ( null === $known_type || 'unit' === $known_type ) && $item['unit_value'] > 0 ) {366 update_post_meta( $product_id, 'sbs_price_cost_paid', $item['unit_value'] );367 if ( null === $known_type ) {368 update_post_meta( $product_id, 'sbs_price_sale_type', 'unit' );369 }370 }371 }372 373 SBNFEBR_Notes_Service::set_item_product_id( $item_id, $product_id );374 SBNFEBR_Notes_Service::propagate_link( $item, $product_id );375 376 if ( class_exists( 'SBNFEBR_Audit_Service' ) ) {377 SBNFEBR_Audit_Service::log(378 SBNFEBR_Audit_Service::EVENT_PRODUCT_LINKED,379 array(380 'note_id' => (int) $item['note_id'],381 'product_id' => (int) $product_id,382 'detail' => $item['description'] . ' (preço/fonte)',383 )384 );385 }386 387 return array( 'product_id' => (int) $product_id, 'sku_status' => $sku_status );388 }389 390 /**391 * Aplica 1 item da revisão pós-import num produto JÁ resolvido pela392 * identidade (ver393 * SBNFEBR_Notes_Service::get_post_import_review()) — diferente de394 * sync_full(), não depende do item já ter `wc_product_id` gravado395 * nele (o item recém-importado normalmente ainda não tem; quem396 * decide o produto é o cálculo da revisão, feito ANTES de chamar397 * aqui). Sempre grava identidade + fiscal completo + estoque opcional398 * — é o "aceitar esta mudança" do lote.399 *400 * @param int $item_id ID da linha em sbnfebr_note_items.401 * @param int $product_id Produto já resolvido pra este item.402 * @param string $stock_action 'none'|'sum'|'replace'.403 * @param float|null $stock_value Estoque final — obrigatório quando $stock_action !== 'none'.404 * @return array|WP_Error { product_id }405 */406 public static function apply_review_item( $item_id, $product_id, $stock_action = 'none', $stock_value = null ) {407 $item = SBNFEBR_Notes_Service::get_item( $item_id );408 if ( ! $item ) {409 return new WP_Error( 'sbnfebr_item_not_found', __( 'Item não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) );410 }411 412 $product = get_post( $product_id );413 if ( ! $product || 'trash' === $product->post_status ) {414 return new WP_Error( 'sbnfebr_product_not_found', __( 'Produto não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) );415 }416 417 $note = SBNFEBR_Notes_Service::get_note( $item['note_id'] );418 419 self::apply_identity_meta( $product_id, $item );420 // class_exists() checks the class is actually loaded, not just the flag.421 if ( class_exists( 'SBNFEBR_Draft_Service_Plus' ) ) {422 // NCM é a única diferença fiscal que a revisão exibe e o usuário aceita; o resto só preenche vazios.423 if ( '' !== (string) $item['ncm'] ) {424 update_post_meta( $product_id, '_ncm', $item['ncm'] );425 }426 SBNFEBR_Draft_Service_Plus::apply_fiscal_meta( $product_id, $item, $note, 'empty' );427 SBNFEBR_Draft_Service_Plus::apply_price_calc_meta( $product_id, $item );428 SBNFEBR_Draft_Service_Plus::apply_tax_meta( $product_id, $item );429 }430 431 $stock_action = in_array( $stock_action, array( 'sum', 'replace' ), true ) ? $stock_action : 'none';432 if ( 'none' !== $stock_action && null !== $stock_value ) {433 $wc_product = wc_get_product( $product_id );434 if ( $wc_product ) {435 $wc_product->set_manage_stock( true );436 $wc_product->set_stock_quantity( (float) $stock_value );437 $wc_product->save();438 }439 }440 441 SBNFEBR_Notes_Service::set_item_product_id( $item_id, $product_id );442 SBNFEBR_Notes_Service::propagate_link( $item, $product_id );443 444 if ( class_exists( 'SBNFEBR_Audit_Service' ) ) {445 SBNFEBR_Audit_Service::log(446 SBNFEBR_Audit_Service::EVENT_PRODUCT_SYNCED,447 array(448 'note_id' => (int) $item['note_id'],449 'product_id' => $product_id,450 'detail' => $item['description'] . ' (revisão pós-import)',451 )452 );453 }454 455 return array( 'product_id' => $product_id );456 }457 458 /**459 * Identidade do item no produto — GTIN nativo do WC, código do460 * produto no fornecedor, vínculo com o fornecedor (taxonomia461 * `sbs_supplier`) e a chave de matching durável.462 *463 * @param int $product_id ID do produto.464 * @param array $item Linha de sbnfebr_note_items.465 * @param string|null $gtin_kind 'unit'|'box' — escolha explícita do466 * usuário (Draft/Link). Null deixa467 * resolve_gtin_kind() decidir (persistido468 * de uma vez anterior, ou heurística por469 * tamanho).470 * @param string $sku_source 'none'|'gtin'|'product_code' — rádio no471 * modal "Preencher SKU como", não checkbox.472 * @return string 'set'|'has_sku'|'conflict'|'not_applicable' — status do SKU (ver maybe_set_sku()).473 */474 307 protected static function apply_identity_meta( $product_id, array $item, $gtin_kind = null, $sku_source = 'gtin' ) { 475 308 $sku_status = 'not_applicable'; … … 487 320 } 488 321 489 // "product_code" funciona mesmo sem GTIN na nota (o código do490 // fornecedor sempre existe), por isso fica FORA do bloco491 322 // `if ($has_gtin)` acima. 492 323 if ( 'gtin' === $sku_source && $has_gtin ) { … … 496 327 } 497 328 498 // sbs_supplier_product_code: código que ESTE fornecedor deu a499 // ESTE produto (cProd da nota) — campo do Gerenciador de500 329 // Códigos da Sheet, dedicado a isso. NUNCA usar 501 // 'sbs_supplier_code' aqui: esse é outro campo, o código do502 // FORNECEDOR em si (mirror automático da taxonomia sbs_supplier,503 // ver mirror_to_product() abaixo) — nomes parecidos de propósito504 330 // mas são conceitos diferentes. 505 331 if ( '' !== $item['product_code'] ) { … … 514 340 } 515 341 516 /**517 * SKU = GTIN ou código do produto — rádio no modal. Só preenche518 * quando o produto ainda NÃO TEM SKU — nunca sobrescreve um SKU que519 * já existia (catálogo próprio do lojista tem prioridade sobre o520 * automático). SKU é único no WooCommerce — `set_sku()` valida isso521 * e lança `WC_Data_Exception` se outro produto já usa esse valor.522 *523 * Não trava o Draft/Link quando isso acontece (valor duplicado como524 * SKU em 2 produtos é sinal de outro problema, não algo pra travar525 * a ação inteira), mas devolve o motivo pra quem chamou poder526 * avisar o usuário em vez de engolir a falha em silêncio.527 *528 * @param int $product_id529 * @param string $value GTIN ou código do produto, já validado (não vazio).530 * @return string 'set'|'has_sku'|'conflict'.531 */532 342 protected static function maybe_set_sku( $product_id, $value ) { 533 343 $current_sku = get_post_meta( $product_id, '_sku', true ); … … 548 358 } 549 359 550 /**551 * Decide 'unit' ou 'box' pra este GTIN — 3 fontes, nesta ordem:552 * 1. Escolha explícita do usuário ($requested_kind, vinda do radio553 * no modal de Draft/Link) — grava como novo padrão do produto.554 * 2. Escolha anterior já persistida no produto (Sync/link-update555 * reaplicando sem perguntar de novo).556 * 3. Heurística por tamanho — 14 dígitos é GTIN-14, tipicamente557 * código de caixa/pallet no padrão GS1 (não existe GTIN-14 de558 * unidade); 8/12/13 é sempre unidade. Sem heurística melhor559 * possível sem ler a descrição do item (mesma limitação já560 * registrada no backlog da Calculadora de Preço).561 *562 * @param int $product_id563 * @param string $gtin Já trimado, "SEM GTIN" já filtrado fora.564 * @param string|null $requested_kind 'unit'|'box'|null.565 * @return string 'unit'|'box'.566 */567 360 protected static function resolve_gtin_kind( $product_id, $gtin, $requested_kind ) { 568 361 if ( in_array( $requested_kind, array( 'unit', 'box' ), true ) ) { … … 582 375 } 583 376 584 /**585 * Vincula o produto ao fornecedor certo na taxonomia `sbs_supplier`586 * (mesma taxonomia que a Biblioteca de Fornecedores do SBNFEBR já587 * usa — funciona standalone, sem depender da Sheet). Marca como588 * "principal" e, se a Sheet Plus estiver ativa, chama589 * `mirror_to_product()` dela — é isso que preenche590 * `sbs_supplier_code`/`sbs_supplier_name`/telefone/endereço etc.591 * sozinho, com o valor certo (código do FORNECEDOR, não do592 * produto). Sem Sheet Plus: só o vínculo nativo acontece (visível593 * em qualquer lugar que leia a taxonomia), os campos-espelho ficam594 * vazios (não existe nada que os leia sem a Sheet mesmo).595 *596 * Fornecedor não encontrado (nem na Biblioteca do SBNFEBR, nem na597 * da Sheet — é a mesma taxonomia): não faz nada, mesmo padrão de598 * "não inventa dado" do resto do plugin.599 *600 * @param int $product_id ID do produto.601 * @param string $supplier_cnpj CNPJ do fornecedor (com ou sem pontuação).602 * @return void603 */604 377 protected static function link_supplier( $product_id, $supplier_cnpj ) { 605 378 $term_id = SBNFEBR_Supplier_Service::find_by_document( $supplier_cnpj ); -
sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-error-log-service.php
r3725460 r3782421 1 1 <?php 2 /**3 * Log de erros interno do SBNFEBR — mesmo padrão da SanBar EXPress4 * Sheet (`SBESFW_Error_Log_Service`, `class-sbsheet-error-log-service.php`):5 * captura toda resposta de erro das rotas REST próprias (sbnfebr/v1/*)6 * num único ponto central (`rest_request_after_callbacks`), sem tocar7 * em cada controller individualmente. Puramente observacional.8 *9 * @package SBNFEBR10 * @since 0.5.111 */12 2 13 3 defined( 'ABSPATH' ) || exit; 14 4 15 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared16 // Tabela própria (sbnfebr_error_log, fora do schema padrão do WP) — acesso direto via $wpdb é17 // inerente a esse modelo; sem cache de objeto porque o log é escrito a cada erro REST e lido só18 // sob demanda. Nome de tabela sempre vem de self::table_name() (fixo, nunca input de usuário).19 5 class SBNFEBR_Error_Log_Service { 20 6 21 /** Versão do schema — bump aqui força dbDelta rodar de novo em upgrade futuro. */22 7 const DB_VERSION = '1.0'; 23 8 24 /** Option key que guarda a versão do schema já aplicada. */25 9 const DB_VERSION_OPTION = 'sbnfebr_error_log_db_version'; 26 10 27 /** Máximo de linhas mantidas no total (mais antigas são descartadas). */28 11 const MAX_ROWS = 500; 29 12 30 /** Option key do nível de verbosidade ('all' ou 'errors_only'). */31 13 const OPTION_LEVEL = 'sbnfebr_error_log_level'; 32 14 33 /** User meta que guarda até quando o usuário já viu o log (ícone volta a normal). */34 15 const SEEN_META_KEY = 'sbnfebr_errorlog_last_seen'; 35 16 36 /**37 * Nome completo da tabela (com prefixo do WP).38 *39 * @return string40 */41 17 public static function table_name() { 42 18 global $wpdb; … … 44 20 } 45 21 46 /**47 * Cria a tabela se não existir, ou atualiza o schema se DB_VERSION48 * mudou. Idempotente.49 *50 * @return void51 */52 22 public static function create_table() { 53 23 $installed_version = get_option( self::DB_VERSION_OPTION ); … … 80 50 } 81 51 82 /**83 * Registra o hook central de captura. Chamado uma vez pelo84 * bootstrap em plugins_loaded.85 *86 * @return void87 */88 52 public static function init() { 89 53 add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'capture' ), 10, 3 ); 90 54 } 91 55 92 /**93 * Roda depois de QUALQUER callback REST resolver. Só reage a rotas94 * sbnfebr/v1 que voltaram erro (WP_Error, ou WP_REST_Response com95 * status >= 400) — sucesso passa direto, sem custo extra.96 *97 * @param WP_REST_Response|WP_Error|mixed $response Resposta original.98 * @param array $handler Handler resolvido.99 * @param WP_REST_Request $request Requisição REST.100 * @return mixed Mesmo $response, inalterado — isto é só observação.101 */102 56 public static function capture( $response, $handler, $request ) { 103 57 $route = $request->get_route(); … … 135 89 } 136 90 137 /**138 * Decide se um status deve ser gravado, conforme o nível139 * configurado em Configure ('all' ou 'errors_only'). 'all' grava140 * >=400 (inclui validação normal, útil pra acompanhar de perto);141 * 'errors_only' só >=500 (falha real/exceção).142 *143 * @param int $status Status HTTP da resposta.144 * @return bool145 */146 91 protected static function should_log( $status ) { 147 92 $level = self::get_level(); … … 152 97 } 153 98 154 /**155 * Lê o nível de verbosidade configurado ('all' por padrão).156 *157 * @return string 'all'|'errors_only'.158 */159 99 public static function get_level() { 160 100 $level = (string) get_option( self::OPTION_LEVEL, 'all' ); … … 162 102 } 163 103 164 /**165 * Grava o nível de verbosidade (sanitiza pra um dos 2 valores166 * válidos, qualquer outra coisa cai pro default 'all').167 *168 * @param string $level Valor recebido do cliente.169 * @return void170 */171 104 public static function set_level( $level ) { 172 105 $level = 'errors_only' === (string) $level ? 'errors_only' : 'all'; … … 174 107 } 175 108 176 /**177 * Grava uma linha e poda o excesso (mantém só as MAX_ROWS mais178 * recentes) — sem precisar de cron novo.179 *180 * @param string $route Rota REST (ex: /sbnfebr/v1/import).181 * @param string $method Método HTTP.182 * @param string $code Código do erro (WP_Error code).183 * @param string $message Mensagem do erro.184 * @param int $status Status HTTP.185 * @return void186 */187 109 protected static function record( $route, $method, $code, $message, $status ) { 188 110 global $wpdb; … … 209 131 } 210 132 211 /**212 * Mantém no máximo MAX_ROWS linhas — apaga as mais antigas213 * quando ultrapassa.214 *215 * @return void216 */217 133 protected static function prune() { 218 134 global $wpdb; 219 135 $table = self::table_name(); 220 136 221 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName137 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); 222 138 if ( $total <= self::MAX_ROWS ) { 223 139 return; … … 227 143 $wpdb->query( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 228 144 $wpdb->prepare( 229 "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName145 "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d", 230 146 $excess 231 147 ) … … 233 149 } 234 150 235 /**236 * Lista paginada, mais recente primeiro.237 *238 * @param int $page Página (1-based).239 * @param int $per_page Itens por página (máx 100).240 * @return array{entries:array,total:int,total_pages:int}241 */242 151 public static function list_entries( $page = 1, $per_page = 30 ) { 243 152 global $wpdb; … … 247 156 $offset = ( $page - 1 ) * $per_page; 248 157 249 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName158 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); 250 159 251 160 $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 252 161 $wpdb->prepare( 253 "SELECT * FROM {$table} ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName162 "SELECT * FROM {$table} ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", 254 163 $per_page, 255 164 $offset … … 279 188 } 280 189 281 /**282 * Estado do ícone (!) — se existe erro mais novo que a última vez283 * que o usuário atual abriu o log.284 *285 * @return array{has_new:bool,count:int}286 */287 190 public static function status_for_current_user() { 288 191 global $wpdb; … … 294 197 if ( $seen ) { 295 198 $count = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 296 $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE created_at > %s", $seen ) // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName199 $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE created_at > %s", $seen ) 297 200 ); 298 201 } else { 299 $count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName202 $count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); 300 203 } 301 204 … … 306 209 } 307 210 308 /**309 * Marca "visto agora" pro usuário atual — ícone volta ao normal.310 *311 * @return void312 */313 211 public static function mark_seen() { 314 212 $user_id = get_current_user_id(); … … 327 225 global $wpdb; 328 226 $table = self::table_name(); 329 // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- nome de tabela fixo ($wpdb->prefix . 'sbnfebr_error_log'), sem input de usuário.330 227 $wpdb->query( "TRUNCATE TABLE {$table}" ); 331 228 } -
sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-match-service.php
r3725460 r3782421 1 1 <?php 2 /**3 * Checa se um GTIN de item de nota já existe cadastrado em algum4 * produto WooCommerce — campo de unidade (`_global_unique_id`) ou5 * caixa/pacote (`sbs_gtin_box`).6 *7 * @package SBNFEBR8 * @since 0.5.59 */10 2 11 3 defined( 'ABSPATH' ) || exit; 12 4 13 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare14 // Consultas cruzam $wpdb->postmeta/$wpdb->posts (tabelas nativas do WP, não input externo) com15 // placeholders IN(...) de tamanho dinâmico montados via implode() ANTES do prepare() real —16 // padrão seguro estabelecido (ver comentário em cada bloco), mas o PHPCS não consegue verificar17 // estaticamente um array de %s montado dinamicamente, daí o falso positivo de18 // UnfinishedPrepare/InterpolatedNotPrepared em cada uma dessas 3 queries.19 5 class SBNFEBR_Match_Service { 20 6 21 /**22 * Pra cada GTIN válido da lista, procura produto WooCommerce (não23 * lixeira) com o mesmo valor em `_global_unique_id` (unidade) OU em24 * `sbs_gtin_box` (caixa/pacote, campo da Sheet). Quando o mesmo valor25 * bate nos 2 campos (produtos diferentes), unidade tem prioridade —26 * `ORDER BY FIELD()` garante isso antes do "primeiro encontrado27 * vence" de baixo. GTIN duplicado em mais de 1 produto (mesmo28 * campo) usa o primeiro encontrado — ambiguidade de cadastro não é29 * problema deste plugin resolver aqui.30 *31 * @param array $gtins Lista de GTINs (strings) a checar.32 * @return array Mapa gtin => { product_id, name, edit_url, field: 'unit'|'box'|'sku' }.33 */34 7 public static function match_by_gtin( array $gtins ) { 35 8 global $wpdb; … … 42 15 $placeholders = implode( ',', array_fill( 0, count( $gtins ), '%s' ) ); 43 16 44 // '_sku' cobre catálogo que guarda o GTIN no campo de SKU em vez do45 // campo de GTIN nativo. Sinal mais fraco que os outros 2 (SKU pode46 // coincidir com o GTIN por acaso) — por isso vem por último no47 // ORDER BY; o front marca esse tipo de match visualmente diferente.48 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- placeholders montados acima, valores via prepare(); $wpdb->postmeta/posts são propriedades do próprio $wpdb, não input externo.49 17 $sql = $wpdb->prepare( 50 18 "SELECT pm.meta_value AS gtin, pm.meta_key AS meta_field, p.ID AS product_id, p.post_title AS name … … 55 23 AND p.post_type IN ('product', 'product_variation') 56 24 AND p.post_status <> 'trash' 57 ORDER BY FIELD( pm.meta_key, '_global_unique_id', 'sbs_gtin_box', '_sku' )", 25 ORDER BY FIELD( pm.meta_key, '_global_unique_id', 'sbs_gtin_box', '_sku' )", // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare 58 26 $gtins 59 27 ); 60 28 61 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql já veio de $wpdb->prepare() logo acima. 62 $rows = $wpdb->get_results( $sql, ARRAY_A ); 29 $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 63 30 64 31 $matches = array(); 65 32 foreach ( $rows as $row ) { 66 // Primeiro encontrado vence (unidade > caixa > SKU, graças ao 67 // ORDER BY acima, quando o mesmo valor bate em mais de um campo). 33 if ( apply_filters( 'sbnfebr_match_rejected', false, 'gtin', $row['gtin'], (int) $row['product_id'] ) ) { 34 continue; 35 } 68 36 if ( isset( $matches[ $row['gtin'] ] ) ) { 69 37 continue; … … 86 54 } 87 55 88 /**89 * Cruzamento com o cadastro — reaproveita match_by_gtin() e enriquece90 * cada achado com o que o modal "Checar cadastro" mostra do lado "No91 * cadastro": preço, categoria (só a categoria PAI — se o produto tem92 * subcategoria, sobe a árvore até a raiz), marca, e os mesmos campos93 * de `get_snapshot()` (estoque, custo, sale_type, campos fiscais).94 *95 * Marca: WooCommerce não tem taxonomia nativa de marca em toda96 * instalação — tenta `product_brand` (nativo desde WC 9.6) e97 * `pwb-brand` (Perfect WooCommerce Brands, plugin de terceiro comum)98 * nessa ordem; se nenhuma existir, fica vazio.99 *100 * O diff de verdade (o que mudou vs. o que a nota traz) é calculado101 * no cliente via `FISCAL_FIELD_MAP` — aqui só entrega o retrato cru.102 *103 * @param array $gtins Lista de GTINs (strings) a checar.104 * @return array Mapa gtin => { product_id, name, edit_url, field, price, category, brand, stock, cost_paid, sale_type, ncm, cest, ... }.105 */106 56 public static function registry_check( array $gtins ) { 107 57 $matches = self::match_by_gtin( $gtins ); … … 119 69 } 120 70 121 /**122 * Categoria RAIZ do produto (sobe a árvore até o topo, se a123 * categoria atribuída for subcategoria) — cabe numa coluna estreita124 * sem o caminho completo tipo "Cozinha › Canecas". Usa a primeira125 * categoria atribuída quando o produto tem mais de uma — sem126 * critério de "principal" nativo no WooCommerce pra desempatar.127 *128 * @param int $product_id129 * @return string Nome da categoria raiz, ou '' se o produto não tem nenhuma.130 */131 71 protected static function get_root_category_name( $product_id ) { 132 72 $terms = get_the_terms( $product_id, 'product_cat' ); … … 135 75 } 136 76 $term = $terms[0]; 137 // Sobe até não ter mais pai — WooCommerce não impõe limite de138 // profundidade, mas categoria de produto raramente passa de 2-3139 // níveis, não precisa de trava de segurança contra loop aqui.140 77 while ( $term->parent ) { 141 78 $parent = get_term( $term->parent, 'product_cat' ); … … 148 85 } 149 86 150 /**151 * Marca do produto — ver nota de `registry_check()` sobre as 2152 * taxonomias tentadas, nessa ordem, primeira que existir vence.153 *154 * @param int $product_id155 * @return string Nome da marca, ou '' se nenhuma taxonomia de marca existir/estiver vazia.156 */157 87 protected static function get_brand_name( $product_id ) { 158 88 foreach ( array( 'product_brand', 'pwb-brand' ) as $taxonomy ) { … … 168 98 } 169 99 170 /**171 * "SEM GTIN"/vazio não é GTIN de verdade — mesmo critério usado em172 * SBNFEBR_Draft_Service::apply_fiscal_meta().173 *174 * @param string $gtin GTIN bruto.175 * @return string GTIN normalizado, ou '' se inválido.176 */177 100 protected static function normalize( $gtin ) { 178 101 $gtin = trim( (string) $gtin ); … … 183 106 } 184 107 185 /**186 * Segundo critério de matching, usado quando o GTIN não bate. Procura187 * produto já vinculado a esse fornecedor+código antes, via188 * `_sbnfebr_supplier_key` (`CNPJ|código`).189 *190 * @param array $keys Lista de chaves já montadas no formato `CNPJ|código`.191 * @return array Mapa chave => { product_id, name, edit_url }.192 */193 108 public static function match_by_supplier_key( array $keys ) { 194 109 global $wpdb; … … 201 116 $placeholders = implode( ',', array_fill( 0, count( $keys ), '%s' ) ); 202 117 203 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- placeholders montados acima, valores via prepare(); $wpdb->postmeta/posts são propriedades do próprio $wpdb, não input externo.204 118 $sql = $wpdb->prepare( 205 119 "SELECT pm.meta_value AS supplier_key, p.ID AS product_id, p.post_title AS name … … 209 123 AND pm.meta_value IN ({$placeholders}) 210 124 AND p.post_type IN ('product', 'product_variation') 211 AND p.post_status <> 'trash'", 125 AND p.post_status <> 'trash'", // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare 212 126 $keys 213 127 ); 214 128 215 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql já veio de $wpdb->prepare() logo acima. 216 $rows = $wpdb->get_results( $sql, ARRAY_A ); 129 $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 217 130 218 131 $matches = array(); 219 132 foreach ( $rows as $row ) { 220 // Mesma regra do GTIN: primeiro encontrado vence se, por 221 // algum motivo, a chave se repetir em mais de 1 produto. 133 if ( apply_filters( 'sbnfebr_match_rejected', false, 'supplier_key', $row['supplier_key'], (int) $row['product_id'] ) ) { 134 continue; 135 } 222 136 if ( isset( $matches[ $row['supplier_key'] ] ) ) { 223 137 continue; … … 233 147 } 234 148 235 /**236 * "Foto" do produto pra montar o diff do prompt de "produto já237 * cadastrado, deseja atualizar?" — estoque atual e custo atual (só238 * confiável quando `sale_type` é `unit`, mesma ressalva239 * de `SBNFEBR_Draft_Service::apply_fiscal_meta()`: pra peso/litro/240 * caixa o preço unitário da nota não é diretamente comparável com241 * um único "custo", fica de fora do diff por enquanto).242 * Também devolve a última escolha lembrada (se o usuário marcou243 * "lembrar" numa atualização anterior) — só pré-seleciona o prompt,244 * nunca pula a confirmação sozinho.245 *246 * @param int $product_id ID do produto.247 * @param int $exclude_item_id Item da ação em andamento — não conta248 * como "outro item" no aviso de uso249 * duplicado (0 = não exclui nenhum).250 * @return array{stock:float|null,cost_paid:float|null,sale_type:string,remembered:array}251 */252 149 public static function get_snapshot( $product_id, $exclude_item_id = 0 ) { 253 150 $product_id = (int) $product_id; … … 269 166 'cost_paid' => $cost_paid, 270 167 'sale_type' => $sale_type, 271 // Todos os campos fiscais (não só NCM+custo) — permite o card272 // "Update information" comparar campo a campo com a nota, em273 // vez de um sinal parcial que esconderia mudanças em CEST/274 168 // CST/unidades/etc. 275 169 'ncm' => (string) get_post_meta( $product_id, '_ncm', true ), … … 285 179 'cbenef' => (string) get_post_meta( $product_id, '_cbenef', true ), 286 180 'fornecedor_st' => (string) get_post_meta( $product_id, '_fornecedor_st', true ), 287 // Identificação do produto — mostrada nos cards de match/link288 // da grid (nome vindo do produto de verdade, não da nota).289 // GTIN usa a chave nativa do WooCommerce (mesma que a Sheet usa290 // no Gerenciador de Códigos, ver class-sbsheet-product-codes-service.php).291 181 'name' => $post ? $post->post_title : '', 292 182 'sku' => (string) get_post_meta( $product_id, '_sku', true ), 293 183 'gtin' => (string) get_post_meta( $product_id, '_global_unique_id', true ), 294 // Preço de venda atual + data de cadastro/última alteração —295 // contexto pra confirmar visualmente se é o produto certo sem296 184 // abrir o editor. 297 185 'price' => (string) get_post_meta( $product_id, '_price', true ), 298 186 'created_at' => $post ? $post->post_date : '', 299 187 'modified_at' => $post ? $post->post_modified : '', 300 // "Este produto já está em uso por outro item" — checagem301 // central, usada antes de Link/Sync pra nunca sobrescrever302 188 // silenciosamente o que outro item já gravou. 303 189 'used_by_other_item' => $exclude_item_id … … 308 194 'price_action' => (string) get_post_meta( $product_id, '_sbnfebr_remember_price_action', true ), 309 195 ), 310 // Deixa a decisão de escopo de identidade visível/alterável a311 // qualquer momento no modal de ação, não só no card de upgrade312 196 // na revisão pós-import. 313 197 'identity_scope' => (string) get_post_meta( $product_id, SBNFEBR_Notes_Service::META_IDENTITY_SCOPE, true ), … … 315 199 } 316 200 317 /** 318 * Busca produtos WooCommerce por nome ou SKU — usado quando um item 319 * da nota não bate nem por GTIN nem por fornecedor+código, e o 320 * usuário escolhe manualmente um produto já existente pra linkar 321 * (útil pra catálogo antigo, sem GTIN nem histórico de import). 322 * Sempre exclui lixeira; não distingue rascunho/publicado — qualquer 323 * status "vivo" é candidato a link. 324 * 325 * @param string $query Termo de busca (nome ou SKU). 326 * @param int $exclude_item_id Item da ação em andamento — não 327 * conta como "já em uso" pra ele 328 * mesmo (0 = não exclui nenhum). 329 * @return array Lista de { id, name, sku }, no máximo 20. 330 */ 331 public static function search_products( $query, $exclude_item_id = 0 ) { 201 public static function search_products( $query, $exclude_item_id = 0, $field = 'all' ) { 332 202 global $wpdb; 333 203 … … 338 208 339 209 $like = '%' . $wpdb->esc_like( $query ) . '%'; 340 341 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- monta com prepare() logo abaixo; $wpdb->postmeta/posts são propriedades do próprio $wpdb, não input externo.342 $sql =$wpdb->prepare(343 "SELECT DISTINCT p.ID, p.post_title,210 $field = in_array( $field, array( 'name', 'sku', 'gtin', 'sup' ), true ) ? $field : 'all'; 211 $rows = $wpdb->get_results( 212 $wpdb->prepare( 213 "SELECT DISTINCT p.ID, p.post_title, 344 214 ( SELECT meta_value FROM {$wpdb->postmeta} sm WHERE sm.post_id = p.ID AND sm.meta_key = '_sku' LIMIT 1 ) AS sku 345 215 FROM {$wpdb->posts} p 346 LEFT JOIN {$wpdb->postmeta} pm_sku ON pm_sku.post_id = p.ID AND pm_sku.meta_key = '_sku'347 216 WHERE p.post_type IN ('product', 'product_variation') 348 217 AND p.post_status <> 'trash' 349 AND ( p.post_title LIKE %s OR pm_sku.meta_value LIKE %s ) 218 AND ( 219 ( %s IN ('all', 'name') AND p.post_title LIKE %s ) 220 OR ( %s IN ('all', 'sku') AND EXISTS ( SELECT 1 FROM {$wpdb->postmeta} m1 WHERE m1.post_id = p.ID AND m1.meta_key = '_sku' AND m1.meta_value LIKE %s ) ) 221 OR ( %s IN ('all', 'gtin') AND EXISTS ( SELECT 1 FROM {$wpdb->postmeta} m2 WHERE m2.post_id = p.ID AND m2.meta_key IN ('_global_unique_id', 'sbs_gtin_box') AND m2.meta_value LIKE %s ) ) 222 OR ( %s IN ('all', 'sup') AND EXISTS ( SELECT 1 FROM {$wpdb->postmeta} m3 WHERE m3.post_id = p.ID AND m3.meta_key IN ('sbs_supplier_product_code', '_sbnfebr_supplier_key') AND m3.meta_value LIKE %s ) ) 223 ) 350 224 ORDER BY p.post_title ASC 351 225 LIMIT 20", 352 $like, 353 $like 354 ); 355 356 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql já veio de $wpdb->prepare() logo acima. 357 $rows = $wpdb->get_results( $sql, ARRAY_A ); 226 $field, 227 $like, 228 $field, 229 $like, 230 $field, 231 $like, 232 $field, 233 $like 234 ), 235 ARRAY_A 236 ); 358 237 359 238 $results = array(); … … 368 247 'name' => $row['post_title'], 369 248 'sku' => (string) $row['sku'], 370 // Thumbnail pra ajudar a identificar visualmente no popup de371 // link manual — string vazia se o produto não tem imagem,372 249 // cliente decide o placeholder. 373 250 'thumbnail_url' => $thumb_id ? (string) wp_get_attachment_image_url( $thumb_id, 'thumbnail' ) : '', 374 // "Já em uso por outro item" — mesma checagem central do375 // get_snapshot(), aqui pra marcar visualmente na lista de376 251 // resultados antes de escolher. 377 252 'used_by_other_item' => $other_item, -
sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-notes-service.php
r3725460 r3782421 1 1 <?php 2 /**3 * Persistence for imported NF-e: header (sbnfebr_notes, 1 row per note,4 * keeps the raw XML) + items (sbnfebr_note_items, 1 row per item, append5 * only — past rows are never edited).6 *7 * @package SBNFEBR8 * @since 0.2.09 */10 2 11 3 defined( 'ABSPATH' ) || exit; 12 4 13 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter14 // Duas tabelas próprias (sbnfebr_notes/sbnfebr_note_items, fora do schema padrão do WP) — todo15 // acesso é via $wpdb direto, sem cache de objeto (volume e padrão de leitura não justificam:16 // grid paginada, sempre filtrada, nunca "listar tudo"). Nomes de tabela sempre vêm de17 // self::items_table()/self::notes_table() ($wpdb->prefix . 'sbnfebr_...', fixo — nunca input de18 // usuário), interpolados em {$items_table}/{$notes_table} e passados por $wpdb->prepare() pros19 // valores de verdade (%s/%d) em toda query — o "unescaped parameter" é o SQL final já preparado,20 5 // não dado cru do usuário. 21 6 class SBNFEBR_Notes_Service { 22 7 23 /** Versão do schema — bump aqui força dbDelta rodar de novo em upgrade futuro. */24 8 const DB_VERSION = '1.6'; 25 9 26 /** Option key que guarda a versão do schema já aplicada. */27 10 const DB_VERSION_OPTION = 'sbnfebr_notes_db_version'; 28 11 29 /**30 * Nome completo (com prefixo do site) da tabela de cabeçalho de notas.31 *32 * @return string33 */34 12 public static function notes_table() { 35 13 global $wpdb; … … 37 15 } 38 16 39 /**40 * Nome completo (com prefixo do site) da tabela de itens.41 *42 * @return string43 */44 17 public static function items_table() { 45 18 global $wpdb; … … 47 20 } 48 21 49 /**50 * Resolve a cláusula ORDER BY a partir de `$args['order_by']`/51 * `$args['order_dir']`, contra uma WHITELIST fixa de coluna->expressão52 * SQL — nome de coluna nunca dá pra parametrizar como valor de53 * `$wpdb->prepare()`, então NUNCA aceitar o que vier do cliente direto54 * aqui. Sem `order_by` reconhecido (ou não presente na whitelist),55 * devolve `$default` sem mexer em nada.56 *57 * @param array $args Args do endpoint (order_by, order_dir).58 * @param array $whitelist Mapa 'chave aceita pelo cliente' => 'expressão SQL'.59 * @param string $default Cláusula ORDER BY completa (sem "ORDER BY") a usar sem sort ativo.60 * @return string61 */62 22 private static function resolve_order_by( array $args, array $whitelist, $default ) { 63 23 $key = isset( $args['order_by'] ) ? (string) $args['order_by'] : ''; … … 69 29 } 70 30 71 /**72 * Cria (ou atualiza) as duas tabelas via dbDelta. Idempotente —73 * só roda de fato quando DB_VERSION muda.74 *75 * @return void76 */77 31 public static function create_table() { 78 32 $installed_version = get_option( self::DB_VERSION_OPTION ); … … 86 40 $items_table = self::items_table(); 87 41 88 // dbDelta é sensível a formatação: dois espaços após PRIMARY KEY,89 // tipos em maiúsculo, sem vírgula sobrando na última coluna.90 42 $sql_notes = "CREATE TABLE {$notes_table} ( 91 43 id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, … … 179 131 } 180 132 181 /**182 * Verifica se uma chave de acesso já foi importada.183 *184 * @param string $access_key Chave de 44 dígitos.185 * @return int ID da nota existente, ou 0 se não encontrada.186 */187 133 public static function find_by_access_key( $access_key ) { 188 134 global $wpdb; … … 190 136 191 137 return (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 192 $wpdb->prepare( "SELECT id FROM {$notes_table} WHERE access_key = %s", $access_key ) // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName 193 ); 194 } 195 196 /** 197 * Grava uma nota (cabeçalho + itens) já parseada. NUNCA reimporta 198 * por cima de uma chave de acesso existente — chamador deve checar 199 * find_by_access_key() antes (o controller REST já faz isso). 200 * NF-e autorizada não muda de conteúdo (correção real do emitente 201 * vem por Carta de Correção ou cancelamento+nova nota, nunca reenvio 202 * da mesma chave com valores diferentes) — "reprocessar" só faria 203 * sentido no dia em que O PARSER ganhar campo novo e alguém quiser 204 * fazer backfill em nota antiga. Gravação é transacional: se 205 * qualquer item falhar, desfaz cabeçalho + itens 206 * já gravados nesta chamada, nunca deixa nota pela metade. 207 * 208 * @param array $parsed Estrutura retornada por SBNFEBR_Xml_Parser_Service::parse(). 209 * @return array{note_id:int,items_parsed:int,items_saved:int}|WP_Error 210 */ 138 $wpdb->prepare( "SELECT id FROM {$notes_table} WHERE access_key = %s", $access_key ) 139 ); 140 } 141 211 142 public static function save_note( array $parsed ) { 212 143 global $wpdb; … … 226 157 $row = array( 227 158 'access_key' => $header['access_key'], 228 // SHA-256 do XML original — a chave de acesso já é bloqueada229 // contra reimport (ver check acima); o hash serve como trilha230 // de auditoria (mesma chave sempre deveria ter o mesmo hash —231 // se não tiver, algo alterou o XML depois de emitido) e pra um232 // futuro "Reprocessar XML" saber se o conteúdo realmente mudou.233 159 'xml_hash' => hash( 'sha256', $parsed['raw_xml'] ), 234 160 'note_number' => $header['note_number'], … … 266 192 ); 267 193 268 // $wpdb->insert() usa %s por padrão pra todo campo — um valor PHP269 // null nesse placeholder vira string vazia '', não SQL NULL, o que270 // quebraria insert em coluna DATETIME (não aceita '' como data)271 // sob SQL strict mode. Remove a chave inteira quando null: a272 // coluna nem entra no INSERT, MySQL usa NULL por conta própria273 194 // (nenhuma das duas tem DEFAULT explícito != NULL). 274 195 foreach ( array( 'exit_entry_date', 'protocol_date' ) as $nullable_date_key ) { … … 278 199 } 279 200 280 // Transação cobre cabeçalho + todos os itens — ou grava a nota281 // inteira, ou não grava nada. Tabelas do plugin usam o engine282 // padrão do WordPress (InnoDB), que suporta transação real.283 201 $wpdb->query( 'START TRANSACTION' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery 284 202 … … 286 204 if ( false === $insert_ok ) { 287 205 $wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery 288 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log 289 error_log( sprintf( 'SBNFEBR: failed to insert note header for access_key %s — %s', $header['access_key'], $wpdb->last_error ) ); 206 error_log( sprintf( 'SBNFEBR: failed to insert note header for access_key %s — %s', $header['access_key'], $wpdb->last_error ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log 290 207 return new WP_Error( 291 208 'sbnfebr_save_failed', … … 310 227 if ( false === $ok ) { 311 228 $wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery 312 // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log 313 error_log( sprintf( 'SBNFEBR: failed to insert note item %d for access_key %s — %s (transaction rolled back)', (int) $item['item_number'], $header['access_key'], $wpdb->last_error ) ); 229 error_log( sprintf( 'SBNFEBR: failed to insert note item %d for access_key %s — %s (transaction rolled back)', (int) $item['item_number'], $header['access_key'], $wpdb->last_error ) ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log 314 230 return new WP_Error( 315 231 'sbnfebr_partial_save', … … 322 238 ); 323 239 } 240 241 $workflow = SBNFEBR_Workflow_Service::create_from_import( 242 (int) $wpdb->insert_id, 243 $header['access_key'], 244 $header, 245 $item 246 ); 247 if ( is_wp_error( $workflow ) ) { 248 $wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery 249 return $workflow; 250 } 324 251 ++$inserted; 325 252 } 326 253 327 254 $wpdb->query( 'COMMIT' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery 255 256 do_action( 'sbnfebr_note_items_saved', $note_id ); 328 257 329 258 if ( class_exists( 'SBNFEBR_Audit_Service' ) ) { … … 345 274 } 346 275 347 /** 348 * Lista itens com filtros opcionais — alimenta as 3 visões da grid 349 * (All global, filtrado por fornecedor, filtrado por nota). 350 * 351 * @param array $args { 352 * @type string $supplier_cnpj Filtra por fornecedor (opcional). 353 * @type int $note_id Filtra por nota específica (opcional). 354 * @type string $search Busca livre em descrição/código/GTIN (opcional). 355 * @type string $mode '' | 'duplicates' | 'notes_period' | 'price_period' (opcional). 356 * @type string $date_from 'Y-m-d', obrigatório pros modos *_period. 357 * @type string $date_to 'Y-m-d', obrigatório pros modos *_period. 358 * } 359 * @return array[] 360 */ 276 private static function catalog_mode_clause( $mode ) { 277 $wi = SBNFEBR_Workflow_Service::items_table(); 278 $ev = SBNFEBR_Workflow_Service::events_table(); 279 $by = "SELECT 1 FROM {$wi} w WHERE w.source_item_id = i.id"; 280 switch ( $mode ) { 281 case 'lvl_none': 282 return "NOT EXISTS ({$by} AND ( w.stage <> 'entry' OR w.creation_level <> 'none' ))"; 283 case 'lvl_prep': 284 return "EXISTS ({$by} AND w.stage = 'review')"; 285 case 'lvl_simple': 286 case 'lvl_invoice': 287 case 'lvl_regime': 288 return "EXISTS ({$by} AND w.creation_level = '" . substr( $mode, 4 ) . "')"; 289 case 'lvl_issues': 290 return "EXISTS ({$by} AND EXISTS ( SELECT 1 FROM {$ev} e WHERE e.workflow_id = w.id AND e.event_type = 'sent_with_issues' ))"; 291 } 292 return ''; 293 } 294 361 295 public static function get_items( array $args = array() ) { 362 296 global $wpdb; … … 367 301 $params = array(); 368 302 369 // Ordenação por coluna, Fornecedor/Descrição só (whitelist fixa,370 // nome de coluna não dá pra parametrizar como valor — nunca371 // aceitar o que vier do cliente direto no ORDER BY). Sem372 // $args['order_by'] reconhecido, mantém o padrão (data da nota).373 303 $order_sql = self::resolve_order_by( 374 304 $args, … … 387 317 if ( ! empty( $args['search'] ) ) { 388 318 $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; 389 $where[] = '(i.description LIKE %s OR i.product_code LIKE %s OR i.gtin LIKE %s )';319 $where[] = '(i.description LIKE %s OR i.product_code LIKE %s OR i.gtin LIKE %s OR n.supplier_name LIKE %s)'; 390 320 $params[] = $like; 391 321 $params[] = $like; 392 322 $params[] = $like; 393 }394 395 // Busca direta por lista de IDs — usada pra buscar os dados 323 $params[] = $like; 324 } 325 396 326 // completos de uma SELEÇÃO que pode ter itens de 397 // páginas diferentes ("Copy codes"/"Show only selected" cruzando398 // página — a seleção sobrevive à paginação, mas o cliente só tem399 // os dados da página atual carregada; isso busca o resto).400 327 $ids_filter = array(); 401 328 if ( ! empty( $args['ids'] ) && is_array( $args['ids'] ) ) { … … 408 335 } 409 336 410 // Itens ignorados somem de TODA visão por padrão — só aparecem411 337 // com mode='ignored' explicitamente. Evita que a 412 // lista de "pendentes" continue poluída depois de marcar algo413 338 // como "nunca vai virar produto". 414 339 $mode_arg = isset( $args['mode'] ) ? (string) $args['mode'] : ''; … … 419 344 } 420 345 421 // Filtro de modo (select "Filtro" na toolbar) — 4 opções, mutuamente422 // exclusivas. 'duplicates' e 'price_period' reaproveitam a mesma423 // noção de "GTIN em fornecedor diferente" / "preço variou" que já424 346 // alimenta as cores do ícone de histórico. 425 347 $mode = isset( $args['mode'] ) ? (string) $args['mode'] : ''; … … 431 353 432 354 if ( 'duplicates' === $mode ) { 433 // Mesmo GTIN visto em mais de 1 fornecedor — mesmo critério434 355 // que pinta o ícone de histórico de vermelho. 435 356 $where[] = "( … … 439 360 ) > 1"; 440 361 } elseif ( 'notes_period' === $mode && $date_from && $date_to ) { 441 // Simples: só itens de notas emitidas dentro do intervalo.442 362 $where[] = 'n.emission_date BETWEEN %s AND %s'; 443 363 $params[] = $date_from; 444 364 $params[] = $date_to; 445 365 } elseif ( 'price_period' === $mode && $date_from && $date_to ) { 446 // Acha os pares fornecedor+código que variaram de preço DENTRO447 // do intervalo, depois mostra o HISTÓRICO COMPLETO desses448 // produtos (inclusive notas fora do intervalo, como contexto)449 // — por isso o filtro de data não entra direto no WHERE450 // principal, só serve pra decidir QUAIS produtos aparecem.451 366 $join_sql = "INNER JOIN ( 452 367 SELECT i5.supplier_cnpj AS flag_cnpj, i5.product_code AS flag_code … … 459 374 $join_params[] = $date_from; 460 375 $join_params[] = $date_to; 376 } elseif ( self::catalog_mode_clause( $mode ) ) { 377 $where[] = self::catalog_mode_clause( $mode ); 461 378 } elseif ( 'linked' === $mode ) { 462 // Já tem produto vinculado (ícone ✓ verde) — filtro de ESTADO463 379 // atual, sem depender de período. 464 380 $where[] = 'i.wc_product_id IS NOT NULL'; … … 467 383 $where[] = 'i.wc_product_id IS NULL'; 468 384 } elseif ( 'price_warn' === $mode ) { 469 // Mesmo critério do ícone âmbar de histórico: preço variou470 // entre notas do mesmo fornecedor+código, SEM limite de período471 // (esse já existe como price_period, este aqui é "sempre").472 385 $where[] = "( 473 386 SELECT COUNT(DISTINCT ROUND(i6.unit_value, 2)) … … 476 389 ) > 1"; 477 390 } elseif ( 'supplier_match' === $mode ) { 478 // Itens ainda sem produto, mas que batem por fornecedor+código479 // com um produto JÁ cadastrado (mesma chave que alimenta o480 // ícone "!" vermelho/match_source='supplier_key' no cliente —481 // ver match_by_supplier_key() em class-sbnfebr-match-service.php).482 391 $where[] = 'i.wc_product_id IS NULL'; 483 392 $where[] = $wpdb->prepare( … … 493 402 ); 494 403 } elseif ( 'sync_pending' === $mode ) { 495 // Item já vinculado, mas o produto nunca recebeu fiscal (NCM496 // vazio — ex: linkado via Lite) OU o NCM gravado é diferente497 // do que esta nota traz — sinal de "precisa de Sync"498 // Mesmo sinal parcial (só NCM) já usado no card "Update499 404 // information" — não é diff completo 500 // de CEST/CST/CFOP/impostos/custo, cobre o caso mais comum.501 405 $where[] = 'i.wc_product_id IS NOT NULL'; 502 406 $where[] = "( … … 506 410 )"; 507 411 } elseif ( 'has_fiscal' === $mode ) { 508 // Oposto exato de sync_pending: vinculado E com o NCM desta509 // nota já gravado no produto (fiscal sincronizado). Plus only,510 // mesmo dado (NCM) que sync_pending já usa como sinal.511 412 $where[] = 'i.wc_product_id IS NOT NULL'; 512 413 $where[] = "i.ncm <> ''"; 513 414 $where[] = "(SELECT pm7b.meta_value FROM {$wpdb->postmeta} pm7b WHERE pm7b.post_id = i.wc_product_id AND pm7b.meta_key = '_ncm' LIMIT 1) = i.ncm"; 514 415 } elseif ( 'stale' === $mode ) { 515 // Mesma regra de get_stale_reason(): produto vinculado que sumiu/516 // foi pra lixeira, ou cujo GTIN atual diverge do snapshot517 416 // gravado no momento do vínculo. 518 417 $where[] = "i.wc_product_id IS NOT NULL AND ( … … 528 427 } 529 428 530 // price_variants / gtin_supplier_count alimentam os 3 estados do531 // ícone de histórico na grid (cinza/âmbar/vermelho) — calculados532 // aqui, em bloco, pra não precisar de 1 requisição por linha.533 // gtin_supplier_count ignora GTIN vazio/"SEM GTIN" (não é534 // identificador de verdade, contaria falso positivo cruzando535 // itens sem GTIN de fornecedores diferentes). ROUND(unit_value,2)536 // na comparação de price_variants: `vUnCom` do XML às vezes vem537 429 // com 10 casas decimais (resultado de divisão, ex: 538 // 5.8316666667) — sem arredondar, duas notas com o MESMO preço539 // em reais/centavos podiam contar como "variou" por causa de540 // ruído de precisão que o usuário nem vê na tela.541 430 $sql = "SELECT i.*, n.note_number, n.series, n.emission_date, n.supplier_name, 542 431 ( … … 565 454 ORDER BY ' . $order_sql; 566 455 567 // join_params vem ANTES de params na string final (o JOIN aparece568 // antes do WHERE no SQL), a ordem dos placeholders precisa bater.569 456 $all_params = array_merge( $join_params, $params ); 570 457 571 // Paginação — lista sem limite pesava com muitos itens (sem572 // rolagem virtual, tudo no DOM de uma vez). 25/50/75/100,573 // mesmas opções que a preferência salva no cliente oferece.574 458 $per_page_options = array( 25, 50, 75, 100 ); 575 459 if ( $ids_filter ) { 576 // Busca por ID explícita — devolve todos de uma vez, sem as577 // opções fechadas de per_page (é uma seleção pontual, não578 460 // navegação de catálogo). 579 461 $per_page = count( $ids_filter ); … … 585 467 } 586 468 587 // Total ANTES do LIMIT — mesmo WHERE/JOIN do SQL principal, sem os588 // subselects de price_variants/gtin_supplier_count/linked_ncm589 469 // (não afetam contagem, só custariam à toa). 590 470 $count_sql = "SELECT COUNT(*), COUNT(DISTINCT i.note_id) … … 598 478 $note_count = $count_row ? (int) $count_row[1] : 0; 599 479 600 // Skips the row fetch below — used by the per-product view to get601 // the true item count for the "Items" stat without paying for the602 // full row query (mirrors get_items_by_product()'s count_only).603 480 if ( ! empty( $args['count_only'] ) ) { 604 481 return array( 'total' => $total, 'note_count' => $note_count ); … … 610 487 $items = $wpdb->get_results( $prepared, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 611 488 612 // Apelido: troca supplier_name pelo apelido na grid, quando o613 // fornecedor tem "Exibir apelido" marcado. Nada mais depende do614 // nome legal aqui (filtro usa supplier_cnpj), seguro trocar direto.615 489 self::apply_supplier_nicknames( $items ); 616 490 self::apply_stale_flags( $items ); … … 625 499 } 626 500 627 /**628 * Troca `supplier_name` pelo apelido, in-place, nas linhas que629 * tiverem `supplier_cnpj` batendo com o mapa de apelidos.630 * Helper comum entre get_items() e get_items_by_product() — mesma631 * regra, 2 formatos de linha diferentes.632 *633 * @param array[] $rows Alterado por referência.634 * @return void635 */636 501 protected static function apply_supplier_nicknames( array &$rows ) { 637 502 if ( ! $rows || ! class_exists( 'SBNFEBR_Supplier_Service' ) ) { … … 650 515 } 651 516 652 /**653 * Agrega itens por identidade de produto (GTIN, ou fornecedor+código654 * quando não há GTIN) — visão "por produto" em vez de "por655 * lançamento de nota" — cada linha do resultado é 1 produto, não 1656 * ocorrência numa nota. Mesma noção de identidade de657 * get_gtin_family()/propagate_link(): GTIN cruza fornecedor,658 * fornecedor+código sem GTIN não cruza.659 *660 * Suporta o mesmo filtro "modo especial" de get_items(), com o661 * subconjunto que faz sentido agregado por identidade: linked/662 * pending/price_warn/supplier_match/sync_pending/notes_period/663 * price_period. FICAM DE FORA: 'duplicates' (a visão já é664 * deduplicada por identidade, nunca duplica) e 'ignored' (a visão665 * por produto sempre esconde item ignorado, sem exceção). Os666 * filtros entram no WHERE ANTES do GROUP BY, então note_count/667 * supplier_count refletem só o escopo filtrado (comportamento668 * esperado de qualquer filtro aqui).669 *670 * @param array $args { supplier_cnpj, search, note_id, mode, date_from, date_to, page, per_page }671 * @return array672 */673 517 public static function get_items_by_product( array $args = array() ) { 674 518 global $wpdb; … … 683 527 $params[] = $args['supplier_cnpj']; 684 528 } 685 // Mesmo tratamento de get_items(): filtra as linhas ANTES do686 // GROUP BY, então note_count/supplier_count também refletem só o687 // escopo filtrado — mesmo comportamento esperado em qualquer688 529 // outro filtro da grid. 689 530 if ( ! empty( $args['note_id'] ) ) { … … 693 534 if ( ! empty( $args['search'] ) ) { 694 535 $like = '%' . $wpdb->esc_like( $args['search'] ) . '%'; 695 $where[] = '(i.description LIKE %s OR i.product_code LIKE %s OR i.gtin LIKE %s )';536 $where[] = '(i.description LIKE %s OR i.product_code LIKE %s OR i.gtin LIKE %s OR n.supplier_name LIKE %s)'; 696 537 $params[] = $like; 697 538 $params[] = $like; 698 539 $params[] = $like; 699 } 700 701 // Mesmo "filtro especial" de get_items(), subconjunto ver 702 // docblock. Mesmas subqueries/JOIN daquela função, só com 703 // aliases próprios (i8/i9/n8) pra não colidir com nada dentro 540 $params[] = $like; 541 } 542 704 543 // desta mesma query. 705 544 $mode = isset( $args['mode'] ) ? (string) $args['mode'] : ''; … … 725 564 $join_params[] = $date_from; 726 565 $join_params[] = $date_to; 566 } elseif ( self::catalog_mode_clause( $mode ) ) { 567 $where[] = self::catalog_mode_clause( $mode ); 727 568 } elseif ( 'linked' === $mode ) { 728 569 $where[] = 'i.wc_product_id IS NOT NULL'; … … 776 617 $identity_expr = "CASE WHEN i.gtin <> '' AND i.gtin <> 'SEM GTIN' THEN CONCAT('G:', i.gtin) ELSE CONCAT('S:', i.supplier_cnpj, ':', i.product_code) END"; 777 618 $where_sql = implode( ' AND ', $where ); 778 // join_params vem ANTES de params (o JOIN aparece antes do WHERE779 619 // no SQL final) — mesma ordem de get_items(). 780 620 $count_join_params = array_merge( $join_params, $params ); … … 792 632 $total = (int) $wpdb->get_var( $count_prepared ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 793 633 794 // Badge "Produtos únicos" na barra de stats, visível nos 2 modos795 634 // de visão. Só precisa do 796 // $total acima (já conta identidade com E sem GTIN, a expressão797 // CASE cobre os 2 casos) — pula os 2 SELECTs pesados (grupo +798 // linhas representantes) que só fazem sentido pra renderizar a799 635 // grid de verdade. 800 636 if ( ! empty( $args['count_only'] ) ) { … … 807 643 $page = max( 1, (int) ( $args['page'] ?? 1 ) ); 808 644 809 // MAX(i.id) como "linha representante" do grupo — mais barato que810 // subquery correlacionada por data, e id crescente já é uma boa811 // aproximação de "ocorrência mais recente" (inserção segue a812 645 // ordem de import). 813 // COUNT(DISTINCT i.supplier_cnpj) sem CASE de propósito: no grupo814 // sem GTIN, supplier_cnpj já É parte da chave de identidade (só815 // pode dar 1); no grupo por GTIN, conta os fornecedores de816 646 // verdade que já venderam esse mesmo GTIN. 817 // Ordenação por Descrição também na visão por produto (Fornecedor818 // não existe aqui, é agregado — ver PRODUCT_COLS no front).819 // MAX(i.description) como valor representante do grupo (mesmo820 647 // raciocínio de rep_item_id). 821 648 $order_sql = self::resolve_order_by( … … 854 681 } 855 682 856 // Dados completos das linhas representantes, mesmo formato de857 // get_items() — grid/modal reaproveitam sem adaptação nenhuma.858 683 $rep_ids = array_map( function ( $g ) { return (int) $g['rep_item_id']; }, $groups ); 859 684 $id_placeholders = implode( ',', array_fill( 0, count( $rep_ids ), '%d' ) ); 860 // price_variants: mesma noção de sempre, escopada ao861 685 // fornecedor/código da LINHA REPRESENTANTE (mesmo 862 // critério já usado na visão por nota, sem inventar um novo).863 686 $rows_sql = "SELECT i.*, n.note_number, n.series, n.emission_date, n.supplier_name, 864 687 (SELECT pm.meta_value FROM {$wpdb->postmeta} pm WHERE pm.post_id = i.wc_product_id AND pm.meta_key = '_ncm' LIMIT 1) AS linked_ncm, … … 889 712 continue; 890 713 } 891 // wc_product_id agregado (MAX de todo o grupo) — a linha892 714 // representante já devia estar sincronizada por 893 // propagate_link(), mas usa o agregado por garantia (cobre894 // uma eventual dessincronia sem precisar rodar migração).895 715 $row['wc_product_id'] = $g['wc_product_id'] ? (int) $g['wc_product_id'] : null; 896 716 $row['product_note_count'] = (int) $g['note_count']; 897 717 $row['product_supplier_count'] = (int) $g['supplier_count']; 898 // Data da nota mais recente do grupo inteiro, já calculada pra899 // ordenar (latest_date); só devolve pro cliente em vez de descartar.900 718 $row['product_last_date'] = $g['latest_date']; 901 719 if ( $row['wc_product_id'] ) { … … 905 723 } 906 724 907 // Estoque atual — 1 query só pra todos os produtos908 // linkados da página, em vez de 1 subquery por linha (estoque é909 // do WooCommerce, não da nossa tabela — não cabe no mesmo SELECT910 725 // que já tem i.*). 911 726 if ( $linked_product_ids ) { … … 933 748 } 934 749 935 /**936 * Busca 1 item pelo ID — usado pra descobrir supplier_cnpj/product_code937 * antes de montar o histórico de preço (ver get_price_history()).938 *939 * @param int $item_id ID da linha em sbnfebr_note_items.940 * @return array|null941 */942 750 public static function get_item( $item_id ) { 943 751 global $wpdb; … … 945 753 946 754 return $wpdb->get_row( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 947 $wpdb->prepare( "SELECT * FROM {$items_table} WHERE id = %d", (int) $item_id ), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName755 $wpdb->prepare( "SELECT * FROM {$items_table} WHERE id = %d", (int) $item_id ), 948 756 ARRAY_A 949 757 ); 950 758 } 951 759 952 /**953 * Marca/desmarca um ou mais itens como "ignorado" — item que o954 * usuário decidiu que nunca vai virar produto (amostra, brinde, uso955 * interno etc). Some da visão padrão (ver get_items()), só aparece956 * com o filtro "Ignored" ativo. Não mexe em `wc_product_id` nem em957 * nada mais — reversível a qualquer momento.958 *959 * @param int[] $item_ids IDs de linhas em sbnfebr_note_items.960 * @param bool $ignored true = marca, false = desmarca.961 * @return int Quantidade de linhas afetadas.962 */963 760 public static function set_ignored( array $item_ids, $ignored ) { 964 761 global $wpdb; … … 971 768 972 769 $placeholders = implode( ',', array_fill( 0, count( $item_ids ), '%d' ) ); 973 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- placeholders montados acima, valores via prepare().974 770 return (int) $wpdb->query( 975 771 $wpdb->prepare( … … 980 776 } 981 777 982 /**983 * Checa se um produto já está vinculado a ALGUM outro item de nota984 * (diferente do informado) — base do aviso "este produto já está em985 * uso" antes de Link/Sync, evitando que 2 itens diferentes apontem986 * pro mesmo produto e cada Sync sobrescreva o outro silenciosamente.987 *988 * @param int $product_id ID do produto WooCommerce.989 * @param int $exclude_item_id Item que NÃO conta como "outro" (o990 * próprio item da ação em andamento).991 * @return array|null { id, description, note_number, series } ou null.992 */993 778 public static function get_other_item_using_product( $product_id, $exclude_item_id ) { 994 779 global $wpdb; … … 1010 795 } 1011 796 1012 /**1013 * Busca 1 nota (cabeçalho) pelo ID — usado pelo Draft Service pra1014 * ler o CRT do fornecedor (decide CSOSN vs CST) na hora de criar o1015 * rascunho.1016 *1017 * @param int $note_id ID da linha em sbnfebr_notes.1018 * @return array|null1019 */1020 797 public static function get_note( $note_id ) { 1021 798 global $wpdb; … … 1023 800 1024 801 return $wpdb->get_row( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 1025 $wpdb->prepare( "SELECT * FROM {$notes_table} WHERE id = %d", (int) $note_id ), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName802 $wpdb->prepare( "SELECT * FROM {$notes_table} WHERE id = %d", (int) $note_id ), 1026 803 ARRAY_A 1027 804 ); 1028 805 } 1029 806 1030 /**1031 * Exclui uma nota (cabeçalho + itens). Produtos WooCommerce já1032 * criados a partir de itens desta nota (`wc_product_id`) NÃO são1033 * afetados — a nota é só a origem/histórico, nunca dona do produto.1034 * Transacional: cabeçalho e itens saem juntos, ou nada sai.1035 *1036 * @param int $note_id ID da linha em sbnfebr_notes.1037 * @return true|WP_Error1038 */1039 807 public static function delete_note( $note_id ) { 1040 808 global $wpdb; … … 1078 846 } 1079 847 1080 /**1081 * Grava o `wc_product_id` numa linha de item — chamado depois que o1082 * Draft Service cria (ou linka) o produto WooCommerce.1083 *1084 * @param int $item_id ID da linha em sbnfebr_note_items.1085 * @param int $product_id ID do produto WooCommerce.1086 * @return void1087 */1088 848 public static function set_item_product_id( $item_id, $product_id ) { 1089 849 global $wpdb; … … 1100 860 } 1101 861 1102 /**1103 * Compara o snapshot gravado no vínculo contra o estado atual do1104 * produto. Só GTIN e existência — nome muda por motivos cosméticos1105 * o tempo todo, comparar geraria falso positivo constante. A UI oferece1106 * ações diferentes pra cada motivo (produto sumiu: só religar; GTIN1107 * mudou: aceitar o novo ou religar).1108 *1109 * @param array $item Linha de sbnfebr_note_items (wc_product_id, link_snapshot_gtin).1110 * @return string '' (em dia ou sem vínculo) | 'missing' | 'gtin_changed'.1111 */1112 862 public static function get_stale_reason( array $item ) { 1113 863 $product_id = (int) ( $item['wc_product_id'] ?? 0 ); … … 1127 877 } 1128 878 1129 /**1130 * Preenche `stale`/`stale_reason` nas linhas, carregando posts e postmeta1131 * de todos os produtos vinculados em lote (2 queries no total) em vez de1132 * 1-2 por linha dentro de get_stale_reason().1133 *1134 * @param array $items Linhas de sbnfebr_note_items, por referência.1135 * @return void1136 */1137 879 protected static function apply_stale_flags( array &$items ) { 1138 880 $product_ids = array(); … … 1154 896 } 1155 897 1156 /**1157 * Aceita o estado atual do produto como novo "normal" do vínculo:1158 * regrava o snapshot de GTIN de toda linha ligada a ele que já tinha um.1159 * Linhas sem snapshot nunca são marcadas por GTIN, ficam como estão.1160 *1161 * @param int $product_id Produto WooCommerce vinculado.1162 * @return void1163 */1164 public static function refresh_link_snapshot( $product_id ) {1165 global $wpdb;1166 $product_id = (int) $product_id;1167 $items_table = self::items_table();1168 $wpdb->query( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared1169 $wpdb->prepare(1170 "UPDATE {$items_table} SET link_snapshot_gtin = %s, link_snapshot_name = %s WHERE wc_product_id = %d AND link_snapshot_gtin <> ''", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared1171 (string) get_post_meta( $product_id, '_global_unique_id', true ),1172 (string) get_the_title( $product_id ),1173 $product_id1174 )1175 );1176 }1177 1178 /**1179 * Acha um item vinculado a $product_id cuja identidade seja DIFERENTE1180 * da de $item (mesmo critério de propagate_link(): GTIN, ou1181 * fornecedor+código quando sem GTIN) — impõe "1 produto do cadastro1182 * = 1 identidade da NFE", usado por enforce_single_link() antes de1183 * gravar um novo vínculo.1184 *1185 * @param array $item Item que está tentando linkar (gtin, supplier_cnpj, product_code).1186 * @param int $product_id Produto alvo.1187 * @return array|null Linha de sbnfebr_note_items + note_number/series, ou null sem conflito.1188 */1189 898 public static function find_link_conflict( array $item, $product_id ) { 1190 899 global $wpdb; … … 1198 907 "SELECT i.*, n.note_number, n.series FROM {$items_table} i 1199 908 INNER JOIN {$notes_table} n ON n.id = i.note_id 1200 WHERE i.wc_product_id = %d AND i.gtin <> %s LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName909 WHERE i.wc_product_id = %d AND i.gtin <> %s LIMIT 1", 1201 910 (int) $product_id, 1202 911 $gtin … … 1206 915 "SELECT i.*, n.note_number, n.series FROM {$items_table} i 1207 916 INNER JOIN {$notes_table} n ON n.id = i.note_id 1208 WHERE i.wc_product_id = %d AND ( i.supplier_cnpj <> %s OR i.product_code <> %s ) LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName917 WHERE i.wc_product_id = %d AND ( i.supplier_cnpj <> %s OR i.product_code <> %s ) LIMIT 1", 1209 918 (int) $product_id, 1210 919 (string) ( $item['supplier_cnpj'] ?? '' ), … … 1216 925 } 1217 926 1218 /**1219 * Desvincula só a IDENTIDADE de $item (mesmo escopo de propagate_link:1220 * GTIN, ou fornecedor+código sem GTIN) — diferente de1221 * clear_product_link(), que limpa TODA linha apontando pro produto1222 * (usado só quando o produto em si é excluído).1223 *1224 * @param array $item Item cuja identidade será desvinculada (gtin, supplier_cnpj, product_code).1225 * @return void1226 */1227 927 public static function unlink_identity( array $item ) { 1228 928 global $wpdb; … … 1252 952 } 1253 953 1254 /**1255 * Trava "1 produto do cadastro = 1 identidade da NFE" — chamado por1256 * todo caminho que grava1257 * wc_product_id num produto ESCOLHIDO pelo usuário (link manual,1258 * match automático, ou implícito via Estoque/Preço/Fiscal quando o1259 * item ainda não tinha vínculo). Sem $reassign, recusa e devolve os1260 * dados do conflito pro front alertar antes de deixar escolher; com1261 * $reassign=true, desvincula a identidade antiga primeiro (não o1262 * produto todo — outros itens de OUTRAS identidades continuam como1263 * estavam) e segue.1264 *1265 * @param array $item Item que está tentando linkar.1266 * @param int $product_id Produto alvo.1267 * @param bool $reassign Se true, resolve desvinculando o conflito em vez de recusar.1268 * @return true|WP_Error1269 */1270 954 public static function enforce_single_link( array $item, $product_id, $reassign = false ) { 1271 955 $conflict = self::find_link_conflict( $item, $product_id ); … … 1295 979 } 1296 980 1297 /**1298 * Identidade de produto: pra qualquer linha que1299 * compartilhe a MESMA identidade de outra já vinculada, "já tem1300 * produto?" deixa de ser uma pergunta sobre a linha (`wc_product_id`1301 * dela) e vira uma pergunta sobre a identidade inteira — GTIN é1302 * identificador global (vale entre fornecedores diferentes); sem1303 * GTIN, fornecedor+código só é confiável DENTRO do mesmo fornecedor1304 * (código igual em fornecedores diferentes pode ser coincidência).1305 *1306 * @param array $item Linha de sbnfebr_note_items (precisa de gtin, supplier_cnpj, product_code).1307 * @return int ID do produto já vinculado a essa identidade, ou 0 se nenhuma linha da família tem vínculo ainda.1308 */1309 /** Postmeta privado — 'supplier_only' trava a identidade deste produto pra nunca cruzar fornecedor por GTIN. Vazio/ausente = padrão (GTIN vale entre fornecedores). */1310 981 const META_IDENTITY_SCOPE = '_sbnfebr_identity_scope'; 1311 982 … … 1318 989 $pid = $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 1319 990 $wpdb->prepare( 1320 "SELECT wc_product_id FROM {$items_table} WHERE gtin = %s AND wc_product_id > 0 LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName991 "SELECT wc_product_id FROM {$items_table} WHERE gtin = %s AND wc_product_id > 0 LIMIT 1", 1321 992 $gtin 1322 993 ) … … 1324 995 $pid = $pid ? (int) $pid : 0; 1325 996 1326 // Produto marcado "supplier_only" nunca aceita match por GTIN1327 // vindo de fornecedor diferente do que1328 // já está vinculado — só um "Ampliar identificação" explícito1329 // (ver set_identity_scope()) libera isso.1330 997 if ( $pid && 'supplier_only' === get_post_meta( $pid, self::META_IDENTITY_SCOPE, true ) ) { 1331 998 $same_supplier = $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 1332 999 $wpdb->prepare( 1333 "SELECT wc_product_id FROM {$items_table} WHERE gtin = %s AND supplier_cnpj = %s AND wc_product_id > 0 LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName1000 "SELECT wc_product_id FROM {$items_table} WHERE gtin = %s AND supplier_cnpj = %s AND wc_product_id > 0 LIMIT 1", 1334 1001 $gtin, 1335 1002 (string) ( $item['supplier_cnpj'] ?? '' ) … … 1347 1014 $pid = $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 1348 1015 $wpdb->prepare( 1349 "SELECT wc_product_id FROM {$items_table} WHERE supplier_cnpj = %s AND product_code = %s AND wc_product_id > 0 LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName1016 "SELECT wc_product_id FROM {$items_table} WHERE supplier_cnpj = %s AND product_code = %s AND wc_product_id > 0 LIMIT 1", 1350 1017 $item['supplier_cnpj'], 1351 1018 $item['product_code'] … … 1355 1022 } 1356 1023 1357 /**1358 * Grava a decisão do usuário (revisão pós-import) sobre um1359 * produto que ganhou GTIN novo: 'expand' remove a restrição (GTIN1360 * passa a valer entre qualquer fornecedor, comportamento padrão —1361 * na prática só apaga o postmeta), 'restrict' marca `supplier_only`1362 * (nunca cruza fornecedor sozinho a partir de agora).1363 *1364 * @param int $product_id1365 * @param string $decision 'expand'|'restrict'.1366 * @return void1367 */1368 public static function set_identity_scope( $product_id, $decision ) {1369 if ( 'restrict' === $decision ) {1370 update_post_meta( $product_id, self::META_IDENTITY_SCOPE, 'supplier_only' );1371 return;1372 }1373 delete_post_meta( $product_id, self::META_IDENTITY_SCOPE );1374 }1375 1376 /**1377 * Propaga `wc_product_id` pra TODA linha que compartilhe a mesma1378 * identidade do item vinculado — não só a linha que disparou a1379 * ação. Mesmo escopo de resolve_linked_product_id(): GTIN cruza1380 * fornecedor (a menos que o produto esteja marcado `supplier_only`),1381 * fornecedor+código nunca cruza.1382 *1383 * @param array $item Linha de sbnfebr_note_items JÁ vinculada (gtin, supplier_cnpj, product_code).1384 * @param int $product_id Produto a propagar pra toda a família.1385 * @return void1386 */1387 1024 public static function propagate_link( array $item, $product_id ) { 1388 1025 global $wpdb; … … 1416 1053 } 1417 1054 1418 /**1419 * Limpa `wc_product_id` de toda linha que apontava pro produto —1420 * chamado quando o produto é excluído/apagado, e também pelo1421 * "Unlink": como propagate_link() garante que1422 * toda a família aponta pro MESMO produto, limpar por `wc_product_id`1423 * já É a propagação reversa correta — não precisa recalcular1424 * identidade de novo pra desvincular.1425 *1426 * @param int $product_id ID do produto WooCommerce removido/desvinculado.1427 * @return void1428 */1429 1055 public static function clear_product_link( $product_id ) { 1430 1056 global $wpdb; … … 1440 1066 } 1441 1067 1442 /**1443 * Re-vincula toda linha que apontava pro post_id antigo pro post_id1444 * novo — mesma ideia de clear_product_link() (atualiza por1445 * `wc_product_id`, sem precisar recalcular identidade), só que troca1446 * em vez de zerar. Update direto, sem passar por link_existing()/1447 * enforce_single_link(): não é um vínculo NOVO sendo criado, é o1448 * MESMO vínculo seguindo o produto que teve o post_id recriado (ex:1449 * conversão simples→variável na Sheet) — os dados de identidade já1450 * migraram junto no produto, só a referência aqui precisa acompanhar.1451 *1452 * @param int $old_product_id ID do post que deixou de representar o item.1453 * @param int $new_product_id ID do post novo que passou a representá-lo.1454 * @return void1455 */1456 1068 public static function move_product_link( $old_product_id, $new_product_id ) { 1457 1069 global $wpdb; … … 1468 1080 } 1469 1081 1470 /**1471 * "Deslinkar" — desfaz o vínculo de toda a família (não só a linha1472 * clicada, mantendo consistência com "GTIN é 1 produto só"). Não1473 * mexe no produto WooCommerce em si, só nos vínculos.1474 *1475 * @param int $item_id ID da linha em sbnfebr_note_items.1476 * @return bool True se a linha existia e tinha vínculo pra desfazer.1477 */1478 1082 public static function unlink_item( $item_id ) { 1479 1083 $item = self::get_item( $item_id ); … … 1485 1089 } 1486 1090 1487 /**1488 * Price history of a product within one supplier — every occurrence1489 * of `product_code` in that `supplier_cnpj`'s notes, ordered by date.1490 *1491 * @param string $supplier_cnpj Supplier CNPJ.1492 * @param string $product_code Supplier's product code (`cProd` field in the note).1493 * @return array[]1494 */1495 1091 public static function get_price_history( $supplier_cnpj, $product_code ) { 1496 1092 global $wpdb; … … 1505 1101 INNER JOIN {$notes_table} n ON n.id = i.note_id 1506 1102 WHERE i.supplier_cnpj = %s AND i.product_code = %s 1507 ORDER BY n.emission_date ASC", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName1103 ORDER BY n.emission_date ASC", 1508 1104 $supplier_cnpj, 1509 1105 $product_code … … 1513 1109 } 1514 1110 1515 /**1516 * Ocorrências do mesmo GTIN em fornecedores DIFERENTES do informado —1517 * alimenta a seção "Também comprado de outros fornecedores" do modal1518 * de histórico, só quando o ícone está no estado vermelho (GTIN visto1519 * em mais de 1 fornecedor). GTIN vazio/"SEM GTIN" nunca cruza (não é1520 * identificador confiável).1521 *1522 * @param string $gtin GTIN do item.1523 * @param string $exclude_supplier_cnpj CNPJ do fornecedor atual (não entra no resultado).1524 * @return array[]1525 */1526 1111 public static function get_cross_supplier_history( $gtin, $exclude_supplier_cnpj ) { 1527 1112 $gtin = trim( (string) $gtin ); … … 1541 1126 INNER JOIN {$notes_table} n ON n.id = i.note_id 1542 1127 WHERE i.gtin = %s AND i.supplier_cnpj <> %s 1543 ORDER BY n.emission_date ASC", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName1128 ORDER BY n.emission_date ASC", 1544 1129 $gtin, 1545 1130 $exclude_supplier_cnpj … … 1549 1134 } 1550 1135 1551 /** 1552 * Revisão pós-import: pra cada item recém importado, checa se a 1553 * identidade dele (GTIN, ou fornecedor+código) já resolve pra um 1554 * produto — se sim, monta o diff (custo, NCM, estoque) pro card de 1555 * revisão; se a identidade só resolveu por fornecedor+código mas o 1556 * item trouxe GTIN e o produto ainda não tinha nenhum gravado, marca 1557 * como "upgradable" (a decisão de ampliar o reconhecimento pra 1558 * qualquer fornecedor fica pro usuário, nunca automática). 1559 * 1560 * @param int $note_id ID da nota recém-importada. 1561 * @return array{changed:array[],upgradable:array[],new_count:int,unchanged_count:int} 1562 */ 1563 public static function get_post_import_review( $note_id ) { 1564 global $wpdb; 1565 $items_table = self::items_table(); 1566 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- nome de tabela fixo ($wpdb->prefix . 'sbnfebr_note_items'), sem input de usuário. 1567 $items = $wpdb->get_results( 1568 $wpdb->prepare( "SELECT * FROM {$items_table} WHERE note_id = %d", (int) $note_id ), 1569 ARRAY_A 1570 ); 1571 1572 $changed = array(); 1573 $upgradable = array(); 1574 $new_count = 0; 1575 $unchanged_count = 0; 1576 1577 foreach ( $items as $item ) { 1578 $product_id = self::resolve_linked_product_id( $item ); 1579 if ( ! $product_id ) { 1580 ++$new_count; 1581 continue; 1582 } 1583 1584 $snap = class_exists( 'SBNFEBR_Match_Service' ) 1585 ? SBNFEBR_Match_Service::get_snapshot( $product_id, (int) $item['id'] ) 1586 : array(); 1587 1588 $gtin = trim( (string) $item['gtin'] ); 1589 $has_gtin = '' !== $gtin && 'SEM GTIN' !== strtoupper( $gtin ); 1590 $product_gtin = isset( $snap['gtin'] ) ? trim( (string) $snap['gtin'] ) : ''; 1591 1592 $diffs = array(); 1593 $cost_known = isset( $snap['sale_type'] ) && 'unit' === $snap['sale_type'] && null !== $snap['cost_paid']; 1594 $cost_changed = $cost_known && abs( (float) $snap['cost_paid'] - (float) $item['unit_value'] ) > 0.001; 1595 if ( $cost_changed ) { 1596 $diffs[] = array( 'key' => 'cost', 'current' => $snap['cost_paid'], 'incoming' => (float) $item['unit_value'] ); 1597 } 1598 $ncm_changed = ! empty( $item['ncm'] ) && ! empty( $snap['ncm'] ) && (string) $snap['ncm'] !== (string) $item['ncm']; 1599 if ( $ncm_changed ) { 1600 $diffs[] = array( 'key' => 'ncm', 'current' => $snap['ncm'], 'incoming' => $item['ncm'] ); 1601 } 1602 1603 // Identidade resolveu (por fornecedor+código, já que se 1604 // tivesse resolvido por GTIN o produto JÁ teria esse GTIN 1605 // gravado) mas o item trouxe GTIN e o produto ainda não tem 1606 // nenhum — é o momento exato do "ganhou GTIN agora". 1607 $is_upgrade = $has_gtin && '' === $product_gtin; 1608 if ( $is_upgrade ) { 1609 $upgradable[] = array( 1610 'item_id' => (int) $item['id'], 1611 'product_id' => $product_id, 1612 'gtin' => $gtin, 1613 'name' => $item['description'], 1614 'product_code' => $item['product_code'], 1615 'supplier_name' => isset( $item['supplier_cnpj'] ) ? self::get_supplier_name_cached( $item['supplier_cnpj'] ) : '', 1616 ); 1617 } 1618 1619 if ( $diffs || ( (float) $item['quantity'] > 0 ) ) { 1620 $changed[] = array( 1621 'item_id' => (int) $item['id'], 1622 'product_id' => $product_id, 1623 'name' => $item['description'], 1624 'product_code' => $item['product_code'], 1625 'diffs' => $diffs, 1626 'stock_current' => $snap['stock'] ?? null, 1627 'stock_incoming' => (float) $item['quantity'], 1628 ); 1629 } else { 1630 ++$unchanged_count; 1631 } 1632 } 1633 1634 return array( 1635 'changed' => $changed, 1636 'upgradable' => $upgradable, 1637 'new_count' => $new_count, 1638 'unchanged_count' => $unchanged_count, 1639 ); 1640 } 1641 1642 /** 1643 * Nome do fornecedor pra exibir no card de upgrade — evita 1 query 1644 * por item repetindo o mesmo fornecedor (nota inteira é sempre do 1645 * mesmo fornecedor, mas o item já tem o CNPJ, não o nome). 1646 * 1647 * @param string $supplier_cnpj 1648 * @return string 1649 */ 1650 protected static function get_supplier_name_cached( $supplier_cnpj ) { 1651 static $cache = array(); 1652 if ( isset( $cache[ $supplier_cnpj ] ) ) { 1653 return $cache[ $supplier_cnpj ]; 1654 } 1655 global $wpdb; 1656 $notes_table = self::notes_table(); 1657 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- nome de tabela fixo ($wpdb->prefix . 'sbnfebr_notes'), sem input de usuário. 1658 $name = $wpdb->get_var( 1659 $wpdb->prepare( "SELECT supplier_name FROM {$notes_table} WHERE supplier_cnpj = %s ORDER BY id DESC LIMIT 1", $supplier_cnpj ) 1660 ); 1661 $cache[ $supplier_cnpj ] = (string) $name; 1662 return $cache[ $supplier_cnpj ]; 1663 } 1664 1665 /** 1666 * Família completa de um GTIN — toda ocorrência em qualquer nota, de 1667 * qualquer fornecedor, com o `id` da linha (diferente de 1668 * get_cross_supplier_history(), que é só pra EXIBIR no popup de 1669 * histórico e não devolve id nenhum). É essa lista que alimenta o 1670 * seletor de fonte do modal de ação — trocar a fonte precisa saber 1671 * qual `item_id` virar o alvo de Make Draft/Link/Sync. 1672 * 1673 * @param string $gtin GTIN do item. 1674 * @param int $exclude_item_id Item atualmente aberto no modal (não entra no resultado). 1675 * @return array[] { id, note_number, series, emission_date, supplier_cnpj, supplier_name, 1676 * quantity, unit_value, ncm, cst_csosn, product_code, description, unit, 1677 * wc_product_id } — os últimos 4 permitem ao front reabrir o modal de ação 1678 * já mirado nesse item, tratando-o como se tivesse sido o clicado 1679 * (mesma lógica de hasProduct/hasMatch, ver nfebr-item-actions.js). 1680 */ 1681 public static function get_gtin_family( $gtin, $exclude_item_id ) { 1136 public static function get_gtin_family( $gtin, $exclude_item_id, $supplier_cnpj = '', $product_code = '' ) { 1682 1137 $gtin = trim( (string) $gtin ); 1683 if ( '' === $gtin || 'SEM GTIN' === strtoupper( $gtin ) ) { 1138 $has_gtin = '' !== $gtin && 'SEM GTIN' !== strtoupper( $gtin ); 1139 if ( ! $has_gtin && ( '' === trim( (string) $supplier_cnpj ) || '' === trim( (string) $product_code ) ) ) { 1684 1140 return array(); 1685 1141 } … … 1688 1144 $items_table = self::items_table(); 1689 1145 $notes_table = self::notes_table(); 1146 1147 $where = $has_gtin ? 'i.gtin = %s' : 'i.supplier_cnpj = %s AND i.product_code = %s'; 1148 $params = $has_gtin ? array( $gtin ) : array( $supplier_cnpj, $product_code ); 1149 $params[] = (int) $exclude_item_id; 1690 1150 1691 1151 return $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared … … 1696 1156 FROM {$items_table} i 1697 1157 INNER JOIN {$notes_table} n ON n.id = i.note_id 1698 WHERE i.gtin = %s AND i.id <> %d 1699 ORDER BY n.emission_date DESC", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName 1700 $gtin, 1701 (int) $exclude_item_id 1158 WHERE {$where} AND i.id <> %d 1159 ORDER BY n.emission_date DESC", 1160 $params 1702 1161 ), 1703 1162 ARRAY_A … … 1705 1164 } 1706 1165 1707 /**1708 * Retorna o retrato mais recente (nota mais nova) dos dados do1709 * emitente pra um CNPJ — usado pra pré-preencher o cadastro de1710 * fornecedor (ícone "!" na toolbar) com nome/IE/telefone/endereço1711 * já capturados de alguma nota importada, sem o usuário digitar1712 * de novo o que a NF-e já trouxe.1713 *1714 * @param string $supplier_cnpj CNPJ do fornecedor.1715 * @return array|null Campos no formato do formulário de fornecedor, ou null se não achou nota nenhuma.1716 */1717 1166 public static function get_supplier_snapshot( $supplier_cnpj ) { 1718 1167 global $wpdb; … … 1725 1174 supplier_district, supplier_city, supplier_state 1726 1175 FROM {$notes_table} WHERE supplier_cnpj = %s 1727 ORDER BY emission_date DESC LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName1176 ORDER BY emission_date DESC LIMIT 1", 1728 1177 $supplier_cnpj 1729 1178 ), … … 1750 1199 } 1751 1200 1752 /**1753 * Lista fornecedores distintos já importados (pro seletor da toolbar).1754 *1755 * @return array[] Cada item: cnpj, name.1756 */1757 1201 public static function get_suppliers() { 1758 1202 global $wpdb; … … 1767 1211 ); 1768 1212 1769 // Apelido: troca o nome exibido no seletor de fornecedor pelo1770 1213 // apelido, quando o fornecedor tem 1771 // "Exibir apelido" marcado. Reordena depois (a ordenação do SQL1772 // usou o nome legal, apelido pode bagunçar a ordem alfabética).1773 1214 $nicknames = SBNFEBR_Supplier_Service::get_nickname_map(); 1774 1215 if ( $nicknames ) { … … 1787 1228 } 1788 1229 1789 /**1790 * Note/item counts per supplier CNPJ — used by the Suppliers Library1791 * to distinguish "has an active note" from "registered but no note1792 * currently linked" (only counts what exists now; a deleted note1793 * drops out on its own, no extra bookkeeping needed).1794 *1795 * @return array Map cnpj => { note_count, item_count }.1796 */1797 1230 public static function get_supplier_note_stats() { 1798 1231 global $wpdb; … … 1818 1251 } 1819 1252 1820 /**1821 * Lista notas, opcionalmente filtradas por fornecedor (pro seletor1822 * de nota da toolbar, nível 2 da navegação, e pro Gerenciador de1823 * Notas). `items_count` e `total_value` vêm junto pra alimentar a1824 * listagem do gerenciador sem precisar de outra requisição por nota.1825 *1826 * @param string $supplier_cnpj CNPJ do fornecedor (opcional).1827 * @return array[]1828 */1829 1253 public static function get_notes( $supplier_cnpj = '' ) { 1830 1254 global $wpdb; … … 1843 1267 $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 1844 1268 1845 // totals_json vira total_value solto (só o que a listagem precisa),1846 // não expõe o JSON inteiro pra quem só quer mostrar 1 número.1847 1269 foreach ( $rows as &$row ) { 1848 1270 $totals = json_decode( (string) $row['totals_json'], true ); … … 1855 1277 } 1856 1278 1857 /**1858 * Detalhe completo de 1 nota — dados que só existem no XML e nunca1859 * aparecem na tela normal (frete,1860 * base de cálculo, duplicatas, transporte). Nada novo é parseado1861 * nem gravado — `totals_json`/`duplicates_json`/`transport_json` já1862 * vêm completos desde o import (ver parse_header() no XML parser),1863 * só nunca tinham sido devolvidos pro cliente.1864 *1865 * @param int $note_id1866 * @return array|null1867 */1868 1279 public static function get_note_detail( $note_id ) { 1869 1280 global $wpdb; … … 1871 1282 1872 1283 $row = $wpdb->get_row( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared 1873 $wpdb->prepare( "SELECT * FROM {$notes_table} WHERE id = %d", (int) $note_id ), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName1284 $wpdb->prepare( "SELECT * FROM {$notes_table} WHERE id = %d", (int) $note_id ), 1874 1285 ARRAY_A 1875 1286 ); -
sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-supplier-service.php
r3725460 r3782421 1 1 <?php 2 /**3 * Fornecedor (supplier) — integração com a taxonomia `sbs_supplier` da4 * SanBar EXPress Sheet (mesmo namespace de dado, mesmas chaves de term5 * meta). Registrada por QUALQUER um dos dois plugins que carregar6 * primeiro — a taxonomia e o term meta vivem nas tabelas nativas do7 * WordPress (`wp_terms`/`wp_term_taxonomy`/`wp_termmeta`), não8 * pertencem a nenhum plugin específico.9 *10 * Se a Sheet já registrou `sbs_supplier` nesta request, o SBNFEBR NÃO11 * registra de novo (evita duas declarações concorrentes) — só usa. Se12 * a Sheet não estiver ativa, o SBNFEBR registra a própria cópia (mesmo13 * slug, mesmos argumentos), pra funcionar 100% standalone. Nos dois14 * casos, os dados gravados são os mesmos — se a Sheet for instalada15 * depois, os fornecedores já cadastrados aparecem na Biblioteca dela16 * automaticamente.17 *18 * @package SBNFEBR19 * @since 0.3.020 */21 2 22 3 defined( 'ABSPATH' ) || exit; … … 26 7 const TAXONOMY = 'sbs_supplier'; 27 8 28 /* Meta keys match the SanBar EXPress Sheet plugin's, for shared supplier data. */29 9 const META_DOCUMENT = 'sbs_supplier_document'; 30 10 const META_CODE = 'sbs_supplier_code'; … … 42 22 const META_STATE = 'sbs_supplier_state'; 43 23 const META_NOTES = 'sbs_supplier_notes'; 44 // Apelido: nome de exibição alternativo ao nome legal da nota.45 // use_nickname ('1'/'') controla se telas que mostram supplier_name46 // (seletor, rodapé, grid) devem exibir o apelido no lugar.47 24 const META_NICKNAME = 'sbs_supplier_nickname'; 48 25 const META_USE_NICKNAME = 'sbs_supplier_use_nickname'; 49 26 50 /** Contador do código interno auto-gerado (SB-0001...) — mesma option da Sheet, contador compartilhado. */51 27 const OPTION_NEXT_CODE = 'sbs_supplier_next_code'; 52 28 … … 60 36 } 61 37 62 /**63 * Registra a taxonomia + term meta SÓ se ainda não existir (a Sheet,64 * se ativa, já fez isso antes — `init` roda em ordem de carregamento65 * dos plugins, mas o SBNFEBR usa prioridade 5 pra dar chance de a66 * Sheet (prioridade padrão 10) ainda não ter rodado; por isso o67 * `taxonomy_exists()` é a fonte de verdade, não a ordem).68 *69 * Na prática: se os dois plugins estiverem ativos, o primeiro a70 * rodar "vence" o registro — inofensivo, os argumentos são71 * idênticos nos dois lados.72 *73 * @return void74 */75 38 public static function maybe_register_taxonomy() { 76 39 if ( taxonomy_exists( self::TAXONOMY ) ) { … … 99 62 'show_in_menu' => true, 100 63 'show_admin_column' => false, 101 // Mesmo motivo da Sheet: endpoint genérico do WP não passa102 // pela validação própria (dígito verificador, duplicidade).103 64 'show_in_rest' => false, 104 65 'capabilities' => array( … … 125 86 } 126 87 127 /**128 * Lista de todas as meta keys de fornecedor.129 *130 * @return string[]131 */132 88 public static function meta_keys() { 133 89 return array( … … 152 108 } 153 109 154 /* ===========================================================155 * LEITURA156 * ========================================================= */157 158 /**159 * Lista/busca fornecedores (termos da taxonomia), no formato que o160 * modal da Biblioteca consome.161 *162 * @param string $search Termo de busca (nome, documento ou código).163 * @return array[]164 */165 110 public static function list_suppliers( $search = '' ) { 166 111 $terms = get_terms( … … 180 125 $out = array(); 181 126 182 // Note/item counts, keyed by normalized CNPJ — lets the Suppliers183 // Library tell apart "has a note right now" from "registered but184 // no note currently linked" (see get_supplier_note_stats()).185 127 $note_stats = class_exists( 'SBNFEBR_Notes_Service' ) ? SBNFEBR_Notes_Service::get_supplier_note_stats() : array(); 186 128 … … 206 148 } 207 149 208 /**209 * Monta a linha de retorno de 1 fornecedor a partir do termo.210 *211 * @param WP_Term $term Termo da taxonomia.212 * @return array213 */214 150 protected static function term_to_row( $term ) { 215 151 $document = get_term_meta( $term->term_id, self::META_DOCUMENT, true ); … … 220 156 'id' => $term->term_id, 221 157 'name' => $term->name, 222 // display_name: o que telas fora do cadastro (seletor, rodapé,223 // grid) devem mostrar — resolvido aqui pra centralizar a224 158 // lógica "usa apelido só se marcado E preenchido". 225 159 'display_name' => ( $use_nickname && '' !== $nickname ) ? $nickname : $term->name, … … 246 180 } 247 181 248 /**249 * Mapa `documento (só dígitos) => apelido`, só dos fornecedores com250 * "Exibir apelido" marcado e apelido preenchido — usado por quem exibe251 * fornecedor fora do cadastro (seletor da toolbar, grid principal)252 * pra decidir nome legal vs apelido sem repetir leitura de term meta253 * por linha.254 *255 * @return array<string,string> documento => apelido.256 */257 182 public static function get_nickname_map() { 258 183 global $wpdb; 259 184 260 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching261 185 $rows = $wpdb->get_results( 262 186 $wpdb->prepare( … … 282 206 } 283 207 284 /**285 * Busca o fornecedor cujo documento (CNPJ) bate com o informado —286 * usado pelo import de NF-e pra achar/criar sem duplicar.287 *288 * @param string $document CNPJ (com ou sem pontuação).289 * @return int Term ID, ou 0 se não achou.290 */291 208 public static function find_by_document( $document ) { 292 209 $digits = preg_replace( '/\D/', '', (string) $document ); … … 297 214 } 298 215 299 /* ===========================================================300 * ESCRITA301 * ========================================================= */302 303 /**304 * Cria um fornecedor novo.305 *306 * @param array $fields { name, document, code, ie, phone, email, site, contact, cep, street, number, complement, district, city, state, notes }.307 * @return array|WP_Error Linha do fornecedor criado, ou erro.308 */309 216 public static function create( array $fields ) { 310 217 $name = trim( (string) ( $fields['name'] ?? '' ) ); … … 330 237 } 331 238 332 /**333 * Atualiza um fornecedor existente.334 *335 * @param int $term_id Termo a editar.336 * @param array $fields Mesmos campos de create().337 * @return array|WP_Error338 */339 239 public static function update( $term_id, array $fields ) { 340 240 $term_id = (int) $term_id; … … 360 260 } 361 261 362 /**363 * Remove um fornecedor.364 *365 * @param int $term_id Termo a remover.366 * @return bool|WP_Error367 */368 262 public static function delete( $term_id ) { 369 263 return wp_delete_term( (int) $term_id, self::TAXONOMY ); 370 264 } 371 265 372 /**373 * Salva os campos extras (term meta) de um fornecedor. Chaves374 * ausentes/null não tocam no meta (payload parcial não apaga dado).375 *376 * @param int $term_id Termo.377 * @param array $fields Ver create().378 * @return WP_Error|null Erro do primeiro campo que falhar (documento/código), ou null.379 */380 266 public static function save_fields( $term_id, array $fields ) { 381 267 $first_error = null; … … 420 306 } 421 307 } 422 // use_nickname é booleano, não string livre: grava '1' só quando423 308 // truthy, senão apaga. 424 309 if ( array_key_exists( 'use_nickname', $fields ) && null !== $fields['use_nickname'] ) { … … 441 326 } 442 327 443 /**444 * Salva o documento (CNPJ/CPF) com validação de dígito verificador445 * e checagem de duplicidade. Vazio = permitido (limpa o campo).446 *447 * Escopo Brasil-only (conceito do plugin) — só CNPJ/CPF, diferente448 * da Sheet (multi-país). Documento fora desses dois formatos ainda449 * é aceito como texto livre (ex: fornecedor internacional), só não450 * valida dígito.451 *452 * @param int $term_id453 * @param string $document454 * @return WP_Error|null455 */456 328 public static function save_document( $term_id, $document ) { 457 329 $document = trim( (string) $document ); … … 487 359 'sbnfebr_supplier_document_duplicate', 488 360 sprintf( 489 /* translators: 1: val or do documento, 2: nome do fornecedor. */361 /* translators: 1: value, 2: supplier. */ 490 362 __( 'O CNPJ/CPF "%1$s" já pertence ao fornecedor "%2$s".', 'sanbar-express-nfe-xml-import-br' ), 491 363 self::format_document_for_display( $stored ), … … 500 372 } 501 373 502 /**503 * Formata CNPJ/CPF pra exibição. Outros formatos voltam sem alteração.504 *505 * @param string $value Documento cru (só dígitos, se CNPJ/CPF).506 * @return string507 */508 374 public static function format_document_for_display( $value ) { 509 375 $value = (string) $value; … … 521 387 } 522 388 523 /**524 * Salva o código interno. Vazio = gera sequencial (SB-0001...).525 *526 * @param int $term_id527 * @param string $code528 * @return WP_Error|null529 */530 389 public static function save_code( $term_id, $code ) { 531 390 $code = trim( (string) $code ); … … 555 414 } 556 415 557 /**558 * Gera o próximo código sequencial (SB-0001...) — contador559 * compartilhado com a Sheet (mesma option), pra nunca colidir560 * mesmo cadastrando fornecedor pelos dois lados.561 *562 * @return string563 */564 416 public static function generate_internal_code() { 565 417 for ( $attempt = 0; $attempt < 10; $attempt++ ) { … … 575 427 } 576 428 577 /**578 * Dono de um valor num meta_key qualquer (documento ou código),579 * pra checagem de unicidade.580 *581 * @param string $meta_key582 * @param string $value583 * @param int $exclude_term_id Termo a ignorar (o próprio, ao editar).584 * @return int Term ID dono, ou 0.585 */586 429 protected static function find_meta_owner( $meta_key, $value, $exclude_term_id = 0 ) { 587 430 if ( '' === (string) $value ) { … … 590 433 global $wpdb; 591 434 592 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching593 435 $row = $wpdb->get_var( 594 436 $wpdb->prepare( … … 607 449 } 608 450 609 /* ===========================================================610 * VALIDADORES — algoritmos oficiais (dígito verificador)611 * ========================================================= */612 613 /**614 * Valida dígito verificador de CPF.615 *616 * @param string $value 11 dígitos.617 * @return bool618 */619 451 public static function validate_cpf( $value ) { 620 452 $d = preg_replace( '/\D/', '', (string) $value ); … … 641 473 } 642 474 643 /**644 * Valida dígito verificador de CNPJ.645 *646 * @param string $value 14 dígitos.647 * @return bool648 */649 475 public static function validate_cnpj( $value ) { 650 476 $d = preg_replace( '/\D/', '', (string) $value ); -
sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-xml-parser-service.php
r3725460 r3782421 1 1 <?php 2 /**3 * Parser de XML de NF-e (modelo 55, layout 4.00) — extrai cabeçalho e4 * itens pros campos mapeados a partir do DANFE.5 *6 * Não valida contra o XSD oficial da SEFAZ — assume XML já autorizado7 * (nfeProc) ou só o nó NFe isolado, e é tolerante a campos ausentes8 * (nem toda NF-e tem CEST, ICMS-ST, FCP etc.).9 *10 * @package SBNFEBR11 * @since 0.2.012 */13 2 14 3 defined( 'ABSPATH' ) || exit; … … 16 5 class SBNFEBR_Xml_Parser_Service { 17 6 18 /**19 * Teto de segurança contra XML fora do padrão/malicioso, evitando gastar20 * memória processando milhares de <det>. Distinto do aviso de 100+ itens21 * no preview (ver SBNFEBR_Import_Controller::WARN_ITEMS_THRESHOLD).22 */23 7 const MAX_ITEMS = 1000; 24 8 25 /**26 * Faz o parse de uma string XML de NF-e.27 *28 * @param string $xml_string Conteúdo bruto do arquivo .xml.29 * @return array|WP_Error {30 * @type array header Dados de cabeçalho da nota.31 * @type array items Lista de itens (uma entrada por <det>).32 * @type string raw_xml XML original, preservado pra auditoria.33 * }34 */35 9 public static function parse( $xml_string ) { 36 10 $xml_string = (string) $xml_string; 37 11 38 // XXE hardening: a legitimate NF-e never has DOCTYPE/ENTITY — reject39 // before attempting to load, don't rely solely on libxml flags.40 12 if ( preg_match( '/<!DOCTYPE|<!ENTITY/i', $xml_string ) ) { 41 13 return new WP_Error( 'sbnfebr_xml_insecure', __( 'Este arquivo XML contém uma declaração DOCTYPE/ENTITY e foi rejeitado por motivo de segurança.', 'sanbar-express-nfe-xml-import-br' ) ); 42 14 } 43 15 44 // NF-e XML uses a single default namespace throughout — stripping the45 // xmlns declarations simplifies SimpleXML access without registering46 16 // or prefixing the namespace on every call. 47 17 $clean = preg_replace( '/xmlns(:\w+)?="[^"]*"/', '', $xml_string ); 48 18 49 19 libxml_use_internal_errors( true ); 50 // LIBXML_NONET: never resolves an external (network) reference during51 // parsing, even if an entity slips past the filter above.52 20 $sx = simplexml_load_string( $clean, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NONET ); 53 21 libxml_clear_errors(); … … 64 32 $header = self::parse_header( $inf_nfe ); 65 33 66 // Authorization protocol (<protNFe><infProt>) only exists when the67 // XML is the full "processo" (<nfeProc>), not a bare <NFe> node —68 // empty fields in that case are expected, not an error.69 34 $prot = isset( $sx->protNFe->infProt ) ? $sx->protNFe->infProt : null; 70 35 $header['protocol_status'] = (string) self::prop( $prot, 'cStat' ); … … 73 38 $header['protocol_date'] = self::datetime( self::prop( $prot, 'dhRecbto' ) ); 74 39 75 // Model 55 (NF-e) only. Model 65 (NFC-e) and others share a similar76 // layout but are not the document this plugin handles.77 40 if ( '55' !== $header['model'] ) { 78 41 return new WP_Error( 'sbnfebr_xml_wrong_model', __( 'Este XML não é uma NF-e modelo 55 (este importador só aceita NF-e de compra).', 'sanbar-express-nfe-xml-import-br' ) ); 79 42 } 80 43 81 // Access key is the note's permanent identity (UNIQUE KEY in the82 // database) — reject before attempting to store it.83 44 if ( ! preg_match( '/^\d{44}$/', $header['access_key'] ) ) { 84 45 return new WP_Error( 'sbnfebr_xml_bad_access_key', __( 'Este XML tem uma chave de acesso inválida (precisa ter 44 dígitos).', 'sanbar-express-nfe-xml-import-br' ) ); … … 115 76 } 116 77 117 /**118 * Extrai o cabeçalho: identificação, emitente, destinatário, totais,119 * duplicatas e transporte.120 *121 * @param SimpleXMLElement $inf_nfe Nó <infNFe>.122 * @return array123 */124 78 protected static function parse_header( $inf_nfe ) { 125 79 $id_attr = (string) $inf_nfe['Id']; … … 132 86 $transp = isset( $inf_nfe->transp ) ? $inf_nfe->transp : null; 133 87 134 // $total may be null (malformed/partial NF-e) — avoid accessing a135 // property on non-object, each key falls back to null via num().136 88 $totals = array( 137 89 'icms_base' => self::num( $total ? $total->vBC : null ), … … 146 98 'products_value' => self::num( $total ? $total->vProd : null ), 147 99 'note_value' => self::num( $total ? $total->vNF : null ), 148 // vTotTrib: approximate total tax burden (Lei 12.741/2012 /149 // "Lei da Transparência"). Informational only, not a separately150 100 // charged tax. 151 101 'approx_taxes' => self::num( $total ? $total->vTotTrib : null ), … … 174 124 } 175 125 176 // <pag><detPag> may repeat when payment is split across multiple177 // methods; tPag is the raw XML payment-method code, translated only178 126 // at display time (nfebr-note-info.js), not here. 179 127 $payments = array(); … … 193 141 'access_key' => $access_key, 194 142 'model' => (string) $ide->mod, 195 // tpNF: 0=Entrada, 1=Saída — standardized XML field, more196 // reliable than natOp (free text typed by the issuer). Outbound197 // notes are not blocked automatically, only flagged in the198 143 // preview; the decision is left to the user. 199 144 'nfe_type' => (string) $ide->tpNF, 200 // finNFe: 1=Normal, 2=Complementar, 3=Ajuste, 4=Devolução/Retorno.201 // Shown in the note's info modal (nfebr-note-info.js), does not202 145 // block import. 203 146 'nfe_purpose' => (string) self::prop( $ide, 'finNFe' ), … … 207 150 'emission_date' => self::datetime( $ide->dhEmi ?? null ), 208 151 'exit_entry_date' => self::datetime( $ide->dhSaiEnt ?? null ), 209 // NF-e XSD already guarantees <CNPJ> is digits-only — this is a210 // defensive second pass against malformed/tampered XML.211 152 'supplier_cnpj' => preg_replace( '/\D/', '', (string) $emit->CNPJ ), 212 153 'supplier_name' => (string) $emit->xNome, 213 154 'supplier_fantasy' => (string) ( $emit->xFant ?? '' ), 214 155 'supplier_ie' => (string) ( $emit->IE ?? '' ), 215 // CRT (Código de Regime Tributário): 1/2 = Simples Nacional216 // (product uses CSOSN), 3 = Regime Normal (product uses CST) —217 // used when creating a draft to pick the item's tax code table.218 156 'supplier_crt' => (string) ( $emit->CRT ?? '' ), 219 // <fone> lives inside <enderEmit>, not directly under <emit>.220 157 'supplier_phone' => (string) self::prop( $ender_emit, 'fone' ), 221 // Supplier address, used to prefill supplier registration222 // (toolbar "!" icon) from data the note already carries.223 158 'supplier_cep' => (string) self::prop( $ender_emit, 'CEP' ), 224 159 'supplier_street' => (string) self::prop( $ender_emit, 'xLgr' ), … … 230 165 'dest_document' => preg_replace( '/\D/', '', (string) ( $dest->CNPJ ?? $dest->CPF ?? '' ) ), 231 166 'dest_name' => (string) ( $dest->xNome ?? '' ), 232 // infCpl: supplier free text (order, terms, sales rep, etc.),233 // lives under <infAdic>, not directly under <infNFe>.234 167 'additional_info' => (string) self::prop( self::prop( $inf_nfe, 'infAdic' ), 'infCpl' ), 235 168 'payments' => $payments, … … 240 173 } 241 174 242 /**243 * Extrai um item (<det>) pros campos da grid fiscal (mesma ordem de244 * colunas do DANFE) + extras num JSON à parte.245 *246 * @param SimpleXMLElement $det Nó <det>.247 * @return array248 */249 175 protected static function parse_item( $det ) { 250 176 $prod = $det->prod; 251 177 $imposto = $det->imposto; 252 178 253 // ICMS's actual child tag is dynamic (ICMS00/10/20/30/40/51/60/70/90,254 // ICMSSN101...900 for Simples Nacional) — take the first (only)255 179 // child of <ICMS>, regardless of its name. 256 180 $icms_node = null; … … 264 188 $ipi_trib = isset( $imposto->IPI->IPITrib ) ? $imposto->IPI->IPITrib : null; 265 189 266 // PIS/COFINS follow the same dynamic-child pattern as ICMS above267 // (PISAliq/PISQtde/PISNT/PISSN/PISOutr depending on CST).268 190 $pis_node = null; 269 191 if ( isset( $imposto->PIS ) ) { … … 281 203 } 282 204 283 // cclasstrib/nfci/cbenef are promoted to a direct field in the284 // fiscal_brasil group, so Make Draft can write them without285 205 // decoding extra_fiscal_json. 286 206 $ibscbs_node = self::prop( $imposto, 'IBSCBS' ); 287 207 $cclasstrib = (string) self::prop( $ibscbs_node, 'cClassTrib' ); 288 208 289 // gIBSCBS/gIBSUF/gIBSMun/gCBS are nested sub-groups, not direct290 // children of IBSCBS. II and ICMSUFDest (DIFAL) are direct children291 // of <imposto> with a fixed shape (no CST-based variation like292 209 // ICMS/PIS/COFINS). 293 210 $gibscbs_node = self::prop( $ibscbs_node, 'gIBSCBS' ); … … 297 214 $ii_node = self::prop( $imposto, 'II' ); 298 215 $difal_node = self::prop( $imposto, 'ICMSUFDest' ); 299 // IS (Imposto Seletivo): its own separate group (not nested under300 // IBSCBS), fixed shape like II/DIFAL. Applies only to specific301 // products (cigarettes, alcoholic beverages, etc.), so its absence302 216 // on most notes is expected. 303 217 $is_node = self::prop( $imposto, 'IS' ); … … 313 227 'icms_desoneracao' => self::num( self::prop( $icms_node, 'vICMSDeson' ) ), 314 228 'icms_st_desoneracao' => self::num( self::prop( $icms_node, 'vICMSSTDeson' ) ), 315 // Always use pICMSST directly — do NOT derive it from316 // vICMSST/vBCST: vICMSST is a NET value (own ICMS already317 // deducted), so the simple division yields a much lower318 229 // effective rate than the real one. 319 230 'icms_st_rate' => self::num( self::prop( $icms_node, 'pICMSST' ) ), … … 324 235 'cofins_rate' => self::num( self::prop( $cofins_node, 'pCOFINS' ) ), 325 236 'cofins_value' => self::num( self::prop( $cofins_node, 'vCOFINS' ) ), 326 // II (Imposto de Importação): the block only carries R$327 // values (vBC/vII), no ready-made rate. Unlike ICMS-ST there328 // is no credit/discount involved, so deriving the rate as329 237 // vII/vBC is mathematically correct here. 330 238 'ii_base' => self::num( self::prop( $ii_node, 'vBC' ) ), 331 239 'ii_value' => self::num( self::prop( $ii_node, 'vII' ) ), 332 // DIFAL (ICMSUFDest): pICMSUFDest comes ready in the note,333 // like pICMS/pIPI. Only present for interstate sales to a334 240 // non-contributor end consumer. 335 241 'difal_rate' => self::num( self::prop( $difal_node, 'pICMSUFDest' ) ), 336 242 'is_rate' => self::num( self::prop( $is_node, 'pIS' ) ), 337 // IBS/CBS: pIBSUF and pIBSMun are the two shares (state +338 // municipal) of the same IBS tax, summed here into a single339 // rate to match the catalog's single 'ibs' kind. CBS is340 243 // federal, kept as a separate 'cbs' kind. 341 244 'ibs_uf_rate' => self::num( self::prop( $gibsuf_node, 'pIBSUF' ) ), 342 245 'ibs_mun_rate' => self::num( self::prop( $gibsmun_node, 'pIBSMun' ) ), 343 246 'cbs_rate' => self::num( self::prop( $gcbs_node, 'pCBS' ) ), 344 // cEANTrib: GTIN of the TAXABLE unit, which can differ from345 // cEAN (commercial unit GTIN) when the sale unit differs346 // from the tax-calculation unit. 'gtin' stays as cEAN only.347 247 'gtin_taxable' => (string) self::prop( $prod, 'cEANTrib' ), 348 248 'info_adicional' => (string) self::prop( $det, 'infAdProd' ), 349 249 'ibscbs' => isset( $imposto->IBSCBS ) ? self::xml_to_array( $imposto->IBSCBS ) : null, 350 // Freight/insurance/other expenses allocated per item351 250 // (optional in the XSD, absent on most notes). 352 251 'item_freight' => self::num( self::prop( $prod, 'vFrete' ) ), 353 252 'item_insurance' => self::num( self::prop( $prod, 'vSeg' ) ), 354 253 'item_other_expenses' => self::num( self::prop( $prod, 'vOutro' ) ), 355 // rastro (lot/expiry): common for food/cosmetics/pharma, can356 // repeat (multiple lots per item). No dedicated UI yet.357 254 'rastro' => self::parse_rastro( $prod ), 358 255 ), … … 373 270 'origem' => (string) self::prop( $icms_node, 'orig' ), 374 271 'unit' => (string) $prod->uCom, 375 // Taxable unit (uTrib) can differ from the commercial one376 272 // (uCom) for regulated NCMs. 377 273 'unit_taxable' => (string) self::prop( $prod, 'uTrib' ), … … 381 277 'ind_escala' => (string) self::prop( $prod, 'indEscala' ), 382 278 'cnpj_fabricante' => (string) self::prop( $prod, 'CNPJFab' ), 383 // Columns are NOT NULL DEFAULT 0 — an explicit null breaks the384 // insert under strict MySQL mode (DEFAULT only applies to an385 // OMITTED column, not an explicit NULL). A missing XML field386 // means "not applicable", financially 0; extra_fiscal_json387 // still distinguishes "0 reported" from "field absent".388 279 'quantity' => self::num( $prod->qCom ) ?? 0, 389 280 'unit_value' => self::num( $prod->vUnCom ) ?? 0, … … 401 292 } 402 293 403 /**404 * Lê os blocos <rastro> de um item — lote, quantidade, fabricação,405 * validade. Pode se repetir (mais de 1 lote no mesmo item); retorna406 * array vazio (nunca null) quando ausente.407 *408 * @param SimpleXMLElement $prod Nó <prod>.409 * @return array410 */411 294 protected static function parse_rastro( $prod ) { 412 295 if ( ! isset( $prod->rastro ) ) { … … 425 308 } 426 309 427 /**428 * Valida o dígito verificador (44º dígito) da chave de acesso —429 * módulo 11 sobre os 43 dígitos anteriores, pesos 2-9 ciclados da430 * direita pra esquerda (mesmo algoritmo do DV de CNPJ/CPF, só que431 * sobre a chave inteira). Pega XML corrompido/adulterado que por432 * acaso ainda bateria no formato de 44 dígitos.433 *434 * @param string $access_key 44 dígitos.435 * @return bool436 */437 310 protected static function access_key_dv_valid( $access_key ) { 438 311 $digits = str_split( substr( $access_key, 0, 43 ) ); … … 455 328 } 456 329 457 /**458 * Leitura null-safe de propriedade de um SimpleXMLElement que pode459 * ser o próprio `null` (não um SimpleXMLElement "vazio") — evita460 * "Attempt to read property on null" quando o nó pai (ex: ICMS,461 * IPITrib) simplesmente não existe no item.462 *463 * @param SimpleXMLElement|null $node Nó pai, possivelmente null.464 * @param string $name Nome da propriedade filha.465 * @return SimpleXMLElement|null466 */467 330 protected static function prop( $node, $name ) { 468 331 return null === $node ? null : $node->{$name}; 469 332 } 470 333 471 /**472 * Converte um valor numérico de XML (string) em float, tolerando nó ausente.473 *474 * @param SimpleXMLElement|null $node Nó com valor numérico.475 * @return float|null476 */477 334 protected static function num( $node ) { 478 335 if ( null === $node ) { … … 483 340 } 484 341 485 /**486 * Converte um nó SimpleXML numa datetime MySQL, tolerando nó ausente.487 * O XML da NF-e traz ISO 8601 com offset (ex: 2026-08-14T14:33:24-03:00).488 *489 * Keeps the LITERAL time from the string (as printed on the DANFE)490 * instead of interpreting the offset — converting via strtotime()+491 * gmdate() would shift to UTC, possibly changing the displayed DAY492 * near midnight. Matching what the user sees on the note matters493 * more here than representing an absolute instant.494 *495 * @param SimpleXMLElement|null $node Nó de data/hora.496 * @return string|null Formato 'Y-m-d H:i:s' ou null.497 */498 342 protected static function datetime( $node ) { 499 343 if ( null === $node ) { … … 507 351 return $matches[1] . ' ' . $matches[2]; 508 352 } 509 // Fallback for formats without the expected "T" separator.510 353 $ts = strtotime( $str ); 511 354 return $ts ? gmdate( 'Y-m-d H:i:s', $ts ) : null; 512 355 } 513 356 514 /**515 * Converte recursivamente um SimpleXMLElement num array associativo.516 * Usado só pro bloco IBSCBS, guardado como extra sem coluna própria.517 *518 * @param SimpleXMLElement $node Nó a converter.519 * @return array520 */521 357 protected static function xml_to_array( $node ) { 522 358 $result = array(); -
sanbar-express-nfe-xml-import-br/trunk/readme.txt
r3725460 r3782421 1 1 === SanBar EXPress NF-e XML Import-BR === 2 2 Contributors: sanbazar 3 Tags: xml, nota fiscal, danfe, importar nfe, woocommerce4 Requires at least: 6. 03 Tags: woocommerce, nfe, xml, fiscal, brazil 4 Requires at least: 6.2 5 5 Tested up to: 7.1 6 6 Requires PHP: 7.4 7 Stable tag: 1.07 Stable tag: 2.0 8 8 License: GPLv2 or later 9 9 License URI: https://www.gnu.org/licenses/gpl-2.0.html 10 10 11 Import Brazilian NF-e purchase invoice XML into WooCommerce with full fiscal data and automatic product creation.11 Import Brazilian purchase NF-e XML into WooCommerce, with built-in fiscal checking, so products are created right the first time. 12 12 13 13 == Description == 14 14 15 **SanBar EXPress NF-e XML Import-BR** reads the NF-e (Brazilian Electronic Invoice) XML file your supplier issued for a purchase, and brings the items straight into WooCommerce in a grid organized exactly like the invoice's own fields (Code, EAN/GTIN, NCM, CST, CFOP, ICMS/IPI values and other taxes), ready to become a product — no manual data entry.15 **SanBar EXPress NF-e XML Import-BR** reads the NF-e (Brazilian Electronic Invoice) XML your supplier issued for a purchase and brings the items into WooCommerce in a grid laid out like the invoice itself (Code, EAN/GTIN, NCM, CST, CFOP, ICMS/IPI values and other taxes). Nothing is saved before you review and confirm it. 16 16 17 Standalone plugin: works on its own, with no dependency on any other plugin from the SanBar suite. A **Plus** edition also exists, with one-action complete product creation (fiscal data + Price Calculator fields + taxes), manual linking, stock updates, and syncing already-registered data — the features marked below as "Plus only". 17 **New in 2.0 — now unified with Fiscal Check.** The fiscal checking that used to live in the separate SanBar EXPress Fiscal Check plugin is now part of this plugin. One plugin, one screen, one flow: import the invoice, check the fiscal data, approve, and register the product. Easier to use and more complete. A **Plus** edition also exists, with complete product creation, manual linking, stock updates and batch tools. 18 19 Standalone plugin: works on its own, with no dependency on any other plugin from the SanBar suite. 18 20 19 21 = How it works = 20 22 21 1. Upload the purchase NF-e XML file. 22 2. Review the summary (supplier, invoice number, items, total, access key) before anything is saved. 23 3. Review the items in the grid, laid out exactly like the invoice's own fiscal fields. 24 4. Create the product, link it to an existing one, or just update price/stock/fiscal data — each action is independent and always asks for confirmation before applying. 23 1. **Entry** — upload the purchase XML and review the summary (supplier, number, items, total, access key). 24 2. **Review** — check each item with the fiscal checking: regime, NCM, CEST, CFOP/CSOSN and GTIN. Approve the review when it is right. 25 3. **Sync** — create the product, link it to an existing one, or update cost/data — each action is independent and asks for confirmation. 25 26 26 = Features =27 = Features (all editions) = 27 28 28 * XML upload with security validation (access key, check digit, protection against malicious XML, file size limit) 29 * Review grid in the invoice's fiscal layout, with pagination, search, and column sorting (Supplier, Description) 30 * Two views: per invoice line and per product (aggregated by identity) 31 * Special filters: linked, pending, price changed between invoices, duplicate/same GTIN, invoices or price in a date range, ignored, linked with full fiscal data (Plus only) 32 * Product creation as a draft — individually or in bulk 33 * Automatic linking to an already-registered product by GTIN match 34 * Manual linking to an existing product, writing full identity and fiscal data (Plus only) 35 * Additional matching by supplier + code when the invoice has no GTIN (Plus only) 36 * One-action complete product creation — identity, fiscal data, Price Calculator fields, and taxes (Plus only) 37 * Stock update (add to or set the quantity) straight from the invoice (Plus only) 38 * Price (cost) update and SKU/GTIN source update on an already-registered product 39 * Fiscal data sync on an already-linked product, without duplicating it (Plus only) 40 * "One registered product = one NF-e identity" rule, with a warning and assisted resolution on conflict 41 * Registry cross-check against the WooCommerce catalog — shows what the invoice brings side by side with what is already registered 42 * Price history per product/supplier, with a visual indicator for price variation between invoices or between different suppliers 43 * "Ignore" system for items that will never become a product (samples, giveaways, internal use) 44 * Invoice manager (safe deletion, without affecting products already created) and Supplier library (registration with CNPJ/CPF validation) 45 * Internal audit log and error log, with a configurable verbosity level 46 * Icon glossary — explains what each on-screen indicator means 47 * Optional integration with SanBar EXPress Store Manager, when installed 29 * XML upload with security validation (access key check digit, protection against malicious XML, size limit) 30 * Review grid in the invoice's fiscal layout, with pagination, search, sorting and filters 31 * Three-step flow (Entry, Review, Sync) with history of each item and the option to compare XML, current and approved data 32 * Built-in fiscal checking: tax regime detection from the store settings, format and consistency checks, and CEST suggestions from the public NCM table (always as a suggestion — nothing is applied without your decision) 33 * GTIN lookup against the tax authority, using your A1 certificate (optional) 34 * A1 certificate stored encrypted in a shared vault (also usable by SanBar EXPress NF-e PDV) 35 * Product creation as a draft, individually or in bulk 36 * Automatic linking to a registered product by GTIN 37 * Cost update on a registered product, with price history per product and supplier 38 * "One registered product = one NF-e identity" rule, with warning and assisted resolution 39 * Registry cross-check against the WooCommerce catalog 40 * "Ignore" system for items that will never become a product 41 * Invoice manager and supplier library (CNPJ/CPF validation) 42 * Full backup and restore of the plugin's data, in one file 43 * Audit log and error log with configurable verbosity; icon glossary 44 * Optional integration with SanBar EXPress Store Manager 48 45 49 46 = Fiscal security = … … 52 49 * Protection against XXE (external entities) and an upload size limit 53 50 * An invoice already imported is rejected — never overwrites an existing link 54 * Transactional saving: if any item fails, the whole invoice is not left partially saved 51 * Transactional saving: if any item fails, the invoice is not left partially saved 52 * Certificate and password stored encrypted; never shown in the interface 55 53 56 54 == Installation == … … 64 62 = Do I need another SanBar plugin installed? = 65 63 66 No. SanBar EXPress NF-e XML Import-BR works on its own. It integrates automatically with SanBar EXPress Store Manager when that is also installed, but this is optional. 64 No. It works on its own. It integrates with SanBar EXPress Store Manager and SanBar EXPress NF-e PDV when they are installed, but this is optional. 65 66 = What happened to the Fiscal Check plugin? = 67 68 Version 2.0 unifies it with this plugin: the fiscal checking is built in. You do not need the separate plugin; the fiscal data already saved on your products is kept and keeps working. 67 69 68 70 = Does the plugin also import sales NF-e? = … … 72 74 = Which taxes does the plugin capture from the invoice? = 73 75 74 ICMS, ICMS-ST, IPI, FCP, PIS, COFINS, II, DIFAL, IBS, CBS, and IS — the full list of taxes that a model-55 purchase NF-e allows capturing safely. Applying that data to the product in one action is a Plus edition feature. 76 ICMS, ICMS-ST, IPI, FCP, PIS, COFINS, II, DIFAL, IBS, CBS, and IS — the full list of taxes that a model-55 purchase NF-e allows capturing safely. 77 78 = Does the plugin change prices, costs or stock on its own? = 79 80 No. Every change to cost, price or stock is a choice you confirm. 75 81 76 82 = What is the difference from the Plus edition? = 77 83 78 This edition (Lite) already covers reading the invoice, the grid, draft creation, and automatic linking by GTIN. The Plus edition adds: one-action complete product creation (fiscal data + Price Calculator fields + taxes), manual linking and linking by supplier + code, stock updates, and fiscal data sync on an already-linked product. 84 This edition (Lite) covers reading the invoice, the review flow with fiscal checking, draft creation and linking by GTIN. The Plus edition adds complete product creation, manual linking and linking by supplier + code, stock updates, batch tools and fiscal sync on linked products. 85 86 == Third-party libraries == 87 88 Bundled in the `lib/` folder, used only for the optional GTIN lookup with your A1 certificate: 89 90 * **NFePHP sped-common 5.1.17** — LGPL v3 — https://github.com/nfephp-org/sped-common — reads the A1 certificate and prepares the signed request. 91 * **NFePHP sped-gtin 1.1.2** — LGPL v3 — https://github.com/nfephp-org/sped-gtin — queries the tax authority's GTIN service. 92 * **PSR Log 3.0.2** — MIT — https://github.com/php-fig/log — logger interface required by the libraries above. 93 94 They were adapted for WordPress (requests go through the WordPress HTTP API; unused classes were removed). The changes are listed in `lib/MODIFICATIONS.txt`. 95 * **Freemius SDK 2.13.5** — GPL v3 — https://github.com/Freemius/wordpress-sdk — licensing and the optional Plus trial (see "External services"). 96 97 == External services == 98 99 **Public NCM table (Siscomex).** When you use the fiscal checking and ask to download the table, the plugin requests the public NCM nomenclature from `https://portalunico.siscomex.gov.br`. No site or personal data is sent. Terms: https://portalunico.siscomex.gov.br 100 101 **GTIN lookup (SEFAZ / SVRS).** Only when you press the lookup button on an item and have an A1 certificate saved, the plugin sends the item's GTIN, signed with your certificate, to the tax authority's GTIN web service. Nothing is sent otherwise. 102 103 **Freemius (licensing).** Licensing and the optional Plus trial are handled by Freemius (`https://freemius.com`). Nothing is sent until you opt in on the first-run screen (or start a trial / enter a license): then the site URL, WordPress, PHP and plugin versions, your admin name and e-mail are sent to `https://api.freemius.com`. You can skip the opt-in and use every feature of this edition. Terms: https://freemius.com/terms/ — Privacy: https://freemius.com/privacy/ 79 104 80 105 == Changelog == 81 106 107 = 2.0 = 108 * New: unified with Fiscal Check — fiscal checking (regime, NCM, CEST suggestions, GTIN lookup, shared certificate) now built in. 109 * New: three-step flow (Entry, Review, Sync) with item history and comparison of XML, current and approved data. 110 * New: full backup and restore of the plugin's data. 111 * New: cleaner filters, search and glossary; one standard set of buttons; background no longer scrolls behind dialogs. 112 * Improvement: product opening goes to Store Manager when installed, otherwise the WooCommerce editor. 113 * Improvement: safer sync (duplicate-click protection, stock checked once) and stale items cleaned when a product is deleted. 114 * Free 3-day trial of the Plus edition (no credit card), via Freemius opt-in. 115 116 = 1.1 = 117 * New: free 3-day trial of the Plus edition, license card in Configure. 118 * Improvement: uninstall also removes the error log and audit log tables. 119 82 120 = 1.0 = 83 121 * Initial release. -
sanbar-express-nfe-xml-import-br/trunk/sanbar-express-nfe-xml-import-br.php
r3725460 r3782421 4 4 * Plugin URI: https://software.sanbazar.com.br 5 5 * Description: Import de XML de NF-e de compra para o WooCommerce — leitura fiscal, grid no layout da nota e cadastro/atualização de produtos. 6 * Version: 1.07 * Requires at least: 6. 06 * Version: 2.0 7 * Requires at least: 6.2 8 8 * Requires PHP: 7.4 9 9 * Author: SanBar (Sandro Barboza) … … 20 20 defined( 'ABSPATH' ) || exit; 21 21 22 /* =========================================================== 23 * Edition flag (Lite vs Plus) 24 * =========================================================== 25 * Single source of truth for which edition is running. Never read the 26 * constant directly, always via sbnfebr_is_plus(). 27 * ========================================================= */ 22 if ( function_exists( 'sbnfebr_fs' ) ) { 23 sbnfebr_fs()->set_basename( is_dir( __DIR__ . '/plus' ), __FILE__ ); 24 return; 25 } 28 26 29 27 define( 'SBNFEBR_IS_PLUS', false ); 30 28 31 /** 32 * Whether the Plus edition is running. 33 * 34 * @return bool 35 */ 36 function sbnfebr_is_plus() { 37 return defined( 'SBNFEBR_IS_PLUS' ) && SBNFEBR_IS_PLUS === true; 38 } 39 40 /* =========================================================== 41 * Constants 42 * ========================================================= */ 43 44 define( 'SBNFEBR_VERSION', '1.0' ); 29 define( 'SBNFEBR_FREEMIUS_ENABLED', true ); 30 31 if ( SBNFEBR_FREEMIUS_ENABLED && ! function_exists( 'sbnfebr_fs' ) ) { 32 /** 33 * Freemius SDK instance. 34 * 35 * @return Freemius 36 */ 37 function sbnfebr_fs() { 38 global $sbnfebr_fs; 39 40 if ( ! isset( $sbnfebr_fs ) ) { 41 require_once dirname( __FILE__ ) . '/vendor/freemius/start.php'; 42 43 $menu = array( 44 'slug' => 'sbnfebr', 45 'account' => false, 46 'contact' => false, 47 'support' => false, 48 'pricing' => false, 49 ); 50 $active_plugins = (array) get_option( 'active_plugins', array() ); 51 if ( in_array( 'sb-softwares-hub/sb-softwares-hub.php', $active_plugins, true ) ) { 52 $menu['parent'] = array( 'slug' => 'sb-softwares' ); 53 } 54 55 $sbnfebr_fs = fs_dynamic_init( 56 array( 57 'id' => '41770', 58 'slug' => 'sanbar-express-nfe-xml-import-br', 59 'premium_slug' => 'sanbar-express-nfe-xml-import-br-premium', 60 'type' => 'plugin', 61 'public_key' => 'pk_5d4f8abc711809f12fdc5cfffa6ea', 62 'is_premium' => SBNFEBR_IS_PLUS, 63 'premium_suffix' => 'Plus', 64 'has_premium_version' => true, 65 'has_addons' => false, 66 'has_paid_plans' => true, 67 'is_org_compliant' => true, 68 'trial' => array( 69 'days' => 3, 70 'is_require_payment' => false, 71 ), 72 'menu' => $menu, 73 ) 74 ); 75 } 76 77 return $sbnfebr_fs; 78 } 79 80 sbnfebr_fs(); 81 do_action( 'sbnfebr_fs_loaded' ); 82 } 83 84 require_once __DIR__ . '/includes/class-sbnfebr-uninstall.php'; 85 86 if ( function_exists( 'sbnfebr_fs' ) ) { 87 sbnfebr_fs()->add_action( 'after_uninstall', 'sbnfebr_uninstall_cleanup' ); 88 } elseif ( is_admin() ) { 89 register_uninstall_hook( __FILE__, 'sbnfebr_uninstall_cleanup' ); 90 } 91 92 if ( ! function_exists( 'sbnfebr_is_plus' ) ) { 93 function sbnfebr_is_plus() { 94 if ( ! defined( 'SBNFEBR_IS_PLUS' ) || SBNFEBR_IS_PLUS !== true ) { 95 return false; 96 } 97 if ( ! SBNFEBR_FREEMIUS_ENABLED || ! function_exists( 'sbnfebr_fs' ) ) { 98 return true; 99 } 100 return sbnfebr_fs()->can_use_premium_code(); 101 } 102 } 103 104 define( 'SBNFEBR_VERSION', '2.0' ); 45 105 define( 'SBNFEBR_FILE', __FILE__ ); 46 106 define( 'SBNFEBR_DIR', plugin_dir_path( __FILE__ ) ); 47 107 define( 'SBNFEBR_URL', plugin_dir_url( __FILE__ ) ); 48 49 /* ===========================================================50 * Admin notice when WooCommerce is missing51 * ========================================================= */52 108 53 109 add_action( … … 64 120 } 65 121 ); 66 67 /* ===========================================================68 * HPOS / custom order tables compatibility69 * ========================================================= */70 122 71 123 add_action( … … 82 134 ); 83 135 84 /* =========================================================== 85 * Module loading 86 * ========================================================= */ 87 88 /** 89 * Require every PHP module of the plugin. 90 * 91 * Order: services (data logic) -> controllers (thin REST layer) -> 92 * top-level orchestrators. 93 * 94 * @return void 95 */ 96 function sbnfebr_load_modules() { 97 $base = SBNFEBR_DIR . 'includes/'; 98 99 // 1. Services — data logic (parsing, persistence). 100 require_once $base . 'services/class-sbnfebr-notes-service.php'; 101 require_once $base . 'services/class-sbnfebr-xml-parser-service.php'; 102 require_once $base . 'services/class-sbnfebr-supplier-service.php'; 103 require_once $base . 'services/class-sbnfebr-draft-service.php'; 104 require_once $base . 'services/class-sbnfebr-error-log-service.php'; 105 require_once $base . 'services/class-sbnfebr-audit-service.php'; 106 require_once $base . 'services/class-sbnfebr-match-service.php'; 107 108 // 2. Controllers — thin REST layer over the services. 109 require_once $base . 'controllers/class-sbnfebr-import-controller.php'; 110 require_once $base . 'controllers/class-sbnfebr-items-controller.php'; 111 require_once $base . 'controllers/class-sbnfebr-suppliers-library-controller.php'; 112 require_once $base . 'controllers/class-sbnfebr-draft-controller.php'; 113 require_once $base . 'controllers/class-sbnfebr-settings-controller.php'; 114 require_once $base . 'controllers/class-sbnfebr-error-log-controller.php'; 115 require_once $base . 'controllers/class-sbnfebr-match-controller.php'; 116 117 // Plus — only loaded when the Plus edition is active. Kept in a 118 // separate tree (plus/includes/), never mixed with Lite files in the 119 // same folder. Order matters: these files `extends` the Lite 120 // equivalent classes loaded above (services/controllers, steps 1/2). 121 if ( sbnfebr_is_plus() ) { 122 $plus_base = SBNFEBR_DIR . 'plus/includes/'; 123 require_once $plus_base . 'services/class-sbnfebr-draft-service-plus.php'; 124 require_once $plus_base . 'controllers/class-sbnfebr-draft-controller-plus.php'; 125 } 126 127 // 3. Top-level orchestrators. 128 require_once $base . 'class-sbnfebr-rest.php'; 129 require_once $base . 'class-sbnfebr-admin.php'; 130 131 } 132 133 /* =========================================================== 134 * Bootstrap 135 * ========================================================= */ 136 if ( ! function_exists( 'sbnfebr_load_modules' ) ) { 137 function sbnfebr_load_modules() { 138 $base = SBNFEBR_DIR . 'includes/'; 139 140 // 1. Services — data logic (parsing, persistence). 141 require_once $base . 'services/class-sbnfebr-fiscal-settings.php'; 142 require_once $base . 'services/class-sbnfebr-fiscal-tables.php'; 143 require_once $base . 'services/class-sbnfebr-fiscal-rules.php'; 144 require_once $base . 'services/class-sbnfebr-workflow-service.php'; 145 require_once $base . 'services/class-sbnfebr-fiscal-check-service.php'; 146 require_once $base . 'services/class-sbnfebr-cert-legacy.php'; 147 require_once $base . 'services/class-sbnfebr-cert.php'; 148 require_once $base . 'services/class-sbnfebr-sefaz-gtin.php'; 149 require_once $base . 'services/class-sbnfebr-gtin-lookup.php'; 150 require_once $base . 'services/class-sbnfebr-notes-service.php'; 151 require_once $base . 'services/class-sbnfebr-xml-parser-service.php'; 152 require_once $base . 'services/class-sbnfebr-supplier-service.php'; 153 require_once $base . 'services/trait-sbnfebr-product-data-writers.php'; 154 require_once $base . 'services/class-sbnfebr-draft-service.php'; 155 require_once $base . 'services/class-sbnfebr-error-log-service.php'; 156 require_once $base . 'services/class-sbnfebr-audit-service.php'; 157 require_once $base . 'services/class-sbnfebr-match-service.php'; 158 require_once $base . 'services/class-sbnfebr-cest-service.php'; 159 require_once $base . 'services/class-sbnfebr-full-backup-service.php'; 160 161 require_once $base . 'controllers/class-sbnfebr-import-controller.php'; 162 require_once $base . 'controllers/class-sbnfebr-workflow-controller.php'; 163 require_once $base . 'controllers/class-sbnfebr-items-controller.php'; 164 require_once $base . 'controllers/class-sbnfebr-suppliers-library-controller.php'; 165 require_once $base . 'controllers/class-sbnfebr-draft-controller.php'; 166 require_once $base . 'controllers/class-sbnfebr-settings-controller.php'; 167 require_once $base . 'controllers/class-sbnfebr-error-log-controller.php'; 168 require_once $base . 'controllers/class-sbnfebr-match-controller.php'; 169 require_once $base . 'controllers/class-sbnfebr-fiscal-controller.php'; 170 require_once $base . 'controllers/class-sbnfebr-full-backup-controller.php'; 171 172 173 // 3. Top-level orchestrators. 174 require_once $base . 'class-sbnfebr-rest.php'; 175 require_once $base . 'class-sbnfebr-admin.php'; 176 177 } 178 } 136 179 137 180 add_action( … … 145 188 146 189 // dbDelta only runs when DB_VERSION changes. 190 SBNFEBR_Workflow_Service::create_table(); 191 SBNFEBR_Fiscal_Tables::init(); 192 SBNFEBR_Fiscal_Settings::init(); 147 193 SBNFEBR_Notes_Service::create_table(); 194 SBNFEBR_Workflow_Service::prepare_legacy_backfill(); 148 195 SBNFEBR_Error_Log_Service::create_table(); 149 196 SBNFEBR_Audit_Service::create_table(); … … 158 205 ); 159 206 160 /* ===========================================================161 * Activation / Deactivation162 * ========================================================= */163 164 207 register_activation_hook( 165 208 __FILE__, 166 209 function () { 167 210 sbnfebr_load_modules(); 211 SBNFEBR_Workflow_Service::create_table(); 212 SBNFEBR_Fiscal_Tables::install(); 168 213 SBNFEBR_Notes_Service::create_table(); 214 SBNFEBR_Workflow_Service::prepare_legacy_backfill(); 169 215 SBNFEBR_Error_Log_Service::create_table(); 170 216 SBNFEBR_Audit_Service::create_table(); … … 175 221 __FILE__, 176 222 function () { 223 wp_clear_scheduled_hook( 'sbnfebr_ncm_refresh' ); 177 224 flush_rewrite_rules( false ); 178 225 }
Note:
See TracChangeset
for help on using the changeset viewer.