Plugin Directory

Changeset 3782421


Ignore:
Timestamp:
11/03/2026 06:23:52 PM (3 weeks ago)
Author:
sanbazar
Message:

new features;
new integration;
new layout and more.
now PLUS on sale!!!

Location:
sanbar-express-nfe-xml-import-br
Files:
653 added
36 edited

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
    72
    83:root {
    … …  
    2419}
    2520
    26 /* Standard 4px border-radius on every input/select/button. Scoped to
    27    the plugin's 3 containers (main grid + the 2 modal skeletons) so it
    28    never leaks into the rest of wp-admin. More specific rules later in
    29    the file (e.g. pill shapes with border-radius:10px/50%) win by
    30    normal specificity, no !important needed here. */
    3121#sbnfebr-wrap input,
    3222#sbnfebr-wrap select,
    … …  
    6555}
    6656.sb-brand { display: inline-flex; align-items: baseline; gap: 5px; }
     57.sb-brand__mobile { display: none; }
    6758.sb-brand__prefix,
    6859.sb-brand__suffix { font-size: 15px; font-weight: 600; color: #1d2327; }
    … …  
    126117        gap: 6px;
    127118}
    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
    130127.sbnfebr-row2 {
    131128        display: flex;
    … …  
    146143}
    147144#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
    150146#sbnfebr-filter-supplier,
    151147#sbnfebr-filter-note { min-width: 235px; }
    … …  
    167163.sbnfebr-stats__left,
    168164.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
    171166.sbnfebr-view-toggle {
    172167        display: inline-flex;
    … …  
    200195        font-size: 12px;
    201196}
     197.sbnfebr-pagination__per-page { color: #6b7280; white-space: nowrap; }
    202198.sbnfebr-pagination #sbnfebr-page-prev,
    203199.sbnfebr-pagination #sbnfebr-page-next {
    … …  
    218214        line-height: 1.2;
    219215        box-sizing: border-box;
    220         /* 2x the default width — native select arrow overlapped the number
    221            at the previous, tighter size. */
     216
    222217        width: 76px;
    223218        padding: 1px 20px 1px 6px;
    … …  
    225220        border-color: #d1d5db;
    226221}
    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
    231223.sbnfebr-stat {
    232224        display: inline-flex;
    … …  
    260252}
    261253.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
    263262.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}
    264270
    265271/* ===== BUTTONS ===== */
    … …  
    280286.sbnfebr-btn--blue     { background: #3b82f6; color: #fff; border-color: #2563eb; }
    281287.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
    284289#sbnfebr-btn-upload,
    285290#sbnfebr-btn-upload-empty {
    … …  
    293298        font-weight: 600;
    294299}
    295 /* Bulk Draft+ — amber matches the "Plus feature" visual indicator
    296    already used on the supplier+code match icons. */
     300
    297301.sbnfebr-btn--amber     { background: #f59e0b; color: #fff; border-color: #d97706; }
    298302.sbnfebr-btn--amber:hover { background: #d97706; }
     303#sbnfebr-btn-upgrade { text-decoration: none; }
     304#sbnfebr-btn-upgrade:hover { color: #fff; }
    299305#sbnfebr-btn-bulk-draft-plus,
    300306#sbnfebr-btn-bulk-ignore,
    … …  
    315321        box-sizing: border-box;
    316322}
    317 /* "X clear" — shows/hides together with the bulk button. */
     323
    318324#sbnfebr-btn-bulk-clear {
    319325        width: 30px;
    … …  
    360366.sbnfebr-notice--warning { background: #fef3c7; color: #92400e; border-color: #fcd34d; }
    361367.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
    364369.sbnfebr-notice--actions {
    365370        display: flex;
    … …  
    451456}
    452457
    453 /* Product view — larger, more spaced-out layout than the note view:
    454    fewer columns on screen, more room to breathe. ~14px font, wider
    455    column gaps, action buttons proportionally ~30% larger. */
    456458.sbnfebr-grid--product thead th {
    457459        padding: 10px 16px;
    … …  
    463465}
    464466.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;
    471470}
    472471.sbnfebr-grid--product .sbnfebr-action-btn {
    … …  
    481480        font-size: 13px;
    482481}
    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
    488483.sbnfebr-grid--product .sbnfebr-col-product_supplier_count,
    489484.sbnfebr-grid--product .sbnfebr-col-product_note_count,
    … …  
    494489}
    495490
    496 /* Soft rectangular badges — price, stock, last purchase in the
    497    product view. Color is FIXED per column (decorative, helps scan the
    498    row faster) rather than representing state; the ⚠ inside the badge
    499    signals attention (price changed / stock at zero), not the
    500    background color. */
    501491.sbnfebr-value-badge {
    502492        display: inline-block;
    … …  
    517507}
    518508
    519 /* Action column — always first, fixed and narrow (fits only the
    520    buttons, never grows with content). */
    521509.sbnfebr-col-select {
    522510        width: 24px;
    … …  
    530518#sbnfebr-select-all {
    531519        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;
    534521}
    535522.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;
    545526        text-align: left;
    546527        padding: 3px 3px 3px 1px !important;
    … …  
    563544.sbnfebr-action-btn + .sbnfebr-action-btn { margin-left: 2px; }
    564545
    565 /* History button states — amber (price changed with the same
    566    supplier) and red (same GTIN across different suppliers, takes
    567    priority over amber). */
    568546.sbnfebr-action-btn--warn {
    569547        background: #fffbeb;
    … …  
    576554}
    577555.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
    580557.sbnfebr-action-btn--ignored {
    581558        background: #fef2f2;
    … …  
    585562}
    586563.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. */
    622565.sbnfebr-ac-gicon-group { display: inline-flex; align-items: center; gap: 2px; }
    623 .sbnfebr-ac-gicon-wrap { position: relative; display: inline-block; }
    624566.sbnfebr-ac-gicon {
    625567        width: 20px;
    … …  
    637579.sbnfebr-ac-gicon:hover { background: #f3f4f6; }
    638580.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
    693582.sb-library-overlay--narrow { width: 560px; max-width: 92vw; height: auto; max-height: 80vh; }
    694583
    695 /* Modal --registry. Width is the sum of columns: note group 554px +
    696    divider 20px + registry group 574px + actions 200px (5-icon group
    697    20px + 4×2px gap = 108px, + ↗ 24px + SM 48px + group gaps)
    698    = 1348px content + gaps between columns (3×6px) + row padding
    699    (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, so
    702    .sb-library-overlay (base, 800px/88vh) wins the specificity tie
    703    (same weight, single class) by cascade order — without it the modal
    704    renders at the base size. Height grows with content up to an 85vh
    705    cap rather than staying fixed at 88vh. */
    706584.sb-library-overlay--registry {
    707585        width: 1450px !important;
    … …  
    711589}
    712590.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
    718594.sbnfebr-regcheck-subtitle {
    719595        font-size: 12px;
    … …  
    838714
    839715.sbnfebr-regcheck-actions {
    840         display: flex;
    841         align-items: center;
    842         justify-content: center;
     716        display: grid;
     717        grid-template-columns: 104px 56px 30px;
    843718        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
    874723.sbnfebr-danger-modal.sbnfebr-itemaction-modal {
    875724        border-top: 4px solid #3b82f6;
    … …  
    880729        box-sizing: border-box;
    881730}
    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
    891732@media (min-width: 700px) {
    892733        .sbnfebr-danger-modal.sbnfebr-itemaction-modal--has-source {
    … …  
    945786}
    946787
    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 several
    950    screens (item modal, import), hence living in core.css rather than
    951    a screen-specific file. */
    952788.sbnfebr-alert {
    953789        border: 1px solid;
    … …  
    985821.sbnfebr-ia-product-info-line { opacity: 0.9; }
    986822.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
    990824        border: 1px solid #d1d5db;
    991825        border-radius: 4px;
    … …  
    998832.sbnfebr-itemaction-name-input:disabled { background: #f3f4f6; color: #9ca3af; }
    999833
    1000 /* Make Draft block buttons — 2 lines of text, fixed size: "create
    1001    draft" and "link" share the same size (150x50); "identity only" is
    1002    smaller (150x25). */
    1003834.sbnfebr-ia-draft-btn,
    1004835.sbnfebr-ia-manual-link-toggle {
    … …  
    1026857        border: 1px solid #d1d5db !important;
    1027858}
    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
    1031860.sbnfebr-ia-open-sm-btn {
    1032861        margin-right: 5px;
    … …  
    1037866.sbnfebr-ia-open-sm-btn:hover { background: #fffbeb !important; }
    1038867
    1039 /* Four separate, atomic action cards (Draft/Link, Stock, Price/Source,
    1040    Tax data). Never `disabled` — only switches between pulsing (has a
    1041    difference to apply) and dimmed (nothing new, still clickable). */
    1042868.sbnfebr-ac-cards {
    1043869        display: flex;
    … …  
    1078904}
    1079905
    1080 /* Alert — has a difference to apply, pulsing ring on the icon. */
    1081906.sbnfebr-ac-card--alert { border-color: #d97706; background: #fffbeb; }
    1082907.sbnfebr-ac-card--alert .sbnfebr-ac-icon { border-color: #d97706; position: relative; }
    … …  
    1101926.sbnfebr-ac-card--alert .sbnfebr-ac-btn { background: #f59e0b; border: 1px solid #d97706; color: #fff; }
    1102927
    1103 /* Dimmed — nothing new, but still clickable (the decision is always the user's). */
    1104928.sbnfebr-ac-card--quiet { background: #f8f9fb; }
    1105929.sbnfebr-ac-card--quiet .sbnfebr-ac-btn { background: #fff; border: 1px solid #d1d5db; color: #9ca3af; }
    … …  
    1111935.sbnfebr-ac-card--done .sbnfebr-ac-btn { background: #fff; border: 1px solid #a7f3d0; color: #065f46; }
    1112936
    1113 /* Locked Plus feature, shown flagged (not hidden) in Lite. "Learn
    1114    more" opens static text only — no Plus logic ships in the Lite build. */
    1115937.sbnfebr-ac-card--locked { background: #f8f9fb; }
    1116938.sbnfebr-ac-card--locked .sbnfebr-ac-icon { background: #f3f4f6; color: #9ca3af; border-style: dashed; }
    1117939.sbnfebr-ac-card--locked .sbnfebr-ac-btn { background: #fff; border: 1px solid #f59e0b; color: #b45309; }
    1118940
    1119 /* Individual popup — same .sbnfebr-danger-backdrop/.sbnfebr-danger-modal
    1120    skeleton, without the standard red top border. */
    1121941.sbnfebr-ac-popup {
    1122942        position: relative;
    … …  
    1148968        font-size: 9px !important;
    1149969}
    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
    1153971.sbnfebr-ac-popup .sbnfebr-ac-ribbon {
    1154972        z-index: 0;
    … …  
    12141032        padding: 0 6px;
    12151033}
    1216 /* Icon glossary — same .sbnfebr-danger-backdrop/.sbnfebr-danger-modal
    1217    skeleton as usual. */
     1034
    12181035.sbnfebr-glossary-modal {
    12191036        border-top: 4px solid #3b82f6;
    … …  
    12611078.sbnfebr-ac-popup-btnrow { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
    12621079
    1263 /* Fiscal popup — note × product table, same look as .sbnfebr-noteinfo-dup-table. */
    12641080.sbnfebr-ac-popup--wide { width: 540px; }
    12651081.sbnfebr-ac-fiscal-table {
    … …  
    12871103.sbnfebr-ac-fiscal-empty { color: #9ca3af; font-style: italic; }
    12881104
    1289 /* "Choose" (Draft/Link with match) — 2-3 options as cards. */
    12901105.sbnfebr-ac-choose-list { display: flex; flex-direction: column; gap: 8px; }
    12911106.sbnfebr-ac-choose-opt {
    … …  
    13021117.sbnfebr-ac-choose-btn { font-size: 11px; padding: 5px 10px; }
    13031118
    1304 /* Progress toast — bottom right corner, z-index above any modal
    1305    (.sbnfebr-danger-backdrop already uses high values, this needs to
    1306    win). */
    13071119#sbnfebr-toast-stack {
    13081120        position: fixed;
    … …  
    13411153.sbnfebr-toast-pct { font-weight: 600; }
    13421154
    1343 /* Confirmation toast — green, checkmark instead of spinner, dismisses
    1344    itself. */
    13451155.sbnfebr-toast--success { background: #065f46; }
    13461156.sbnfebr-toast--error { background: #b91c1c; }
    … …  
    13581168}
    13591169
    1360 /* Temporary highlight on a row that just changed — fades out after
    1361    FLASH_MS (see renderGrid() in nfebr-main.js). Stays above the
    1362    normal row colors (even/odd/selected) via source order, no
    1363    !important needed. */
    13641170@keyframes sbnfebr-row-flash {
    13651171        0%   { background-color: #bbf7d0; }
    … …  
    13701176}
    13711177
    1372 /* "Update information" card (Plus) — same diagonal PLUS ribbon the
    1373    Sheet uses on locked-feature cards in Lite. */
    13741178.sbnfebr-sync-card {
    13751179        position: relative;
    … …  
    14171221        font-weight: 700;
    14181222}
    1419 /* "Already synced or not" status for the already-linked item card —
    1420    empty until the async check resolves. */
     1223
    14211224.sbnfebr-ia-sync-status:empty { display: none; }
    14221225.sbnfebr-ia-sync-status {
    … …  
    14361239        border: 1px solid #fde68a;
    14371240}
    1438 /* "Never synced" — neither matching nor changed: has never received
    1439    any tax data yet (e.g. linked via Lite). */
     1241
    14401242.sbnfebr-ia-sync-status--neutral {
    14411243        background: #eff6ff;
    … …  
    14471249        font-size: 11px;
    14481250}
    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
    14531252.sbnfebr-ia-sync-status-detail {
    14541253        margin-top: 4px;
    … …  
    14571256}
    14581257
    1459 /* diffCard (nfebr-diff-card.js) — diverging field row (batch review). */
    14601258.sbnfebr-diffcard-row {
    14611259        display: flex;
    … …  
    14711269.sbnfebr-diffcard-incoming { color: #1d2327; font-weight: 700; }
    14721270
    1473 /* diffCard — source selector row (multiple occurrences of the GTIN). */
    14741271.sbnfebr-diffcard-source {
    14751272        all: unset;
    … …  
    14911288        background: #eff6ff;
    14921289}
     1290.sbnfebr-diffcard-source:disabled { cursor: default; }
     1291.sbnfebr-diffcard-source.is-loading { opacity: .65; }
    14931292.sbnfebr-diffcard-source-main { display: flex; flex-direction: column; gap: 2px; font-size: 12px; }
    14941293.sbnfebr-diffcard-source-note { font-weight: 700; color: #1d2327; }
    … …  
    15001299.sbnfebr-diffcard-source-delta--down { color: #059669; }
    15011300.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;
    15191320        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 {
    15631326        display: flex;
    15641327        align-items: center;
    15651328        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
    15691350.sbnfebr-diffcard-supplier-warn {
    15701351        background: #fffbeb;
    … …  
    15781359}
    15791360
    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). */
    15831362.sbnfebr-danger-modal.sbnfebr-noteinfo-modal {
    15841363        width: 480px;
    … …  
    16341413        border-bottom: 1px solid #f1f5f9;
    16351414}
    1636 /* Supplementary info — free text from the supplier, can be long,
    1637    wraps normally. */
     1415
    16381416.sbnfebr-noteinfo-freetext {
    16391417        white-space: pre-wrap;
    … …  
    16531431.sb-suite-tab--active { background: #eff6ff; color: #1d4ed8; cursor: default; }
    16541432.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
    52
    63.sbnfebr-notes-group {
    … …  
    96.sbnfebr-notes-group:last-child { border-bottom: none; }
    107
    11 /* Per-supplier accordion — header is a clickable button, body is
    12    collapsed by default (max-height:0), chevron rotates 90° when open. */
    138.sbnfebr-notes-group-head {
    149        display: flex;
    … …  
    9085.sbnfebr-protocol-badge--neutral { background: #e5e7eb; color: #374151; }
    9186
    92 /* === Destructive sub-modal (type "DELETE" to confirm) === */
    9387.sbnfebr-danger-backdrop {
    9488        position: fixed;
    … …  
    133127        margin: 0 0 14px;
    134128}
    135 /* Bullet list in SB.confirm() (opts.list) — same visual as the
    136    "Update information" card. */
     129
    137130.sbnfebr-danger-list {
    138131        list-style: none;
    … …  
    193186        margin-top: 16px;
    194187}
    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
    197189.sbnfebr-company-regime-badge {
    198190        font-size: 12px;
    … …  
    215207}
    216208
    217 /* === Import confirmation modal — reuses the
    218    .sbnfebr-danger-backdrop/.sbnfebr-danger-modal/.sbnfebr-danger-actions
    219    skeleton from the destructive modal, without the red top border
    220    since this action isn't destructive. === */
    221209.sbnfebr-import-modal {
    222210        border-top: 4px solid #3b82f6;
    … …  
    279267}
    280268
    281 /* === "Configure" modal — same skeleton as the danger modal, without
    282    the red border. Sections (.sbnfebr-configure-section) let the modal
    283    grow with more option groups beyond "Company data". === */
    284269.sbnfebr-configure-modal {
    285270        border-top: 4px solid #3b82f6;
    … …  
    289274        overflow-y: auto;
    290275}
    291 /* Small hub — "Configure" opens this first, one button per settings group. */
     276
    292277.sbnfebr-configure-modal--hub {
    293278        width: 300px;
    … …  
    309294        font-size: 13px;
    310295}
     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}
    311305.sbnfebr-configure-hint {
    312306        font-size: 11px;
    … …  
    329323        cursor: pointer;
    330324}
    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
    335326.sbnfebr-radio-group {
    336327        display: flex;
    … …  
    359350}
    360351
    361 /* .sbnfebr-ia-diff-loading is still used by the manual link search
    362    (openManualLinkPopup() in nfebr-item-actions.js). */
    363352.sbnfebr-ia-diff-loading {
    364353        font-size: 12px;
    … …  
    367356}
    368357
    369 /* Draft+ row with the manual link button alongside it, in Plus. */
    370358.sbnfebr-ia-draft-row {
    371359        display: flex;
    … …  
    432420        font-size: 11px;
    433421}
    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
    437423.sbnfebr-ia-manual-link-toggle--spaced {
    438424        display: block;
    … …  
    442428}
    443429
    444 /* "Already in use by another item" — visible before selection. */
    445430.sbnfebr-ia-manual-link-item--inuse {
    446431        border-color: #fde68a;
    … …  
    491476}
    492477
    493 /* === Error log popup — reuses .sb-library-* for the skeleton === */
    494478.sbnfebr-errorlog-overlay { width: 640px; height: 70vh; }
    495479.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
    42
    53.sb-library-overlay-backdrop {
    … …  
    170168.sb-library-filter:hover { background: #eef2ff !important; color: #4338ca; }
    171169
    172 /* Suppliers Library groups: active note / registered-with-catalog / bare. */
    173170.sb-library-section-head {
    174171        padding: 8px 12px 4px;
    … …  
    214211}
    215212.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
    221214.sb-library-sup-nickname-row {
    222215        display: flex;
    … …  
    233226        color: #374151;
    234227}
    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
    239229.sb-library-sup-field input:not([type="checkbox"]):not([type="radio"]):not(.sb-sup-f-nickname),
    240230.sb-library-sup-field select,
    … …  
    247237        width: 100% !important;
    248238}
    249 /* "Show nickname" checkbox — resets the generic field styling above
    250    (width/padding/border), which would otherwise stretch it. */
     239
    251240.sb-library-sup-field input[type="checkbox"] {
    252241        -webkit-appearance: checkbox !important;
    … …  
    306295}
    307296
    308 /* "!" icon next to the supplier select on the main toolbar — specific
    309    to this plugin; the Sheet only edits suppliers from the Library. */
    310297.sbnfebr-supplier-info-btn {
    311298        all: unset;
    … …  
    337324.sbnfebr-supplier-info-btn--unregistered:hover { background: #fecaca; }
    338325
    339 /* "i" note info icon — same skeleton as the supplier "!" icon above,
    340    but stateless (purely informational, never turns red/green). */
    341326.sbnfebr-note-info-btn {
    342327        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
    22.sbnfebr-ph-table {
    33        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
    32.sbnfebr-bridge-overlay {
    43    position: fixed;
    … …  
    2625    display: block;
    2726}
    28 /* Standard close button style, duplicated from .sbnfebr-close-btn in
    29    core.css because this screen only loads sheet-bridge.css. */
     27
    3028.sbnfebr-bridge-close {
    3129    position: absolute;
    … …  
    4947}
    5048
    51 /* Plus edition indicator — amber outline on the standard button, no
    52    text/icon change. Inset border via box-shadow, not an outer outline. */
    5349#sbnfebr-bridge-btn.sbnfebr-bridge-btn--plus {
    5450    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 API
    3    helper. Each module is an IIFE that exports into it.
    4    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    128                : function ( s ) { return s; };
    139
    14         /**
    15          * Builds the final URL for a plugin REST endpoint, appending
    16          * querystring parameters. Separator can't be hardcoded '?' — plain
    17          * 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          */
    2310        function buildUrl( endpoint, params ) {
    2411                var base = CFG.rest_url + endpoint;
    … …  
    3017        }
    3118
    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
    4040        function api( endpoint, params, opts ) {
    4141                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                }
    4646                return fetch( buildUrl( endpoint, params ), Object.assign( {}, opts, { headers: headers } ) )
    4747                        .then( function ( res ) {
    … …  
    5151                                                // Preserves WP_Error's code/data — some endpoints
    5252                                                // (e.g. /link, /price-source) send an extra payload
    53                                                 // in `data.conflict` the UI needs beyond the message.
    5453                                                err.code = body.code || null;
    5554                                                err.data = body.data || null;
    … …  
    5756                                        } );
    5857                                }
    59                                 return res.json();
     58                                return res.json().then( function ( data ) {
     59                                        announceSent( endpoint, opts, data );
     60                                        return data;
     61                                } );
    6062                        } );
    6163        }
    6264
    63         /**
    64          * Basic escaping for safe text insertion into innerHTML.
    65          *
    66          * @param {*} s Value to escape.
    67          * @return {string}
    68          */
    6965        function esc( s ) {
    7066                var div = document.createElement( 'div' );
    … …  
    7369        }
    7470
    75         /**
    76          * Formats a 'YYYY-MM-DD...' date (as returned by the DB/REST) into
    77          * 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          */
    8271        function formatDateBR( isoDate ) {
    8372                var m = /^(\d{4})-(\d{2})-(\d{2})/.exec( String( isoDate || '' ) );
    … …  
    8574        }
    8675
    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 bullets
    95          *                         below the message.
    96          *                         checkbox { label, checked } (optional) —
    97          *                         when present, `out` (a mutable object
    98          *                         passed by the caller) receives
    99          *                         `out.checked` BEFORE the Promise resolves;
    100          *                         the Promise itself still resolves only
    101          *                         `true`/`false` (compatible with callers
    102          *                         using `SB.confirm` without a checkbox).
    103          *                         extraHtml (string, optional) — free HTML
    104          *                         inserted before the actions, for content
    105          *                         checkbox/list can't express (e.g. radios).
    106          *                         readExtra(rootEl) (optional) runs BEFORE
    107          *                         resolving with `true`, populating `out` —
    108          *                         same contract as the checkbox.
    109          * @return {Promise<boolean>}
    110          */
    11176        function confirmDialog( message, opts ) {
    11277                opts = opts || {};
    … …  
    164129        }
    165130
    166         /**
    167          * Standardized alert card — title ("what happened") separate from an
    168          * 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          */
    176131        function alertCard( variant, icon, title, detail ) {
    177132                return '<div class="sbnfebr-alert sbnfebr-alert--' + variant + '">' +
    … …  
    179134                        ( detail ? '<div class="sbnfebr-alert-detail">' + detail + '</div>' : '' ) +
    180135                '</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' ] } );
    181240        }
    182241
    … …  
    189248                confirm: confirmDialog,
    190249                alertCard: alertCard,
     250                handleProductsSent: handleProductsSent,
     251                openProduct: openProduct,
     252                productButtons: productButtons,
    191253        } );
    192254})();
  • 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 value
    3    → new value). Rendering only, no network calls.
    4    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    139        var __ = SB.__;
    1410
    15         /**
    16          * One divergent-field row with an opt-in checkbox (checked by
    17          * default), for batch review where each field can be accepted or
    18          * 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          */
    2411        function fieldRow( field, checked ) {
    2512                checked = false !== checked;
    … …  
    3320        }
    3421
    35         /**
    36          * Reads which fields are checked within a container.
    37          *
    38          * @param {HTMLElement} root
    39          * @return {string[]} Checked field keys.
    40          */
    4122        function readCheckedFields( root ) {
    4223                return Array.prototype.map.call(
    … …  
    4627        }
    4728
    48         /**
    49          * Compact row for the source selector — one occurrence of the same
    50          * 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} isSelected
    54          * @param {Object}  baseline   Currently active source, used to compute the price delta and the supplier/NCM-changed flag.
    55          * @return {string}
    56          */
    5729        function sourceRow( source, isSelected, baseline ) {
    5830                var supplierChanged = baseline && source.supplier_cnpj !== baseline.supplier_cnpj;
    … …  
    7244                }
    7345
    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' : '' ) + '>' +
    7553                        '<span class="sbnfebr-diffcard-source-main">' +
    7654                                '<span class="sbnfebr-diffcard-source-note">' + SB.esc( source.note_number + '/' + source.series + ' · ' + dateBR ) + '</span>' +
    … …  
    8159                                ( supplierChanged ? '<i class="sbnfebr-diffcard-flag sbnfebr-diffcard-flag--supplier" title="' + SB.esc( __( 'Fornecedor diferente', 'sanbar-express-nfe-xml-import-br' ) ) + '">🏬</i>' : '' ) +
    8260                                ( 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>' +
    8362                        '</span>' +
    8463                '</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 icon
    3    highlights on unseen errors; opening marks them seen.
    4    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    2016        }
    2117
    22         /* ============================================================
    23          * Ícone — estado normal/destacado
    24          * ========================================================== */
    2518
    2619        function refreshIcon() {
    … …  
    3730        }
    3831
    39         /**
    40          * Called externally (e.g. after a failed upload/import) to re-check
    41          * status; whether the error was actually logged depends on the
    42          * configured log level.
    43          */
    4432        var _notifyTimer = null;
    4533        function notifyApiError() {
    … …  
    4836        }
    4937
    50         /* ============================================================
    51          * Overlay
    52          * ========================================================== */
    5338
    5439        function ensureOverlay() {
    … …  
    190175        }
    191176
    192         /* ============================================================
    193          * "Clear log" — simple confirm dialog.
    194          * ========================================================== */
    195177
    196178        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) + table
    3    rendering; fiscal columns auto-hide when no loaded item has data.
    4    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    139        var __ = SB.__;
    1410
    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.
    1812        var COLS = [
    19                 // Selection checkbox — always the first column, never hidden.
    20                 // Feeds the "Create Draft+" bulk button in the toolbar, but is a
    21                 // base for any future bulk action.
    22                 { key: 'select', label: '', structural: true, isSelect: true },
    23                 // Action column — always first, never hidden (by auto-hide or
    24                 // filter). Not data, it's a button; rendered separately in
    2513                // render() (see isAction).
    2614                { 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' ) },
    2717                { key: 'supplier_name', label: __( 'Fornecedor', 'sanbar-express-nfe-xml-import-br' ), structural: true, sortable: true },
    2818                { key: 'note_ref',      label: __( 'Nota', 'sanbar-express-nfe-xml-import-br' ), structural: true },
    2919                { 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 },
    3220                { key: 'ncm',           label: __( 'NCM/SH', 'sanbar-express-nfe-xml-import-br' ) },
    3321                { key: 'cest',          label: __( 'CEST', 'sanbar-express-nfe-xml-import-br' ) },
    … …  
    3624                { key: 'unit',          label: __( 'Unidade', 'sanbar-express-nfe-xml-import-br' ) },
    3725                { 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 },
    3927                { key: 'total_value',   label: __( 'Valor total', 'sanbar-express-nfe-xml-import-br' ), numeric: true, decimals: 2 },
    4028                { key: 'discount_value', label: __( 'Desconto', 'sanbar-express-nfe-xml-import-br' ), numeric: true, decimals: 2 },
    … …  
    4836        ];
    4937
    50         // "Per-product" view: 1 row per identity (GTIN, or supplier+code),
    51         // not per note line item. Fixed columns, no auto-hide.
    5238        var PRODUCT_COLS = [
    53                 { key: 'select', label: '', structural: true, isSelect: true },
    5439                { key: 'actions', label: '', structural: true, isAction: true },
    5540                { key: 'description', label: __( 'Nome', 'sanbar-express-nfe-xml-import-br' ), sortable: true },
    5641                { key: 'gtin', label: __( 'GTIN', 'sanbar-express-nfe-xml-import-br' ) },
    5742                { key: 'product_code', label: __( 'Código', 'sanbar-express-nfe-xml-import-br' ) },
    58                 // Badges — cell rendered separately (see isBadge in render()),
    5943                // not plain text formatted by formatCell().
    6044                { key: 'last_price', label: __( 'Preço', 'sanbar-express-nfe-xml-import-br' ), isBadge: true },
    … …  
    6549        ];
    6650
    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
    7157        function hasValue( v ) {
    7258                if ( v === null || v === undefined || v === '' ) {
    … …  
    8066        }
    8167
    82         /**
    83          * Soft-colored rectangular badge — per-product view. Color is fixed
    84          * 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} text
    88          * @param {string} variant 'neutral'|'price'|'stock'|'date'.
    89          * @param {string} [warnTitle] When present, adds "⚠" with this title.
    90          * @return {string}
    91          */
    9268        function badgeHTML( text, variant, warnTitle ) {
    9369                if ( ! text ) {
    … …  
    10076        }
    10177
    102         /**
    103          * Most recent price (unit_value of the representative row). Column
    104          * always blue; ⚠ when the price has varied between notes for this
    105          * supplier+code (price_variants, same criterion as the per-note view).
    106          */
    10778        function priceBadgeCell( item ) {
    10879                if ( ! hasValue( item.unit_value ) ) {
    … …  
    11586        }
    11687
    117         /**
    118          * Current stock (WooCommerce, only when linked). Green with a value,
    119          * ⚠ at zero; neutral gray with no linked/managed stock.
    120          */
    12188        function stockBadgeCell( item ) {
    12289                if ( ! item.wc_product_id ) {
    … …  
    13198        }
    13299
    133         /**
    134          * Most recent note date where this product appeared — column always
    135          * purple, no state indicator (informational only).
    136          */
    137100        function lastDateBadgeCell( item ) {
    138101                if ( ! item.product_last_date ) {
    … …  
    172135        }
    173136
    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 } — forces
    179          *                              structural columns per the active
    180          *                              toolbar filter.
    181          * @param {string} [mode]       'note' (default) | 'product'.
    182          * @return {Array} Subset of COLS to render.
    183          */
    184137        function visibleColumns( items, visibility, mode ) {
    185138                if ( 'product' === mode ) {
    … …  
    203156        }
    204157
    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, no
    212          *                            selection if omitted.
    213          * @param {string} [mode]     'note' (default) | 'product'.
    214          * @param {Object} [sortState] { by, dir } — active column/direction
    215          *                             (dir: 'asc'|'desc'), or {} for no sort.
    216          */
    217158        function render( items, elements, visibility, selected, mode, sortState ) {
    218159                var cols = visibleColumns( items, visibility, mode );
    … …  
    231172                                var dir = sortState.by === col.key ? sortState.dir : null;
    232173                                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>';
    237178                } ).join( '' );
    238179
    … …  
    249190                                        return '<td class="sbnfebr-col-' + col.key + '">' + badgeCellHTML( col, item ) + '</td>';
    250191                                }
    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>';
    252197                        } ).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>';
    254202                } ).join( '' );
     203                elements.table.classList.toggle( 'sbnfebr-mobile-selection-active', selected.size > 0 );
    255204
    256205                var hasItems = items.length > 0;
    … …  
    259208        }
    260209
    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. */
    269211        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
    364235        function actionButtonsHTML( item ) {
    365236                var stateClass = '';
    … …  
    379250                var draftBtn = quickActionIconsHTML( item );
    380251
    381                 // "Ignored" icon — only appears when the item is already ignored
    382                 // (clean row otherwise), click undoes it. Right of the price
    383252                // history icon, same cell.
    384253                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. */
    52(function () {
    63        'use strict';
    74
    85        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                } } ) );
    1120        }
    1221
    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 } } ) );
    2824        }
    2925
    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 ); }
    185729        } );
    185830
    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 );
    186433        } );
    186534
    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 );
    187137        } );
    187238
    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        };
    189242})();
  • 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    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    1410        var _overlay = null;
    1511        var _notes = [];
    16         // CNPJs of expanded supplier groups. Empty by default (all
    17         // collapsed); an active search forces everything open (see
    18         // renderList()) without touching this Set, so manual state
    1912        // returns once the search is cleared.
    2013        var _expandedSuppliers = new Set();
    … …  
    4033        }
    4134
    42         /**
    43          * Authorization protocol status badge (note's cStat). Empty when the
    44          * 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          */
    5135        function protocolBadge( status, message ) {
    5236                if ( ! status ) {
    … …  
    6852        }
    6953
    70         /* ============================================================
    71          * Overlay principal — construção (uma vez)
    72          * ========================================================== */
    7354
    7455        function ensureOverlay() {
    … …  
    120101        }
    121102
    122         /* ============================================================
    123          * Carregamento / lista, agrupada por fornecedor
    124          * ========================================================== */
    125103
    126104        function loadNotes() {
    … …  
    165143
    166144                var groups = groupBySupplier( filtered );
    167                 // An active search forces all groups open so filtered results
    168                 // aren't hidden inside a collapsed one; doesn't touch the
    169                 // manual expansion state, just ignores it while `q` is set.
    170145                var forceOpen = !! q;
    171146
    … …  
    215190        }
    216191
    217         /* ============================================================
    218          * Destructive confirm — type "DELETE" to proceed.
    219          * ========================================================== */
    220192
    221193        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 REST
    3    endpoint (sbnfebr/v1/library/suppliers).
    4    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    2319        }
    2420
    25         /* ============================================================
    26          * Overlay — construção (uma vez)
    27          * ========================================================== */
    2821
    2922        function ensureOverlay() {
    … …  
    6457        }
    6558
    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 from
    72          *                               loaded data, since the grid only knows CNPJ, not
    73          *                               term ID). If none is registered yet, opens the
    74          *                               creation form with the document pre-filled.
    75          * }
    76          */
    7759        function openLibrary( opts ) {
    7860                ensureOverlay();
    … …  
    9274                                        return;
    9375                                }
    94                                 // Supplier not registered yet — pulls the latest snapshot
    95                                 // captured from an imported note with this CNPJ (name, IE,
    96                                 // phone, address) so the user doesn't retype what the XML
    9776                                // already provided.
    9877                                SB.api( 'suppliers/' + digits + '/snapshot' )
    … …  
    11594        }
    11695
    117         /* ============================================================
    118          * Carregamento / lista
    119          * ========================================================== */
    12096
    12197        function loadTerms() {
    … …  
    145121                }
    146122
    147                 // Three groups: has an active note right now / registered with a WC
    148                 // product catalog but no note (candidate for future GTIN match) /
    149123                // registered with neither.
    150124                var withNote    = [];
    … …  
    230204                body.querySelectorAll( '.sb-library-row--filterable' ).forEach( function ( row ) {
    231205                        row.addEventListener( 'click', function ( e ) {
    232                                 // Name keeps its own dblclick-to-edit behavior — only the
    233                                 // row's empty space and its badge act as the filter target.
    234206                                if ( e.target.closest( '.sb-library-name, .sb-library-row-actions' ) ) {
    235207                                        return;
    … …  
    255227        }
    256228
    257         /* ============================================================
    258          * Formulário (compartilhado entre editar e criar)
    259          * ========================================================== */
    260229
    261230        function field( cls, label, value, type, placeholder ) {
    … …  
    282251                        + field( 'sb-sup-f-city', __( 'Cidade', 'sanbar-express-nfe-xml-import-br' ), t.city )
    283252                        + 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 a
    285                         // legal entity name, product/brand commonly known by another
    286                         // name). Deliberately not --wide: falls into the grid's right
    287                         // column, same row as State. Keeps the same label+content
    288                         // skeleton as the other fields (empty label of equal size) so
    289                         // it inherits the same label+gap height as State, keeping the
    290                         // checkbox+input row aligned with State's input. Input is
    291                         // disabled when unchecked (toggled in the wire function, not
    292253                        // here — this only builds the initial HTML).
    293254                        + '<div class="sb-library-sup-field sb-library-sup-field--nickname">' +
    … …  
    331292        }
    332293
    333         /**
    334          * Auto-suggests the Code field: 5 letters from the name + 5 digits
    335          * from the document. Stops updating once the user edits Code by hand.
    336          */
    337294        function wireSupplierFormAutosuggest( container, initialCodeSuggested ) {
    338295                var nameInp = container.querySelector( '.sb-sup-f-name' );
    … …  
    357314                codeInp.addEventListener( 'input', function () { codeManuallyEdited = true; } );
    358315
    359                 // Runs once on form open: pre-filled values are set directly via
    360                 // HTML without firing "input", so without this Code would stay
    361316                // empty until the user typed something.
    362317                updateSuggestion();
    363318        }
    364319
    365         /**
    366          * Ties the "Show nickname" checkbox to the nickname input's disabled
    367          * state — unchecked disables the input but keeps its saved value.
    368          */
    369320        function wireNicknameToggle( container ) {
    370321                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    ================================================================ */
    41(function () {
    52        'use strict';
    … …  
    3431                lastItems: [], selected: new Set(),
    3532                page: 1, perPage: loadPerPage(), totalPages: 1,
    36                 // 'note' (default, 1 row per line item) | 'product' (1 row per
    3733                // identity, aggregated — GET /items/by-product).
    3834                viewMode: 'note',
    39                 // Column sort (Supplier/Description only, see COLS/PRODUCT_COLS
    40                 // in nfebr-grid.js). sortBy=null = default order (note date).
    4135                sortBy: null, sortDir: 'asc'
    4236        };
    4337        var searchTimer = null;
     38        var ignoredCountRequest = 0;
    4439
    4540        function q( id ) {
    … …  
    5045        var NOTICE_AUTOHIDE_MS = 5000;
    5146
    52         /**
    53          * Icon glossary — icon + short phrase, grouped. "(Plus)" on lines
    54          * only active in Plus is informational text, not a feature switch.
    55          *
    56          * @return {Array} [{ group: string }|{ icon, text }]
    57          */
    5847        function glossaryEntries() {
    5948                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' ) },
    6955                        { 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' ) },
    7356                        { group: __( 'Histórico de preço', 'sanbar-express-nfe-xml-import-br' ) },
    7457                        { icon: '🕘', text: __( 'Cinza — sem variação de preço entre notas.', 'sanbar-express-nfe-xml-import-br' ) },
    … …  
    11598                els.notice.style.display = '';
    11699
    117                 // Always auto-dismisses, even on error — same pattern as the
    118                 // SanBar EXPress Sheet notification bar (sheet-notifications.js).
    119100                noticeTimer = window.setTimeout( hideNotice, NOTICE_AUTOHIDE_MS );
    120101        }
    121102
    122         /**
    123          * Builds the "Open in Store Manager" action, if detectable — null
    124          * when the SM doesn't exist (SB.sm_admin_url empty), so the caller
    125          * simply doesn't offer the option.
    126          *
    127          * @param {number[]} productIds
    128          * @return {{label:string, onClick:Function}|null}
    129          */
    130103        function buildOpenInSmAction( productIds ) {
    131                 var inIframe = window.parent !== window;
    132                 if ( ! inIframe && ! SB.sm_admin_url ) {
     104                if ( ! SB.sm_admin_url ) {
    133105                        return null;
    134106                }
    … …  
    136108                        label: __( 'Abrir no Store Manager', 'sanbar-express-nfe-xml-import-br' ),
    137109                        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' );
    152112                                hideNotice();
    153113                        }
    … …  
    155115        }
    156116
    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 ) {
    165126                        return null;
    166127                }
    167128                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 + ')',
    169132                        onClick: function () {
    170                                 window.location.href = SB.fc_url + '&sbfcbr_ids=' + productIds.join( ',' );
     133                                urls.forEach( function ( url ) { window.open( url, '_blank' ); } );
     134                                hideNotice();
    171135                        }
    172136                };
    … …  
    178142        }
    179143
    180         /**
    181          * Notice with action buttons. Doesn't auto-dismiss — there's an
    182          * action to take, unlike the plain success/error notice.
    183          *
    184          * @param {string} message
    185          * @param {Array<{label:string, onClick:Function}>} actions
    186          */
    187144        function showActionNotice( message, actions ) {
    188145                window.clearTimeout( noticeTimer );
    … …  
    207164        }
    208165
    209         /**
    210          * Shows a progress bar inside the notice area — used during XML
    211          * upload (1 or several files).
    212          *
    213          * @param {number} current Current file (1-based).
    214          * @param {number} total   Total files.
    215          */
    216166        function showProgress( current, total ) {
    217167                window.clearTimeout( noticeTimer );
    … …  
    224174        }
    225175
    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          */
    231176        function reloadItems( resetPage ) {
    232177                if ( false !== resetPage ) {
    … …  
    247192                        params.note_id = state.noteId;
    248193                }
    249                 // Mode/period also filter the per-product view; 'duplicates' and
    250                 // 'ignored' are excluded (updateViewToggle() prevents selecting them).
    251194                if ( state.mode ) {
    252195                        params.mode = state.mode;
    … …  
    268211                        state.totalPages = res.total_pages || 1;
    269212                        renderGrid();
    270                         notifySelectionChanged();
     213                        if ( SB.is_plus && 'function' === typeof notifySelectionChanged ) {
     214                                notifySelectionChanged();
     215                        }
    271216                        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
    275219                        // changes meaning when the view toggle changes.
    276220                        var countParams = { count_only: 1 };
    … …  
    313257
    314258                        if ( isProductView ) {
    315                                 // get_items_by_product() doesn't compute price_variants/
    316                                 // gtin_supplier_count, so checkMatches() is skipped here.
    317259                                return;
    318260                        }
    319261
    320                         // Runs on every page/filter change so a match against an
    321                         // already-registered GTIN shows without a manual click.
    322262                        checkMatches();
    323263                } );
    324264        }
    325265
    326         /**
    327          * Fetches ALL items matching the current filters, ignoring the
    328          * grid's page — caps at 500 and warns instead of locking up the
    329          * screen on a huge catalog.
    330          *
    331          * @return {Promise<{items: Array, truncated: boolean}>}
    332          */
    333266        function fetchAllItemsForCheck() {
    334267                var CAP = 500;
    … …  
    373306        }
    374307
    375         /**
    376          * Updates the pagination controls' text/state — "◀ Page X of N ▶"
    377          * pattern.
    378          */
    379308        function updatePaginationUI() {
    380309                if ( ! els.pageLabel ) {
    … …  
    386315        }
    387316
    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
    400353        function applyLinkToIdentity( identity, productId, hasFiscal, list ) {
    401354                var gtin = String( identity.gtin || '' ).trim().toUpperCase();
    … …  
    415368                                it.match_product_name = null;
    416369                                it.match_source = null;
    417                                 // Only "upgrades" (never downgrades) — if the backend
    418                                 // already had fiscal data recorded, a link/sync without
    419                                 // fiscal (Lite) doesn't clear this local state. Mirrors the
    420                                 // item's own NCM (not just a truthy sentinel) so the grid's
    421                                 // stale-vs-synced comparison (linked_ncm === ncm) is correct
    422370                                // right after this sync, without a reload.
    423371                                if ( hasFiscal ) {
    … …  
    435383        SB.applyLinkToIdentity = applyLinkToIdentity;
    436384
    437         /**
    438          * Clears every local reference (link or match candidate) to a product
    439          * that turned out not to exist anymore. Local state only — the backend
    440          * already cleared the link when it answered 404.
    441          *
    442          * @param {number}   productId
    443          * @param {Object[]} [list] Defaults to state.lastItems.
    444          * @return {string[]} IDs of the updated items.
    445          */
    446385        function clearMissingProduct( productId, list ) {
    447386                var touchedIds = [];
    … …  
    471410        SB.clearMissingProduct = clearMissingProduct;
    472411
    473         /**
    474          * Finds an item by id — first in the grid's current page
    475          * (state.lastItems), then in the Registry check modal, which loads up to
    476          * 500 items independently of the grid's pagination.
    477          *
    478          * @param {string|number} itemId
    479          * @return {Object|null}
    480          */
    481412        function findItemById( itemId ) {
    482413                var id = String( itemId );
    … …  
    488419        }
    489420
    490         /**
    491          * Temporary highlight (green, self-clearing) on the row(s) that
    492          * just changed (`.sbnfebr-row-just-linked`, see core.css).
    493          *
    494          * @param {string[]} itemIds
    495          */
    496421        function flashRows( itemIds ) {
    497422                if ( ! itemIds || ! itemIds.length || ! els.tbody ) {
    … …  
    505430                        }
    506431                        row.classList.remove( 'sbnfebr-row-just-linked' );
    507                         // Force reflow — without this, removing+adding the class in
    508432                        // the same tick doesn't restart the CSS animation.
    509433                        void row.offsetWidth;
    … …  
    515439        }
    516440
    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
    522443        function renderGrid() {
    523444                // "Show only selected" — local filter, doesn't touch
    524                 // state.lastItems itself (would otherwise lose the page's other
    525445                // items when the filter is turned off).
    526446                var itemsToRender = showOnlySelected
    … …  
    537457        }
    538458
    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 ) {
    618464                                return;
    619465                        }
    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' );
    673471                                } );
    674472                } );
    675473        }
    676474
    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 is
    709         // 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_plus
    740                                 ? __( '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 of
    745                         // 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: confirmOut
    769                         } ).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 real
    781                 // 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 filter
    793                                         // 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.origin
    800                                                 );
    801                                         }
    802 
    803                                         // Surfaces when SKU=GTIN didn't apply for some items
    804                                         // (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, both
    874          * editions), then a supplier+code fallback (POST /match-supplier-key,
    875          * Plus only — Lite has no UI to act on that match).
    876          */
    877475        function checkMatches() {
    878476                var pending = state.lastItems.filter( function ( item ) {
    … …  
    892490                                                        item.match_product_name = match.name;
    893491                                                        item.match_source = 'gtin';
    894                                                         // 'unit'|'box' — which of the Sheet's GTIN fields matched.
    895492                                                        item.match_field = match.field || 'unit';
    896493                                                }
    … …  
    932529                                } )
    933530                                .catch( function () {
    934                                         // A check failure shouldn't lock up the screen — grid
    935                                         // stays in its previous state, no error notice (not an
    936531                                        // explicit user action, just a silent refinement).
    937532                                        renderGrid();
    … …  
    940535        }
    941536
    942         /**
    943          * Reloads the distinct supplier count (stat) — independent of the
    944          * active filter, it's a global count.
    945          */
    946537        function reloadSupplierStat( suppliers ) {
    947538                els.statSuppliers.textContent = String( suppliers.length );
    … …  
    963554        }
    964555
    965         /**
    966          * Populates the note select, filtered (or not) by supplier.
    967          */
    968556        function reloadNotes() {
    969557                var params = state.supplierCnpj ? { supplier_cnpj: state.supplierCnpj } : {};
    … …  
    977565                                } ).join( '' );
    978566
    979                         // Preserves the selection if the note still exists, else
    980                         // falls back to "All notes" — and keeps state.noteId in sync.
    981567                        var stillExists = notes.some( function ( n ) { return String( n.id ) === current; } );
    982568                        els.filterNote.value = stillExists ? current : '';
    … …  
    992578        }
    993579
    994         /**
    995          * Uploads 1 XML file to the given endpoint (actual import or just a
    996          * 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          */
    1002580        function uploadTo( file, endpoint ) {
    1003581                var form = new FormData();
    … …  
    1018596        }
    1019597
    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          */
    1026598        function uploadOne( file ) {
    1027599                return uploadTo( file, 'import' )
    … …  
    1034606        }
    1035607
    1036         /**
    1037          * Toggles the "importing" visual state on the upload buttons —
    1038          * disables them (avoids a double click mid-processing) and swaps the
    1039          * 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          */
    1045608        function setUploadingState( active, current, total ) {
    1046609                [ els.btnUpload, els.btnUploadEmpty ].forEach( function ( btn ) {
    … …  
    1065628        }
    1066629
    1067         /**
    1068          * Imports the files — called only after the user confirms the
    1069          * preview summary.
    1070          *
    1071          * @param {FileList|File[]} files Files already confirmed by the user.
    1072          */
    1073630        function doImport( files ) {
    1074631                var list = Array.prototype.slice.call( files );
    … …  
    1110667                        }
    1111668
    1112                         // Any failure shows in red, even with partial success —
    1113                         // better to highlight what needs attention than hide it
    1114669                        // behind a green "all good" notice.
    1115670                        showNotice( lines.join( ' ' ), errList.length ? 'error' : 'success' );
    … …  
    1121676                        refreshAll();
    1122677
    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.
    1125679                        var importedNoteIds = okList.map( function ( o ) { return o.result.note_id; } ).filter( Boolean );
    1126680                        if ( importedNoteIds.length ) {
    … …  
    1142696        }
    1143697
    1144         /**
    1145          * Shows the preview summary and only calls doImport() if the user
    1146          * explicitly confirms — never window.confirm(). The real warning is
    1147          * `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          */
    1152698        function openImportConfirm( file, preview ) {
    1153699                var backdrop = document.createElement( 'div' );
    1154700                backdrop.className = 'sbnfebr-danger-backdrop';
    1155701
    1156                 // Same title+detail pattern as the item modal: SB.alertCard()
    1157                 // instead of one sentence mixing everything together.
    1158702                var warnings = '';
    1159703                if ( preview.already_imported ) {
    … …  
    1175719                                + '</div>';
    1176720                }
    1177                 // Doesn't block, just asks for an extra check before confirming
    1178721                // (the actual blocking cap is much higher — see
    1179722                // SBNFEBR_Xml_Parser_Service::MAX_ITEMS).
    … …  
    1222765        }
    1223766
    1224         /**
    1225          * Upload entry point: always goes through the preview before writing
    1226          * anything — never imports directly on the first click.
    1227          *
    1228          * @param {File} file File selected in the input.
    1229          */
    1230767        function startImportFlow( file ) {
    1231768                setUploadingState( true, 1, 1 );
    … …  
    1247784        }
    1248785
    1249         /**
    1250          * One field of the "Company data" form — same visual layout as the
    1251          * Suppliers form (.sb-library-sup-field), reused here to stay
    1252          * 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          */
    1259786        function companyField( cls, label, value ) {
    1260787                return '<div class="sb-library-sup-field"><label>' + SB.esc( label ) + '</label>'
    … …  
    1262789        }
    1263790
    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} titleText
    1269          * @param {string} bodyHtml
    1270          * @param {string} saveLabel
    1271          * @param {string} [extraClass] Extra class on the modal (e.g. narrower hub layout).
    1272          * @return {{backdrop: HTMLElement, close: Function}}
    1273          */
    1274791        function openSettingsModal( titleText, bodyHtml, saveLabel, extraClass ) {
    1275792                var backdrop = document.createElement( 'div' );
    … …  
    1285802                        '</div>';
    1286803                document.body.appendChild( backdrop );
     804                document.body.classList.add( 'sbnfebr-settings-modal-open' );
    1287805
    1288806                function close() {
    1289807                        backdrop.remove();
     808                        if ( ! document.querySelector( '.sbnfebr-configure-modal' ) ) {
     809                                document.body.classList.remove( 'sbnfebr-settings-modal-open' );
     810                        }
    1290811                }
    1291812                backdrop.querySelector( '.sbnfebr-danger-cancel' ).addEventListener( 'click', close );
    … …  
    1299820        }
    1300821
    1301         /**
    1302          * Shows a save error inline in a settings sub-modal, above the
    1303          * Cancel/Save row.
    1304          *
    1305          * @param {HTMLElement} backdrop
    1306          * @param {string}      message
    1307          */
    1308822        function showSettingsError( backdrop, message ) {
    1309823                var existing = backdrop.querySelector( '.sbnfebr-danger-error' );
    … …  
    1317831        }
    1318832
    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
    1323882        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
    1356981        function companyRegimeBadgeHtml( taxRegime ) {
    1357982                var tr = taxRegime || { configured: false, label: '' };
    … …  
    1363988        }
    1364989
    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 
    1429990        /**
    1430991         * Error log verbosity level.
    1431992         */
    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
    1466994        function refreshSupplierInfoBtn() {
    1467995                if ( ! els.btnSupplierInfo ) {
    … …  
    15021030                }
    15031031
    1504                 // After creating/editing/removing in the modal, the "!" icon's
    15051032                // status may have changed — rechecks on close.
    15061033                document.addEventListener( 'sbnfebr:library-closed', refreshSupplierInfoBtn );
    15071034
    1508                 // "🔎" in the Suppliers Library — jumps the main grid to this
    1509                 // supplier's items. Only offered for suppliers with an active note,
    1510                 // so the CNPJ is always present in the filter's own options.
    15111035                document.addEventListener( 'sbnfebr:library-filter-supplier', function ( e ) {
    15121036                        var digits = ( ( e.detail && e.detail.document ) || '' ).replace( /\D/g, '' );
    … …  
    15371061                }
    15381062
    1539                 if ( els.btnConfigure ) {
    1540                         els.btnConfigure.addEventListener( 'click', openConfigure );
     1063                if ( els.btnSettings ) {
     1064                        els.btnSettings.addEventListener( 'click', openConfigure );
    15411065                }
    15421066
    … …  
    15461070                }
    15471071
    1548                 // Delegated on the header <tr> (recreated on every renderGrid()).
    1549                 // 3 states per click: no sort -> asc -> desc -> no sort again.
    15501072                if ( els.theadRow ) {
    15511073                        els.theadRow.addEventListener( 'click', function ( e ) {
    … …  
    15691091                }
    15701092
    1571                 // Fetches all items matching current filters, ignoring pagination, capped at 500.
    15721093                if ( els.btnCheckMatch && SB.registryCheck ) {
    15731094                        els.btnCheckMatch.addEventListener( 'click', function () {
     1095                                if ( SB.importPrompt && state.noteId ) {
     1096                                        SB.importPrompt.open( state.noteId );
     1097                                        return;
     1098                                }
    15741099                                els.btnCheckMatch.disabled = true;
    15751100                                fetchAllItemsForCheck().then( function ( result ) {
    … …  
    15821107                                        }
    15831108                                        // Explicit subtitle='' — clears any "note N/S" left
    1584                                         // over from a previous post-import auto-open in the same session.
    15851109                                        SB.registryCheck.open( result.items, '' );
    15861110                                } ).catch( function () {
    … …  
    15901114                }
    15911115
    1592                 // After creating 1 product, offers "Open in editor" + "Open in
    1593                 // Store Manager" (if detectable) instead of opening on its own.
    15941116                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 || [];
    15971127                        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 );
    16091131                        if ( smAction ) {
    16101132                                actions.push( smAction );
    16111133                        }
    16121134                        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
    16191144                document.addEventListener( 'sbnfebr:notes-changed', refreshAll );
    16201145
    1621                 // Auto-opens the Registry Check right after importing, filtered
    1622                 // to this note's items — only if there's at least 1 match.
    16231146                document.addEventListener( 'sbnfebr:notes-imported', function ( e ) {
    1624                         if ( ! SB.registryCheck ) {
     1147                        if ( ! SB.registryCheck || SB.importPrompt ) {
    16251148                                return;
    16261149                        }
    16271150                        ( e.detail.noteIds || [] ).forEach( function ( noteId ) {
    1628                                 // per_page caps at 100 (get_items()) — a note with more
    16291151                                // items only has its 1st page checked here.
    16301152                                SB.api( 'items', { note_id: noteId, per_page: 100 } ).then( function ( res ) {
    … …  
    16701192                } );
    16711193
    1672                 // nfebr-item-actions.js doesn't store the items (main.js holds
    1673                 // state.lastItems) — resolves the requested item and hands it
    16741194                // back to open the modal.
    16751195                document.addEventListener( 'sbnfebr:open-item-action', function ( e ) {
    … …  
    16821202                } );
    16831203
    1684                 // Same pattern as above, for the group of 4 quick-action icons
    1685                 // (stock/price/fiscal/draft-link) in the grid row itself,
    16861204                // without opening the full modal.
    16871205                document.addEventListener( 'sbnfebr:quick-action', function ( e ) {
    … …  
    16941212                } );
    16951213
    1696                 // Item gained (or changed) a linked product via Make Draft/Link/
    1697                 // Sync — updates local state without reloading from the REST API.
    16981214                document.addEventListener( 'sbnfebr:item-linked', function ( e ) {
    1699                         // Identity comes in the event itself — doesn't depend on
    1700                         // finding the clicked row in state.lastItems first (it might
    1701                         // not be in the current view, filtered by supplier/note).
    17021215                        var touchedIds = applyLinkToIdentity( e.detail, e.detail.productId, !! e.detail.hasFiscal );
    17031216                        renderGrid();
    … …  
    17051218                } );
    17061219
    1707                 // "Unlink" — clears the item's local state, without reloading
    1708                 // from the REST API. Reappears as pending (📦) or a match (if
    1709                 // checkMatches() runs again — doesn't run on its own here, the
    17101220                // user can click "Check registry").
    17111221                document.addEventListener( 'sbnfebr:item-unlinked', function ( e ) {
    … …  
    17151225                } );
    17161226
    1717                 // A product the UI still had linked/matched turned out not to exist
    1718                 // anymore (deleted elsewhere while this screen stayed open).
    17191227                document.addEventListener( 'sbnfebr:product-missing', function ( e ) {
    17201228                        var touchedIds = clearMissingProduct( e.detail.productId );
    … …  
    17231231                } );
    17241232
    1725                 // "Accept new GTIN": every item linked to that product stops being
    1726                 // flagged as changed (the backend rewrote all their baselines).
    17271233                document.addEventListener( 'sbnfebr:link-snapshot-accepted', function ( e ) {
    17281234                        var pid = String( e.detail.productId );
    … …  
    17361242                } );
    17371243
    1738                 // GTIN couldn't become the SKU because another product already uses that value.
    17391244                document.addEventListener( 'sbnfebr:sku-conflict', function () {
    17401245                        showNotice( __( 'O GTIN não pôde virar SKU — outro produto já usa esse SKU.', 'sanbar-express-nfe-xml-import-br' ), 'error' );
    17411246                } );
    17421247
    1743                 // Generic — other modules that don't have access to showNotice
    1744                 // (local to this file, not exposed on SB) fire this to request
    17451248                // an error notice without duplicating the notice UI.
    17461249                document.addEventListener( 'sbnfebr:api-error', function ( e ) {
    17471250                        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 );
    17481255                } );
    17491256
    … …  
    17641271                }
    17651272
    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 ) {
    17691279                                var needsDates = 'price_period' === state.mode || 'notes_period' === state.mode;
    17701280                                els.filterDates.style.display = needsDates ? '' : 'none';
    … …  
    17751285                                        els.filterDateTo.value = '';
    17761286                                }
    1777                                 reloadItems();
     1287                        }
     1288                        updateIgnoredDrawer();
     1289                        reloadItems();
     1290                };
     1291
     1292                if ( els.filterMode ) {
     1293                        els.filterMode.addEventListener( 'change', function () {
     1294                                applyEntryMode( els.filterMode.value );
    17781295                        } );
    17791296                }
    … …  
    18281345                } );
    18291346
    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                  */
    18351347                function updateViewToggle() {
    18361348                        var isProductView = 'product' === state.viewMode;
    … …  
    18761388                }
    18771389
     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
    18781401                if ( els.btnViewNote || els.btnViewProduct ) {
    18791402                        updateViewToggle();
    … …  
    18881411                var triggerUpload = function () { els.fileInput.click(); };
    18891412                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                }
    18901447                if ( els.btnUploadEmpty ) {
    18911448                        els.btnUploadEmpty.addEventListener( 'click', triggerUpload );
    … …  
    19091466                        btnNotesManager: q( 'sbnfebr-btn-notes-manager' ),
    19101467                        btnCheckMatch: q( 'sbnfebr-btn-check-match' ),
    1911                         btnConfigure: q( 'sbnfebr-btn-cols' ),
     1468                        btnSettings: q( 'sbnfebr-btn-settings' ),
    19121469                        btnClearFilters: q( 'sbnfebr-btn-clear-filters' ),
    19131470                        btnViewNote: q( 'sbnfebr-btn-view-note' ),
    … …  
    19301487                        statNotes: q( 'sbnfebr-stat-notes' ),
    19311488                        statSuppliers: q( 'sbnfebr-stat-suppliers' ),
     1489                        btnIgnoredDrawer: q( 'sbnfebr-btn-ignored-drawer' ),
     1490                        statIgnored: q( 'sbnfebr-stat-ignored' ),
    19321491                        pagePrev: q( 'sbnfebr-page-prev' ),
    19331492                        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    ================================================================ */
    41(function () {
    52        'use strict';
    … …  
    2017        }
    2118
    22         // modFrete — standard XML code, 0-4 and 9 (layout 4.00).
    2319        function freightByLabel( code ) {
    2420                var map = {
    … …  
    133129                }
    134130
    135                 // Payment method — can have more than one (split payment), same
    136131                // table layout as installments.
    137132                var paymentsHtml = '';
    … …  
    158153                }
    159154
    160                 // Additional information — free text from the supplier, can be long.
    161155                var additionalInfoHtml = '';
    162156                if ( n.additional_info ) {
    … …  
    167161                }
    168162
    169                 // Purpose only shown when different from Normal, to avoid
    170163                // cluttering the header in the common case.
    171164                var purposeHtml = ( n.nfe_purpose && '1' !== String( n.nfe_purpose ) )
    … …  
    194187        }
    195188
    196         /**
    197          * Opens the modal for a specific note.
    198          *
    199          * @param {number} noteId
    200          * @return {void}
    201          */
    202189        function open( noteId ) {
    203190                if ( ! noteId ) {
    … …  
    226213                        } );
    227214                } ).catch( function ( e ) {
    228                         // showNotice isn't exposed on the SB namespace, so dispatch
    229                         // an event that nfebr-main.js listens for and renders.
    230215                        document.dispatchEvent( new CustomEvent( 'sbnfebr:api-error', {
    231216                                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 across
    3    notes from the same supplier, sorted by date.
    4    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    4339        }
    4440
    45         /**
    46          * Rounds to 2 decimals — trend must compare the displayed value,
    47          * not raw XML precision, or equal-looking prices could show a
    48          * false trend arrow.
    49          */
    5041        function round2( v ) {
    5142                return Math.round( Number( v ) * 100 ) / 100;
    5243        }
    5344
    54         /**
    55          * Builds one history table. `rows` must be ASC by date so the trend
    56          * arrow compares each row to its true predecessor; display order is
    57          * 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          */
    6345        function buildTableHTML( rows, withSupplier ) {
    6446                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: pending
    3    items matched against the WooCommerce catalog by GTIN.
    4    ================================================================ */
    51(function () {
    62        'use strict';
    … …  
    1511        var _lastItems = null;
    1612        var _lastSubtitle = '';
    17         // Client-side sort (Supplier/Name) — data is already fully loaded,
    18         // no need to re-query the backend. _lastCandidates/_lastMatches
    19         // hold the last render() so re-sorting skips the catalog search.
    2013        var _sortBy = null;
    2114        var _sortDir = 'asc';
    … …  
    5750
    5851                ov.querySelector( '.sb-library-close' ).addEventListener( 'click', close );
    59                 // Delegated once (overlay is created only on first open, see
    60                 // _overlay cache above), so it covers the sort buttons even
    6152                // after render() recreates the innerHTML.
    6253                ov.addEventListener( 'click', function ( e ) {
    … …  
    9889        }
    9990
    100         /**
    101          * Opens the modal and runs the cross-check over `items` (same shape
    102          * as state.lastItems — whatever is already loaded in the grid at
    103          * click time, not a fresh full fetch from the DB).
    104          *
    105          * @param {Array}  items
    106          * @param {string} [subtitle] "note N/S · SUPPLIER" on the post-import
    107          *                 auto-open; empty when opened manually.
    108          */
    10991        function open( items, subtitle ) {
    11092                _lastItems = items;
    111                 // undefined (not passed) preserves the active subtitle — this is
    112                 // how maybeRefresh() calls back in after an action applies,
    113                 // without losing the "note N/S · SUPPLIER" from the auto-open.
    11493                _lastSubtitle = undefined === subtitle ? _lastSubtitle : subtitle;
    11594                ensureOverlay();
    … …  
    121100                var body = document.getElementById( 'sbnfebr-regcheck-body' );
    122101
    123                 // Only pending items (no product yet) with a real GTIN —
    124                 // nothing to match without one (supplier+code out of scope).
    125102                var candidates = ( items || [] ).filter( function ( it ) {
    126103                        var gtin = String( it.gtin || '' ).trim().toUpperCase();
    … …  
    146123        }
    147124
    148         /**
    149          * Sort button matching the main grid's (▲/▼/⇅), reused for the
    150          * "Name"/"Supplier" headers.
    151          *
    152          * @param {string} key   'description'|'supplier_name'.
    153          * @param {string} label
    154          * @return {string}
    155          */
    156125        function sortHeaderHtml( key, label ) {
    157126                var dir = _sortBy === key ? _sortDir : null;
    … …  
    221190        }
    222191
    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>';
    268211        }
    269212
    … …  
    277220                return '<div class="sbnfebr-regcheck-row">' +
    278221                        '<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>' +
    284227                        '</div>' +
    285228                        '<div class="sbnfebr-regcheck-divider">→</div>' +
    286229                        '<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>' +
    292235                        '</div>' +
    293236                        '<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 ) +
    301239                        '</div>' +
    302240                '</div>';
    … …  
    304242
    305243        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 ) {
    310245                        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                                } } ) );
    315253                        } );
    316254                } );
    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
    338257        function maybeRefresh() {
    339258                if ( _overlay && _overlay.classList.contains( 'open' ) && _lastItems ) {
    … …  
    342261        }
    343262
    344         /**
    345          * Item lookup for nfebr-main.js — this modal loads up to 500 items
    346          * independently of the grid's pagination, so its items are often
    347          * outside state.lastItems.
    348          *
    349          * @param {string|number} itemId
    350          * @return {Object|null}
    351          */
    352263        function getItem( itemId ) {
    353264                var id = String( itemId );
    … …  
    355266        }
    356267
    357         // _lastItems is a separate copy from the grid's state.lastItems, so link
    358         // changes applied there (nfebr-main.js) never reach it — without this,
    359268        // a just-linked item stayed listed as pending here.
    360269        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 own
    3    screen; opens this plugin in an isolated iframe modal.
    4    ================================================================ */
    51(function () {
    62    'use strict';
    … …  
    128    if (!window.SBNFEBR_BRIDGE || !window.SBNFEBR_BRIDGE.modal_url) return;
    139
    14     // Appends the NF-e plugin's version next to the Sheet's own version
    15     // tag (e.g. "v<sheet> / NF-e v<own>"). Retried independently of the button.
    1610    function injectVersionTag() {
    1711        if (document.getElementById('sbnfebr-version-tag')) return true; // already injected
    … …  
    3630        btn.title = __( 'Importar XML de NF-e', 'sanbar-express-nfe-xml-import-br' );
    3731        btn.textContent = '📄 ' + __( 'XML Import', 'sanbar-express-nfe-xml-import-br' );
    38         // Amber outline just signals the installed edition (Plus) —
    3932        // same button, text, and icon otherwise.
    4033        if (window.SBNFEBR_BRIDGE.is_plus) {
    … …  
    5851        document.body.appendChild(overlay);
    5952
    60         // Closing is deliberately X-only — clicking outside or pressing
    61         // Esc does NOT close, to avoid losing in-progress import work
    6253        // to an accidental click/keypress.
    6354        overlay.querySelector('.sbnfebr-bridge-close').addEventListener('click', function () {
    … …  
    6657    }
    6758
    68     // The iframe notifies this page of new product IDs via postMessage;
    69     // e.origin is checked to only accept same-origin messages.
    7059    window.addEventListener('message', function (e) {
    7160        if (e.origin !== window.location.origin) return;
    … …  
    8473    });
    8574
    86     // Execution order between plugins' scripts isn't guaranteed —
    8775    // retries up to 20x (4s) before giving up silently.
    8876    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    ================================================================ */
    41(function () {
    52        'use strict';
    … …  
    2421        }
    2522
    26         /**
    27          * Starts a progress toast, visible only if still running after
    28          * 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          */
    3423        function start( label ) {
    3524                var id = 'sbnfebr-toast-' + ( ++seq );
    … …  
    8170        }
    8271
    83         /**
    84          * Confirmation toast — unlike start(), always appears immediately
    85          * (no 300ms delay, since this is a deliberate confirmation rather
    86          * 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          */
    9272        function success( message, durationMs ) {
    9373                var el = document.createElement( 'div' );
    … …  
    10787        }
    10888
    109         /**
    110          * Error toast — same pattern as success(), red, longer on screen.
    111          * Fallback used by showError() when there's no modal to anchor
    112          * an inline error to.
    113          *
    114          * @param {string} message Ready to display.
    115          * @param {number} [durationMs] Default 4000.
    116          */
    11789        function error( message, durationMs ) {
    11890                var el = document.createElement( 'div' );
  • sanbar-express-nfe-xml-import-br/trunk/includes/class-sbnfebr-admin.php

    r3725460 r3782421  
    11<?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 SB
    7  *     Softwares Hub is active, own top-level menu otherwise)
    8  *   - Enqueue CSS + JS
    9  *   - Render the screen's HTML shell (supplier -> notes -> grid)
    10  *
    11  * @package SBNFEBR
    12  * @since   0.1.0
    13  */
    142
    153defined( 'ABSPATH' ) || exit;
    164
    175if ( ! function_exists( 'sbnfebr_sb_parent_menu_exists' ) ) {
    18         /**
    19          * Checks whether the "sb-softwares" parent menu is already registered
    20          * (typically by the SB Softwares Hub plugin).
    21          *
    22          * @return bool
    23          */
    246        function sbnfebr_sb_parent_menu_exists() {
    257                global $menu;
    … …  
    5335        }
    5436
    55         /**
    56          * Adds a dedicated body class on this plugin's screen, so shell CSS can
    57          * neutralize WP chrome without affecting the rest of admin.
    58          *
    59          * @param string $classes Existing classes.
    60          * @return string
    61          */
    6237        public static function body_class( $classes ) {
    6338                $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() ) {
    6540                        $classes .= ' sbnfebr-fullscreen';
    6641                }
    … …  
    6843        }
    6944
    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
    80117        public static function register_menu() {
    81118                if ( sbnfebr_sb_parent_menu_exists() ) {
    82                         // Dentro do hub "SB Softwares" o "SB" já é redundante (o próprio
    83                         // hub já agrupa por isso) — rótulo mais curto só pra esse caso.
    84119                        add_submenu_page(
    85120                                'sb-softwares',
    … …  
    104139        }
    105140
    106         /* ===========================================================
    107          * ENQUEUE
    108          * ========================================================= */
    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 void
    115          */
    116141        public static function enqueue( $hook ) {
    117                 if ( false === strpos( $hook, 'sbnfebr' ) ) {
     142                if ( false === strpos( $hook, 'sbnfebr' ) || ! self::is_plugin_page() ) {
    118143                        return;
    119144                }
    … …  
    126151                        file_exists( $css_path ) ? filemtime( $css_path ) : SBNFEBR_VERSION
    127152                );
     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                }
    128162                self::maybe_add_embed_inline_style();
    129163
    … …  
    152186                );
    153187
     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
    154205                wp_enqueue_script( 'wp-i18n' );
    155206
    … …  
    235286                );
    236287
    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;
    238290                wp_enqueue_script(
    239291                        'sbnfebr-item-actions',
    240                         SBNFEBR_URL . 'assets/js/nfebr-item-actions.js',
     292                        SBNFEBR_URL . $ia_js_rel,
    241293                        array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-diff-card' ),
    242294                        file_exists( $ia_js_path ) ? filemtime( $ia_js_path ) : SBNFEBR_VERSION,
    … …  
    244296                );
    245297
    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                         true
    253                 );
    254 
    255298                $regcheck_js_path = SBNFEBR_DIR . 'assets/js/nfebr-registry-check.js';
    256299                wp_enqueue_script(
    257300                        'sbnfebr-registry-check',
    258301                        SBNFEBR_URL . 'assets/js/nfebr-registry-check.js',
    259                         // Uses SB.itemActions.* (shared icon/popup group), hence the dependency.
    260302                        array( 'sbnfebr-core', 'sbnfebr-toast', 'sbnfebr-item-actions' ),
    261303                        file_exists( $regcheck_js_path ) ? filemtime( $regcheck_js_path ) : SBNFEBR_VERSION,
    … …  
    263305                );
    264306
     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
    265309                $main_path = SBNFEBR_DIR . 'assets/js/nfebr-main.js';
    266310                wp_enqueue_script(
    267311                        'sbnfebr-main',
    268312                        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,
    270314                        file_exists( $main_path ) ? filemtime( $main_path ) : SBNFEBR_VERSION,
    271315                        true
    272316                );
    273317
    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
    275384                // after the handle (see languages/).
    276                 foreach ( array(
     385                $translation_handles = array(
    277386                        'sbnfebr-core',
    278387                        'sbnfebr-grid',
    … …  
    280389                        'sbnfebr-item-actions',
    281390                        'sbnfebr-diff-card',
    282                         'sbnfebr-review-modal',
    283391                        'sbnfebr-library-notes',
    284392                        'sbnfebr-library-supplier',
    … …  
    287395                        'sbnfebr-price-history',
    288396                        '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 ) {
    290408                        wp_set_script_translations(
    291409                                $handle,
    … …  
    301419                                'rest_nonce'  => wp_create_nonce( 'wp_rest' ),
    302420                                'is_plus'     => sbnfebr_is_plus(),
     421                                'can_manage'  => current_user_can( 'manage_woocommerce' ),
    303422                                'adminUrl'    => esc_url_raw( admin_url() ),
    304                                 // Sheet screen URL, only when the Sheet plugin is active in
    305                                 // the same PHP process. Empty means not installed, and the
    306423                                // client hides the option.
    307424                                '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                                ),
    309432                        )
    310433                );
    311434        }
    312435
    313         /**
    314          * Fiscal Check tab: only when both plugins are Plus.
    315          *
    316          * @return bool
    317          */
    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 string
    326          */
    327         public static function fiscal_check_url() {
    328                 $embedded = isset( $_GET['embed'] ) && '1' === $_GET['embed']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    329                 return admin_url( 'admin.php?page=sbfcbr' . ( $embedded ? '&embed=1' : '' ) );
    330         }
    331 
    332         /* ===========================================================
    333          * SHEET INTEGRATION — a button on the Sheet's toolbar opens SBNFEBR
    334          * in a modal. The Sheet exposes #sb-row1-extensions as an anchor
    335          * point; each extension injects its own button there via JS. Does
    336          * not modify anything on the Sheet's side.
    337          * ========================================================= */
    338 
    339         /**
    340          * Enqueues the bridge script only on the Sheet's screen
    341          * (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 check
    344          *                      is the 'page' query param, like enqueue() does via
    345          *                      strpos($hook,'sbnfebr')).
    346          * @return void
    347          */
    348436        public static function enqueue_sheet_bridge( $hook ) {
    349437                if ( ! isset( $_GET['page'] ) || 'sbesfw' !== $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    … …  
    378466                        array(
    379467                                'modal_url' => esc_url_raw( admin_url( 'admin.php?page=sbnfebr&embed=1' ) ),
    380                                 // The "Import from NF-e" button only appears when SBNFEBR is
    381                                 // running the Plus edition — Lite has no Make Draft+ to offer.
    382468                                'is_plus'   => sbnfebr_is_plus(),
    383                                 // Installed NF-e version, shown next to the Sheet's own
    384469                                // version tag (.sb-version-tag).
    385470                                'version'   => SBNFEBR_VERSION,
    … …  
    388473        }
    389474
    390         /**
    391          * When this screen is opened with ?embed=1 (inside the Sheet's modal
    392          * iframe), hides WP-admin chrome (side menu, admin bar, footer) so
    393          * only the plugin content fills the iframe. CSS only — added as an
    394          * inline block on the already-enqueued 'sbnfebr-style-core' handle
    395          * (must run inside enqueue(), on admin_enqueue_scripts: admin_head
    396          * fires after styles are already printed, too late for
    397          * wp_add_inline_style() to have any effect).
    398          *
    399          * @return void
    400          */
    401475        protected static function maybe_add_embed_inline_style() {
    402476                if ( ! isset( $_GET['page'] ) || 'sbnfebr' !== $_GET['page'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    … …  
    415489        }
    416490
    417         /* ===========================================================
    418          * RENDER PAGE (HTML scaffold)
    419          * ========================================================= */
    420 
    421491        /**
    422492         * Renders the plugin's main page.
    … …  
    425495         */
    426496        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 ) );
    427499                ?>
    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">
    429501                        <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; ?>
    430505
    431506                                <div class="sbnfebr-row1">
    … …  
    433508                                                <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>
    434509                                                <span class="sb-brand">
     510                                                        <span class="sb-brand__mobile"><?php esc_html_e( 'XML Import-BR', 'sanbar-express-nfe-xml-import-br' ); ?></span>
    435511                                                        <span class="sb-brand__prefix"><?php esc_html_e( 'SanBar', 'sanbar-express-nfe-xml-import-br' ); ?></span>
    436512                                                        <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>
    438514                                                </span>
    439515                                                <?php if ( sbnfebr_is_plus() ) : ?>
    … …  
    442518                                                        <span class="sb-edition-lite">Lite</span>
    443519                                                <?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; ?>
    444524                                                <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">
    445527                                                <input type="file" id="sbnfebr-file-input" accept=".xml" style="display:none">
    446528                                                <?php
    447                                                 // Tooltip surfaces upload limits (size/items/frequency)
    448529                                                // directly on the button.
    449530                                                $sbnfebr_upload_tooltip = sprintf(
    450                                                         /* translators: 1: max file size in MB, 2: max item count, 3: max uploads per minute. */
     531                                                        /* translators: 1: MB, 2: items, 3: per minute. */
    451532                                                        __( 'Aceita .xml de até %1$dMB, %2$d itens, %3$d envios por minuto.', 'sanbar-express-nfe-xml-import-br' ),
    452533                                                        10,
    … …  
    456537                                                ?>
    457538                                                <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>
    465549                                        <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; ?>
    472550                                                <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>
    474562                                        </div>
    475563                                </div>
    476564
     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">
    477572                                <div class="sbnfebr-row2">
    478573                                        <label for="sbnfebr-filter-supplier" class="screen-reader-text"><?php esc_html_e( 'Filtrar por fornecedor', 'sanbar-express-nfe-xml-import-br' ); ?></label>
    … …  
    486581                                                <option value=""><?php esc_html_e( 'Todas as notas', 'sanbar-express-nfe-xml-import-br' ); ?></option>
    487582                                        </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 ?>
    489584                                        <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>
    490585
    … …  
    492587                                        <select id="sbnfebr-filter-mode" title="<?php esc_attr_e( 'Filtro especial', 'sanbar-express-nfe-xml-import-br' ); ?>">
    493588                                                <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>
    507612                                        </select>
    508613                                        <span id="sbnfebr-filter-dates" style="display:none">
    … …  
    514619
    515620                                        <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">
    517622                                </div>
    518623
    … …  
    523628                                                        <span class="sbnfebr-stat__val" id="sbnfebr-stat-total">—</span>
    524629                                                </div>
    525                                                 <?php /* Counts product identity (GTIN, or supplier+code when no GTIN), visible in both view modes. */ ?>
     630                                                <?php ?>
    526631                                                <div class="sbnfebr-stat">
    527632                                                        <span class="sbnfebr-stat__label"><?php esc_html_e( 'Produtos únicos', 'sanbar-express-nfe-xml-import-br' ); ?></span>
    … …  
    544649                                                        <span class="sbnfebr-stat__val">🔎</span>
    545650                                                </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>
    546655                                        </div>
    547656                                        <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 ?>
    549658                                                <span class="sbnfebr-view-toggle" id="sbnfebr-view-toggle">
    550659                                                        <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>
    … …  
    556665                                                        <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>
    557666                                                        <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>
    558668                                                        <select id="sbnfebr-per-page" title="<?php esc_attr_e( 'Itens por página', 'sanbar-express-nfe-xml-import-br' ); ?>">
    559669                                                                <option value="25">25</option>
    … …  
    563673                                                        </select>
    564674                                                </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>
    568675                                        </div>
     676                                </div>
    569677                                </div>
    570678                        </div>
    … …  
    584692                                </table>
    585693                        </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>
    586730                </div>
    587731                <?php
  • sanbar-express-nfe-xml-import-br/trunk/includes/class-sbnfebr-rest.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * Registers all of the plugin's REST routes (namespace sbnfebr/v1).
    4  *
    5  * @package SBNFEBR
    6  * @since   0.2.0
    7  */
    82
    93defined( 'ABSPATH' ) || exit;
    … …  
    2014        }
    2115
    22         /**
    23          * Registers the routes for each controller.
    24          *
    25          * @return void
    26          */
    2716        public static function register_routes() {
    2817                SBNFEBR_Import_Controller::register_routes();
     18                SBNFEBR_Workflow_Controller::register_routes();
     19                SBNFEBR_Full_Backup_Controller::register_routes();
    2920                SBNFEBR_Items_Controller::register_routes();
    3021                SBNFEBR_Suppliers_Library_Controller::register_routes();
    … …  
    3324                SBNFEBR_Error_Log_Controller::register_routes();
    3425                SBNFEBR_Match_Controller::register_routes();
     26                SBNFEBR_Fiscal_Controller::register_routes();
    3527
    36                 // Plus routes (/sync, /link-update, /link-plus) only exist when the
    37                 // plus/ tree is loaded (see sbnfebr_load_modules() in
    3828                // sanbar-express-nfe-xml-import-br.php).
    3929                if ( class_exists( 'SBNFEBR_Draft_Controller_Plus' ) ) {
  • sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-draft-controller.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * REST controller for the item action modal: Make Draft, Link, Sync
    4  * (Plus), Price/Source, Unlink.
    5  *
    6  * @package SBNFEBR
    7  * @since   0.4.0
    8  */
    92
    103defined( 'ABSPATH' ) || exit;
    … …  
    125class SBNFEBR_Draft_Controller {
    136
    14         /**
    15          * Registers the routes.
    16          *
    17          * @return void
    18          */
    197        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 
    308                register_rest_route(
    319                        'sbnfebr/v1',
    … …  
    3715                        )
    3816                );
     17        }
    3918
    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' ),
    4359                        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,
    9565                        )
    9666                );
    9767        }
    9868
    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' ),
    20473                        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,
    20979                        )
    21080                );
    21181        }
    21282
    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'],
    24997                );
    25098        }
    25199
    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
    283105                );
    284106        }
    285107
    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' );
    421110        }
    422111}
  • sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-error-log-controller.php

    r3725460 r3782421  
    11<?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 SBNFEBR
    14  * @since   0.5.1
    15  */
    162
    173defined( 'ABSPATH' ) || exit;
    … …  
    7359        }
    7460
    75         /**
    76          * Permission: same capability used across the plugin.
    77          *
    78          * @return bool
    79          */
    8061        public static function permission() {
    8162                return current_user_can( 'edit_products' );
    8263        }
    8364
    84         /**
    85          * GET /error-log.
    86          *
    87          * @param WP_REST_Request $request REST request.
    88          * @return WP_REST_Response
    89          */
    9065        public static function get_list( WP_REST_Request $request ) {
    9166                $page     = (int) $request->get_param( 'page' );
    … …  
    10479        }
    10580
    106         /**
    107          * POST /error-log/mark-seen.
    108          *
    109          * @return WP_REST_Response
    110          */
    11181        public static function mark_seen() {
    11282                SBNFEBR_Error_Log_Service::mark_seen();
  • sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-import-controller.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * REST controller for NF-e XML upload/import.
    4  *
    5  * POST /sbnfebr/v1/import/preview  (multipart, field "file") — parses and
    6  *      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 the
    9  *      preview summary; the server keeps no XML cache/state between calls.
    10  *
    11  * @package SBNFEBR
    12  * @since   0.2.0
    13  */
    142
    153defined( 'ABSPATH' ) || exit;
    … …  
    175class SBNFEBR_Import_Controller {
    186
    19         /**
    20          * Maximum accepted NF-e XML size in bytes. A real NF-e, even with many
    21          * items, stays within a few MB; generous enough for legitimate cases,
    22          * low enough to reject clearly malformed files before loading them.
    23          */
    247        const MAX_FILE_SIZE = 10485760; // 10 MB.
    258
    26         /**
    27          * Above this item count, the preview adds a non-blocking warning asking
    28          * for extra confirmation before import. The hard cap is much higher,
    29          * see SBNFEBR_Xml_Parser_Service::MAX_ITEMS.
    30          */
    319        const WARN_ITEMS_THRESHOLD = 100;
    3210
    33         /**
    34          * Upload rate limit — a simple per-user transient counter, guarding
    35          * against resource abuse from unbounded sequential imports.
    36          */
    3711        const RATE_LIMIT_MAX    = 10;
    3812        const RATE_LIMIT_WINDOW = 60; // seconds.
    … …  
    6539        }
    6640
    67         /**
    68          * Permission: same capability used to edit WooCommerce products, since
    69          * importing an NF-e creates or updates a product.
    70          *
    71          * @return bool
    72          */
    7341        public static function permission() {
    7442                return current_user_can( 'edit_products' );
    7543        }
    7644
    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, but
    80          * sufficient to block automated bursts. Shared by preview and import,
    81          * since both call validate_and_parse().
    82          *
    83          * @return true|WP_Error
    84          */
    8545        protected static function check_rate_limit() {
    8646                $key   = 'sbnfebr_import_rate_' . get_current_user_id();
    … …  
    9959                }
    10060
    101                 // TTL resets on each call: window is fixed from the last attempt,
    102                 // not the first, which is sufficient to block automated bursts.
    10361                set_transient( $key, $count + 1, self::RATE_LIMIT_WINDOW );
    10462                return true;
    10563        }
    10664
    107         /**
    108          * Validates the upload (presence, transport error, extension, size),
    109          * reads and parses it. Shared by preview and actual import so both
    110          * 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          */
    11565        protected static function validate_and_parse( WP_REST_Request $request ) {
    11666                $rate_limited = self::check_rate_limit();
    … …  
    14494                }
    14595
    146                 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_get_contents
    14796                $xml_string = file_get_contents( $file['tmp_name'] );
    14897                if ( false === $xml_string ) {
    … …  
    153102        }
    154103
    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 always
    160          * "Saída" on a legitimate purchase note, since it reflects the
    161          * issuer's stock movement, not the recipient's — flagging it would
    162          * false-positive on every normal import.
    163          *
    164          * The real "wrong note" signal is comparing the note's recipient
    165          * 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_Error
    170          */
    171104        public static function handle_preview( WP_REST_Request $request ) {
    172105                $parsed = self::validate_and_parse( $request );
    … …  
    203136        }
    204137
    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_Error
    210          */
    211138        public static function handle_import( WP_REST_Request $request ) {
    212139                $parsed = self::validate_and_parse( $request );
  • sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-items-controller.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * REST controller for reading already-imported items/suppliers/notes.
    4  *
    5  * GET /sbnfebr/v1/items?supplier_cnpj=&note_id=&search=
    6  * GET /sbnfebr/v1/suppliers
    7  * GET /sbnfebr/v1/notes?supplier_cnpj=
    8  *
    9  * @package SBNFEBR
    10  * @since   0.2.0
    11  */
    122
    133defined( 'ABSPATH' ) || exit;
    … …  
    6353                register_rest_route(
    6454                        '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',
    8555                        '/items/(?P<id>\d+)/gtin-family',
    8656                        array(
    … …  
    152122        }
    153123
    154         /**
    155          * Permission: reading requires the same capability as editing products,
    156          * since this is sensitive fiscal data, not public.
    157          *
    158          * @return bool
    159          */
    160124        public static function permission() {
    161125                return current_user_can( 'edit_products' );
    162126        }
    163127
    164         /**
    165          * GET /items.
    166          *
    167          * @param WP_REST_Request $request REST request.
    168          * @return WP_REST_Response
    169          */
    170128        public static function get_items( WP_REST_Request $request ) {
    171                 // 'ids': CSV of IDs, to fetch full data for a selection spanning pages.
    172129                $ids_param = (string) $request->get_param( 'ids' );
    173130                $ids       = '' !== $ids_param ? array_map( 'intval', explode( ',', $ids_param ) ) : array();
    … …  
    189146                        )
    190147                );
     148                if ( ! empty( $result['items'] ) ) {
     149                        $result['items'] = SBNFEBR_Workflow_Service::attach_source_states( $result['items'] );
     150                }
    191151
    192152                return rest_ensure_response( $result );
    193153        }
    194154
    195         /**
    196          * GET /items/by-product. Same listing as /items, aggregated by product
    197          * identity instead of per note entry. See
    198          * SBNFEBR_Notes_Service::get_items_by_product().
    199          *
    200          * @param WP_REST_Request $request REST request.
    201          * @return WP_REST_Response
    202          */
    203155        public static function get_items_by_product( WP_REST_Request $request ) {
    204156                $result = SBNFEBR_Notes_Service::get_items_by_product(
    … …  
    217169                        )
    218170                );
     171                if ( ! empty( $result['items'] ) ) {
     172                        $result['items'] = SBNFEBR_Workflow_Service::attach_source_states( $result['items'] );
     173                }
    219174
    220175                return rest_ensure_response( $result );
    221176        }
    222177
    223         /**
    224          * POST /items/ignore. Body: { item_ids: [...], ignored: bool }. Bulk
    225          * marks items that will never become a product.
    226          *
    227          * @param WP_REST_Request $request REST request.
    228          * @return WP_REST_Response|WP_Error
    229          */
    230178        public static function set_ignored( WP_REST_Request $request ) {
    231179                $body     = $request->get_json_params();
    … …  
    242190        }
    243191
    244         /**
    245          * GET /items/{id}/price-history.
    246          *
    247          * @param WP_REST_Request $request REST request.
    248          * @return WP_REST_Response|WP_Error
    249          */
    250192        public static function get_price_history( WP_REST_Request $request ) {
    251193                $item = SBNFEBR_Notes_Service::get_item( (int) $request->get_param( 'id' ) );
    … …  
    267209        }
    268210
    269         /**
    270          * GET /notes/{id}/review. Post-import review: items already resolving
    271          * to an existing product, with a diff, plus candidates for "expand
    272          * identification".
    273          *
    274          * @param WP_REST_Request $request REST request.
    275          * @return WP_REST_Response
    276          */
    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_Response
    286          */
    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 GTIN
    296          * (any note, any supplier), for the action modal's source selector to
    297          * 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_Error
    301          */
    302211        public static function get_gtin_family( WP_REST_Request $request ) {
    303212                $item_id = (int) $request->get_param( 'id' );
    … …  
    307216                }
    308217
    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 ) );
    310225        }
    311226
    … …  
    319234        }
    320235
    321         /**
    322          * GET /suppliers/{cnpj}/snapshot.
    323          *
    324          * @param WP_REST_Request $request REST request.
    325          * @return WP_REST_Response
    326          */
    327236        public static function get_supplier_snapshot( WP_REST_Request $request ) {
    328237                $cnpj     = (string) $request->get_param( 'cnpj' );
    … …  
    331240        }
    332241
    333         /**
    334          * GET /notes.
    335          *
    336          * @param WP_REST_Request $request REST request.
    337          * @return WP_REST_Response
    338          */
    339242        public static function get_notes( WP_REST_Request $request ) {
    340243                $supplier_cnpj = (string) $request->get_param( 'supplier_cnpj' );
    … …  
    342245        }
    343246
    344         /**
    345          * GET /audit-log?note_id=&page=&per_page=. Event history (note
    346          * imported/deleted, product created).
    347          *
    348          * @param WP_REST_Request $request REST request.
    349          * @return WP_REST_Response
    350          */
    351247        public static function get_audit_log( WP_REST_Request $request ) {
    352248                return rest_ensure_response(
    … …  
    361257        }
    362258
    363         /**
    364          * DELETE /notes/{id}. Deletes the header and items; WooCommerce
    365          * 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_Error
    369          */
    370259        public static function delete_note( WP_REST_Request $request ) {
    371260                $result = SBNFEBR_Notes_Service::delete_note( (int) $request->get_param( 'id' ) );
    … …  
    376265        }
    377266
    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_Error
    384          */
    385267        public static function get_note_detail( WP_REST_Request $request ) {
    386268                $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  
    11<?php
    2 /**
    3  * REST controller for matching note items against existing WooCommerce
    4  * products, by GTIN first, then supplier+code as a fallback for notes
    5  * without a GTIN.
    6  *
    7  * POST /sbnfebr/v1/match-gtin
    8  * POST /sbnfebr/v1/match-supplier-key
    9  *
    10  * @package SBNFEBR
    11  * @since   0.5.5
    12  */
    132
    143defined( 'ABSPATH' ) || exit;
    … …  
    7362        }
    7463
    75         /**
    76          * Permission: same capability used across the plugin.
    77          *
    78          * @return bool
    79          */
    8064        public static function permission() {
    8165                return current_user_can( 'edit_products' );
    8266        }
    8367
    84         /**
    85          * POST /match-gtin. Body: { gtins: [...] }.
    86          *
    87          * @param WP_REST_Request $request REST request.
    88          * @return WP_REST_Response
    89          */
    9068        public static function match_gtin( WP_REST_Request $request ) {
    9169                $body  = $request->get_json_params();
    … …  
    9573        }
    9674
    97         /**
    98          * POST /match-supplier-key. Body: { keys: [...] }, each key in
    99          * `CNPJ|code` format (matches `_sbnfebr_supplier_key`), built client-side.
    100          *
    101          * @param WP_REST_Request $request REST request.
    102          * @return WP_REST_Response
    103          */
    10475        public static function match_supplier_key( WP_REST_Request $request ) {
    10576                $body = $request->get_json_params();
    … …  
    10980        }
    11081
    111         /**
    112          * POST /registry-check. Body: { gtins: [...] }. Available in both Lite
    113          * and Plus; checks the given GTINs (grid items not yet linked to a
    114          * product) against the WooCommerce catalog.
    115          *
    116          * @param WP_REST_Request $request REST request.
    117          * @return WP_REST_Response
    118          */
    11982        public static function registry_check( WP_REST_Request $request ) {
    12083                $body  = $request->get_json_params();
    … …  
    12487        }
    12588
    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_Error
    133          */
    13489        public static function get_snapshot( WP_REST_Request $request ) {
    13590                $product_id = (int) $request->get_param( 'id' );
    … …  
    13792                $post = get_post( $product_id );
    13893                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 links
    140                         // left pointing at a product that vanished without that hook.
    14194                        SBNFEBR_Notes_Service::clear_product_link( $product_id );
    14295                        return new WP_Error(
    … …  
    153106                $snapshot = SBNFEBR_Match_Service::get_snapshot( $product_id, $item_id );
    154107
    155                 // Plus: note-side values keyed like the product meta, for the selective fiscal sync popup.
    156108                if ( $item_id && class_exists( 'SBNFEBR_Draft_Service_Plus' ) ) {
    157109                        $item = SBNFEBR_Notes_Service::get_item( $item_id );
    … …  
    164116        }
    165117
    166         /**
    167          * GET /products-search?q=...&exclude_item_id=... Product search for
    168          * 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_Response
    173          */
    174118        public static function search_products( WP_REST_Request $request ) {
    175119                return rest_ensure_response(
    176120                        SBNFEBR_Match_Service::search_products(
    177121                                (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' ) )
    179124                        )
    180125                );
  • sanbar-express-nfe-xml-import-br/trunk/includes/controllers/class-sbnfebr-settings-controller.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * REST controller for plugin settings: the own-company profile (same
    4  * fields as a supplier record) and error-log verbosity.
    5  *
    6  * The company profile's `document` (CNPJ) is compared against each
    7  * imported note's recipient in the preview, to flag notes not issued to
    8  * this company (see SBNFEBR_Import_Controller::handle_preview()).
    9  *
    10  * No editable tax regime field on the company profile — which taxes
    11  * count as cost is decided in the Sheet's Library → Taxes/Fees. The
    12  * response carries a read-only `tax_regime` block instead (see get_shared_tax_regime()).
    13  *
    14  * GET  /sbnfebr/v1/settings
    15  * POST /sbnfebr/v1/settings
    16  *
    17  * @package SBNFEBR
    18  * @since   0.4.8
    19  */
    202
    213defined( 'ABSPATH' ) || exit;
    … …  
    235class SBNFEBR_Settings_Controller {
    246
    25         /** Option key — full company profile (serialized array). */
    267        const OPTION_COMPANY = 'sbnfebr_own_company';
    278
    28         /** Legacy option key (CNPJ only), read as a migration fallback. */
    299        const OPTION_OWN_CNPJ_LEGACY = 'sbnfebr_own_cnpj';
    3010
    31         /**
    32          * Option compartilhada com a SM (class-sbsheet-settings.php,
    33          * COMPANY_OPTION) — perfil completo da empresa (nome, documento
    34          * fiscal, endereço, contato), editável dos dois lados. É a MESMA
    35          * option lida/gravada por ambos — não existe risco de duas verdades
    36          * desencontradas, só duas portas de entrada pro mesmo dado.
    37          * OPTION_COMPANY (abaixo) continua existindo só como fallback de
    38          * migração de instalações antigas (ver get_company()). Sem campo de
    39          * país/regime tributário — ver docblock da classe.
    40          */
    4111        const SHARED_COMPANY_OPTION = 'sbesfw_company_data';
    4212
    43         /** Campos do perfil espelhados na option compartilhada — mesmos nomes dos dois lados. */
    4413        const SHARED_FIELDS = array( 'name', 'fantasy_name', 'document', 'ie', 'phone', 'email', 'site', 'cep', 'street', 'number', 'complement', 'district', 'city', 'state' );
    4514
    46         /** Option do NF-e PDV (plugin irmão) — dono do regime tributário da loja. Leitura direta, sem class_exists(). */
    4715        const PDV_FISCAL_CONFIG_OPTION = 'nfbr_config_fiscal';
     16
     17        const WELCOME_META = 'sbnfebr_welcome_dismissed';
    4818
    4919        /**
    … …  
    6939                        )
    7040                );
    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
    7857        public static function permission() {
    7958                return current_user_can( 'edit_products' );
    8059        }
    8160
    82         /**
    83          * Full company profile with defaults for every field. Falls back to
    84          * the legacy CNPJ-only option if the full profile was never saved.
    85          *
    86          * @return array
    87          */
    8861        public static function get_company() {
    8962                $stored = get_option( self::OPTION_COMPANY, array() );
    … …  
    11184                $company = array_merge( $defaults, $stored );
    11285
    113                 // Fall back to the legacy CNPJ option for reading only; it is not deleted.
    11486                if ( '' === $company['document'] ) {
    11587                        $legacy = preg_replace( '/\D/', '', (string) get_option( self::OPTION_OWN_CNPJ_LEGACY, '' ) );
    … …  
    11991                }
    12092
    121                 // A option compartilhada com a SM vence, campo a campo, quando já
    122                 // tem algo salvo — fonte única entre os dois plugins (ver
    123                 // SHARED_COMPANY_OPTION). Sem isso, editar qualquer campo pela SM
    12493                // nunca refletiria aqui (e vice-versa).
    12594                $shared = get_option( self::SHARED_COMPANY_OPTION, array() );
    … …  
    135104        }
    136105
    137         /**
    138          * Company CNPJ, digits only. Used by the import preview.
    139          *
    140          * @return string
    141          */
    142106        public static function get_own_cnpj() {
    143107                return preg_replace( '/\D/', '', (string) self::get_company()['document'] );
    144108        }
    145109
    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          */
    152110        public static function get_shared_tax_regime() {
    153111                $raw = get_option( self::PDV_FISCAL_CONFIG_OPTION, null );
    … …  
    193151        }
    194152
    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_Error
    200          */
    201153        public static function update_settings( WP_REST_Request $request ) {
    202154                $body = $request->get_json_params();
    … …  
    216168                        foreach ( self::SHARED_FIELDS as $key ) {
    217169                                if ( 'document' === $key ) {
    218                                         continue; // já setado acima (com a validação de 14 dígitos)
     170                                        continue;
    219171                                }
    220172                                $company[ $key ] = isset( $incoming[ $key ] ) ? sanitize_text_field( (string) $incoming[ $key ] ) : '';
    … …  
    223175                        update_option( self::OPTION_COMPANY, $company, true );
    224176
    225                         // Espelha o perfil inteiro na option compartilhada com a SM —
    226177                        // mesma fonte única dos dois lados.
    227178                        $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  
    11<?php
    2 /**
    3  * REST controller for supplier CRUD (sbs_supplier taxonomy), used by the
    4  * Supplier Library modal.
    5  *
    6  * Route `/library/suppliers` is the editable full registry, separate from
    7  * `/suppliers`, which only lists CNPJs already seen on imported notes for
    8  * the grid filter.
    9  *
    10  * @package SBNFEBR
    11  * @since   0.3.0
    12  */
    132
    143defined( 'ABSPATH' ) || exit;
    … …  
    6756        }
    6857
    69         /**
    70          * Permission: same capability used on the taxonomy (`edit_products`).
    71          *
    72          * @return bool
    73          */
    7458        public static function permission() {
    7559                return current_user_can( 'edit_products' );
    7660        }
    7761
    78         /**
    79          * GET /library/suppliers?search=.
    80          *
    81          * @param WP_REST_Request $request REST request.
    82          * @return WP_REST_Response
    83          */
    8462        public static function list_suppliers( WP_REST_Request $request ) {
    8563                $search = (string) $request->get_param( 'search' );
    … …  
    8765        }
    8866
    89         /**
    90          * GET /library/suppliers/check?document=CNPJ. Lets the toolbar
    91          * indicator check registration status without loading the full list.
    92          *
    93          * @param WP_REST_Request $request REST request.
    94          * @return WP_REST_Response
    95          */
    9667        public static function check_supplier( WP_REST_Request $request ) {
    9768                $document = (string) $request->get_param( 'document' );
    … …  
    10677        }
    10778
    108         /**
    109          * Extracts the supplier field payload from the request body.
    110          *
    111          * @param WP_REST_Request $request REST request.
    112          * @return array
    113          */
    11479        protected static function fields_from_request( WP_REST_Request $request ) {
    11580                $body = $request->get_json_params();
    … …  
    12691        }
    12792
    128         /**
    129          * POST /library/suppliers.
    130          *
    131          * @param WP_REST_Request $request REST request.
    132          * @return WP_REST_Response|WP_Error
    133          */
    13493        public static function create_supplier( WP_REST_Request $request ) {
    13594                $result = SBNFEBR_Supplier_Service::create( self::fields_from_request( $request ) );
    … …  
    14099        }
    141100
    142         /**
    143          * PATCH /library/suppliers/{id}.
    144          *
    145          * @param WP_REST_Request $request REST request.
    146          * @return WP_REST_Response|WP_Error
    147          */
    148101        public static function update_supplier( WP_REST_Request $request ) {
    149102                $term_id = (int) $request->get_param( 'id' );
    … …  
    155108        }
    156109
    157         /**
    158          * DELETE /library/suppliers/{id}.
    159          *
    160          * @param WP_REST_Request $request REST request.
    161          * @return WP_REST_Response|WP_Error
    162          */
    163110        public static function delete_supplier( WP_REST_Request $request ) {
    164111                $term_id = (int) $request->get_param( 'id' );
  • sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-audit-service.php

    r3725460 r3782421  
    11<?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, nota
    5  * excluída. Mesmo padrão estrutural de SBNFEBR_Error_Log_Service
    6  * (tabela própria, dbDelta versionado, poda mantendo só as mais
    7  * recentes) — mas grava evento por chamada explícita de cada
    8  * service/controller, não por um hook central (evento de negócio não
    9  * é "resposta HTTP com erro", não tem um ponto único pra interceptar).
    10  *
    11  * @package SBNFEBR
    12  * @since   0.5.2
    13  */
    142
    153defined( 'ABSPATH' ) || exit;
    164
    17 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, PluginCheck.Security.DirectDB.UnescapedDBParameter
    18 // 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 cada
    20 // evento e lido só sob demanda (sem tela de listagem de alto tráfego). Nome de tabela sempre vem
    21 // 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 juntos
    23 // conforme o filtro é passado ou não, a contagem bate nos 2 casos em runtime.
    245class SBNFEBR_Audit_Service {
    256
    26         /** Versão do schema — bump aqui força dbDelta rodar de novo em upgrade futuro. */
    277        const DB_VERSION = '1.0';
    288
    29         /** Option key que guarda a versão do schema já aplicada. */
    309        const DB_VERSION_OPTION = 'sbnfebr_audit_db_version';
    3110
    32         /** Máximo de linhas mantidas no total (mais antigas são descartadas). */
    3311        const MAX_ROWS = 1000;
    3412
    … …  
    4018        const EVENT_PRODUCT_SYNCED  = 'product_synced';
    4119
    42         /**
    43          * Nome completo da tabela (com prefixo do WP).
    44          *
    45          * @return string
    46          */
    4720        public static function table_name() {
    4821                global $wpdb;
    … …  
    5023        }
    5124
    52         /**
    53          * Cria a tabela se não existir, ou atualiza o schema se DB_VERSION
    54          * mudou. Idempotente.
    55          *
    56          * @return void
    57          */
    5825        public static function create_table() {
    5926                $installed_version = get_option( self::DB_VERSION_OPTION );
    … …  
    8754        }
    8855
    89         /**
    90          * Grava um evento e poda o excesso (mantém só as MAX_ROWS mais
    91          * 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 void
    96          */
    9756        public static function log( $event_type, array $args = array() ) {
    9857                global $wpdb;
    … …  
    11978        }
    12079
    121         /**
    122          * Mantém no máximo MAX_ROWS linhas — apaga as mais antigas
    123          * quando ultrapassa.
    124          *
    125          * @return void
    126          */
    12780        protected static function prune() {
    12881                global $wpdb;
    12982                $table = self::table_name();
    13083
    131                 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName
     84                $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
    13285                if ( $total <= self::MAX_ROWS ) {
    13386                        return;
    … …  
    13790                $wpdb->query( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    13891                        $wpdb->prepare(
    139                                 "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName
     92                                "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d",
    14093                                $excess
    14194                        )
    … …  
    14396        }
    14497
    145         /**
    146          * Lista paginada, mais recente primeiro — usada pelo Gerenciador de
    147          * Notas pra mostrar o histórico de uma nota específica, e por uma
    148          * 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          */
    15398        public static function list_entries( array $args = array() ) {
    15499                global $wpdb;
    … …  
    165110                }
    166111
    167                 $count_sql = "SELECT COUNT(*) FROM {$table} WHERE {$where}"; // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName
     112                $count_sql = "SELECT COUNT(*) FROM {$table} WHERE {$where}";
    168113                $total     = (int) ( $params ? $wpdb->get_var( $wpdb->prepare( $count_sql, $params ) ) : $wpdb->get_var( $count_sql ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    169114
    170115                $list_params   = array_merge( $params, array( $per_page, $offset ) );
    171116                $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.InterpolatedTableName
     117                        $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",
    174119                                $list_params
    175120                        ),
  • sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-draft-service.php

    r3725460 r3782421  
    11<?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 EXPress
    5  * Sheet Plus (grupo `fiscal_brasil`). Nunca grava preço de venda.
    6  *
    7  * @package SBNFEBR
    8  * @since   0.4.0
    9  */
    102
    113defined( 'ABSPATH' ) || exit;
    124
    135class 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
    168        const META_SUPPLIER_KEY = '_sbnfebr_supplier_key';
    179
    18         /**
    19          * Postmeta privado — 'unit'|'box', qual dos 2 campos de GTIN da Sheet
    20          * 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-update
    22          * seguinte reaplicar o mesmo campo sem perguntar de novo — só o
    23          * Draft/Link inicial (com escolha explícita do usuário) grava aqui.
    24          */
    2510        const META_GTIN_KIND = '_sbnfebr_gtin_kind';
    2611
    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 (mais
    31          * seguro deixar a Calculadora no padrão "unit" do que arriscar
    32          * classificar errado uma sigla desconhecida).
    33          *
    34          * @var array<string,string>
    35          */
    3612        const UNIT_TO_SALE_TYPE = array(
    3713                'UN'   => 'unit',
    … …  
    6036        );
    6137
    62         /**
    63          * Classificação MAIS FINA que UNIT_TO_SALE_TYPE — unidade não listada
    64          * aqui usa só o `sale_type` genérico ('box'), sem gravar kind
    65          * nenhum. `sbs_price_sale_type` continua sempre 'box' pra tudo
    66          * 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êntica
    70          * pra qualquer valor aqui (ver popup-pricecalc.js, BOX_KINDS/
    71          * updateBoxKindLabels()). Os valores aqui têm que bater exatamente
    72          * com as chaves de BOX_KINDS na Sheet.
    73          *
    74          * @var array<string,string>
    75          */
    7638        const UNIT_TO_KIND = array(
    7739                'DZ'  => 'dozen',
    … …  
    8345        );
    8446
     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
    8557        /**
    8658         * Hook registration.
    … …  
    9163                add_action( 'wp_trash_post', array( __CLASS__, 'on_product_removed' ) );
    9264                add_action( 'before_delete_post', array( __CLASS__, 'on_product_removed' ) );
    93                 // Integração opcional, sem dependência nenhuma da Sheet: se ela
    94                 // estiver instalada (qualquer versão, Lite ou Plus) e disparar
    95                 // este evento genérico (ex: conversão simples→variável recriando
    96                 // o post_id de um produto), a gente re-vincula sozinho. Se a
    97                 // Sheet não estiver instalada, ou for uma versão que nunca
    98                 // dispara isto, o hook simplesmente nunca é chamado — sem erro,
    99                 // sem checagem de classe/versão necessária dos dois lados.
    10065                add_action( 'sbsheet_product_identity_moved', array( __CLASS__, 'on_product_identity_moved' ), 10, 2 );
    10166        }
    10267
    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
    110162        public static function on_product_removed( $post_id ) {
    111163                if ( in_array( get_post_type( $post_id ), array( 'product', 'product_variation' ), true ) ) {
    112164                        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
    129169        public static function on_product_identity_moved( $old_product_id, $new_product_id ) {
    130170                $old_product_id = (int) $old_product_id;
    … …  
    136176        }
    137177
    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() ) {
    156179                $item = SBNFEBR_Notes_Service::get_item( $item_id );
    157180                if ( ! $item ) {
    158181                        return new WP_Error( 'sbnfebr_item_not_found', __( 'Item não encontrado.', 'sanbar-express-nfe-xml-import-br' ), array( 'status' => 404 ) );
    159182                }
     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                }
    160207
    161208                $existing_id = self::resolve_existing_product_id( $item );
    162209                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                        );
    171215                }
    172216
    … …  
    180224                $product->set_status( 'draft' );
    181225
    182                 // O WordPress aplica a categoria padrão ("Sem categoria") sozinho
    183                 // sempre que salva um produto sem nenhuma categoria — inclusive de
    184                 // novo em qualquer ->save() subsequente (maybe_set_sku(), chamado
    185                 // dentro de apply_identity_meta() logo abaixo, salva outra vez pro
    186                 // SKU). Em vez de correr atrás disso a cada save, desligamos a
    187                 // FONTE (a opção que registra o termo default da taxonomia) durante
    188                 // toda a criação — mecanismo padrão do WordPress, não uma alteração
    189                 // salva em lugar nenhum. Religa logo depois, então não afeta a
    190                 // edição nativa nem outro plugin. Mesma técnica documentada em
    191                 // SBSheet_Product_Service::create() (plugin irmão Sheet).
    192226                add_filter( 'option_default_product_cat', '__return_zero' );
    193227
    … …  
    196230                $product_id = $product->get_id();
    197231
     232                $note       = SBNFEBR_Notes_Service::get_note( $item['note_id'] );
    198233                $sku_status = self::apply_identity_meta( $product_id, $item, $gtin_kind, $sku_source );
     234                self::apply_draft_profile( $product_id, $item, $note, $options );
    199235
    200236                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 pra
    205                 // 'product_cat' reatribuindo a categoria padrão na hora, mesmo fora do
    206                 // filtro acima. Com o filtro já tendo coberto os saves acima, o produto
    207                 // já fica sem categoria — não precisa (e não pode) de mais nada aqui.
    208237
    209238                SBNFEBR_Notes_Service::set_item_product_id( $item_id, $product_id );
    … …  
    224253        }
    225254
    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
    237276        protected static function resolve_existing_product_id( array $item ) {
    238277                if ( ! empty( $item['wc_product_id'] ) ) {
    … …  
    255294        }
    256295
    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 string
    265          */
    266296        protected static function title_case( $text ) {
    267297                $text = (string) $text;
    … …  
    275305        }
    276306
    277         /**
    278          * Vincula o item a um produto WooCommerce JÁ EXISTENTE (achado pelo
    279          * "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ério
    281          * do Make Draft simples) — o produto já existe, não é este método
    282          * 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 outra
    289          *                                identidade, true resolve desvinculando a
    290          *                                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 source
    330          * + opcionalmente o custo desta nota. Nunca mexe em estoque nem em
    331          * 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 pela
    392          * identidade (ver
    393          * SBNFEBR_Notes_Service::get_post_import_review()) — diferente de
    394          * sync_full(), não depende do item já ter `wc_product_id` gravado
    395          * nele (o item recém-importado normalmente ainda não tem; quem
    396          * decide o produto é o cálculo da revisão, feito ANTES de chamar
    397          * aqui). Sempre grava identidade + fiscal completo + estoque opcional
    398          * — é 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 do
    460          * produto no fornecedor, vínculo com o fornecedor (taxonomia
    461          * `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 do
    466          *                                usuário (Draft/Link). Null deixa
    467          *                                resolve_gtin_kind() decidir (persistido
    468          *                                de uma vez anterior, ou heurística por
    469          *                                tamanho).
    470          * @param string      $sku_source 'none'|'gtin'|'product_code' — rádio no
    471          *                                modal "Preencher SKU como", não checkbox.
    472          * @return string 'set'|'has_sku'|'conflict'|'not_applicable' — status do SKU (ver maybe_set_sku()).
    473          */
    474307        protected static function apply_identity_meta( $product_id, array $item, $gtin_kind = null, $sku_source = 'gtin' ) {
    475308                $sku_status = 'not_applicable';
    … …  
    487320                }
    488321
    489                 // "product_code" funciona mesmo sem GTIN na nota (o código do
    490                 // fornecedor sempre existe), por isso fica FORA do bloco
    491322                // `if ($has_gtin)` acima.
    492323                if ( 'gtin' === $sku_source && $has_gtin ) {
    … …  
    496327                }
    497328
    498                 // sbs_supplier_product_code: código que ESTE fornecedor deu a
    499                 // ESTE produto (cProd da nota) — campo do Gerenciador de
    500329                // Códigos da Sheet, dedicado a isso. NUNCA usar
    501                 // 'sbs_supplier_code' aqui: esse é outro campo, o código do
    502                 // FORNECEDOR em si (mirror automático da taxonomia sbs_supplier,
    503                 // ver mirror_to_product() abaixo) — nomes parecidos de propósito
    504330                // mas são conceitos diferentes.
    505331                if ( '' !== $item['product_code'] ) {
    … …  
    514340        }
    515341
    516         /**
    517          * SKU = GTIN ou código do produto — rádio no modal. Só preenche
    518          * quando o produto ainda NÃO TEM SKU — nunca sobrescreve um SKU que
    519          * já existia (catálogo próprio do lojista tem prioridade sobre o
    520          * automático). SKU é único no WooCommerce — `set_sku()` valida isso
    521          * 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 como
    524          * SKU em 2 produtos é sinal de outro problema, não algo pra travar
    525          * a ação inteira), mas devolve o motivo pra quem chamou poder
    526          * avisar o usuário em vez de engolir a falha em silêncio.
    527          *
    528          * @param int    $product_id
    529          * @param string $value GTIN ou código do produto, já validado (não vazio).
    530          * @return string 'set'|'has_sku'|'conflict'.
    531          */
    532342        protected static function maybe_set_sku( $product_id, $value ) {
    533343                $current_sku = get_post_meta( $product_id, '_sku', true );
    … …  
    548358        }
    549359
    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 radio
    553          *      no modal de Draft/Link) — grava como novo padrão do produto.
    554          *   2. Escolha anterior já persistida no produto (Sync/link-update
    555          *      reaplicando sem perguntar de novo).
    556          *   3. Heurística por tamanho — 14 dígitos é GTIN-14, tipicamente
    557          *      código de caixa/pallet no padrão GS1 (não existe GTIN-14 de
    558          *      unidade); 8/12/13 é sempre unidade. Sem heurística melhor
    559          *      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_id
    563          * @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          */
    567360        protected static function resolve_gtin_kind( $product_id, $gtin, $requested_kind ) {
    568361                if ( in_array( $requested_kind, array( 'unit', 'box' ), true ) ) {
    … …  
    582375        }
    583376
    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 como
    588          * "principal" e, se a Sheet Plus estiver ativa, chama
    589          * `mirror_to_product()` dela — é isso que preenche
    590          * `sbs_supplier_code`/`sbs_supplier_name`/telefone/endereço etc.
    591          * sozinho, com o valor certo (código do FORNECEDOR, não do
    592          * produto). Sem Sheet Plus: só o vínculo nativo acontece (visível
    593          * em qualquer lugar que leia a taxonomia), os campos-espelho ficam
    594          * vazios (não existe nada que os leia sem a Sheet mesmo).
    595          *
    596          * Fornecedor não encontrado (nem na Biblioteca do SBNFEBR, nem na
    597          * da Sheet — é a mesma taxonomia): não faz nada, mesmo padrão de
    598          * "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 void
    603          */
    604377        protected static function link_supplier( $product_id, $supplier_cnpj ) {
    605378                $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  
    11<?php
    2 /**
    3  * Log de erros interno do SBNFEBR — mesmo padrão da SanBar EXPress
    4  * 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 tocar
    7  * em cada controller individualmente. Puramente observacional.
    8  *
    9  * @package SBNFEBR
    10  * @since   0.5.1
    11  */
    122
    133defined( 'ABSPATH' ) || exit;
    144
    15 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    16 // 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).
    195class SBNFEBR_Error_Log_Service {
    206
    21         /** Versão do schema — bump aqui força dbDelta rodar de novo em upgrade futuro. */
    227        const DB_VERSION = '1.0';
    238
    24         /** Option key que guarda a versão do schema já aplicada. */
    259        const DB_VERSION_OPTION = 'sbnfebr_error_log_db_version';
    2610
    27         /** Máximo de linhas mantidas no total (mais antigas são descartadas). */
    2811        const MAX_ROWS = 500;
    2912
    30         /** Option key do nível de verbosidade ('all' ou 'errors_only'). */
    3113        const OPTION_LEVEL = 'sbnfebr_error_log_level';
    3214
    33         /** User meta que guarda até quando o usuário já viu o log (ícone volta a normal). */
    3415        const SEEN_META_KEY = 'sbnfebr_errorlog_last_seen';
    3516
    36         /**
    37          * Nome completo da tabela (com prefixo do WP).
    38          *
    39          * @return string
    40          */
    4117        public static function table_name() {
    4218                global $wpdb;
    … …  
    4420        }
    4521
    46         /**
    47          * Cria a tabela se não existir, ou atualiza o schema se DB_VERSION
    48          * mudou. Idempotente.
    49          *
    50          * @return void
    51          */
    5222        public static function create_table() {
    5323                $installed_version = get_option( self::DB_VERSION_OPTION );
    … …  
    8050        }
    8151
    82         /**
    83          * Registra o hook central de captura. Chamado uma vez pelo
    84          * bootstrap em plugins_loaded.
    85          *
    86          * @return void
    87          */
    8852        public static function init() {
    8953                add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'capture' ), 10, 3 );
    9054        }
    9155
    92         /**
    93          * Roda depois de QUALQUER callback REST resolver. Só reage a rotas
    94          * sbnfebr/v1 que voltaram erro (WP_Error, ou WP_REST_Response com
    95          * 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          */
    10256        public static function capture( $response, $handler, $request ) {
    10357                $route = $request->get_route();
    … …  
    13589        }
    13690
    137         /**
    138          * Decide se um status deve ser gravado, conforme o nível
    139          * configurado em Configure ('all' ou 'errors_only'). 'all' grava
    140          * >=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 bool
    145          */
    14691        protected static function should_log( $status ) {
    14792                $level = self::get_level();
    … …  
    15297        }
    15398
    154         /**
    155          * Lê o nível de verbosidade configurado ('all' por padrão).
    156          *
    157          * @return string 'all'|'errors_only'.
    158          */
    15999        public static function get_level() {
    160100                $level = (string) get_option( self::OPTION_LEVEL, 'all' );
    … …  
    162102        }
    163103
    164         /**
    165          * Grava o nível de verbosidade (sanitiza pra um dos 2 valores
    166          * válidos, qualquer outra coisa cai pro default 'all').
    167          *
    168          * @param string $level Valor recebido do cliente.
    169          * @return void
    170          */
    171104        public static function set_level( $level ) {
    172105                $level = 'errors_only' === (string) $level ? 'errors_only' : 'all';
    … …  
    174107        }
    175108
    176         /**
    177          * Grava uma linha e poda o excesso (mantém só as MAX_ROWS mais
    178          * 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 void
    186          */
    187109        protected static function record( $route, $method, $code, $message, $status ) {
    188110                global $wpdb;
    … …  
    209131        }
    210132
    211         /**
    212          * Mantém no máximo MAX_ROWS linhas — apaga as mais antigas
    213          * quando ultrapassa.
    214          *
    215          * @return void
    216          */
    217133        protected static function prune() {
    218134                global $wpdb;
    219135                $table = self::table_name();
    220136
    221                 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName
     137                $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
    222138                if ( $total <= self::MAX_ROWS ) {
    223139                        return;
    … …  
    227143                $wpdb->query( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    228144                        $wpdb->prepare(
    229                                 "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName
     145                                "DELETE FROM {$table} ORDER BY created_at ASC, id ASC LIMIT %d",
    230146                                $excess
    231147                        )
    … …  
    233149        }
    234150
    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          */
    242151        public static function list_entries( $page = 1, $per_page = 30 ) {
    243152                global $wpdb;
    … …  
    247156                $offset   = ( $page - 1 ) * $per_page;
    248157
    249                 $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName
     158                $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
    250159
    251160                $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    252161                        $wpdb->prepare(
    253                                 "SELECT * FROM {$table} ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName
     162                                "SELECT * FROM {$table} ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d",
    254163                                $per_page,
    255164                                $offset
    … …  
    279188        }
    280189
    281         /**
    282          * Estado do ícone (!) — se existe erro mais novo que a última vez
    283          * que o usuário atual abriu o log.
    284          *
    285          * @return array{has_new:bool,count:int}
    286          */
    287190        public static function status_for_current_user() {
    288191                global $wpdb;
    … …  
    294197                if ( $seen ) {
    295198                        $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.InterpolatedTableName
     199                                $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE created_at > %s", $seen )
    297200                        );
    298201                } else {
    299                         $count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQL.InterpolatedTableName
     202                        $count = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
    300203                }
    301204
    … …  
    306209        }
    307210
    308         /**
    309          * Marca "visto agora" pro usuário atual — ícone volta ao normal.
    310          *
    311          * @return void
    312          */
    313211        public static function mark_seen() {
    314212                $user_id = get_current_user_id();
    … …  
    327225                global $wpdb;
    328226                $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.
    330227                $wpdb->query( "TRUNCATE TABLE {$table}" );
    331228        }
  • sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-match-service.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * Checa se um GTIN de item de nota já existe cadastrado em algum
    4  * produto WooCommerce — campo de unidade (`_global_unique_id`) ou
    5  * caixa/pacote (`sbs_gtin_box`).
    6  *
    7  * @package SBNFEBR
    8  * @since   0.5.5
    9  */
    102
    113defined( 'ABSPATH' ) || exit;
    124
    13 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
    14 // Consultas cruzam $wpdb->postmeta/$wpdb->posts (tabelas nativas do WP, não input externo) com
    15 // 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 verificar
    17 // estaticamente um array de %s montado dinamicamente, daí o falso positivo de
    18 // UnfinishedPrepare/InterpolatedNotPrepared em cada uma dessas 3 queries.
    195class SBNFEBR_Match_Service {
    206
    21         /**
    22          * Pra cada GTIN válido da lista, procura produto WooCommerce (não
    23          * lixeira) com o mesmo valor em `_global_unique_id` (unidade) OU em
    24          * `sbs_gtin_box` (caixa/pacote, campo da Sheet). Quando o mesmo valor
    25          * bate nos 2 campos (produtos diferentes), unidade tem prioridade —
    26          * `ORDER BY FIELD()` garante isso antes do "primeiro encontrado
    27          * vence" de baixo. GTIN duplicado em mais de 1 produto (mesmo
    28          * 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          */
    347        public static function match_by_gtin( array $gtins ) {
    358                global $wpdb;
    … …  
    4215                $placeholders = implode( ',', array_fill( 0, count( $gtins ), '%s' ) );
    4316
    44                 // '_sku' cobre catálogo que guarda o GTIN no campo de SKU em vez do
    45                 // campo de GTIN nativo. Sinal mais fraco que os outros 2 (SKU pode
    46                 // coincidir com o GTIN por acaso) — por isso vem por último no
    47                 // 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.
    4917                $sql = $wpdb->prepare(
    5018                        "SELECT pm.meta_value AS gtin, pm.meta_key AS meta_field, p.ID AS product_id, p.post_title AS name
    … …  
    5523                                        AND p.post_type IN ('product', 'product_variation')
    5624                                        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
    5826                        $gtins
    5927                );
    6028
    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
    6330
    6431                $matches = array();
    6532                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                        }
    6836                        if ( isset( $matches[ $row['gtin'] ] ) ) {
    6937                                continue;
    … …  
    8654        }
    8755
    88         /**
    89          * Cruzamento com o cadastro — reaproveita match_by_gtin() e enriquece
    90          * cada achado com o que o modal "Checar cadastro" mostra do lado "No
    91          * cadastro": preço, categoria (só a categoria PAI — se o produto tem
    92          * subcategoria, sobe a árvore até a raiz), marca, e os mesmos campos
    93          * de `get_snapshot()` (estoque, custo, sale_type, campos fiscais).
    94          *
    95          * Marca: WooCommerce não tem taxonomia nativa de marca em toda
    96          * instalação — tenta `product_brand` (nativo desde WC 9.6) e
    97          * `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) é calculado
    101          * 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          */
    10656        public static function registry_check( array $gtins ) {
    10757                $matches = self::match_by_gtin( $gtins );
    … …  
    11969        }
    12070
    121         /**
    122          * Categoria RAIZ do produto (sobe a árvore até o topo, se a
    123          * categoria atribuída for subcategoria) — cabe numa coluna estreita
    124          * sem o caminho completo tipo "Cozinha › Canecas". Usa a primeira
    125          * categoria atribuída quando o produto tem mais de uma — sem
    126          * critério de "principal" nativo no WooCommerce pra desempatar.
    127          *
    128          * @param int $product_id
    129          * @return string Nome da categoria raiz, ou '' se o produto não tem nenhuma.
    130          */
    13171        protected static function get_root_category_name( $product_id ) {
    13272                $terms = get_the_terms( $product_id, 'product_cat' );
    … …  
    13575                }
    13676                $term = $terms[0];
    137                 // Sobe até não ter mais pai — WooCommerce não impõe limite de
    138                 // profundidade, mas categoria de produto raramente passa de 2-3
    139                 // níveis, não precisa de trava de segurança contra loop aqui.
    14077                while ( $term->parent ) {
    14178                        $parent = get_term( $term->parent, 'product_cat' );
    … …  
    14885        }
    14986
    150         /**
    151          * Marca do produto — ver nota de `registry_check()` sobre as 2
    152          * taxonomias tentadas, nessa ordem, primeira que existir vence.
    153          *
    154          * @param int $product_id
    155          * @return string Nome da marca, ou '' se nenhuma taxonomia de marca existir/estiver vazia.
    156          */
    15787        protected static function get_brand_name( $product_id ) {
    15888                foreach ( array( 'product_brand', 'pwb-brand' ) as $taxonomy ) {
    … …  
    16898        }
    16999
    170         /**
    171          * "SEM GTIN"/vazio não é GTIN de verdade — mesmo critério usado em
    172          * SBNFEBR_Draft_Service::apply_fiscal_meta().
    173          *
    174          * @param string $gtin GTIN bruto.
    175          * @return string GTIN normalizado, ou '' se inválido.
    176          */
    177100        protected static function normalize( $gtin ) {
    178101                $gtin = trim( (string) $gtin );
    … …  
    183106        }
    184107
    185         /**
    186          * Segundo critério de matching, usado quando o GTIN não bate. Procura
    187          * produto já vinculado a esse fornecedor+código antes, via
    188          * `_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          */
    193108        public static function match_by_supplier_key( array $keys ) {
    194109                global $wpdb;
    … …  
    201116                $placeholders = implode( ',', array_fill( 0, count( $keys ), '%s' ) );
    202117
    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.
    204118                $sql = $wpdb->prepare(
    205119                        "SELECT pm.meta_value AS supplier_key, p.ID AS product_id, p.post_title AS name
    … …  
    209123                                        AND pm.meta_value IN ({$placeholders})
    210124                                        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
    212126                        $keys
    213127                );
    214128
    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
    217130
    218131                $matches = array();
    219132                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                        }
    222136                        if ( isset( $matches[ $row['supplier_key'] ] ) ) {
    223137                                continue;
    … …  
    233147        }
    234148
    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 ressalva
    239          * de `SBNFEBR_Draft_Service::apply_fiscal_meta()`: pra peso/litro/
    240          * caixa o preço unitário da nota não é diretamente comparável com
    241          * um único "custo", fica de fora do diff por enquanto).
    242          * Também devolve a última escolha lembrada (se o usuário marcou
    243          * "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 conta
    248          *                             como "outro item" no aviso de uso
    249          *                             duplicado (0 = não exclui nenhum).
    250          * @return array{stock:float|null,cost_paid:float|null,sale_type:string,remembered:array}
    251          */
    252149        public static function get_snapshot( $product_id, $exclude_item_id = 0 ) {
    253150                $product_id = (int) $product_id;
    … …  
    269166                        'cost_paid'  => $cost_paid,
    270167                        'sale_type'  => $sale_type,
    271                         // Todos os campos fiscais (não só NCM+custo) — permite o card
    272                         // "Update information" comparar campo a campo com a nota, em
    273                         // vez de um sinal parcial que esconderia mudanças em CEST/
    274168                        // CST/unidades/etc.
    275169                        'ncm'               => (string) get_post_meta( $product_id, '_ncm', true ),
    … …  
    285179                        'cbenef'            => (string) get_post_meta( $product_id, '_cbenef', true ),
    286180                        'fornecedor_st'     => (string) get_post_meta( $product_id, '_fornecedor_st', true ),
    287                         // Identificação do produto — mostrada nos cards de match/link
    288                         // da grid (nome vindo do produto de verdade, não da nota).
    289                         // GTIN usa a chave nativa do WooCommerce (mesma que a Sheet usa
    290                         // no Gerenciador de Códigos, ver class-sbsheet-product-codes-service.php).
    291181                        'name'       => $post ? $post->post_title : '',
    292182                        'sku'        => (string) get_post_meta( $product_id, '_sku', true ),
    293183                        '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 sem
    296184                        // abrir o editor.
    297185                        'price'      => (string) get_post_meta( $product_id, '_price', true ),
    298186                        'created_at' => $post ? $post->post_date : '',
    299187                        'modified_at' => $post ? $post->post_modified : '',
    300                         // "Este produto já está em uso por outro item" — checagem
    301                         // central, usada antes de Link/Sync pra nunca sobrescrever
    302188                        // silenciosamente o que outro item já gravou.
    303189                        'used_by_other_item' => $exclude_item_id
    … …  
    308194                                'price_action' => (string) get_post_meta( $product_id, '_sbnfebr_remember_price_action', true ),
    309195                        ),
    310                         // Deixa a decisão de escopo de identidade visível/alterável a
    311                         // qualquer momento no modal de ação, não só no card de upgrade
    312196                        // na revisão pós-import.
    313197                        'identity_scope' => (string) get_post_meta( $product_id, SBNFEBR_Notes_Service::META_IDENTITY_SCOPE, true ),
    … …  
    315199        }
    316200
    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' ) {
    332202                global $wpdb;
    333203
    … …  
    338208
    339209                $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,
    344214                                        ( SELECT meta_value FROM {$wpdb->postmeta} sm WHERE sm.post_id = p.ID AND sm.meta_key = '_sku' LIMIT 1 ) AS sku
    345215                                FROM {$wpdb->posts} p
    346                                 LEFT JOIN {$wpdb->postmeta} pm_sku ON pm_sku.post_id = p.ID AND pm_sku.meta_key = '_sku'
    347216                                WHERE p.post_type IN ('product', 'product_variation')
    348217                                        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                                        )
    350224                                ORDER BY p.post_title ASC
    351225                                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                );
    358237
    359238                $results = array();
    … …  
    368247                                'name'          => $row['post_title'],
    369248                                'sku'           => (string) $row['sku'],
    370                                 // Thumbnail pra ajudar a identificar visualmente no popup de
    371                                 // link manual — string vazia se o produto não tem imagem,
    372249                                // cliente decide o placeholder.
    373250                                'thumbnail_url' => $thumb_id ? (string) wp_get_attachment_image_url( $thumb_id, 'thumbnail' ) : '',
    374                                 // "Já em uso por outro item" — mesma checagem central do
    375                                 // get_snapshot(), aqui pra marcar visualmente na lista de
    376251                                // resultados antes de escolher.
    377252                                'used_by_other_item' => $other_item,
  • sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-notes-service.php

    r3725460 r3782421  
    11<?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, append
    5  * only — past rows are never edited).
    6  *
    7  * @package SBNFEBR
    8  * @since   0.2.0
    9  */
    102
    113defined( 'ABSPATH' ) || exit;
    124
    13 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    14 // Duas tabelas próprias (sbnfebr_notes/sbnfebr_note_items, fora do schema padrão do WP) — todo
    15 // 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 de
    17 // self::items_table()/self::notes_table() ($wpdb->prefix . 'sbnfebr_...', fixo — nunca input de
    18 // usuário), interpolados em {$items_table}/{$notes_table} e passados por $wpdb->prepare() pros
    19 // valores de verdade (%s/%d) em toda query — o "unescaped parameter" é o SQL final já preparado,
    205// não dado cru do usuário.
    216class SBNFEBR_Notes_Service {
    227
    23         /** Versão do schema — bump aqui força dbDelta rodar de novo em upgrade futuro. */
    248        const DB_VERSION = '1.6';
    259
    26         /** Option key que guarda a versão do schema já aplicada. */
    2710        const DB_VERSION_OPTION = 'sbnfebr_notes_db_version';
    2811
    29         /**
    30          * Nome completo (com prefixo do site) da tabela de cabeçalho de notas.
    31          *
    32          * @return string
    33          */
    3412        public static function notes_table() {
    3513                global $wpdb;
    … …  
    3715        }
    3816
    39         /**
    40          * Nome completo (com prefixo do site) da tabela de itens.
    41          *
    42          * @return string
    43          */
    4417        public static function items_table() {
    4518                global $wpdb;
    … …  
    4720        }
    4821
    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ão
    52          * SQL — nome de coluna nunca dá pra parametrizar como valor de
    53          * `$wpdb->prepare()`, então NUNCA aceitar o que vier do cliente direto
    54          * 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 string
    61          */
    6222        private static function resolve_order_by( array $args, array $whitelist, $default ) {
    6323                $key = isset( $args['order_by'] ) ? (string) $args['order_by'] : '';
    … …  
    6929        }
    7030
    71         /**
    72          * Cria (ou atualiza) as duas tabelas via dbDelta. Idempotente —
    73          * só roda de fato quando DB_VERSION muda.
    74          *
    75          * @return void
    76          */
    7731        public static function create_table() {
    7832                $installed_version = get_option( self::DB_VERSION_OPTION );
    … …  
    8640                $items_table     = self::items_table();
    8741
    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.
    9042                $sql_notes = "CREATE TABLE {$notes_table} (
    9143                        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    … …  
    179131        }
    180132
    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          */
    187133        public static function find_by_access_key( $access_key ) {
    188134                global $wpdb;
    … …  
    190136
    191137                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
    211142        public static function save_note( array $parsed ) {
    212143                global $wpdb;
    … …  
    226157                $row = array(
    227158                        'access_key'          => $header['access_key'],
    228                         // SHA-256 do XML original — a chave de acesso já é bloqueada
    229                         // contra reimport (ver check acima); o hash serve como trilha
    230                         // de auditoria (mesma chave sempre deveria ter o mesmo hash —
    231                         // se não tiver, algo alterou o XML depois de emitido) e pra um
    232                         // futuro "Reprocessar XML" saber se o conteúdo realmente mudou.
    233159                        'xml_hash'            => hash( 'sha256', $parsed['raw_xml'] ),
    234160                        'note_number'         => $header['note_number'],
    … …  
    266192                );
    267193
    268                 // $wpdb->insert() usa %s por padrão pra todo campo — um valor PHP
    269                 // null nesse placeholder vira string vazia '', não SQL NULL, o que
    270                 // quebraria insert em coluna DATETIME (não aceita '' como data)
    271                 // sob SQL strict mode. Remove a chave inteira quando null: a
    272                 // coluna nem entra no INSERT, MySQL usa NULL por conta própria
    273194                // (nenhuma das duas tem DEFAULT explícito != NULL).
    274195                foreach ( array( 'exit_entry_date', 'protocol_date' ) as $nullable_date_key ) {
    … …  
    278199                }
    279200
    280                 // Transação cobre cabeçalho + todos os itens — ou grava a nota
    281                 // inteira, ou não grava nada. Tabelas do plugin usam o engine
    282                 // padrão do WordPress (InnoDB), que suporta transação real.
    283201                $wpdb->query( 'START TRANSACTION' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
    284202
    … …  
    286204                if ( false === $insert_ok ) {
    287205                        $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
    290207                        return new WP_Error(
    291208                                'sbnfebr_save_failed',
    … …  
    310227                        if ( false === $ok ) {
    311228                                $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
    314230                                return new WP_Error(
    315231                                        'sbnfebr_partial_save',
    … …  
    322238                                );
    323239                        }
     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                        }
    324251                        ++$inserted;
    325252                }
    326253
    327254                $wpdb->query( 'COMMIT' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
     255
     256                do_action( 'sbnfebr_note_items_saved', $note_id );
    328257
    329258                if ( class_exists( 'SBNFEBR_Audit_Service' ) ) {
    … …  
    345274        }
    346275
    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
    361295        public static function get_items( array $args = array() ) {
    362296                global $wpdb;
    … …  
    367301                $params = array();
    368302
    369                 // Ordenação por coluna, Fornecedor/Descrição só (whitelist fixa,
    370                 // nome de coluna não dá pra parametrizar como valor — nunca
    371                 // aceitar o que vier do cliente direto no ORDER BY). Sem
    372                 // $args['order_by'] reconhecido, mantém o padrão (data da nota).
    373303                $order_sql = self::resolve_order_by(
    374304                        $args,
    … …  
    387317                if ( ! empty( $args['search'] ) ) {
    388318                        $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)';
    390320                        $params[] = $like;
    391321                        $params[] = $like;
    392322                        $params[] = $like;
    393                 }
    394 
    395                 // Busca direta por lista de IDs — usada pra buscar os dados
     323                        $params[] = $like;
     324                }
     325
    396326                // completos de uma SELEÇÃO que pode ter itens de
    397                 // páginas diferentes ("Copy codes"/"Show only selected" cruzando
    398                 // página — a seleção sobrevive à paginação, mas o cliente só tem
    399                 // os dados da página atual carregada; isso busca o resto).
    400327                $ids_filter = array();
    401328                if ( ! empty( $args['ids'] ) && is_array( $args['ids'] ) ) {
    … …  
    408335                }
    409336
    410                 // Itens ignorados somem de TODA visão por padrão — só aparecem
    411337                // com mode='ignored' explicitamente. Evita que a
    412                 // lista de "pendentes" continue poluída depois de marcar algo
    413338                // como "nunca vai virar produto".
    414339                $mode_arg = isset( $args['mode'] ) ? (string) $args['mode'] : '';
    … …  
    419344                }
    420345
    421                 // Filtro de modo (select "Filtro" na toolbar) — 4 opções, mutuamente
    422                 // exclusivas. 'duplicates' e 'price_period' reaproveitam a mesma
    423                 // noção de "GTIN em fornecedor diferente" / "preço variou" que já
    424346                // alimenta as cores do ícone de histórico.
    425347                $mode      = isset( $args['mode'] ) ? (string) $args['mode'] : '';
    … …  
    431353
    432354                if ( 'duplicates' === $mode ) {
    433                         // Mesmo GTIN visto em mais de 1 fornecedor — mesmo critério
    434355                        // que pinta o ícone de histórico de vermelho.
    435356                        $where[] = "(
    … …  
    439360                        ) > 1";
    440361                } elseif ( 'notes_period' === $mode && $date_from && $date_to ) {
    441                         // Simples: só itens de notas emitidas dentro do intervalo.
    442362                        $where[]  = 'n.emission_date BETWEEN %s AND %s';
    443363                        $params[] = $date_from;
    444364                        $params[] = $date_to;
    445365                } elseif ( 'price_period' === $mode && $date_from && $date_to ) {
    446                         // Acha os pares fornecedor+código que variaram de preço DENTRO
    447                         // do intervalo, depois mostra o HISTÓRICO COMPLETO desses
    448                         // produtos (inclusive notas fora do intervalo, como contexto)
    449                         // — por isso o filtro de data não entra direto no WHERE
    450                         // principal, só serve pra decidir QUAIS produtos aparecem.
    451366                        $join_sql      = "INNER JOIN (
    452367                                SELECT i5.supplier_cnpj AS flag_cnpj, i5.product_code AS flag_code
    … …  
    459374                        $join_params[] = $date_from;
    460375                        $join_params[] = $date_to;
     376                } elseif ( self::catalog_mode_clause( $mode ) ) {
     377                        $where[] = self::catalog_mode_clause( $mode );
    461378                } elseif ( 'linked' === $mode ) {
    462                         // Já tem produto vinculado (ícone ✓ verde) — filtro de ESTADO
    463379                        // atual, sem depender de período.
    464380                        $where[] = 'i.wc_product_id IS NOT NULL';
    … …  
    467383                        $where[] = 'i.wc_product_id IS NULL';
    468384                } elseif ( 'price_warn' === $mode ) {
    469                         // Mesmo critério do ícone âmbar de histórico: preço variou
    470                         // entre notas do mesmo fornecedor+código, SEM limite de período
    471                         // (esse já existe como price_period, este aqui é "sempre").
    472385                        $where[] = "(
    473386                                SELECT COUNT(DISTINCT ROUND(i6.unit_value, 2))
    … …  
    476389                        ) > 1";
    477390                } elseif ( 'supplier_match' === $mode ) {
    478                         // Itens ainda sem produto, mas que batem por fornecedor+código
    479                         // com um produto JÁ cadastrado (mesma chave que alimenta o
    480                         // ícone "!" vermelho/match_source='supplier_key' no cliente —
    481                         // ver match_by_supplier_key() em class-sbnfebr-match-service.php).
    482391                        $where[] = 'i.wc_product_id IS NULL';
    483392                        $where[] = $wpdb->prepare(
    … …  
    493402                        );
    494403                } elseif ( 'sync_pending' === $mode ) {
    495                         // Item já vinculado, mas o produto nunca recebeu fiscal (NCM
    496                         // vazio — ex: linkado via Lite) OU o NCM gravado é diferente
    497                         // do que esta nota traz — sinal de "precisa de Sync"
    498                         // Mesmo sinal parcial (só NCM) já usado no card "Update
    499404                        // information" — não é diff completo
    500                         // de CEST/CST/CFOP/impostos/custo, cobre o caso mais comum.
    501405                        $where[] = 'i.wc_product_id IS NOT NULL';
    502406                        $where[] = "(
    … …  
    506410                        )";
    507411                } elseif ( 'has_fiscal' === $mode ) {
    508                         // Oposto exato de sync_pending: vinculado E com o NCM desta
    509                         // nota já gravado no produto (fiscal sincronizado). Plus only,
    510                         // mesmo dado (NCM) que sync_pending já usa como sinal.
    511412                        $where[] = 'i.wc_product_id IS NOT NULL';
    512413                        $where[] = "i.ncm <> ''";
    513414                        $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";
    514415                } elseif ( 'stale' === $mode ) {
    515                         // Mesma regra de get_stale_reason(): produto vinculado que sumiu/
    516                         // foi pra lixeira, ou cujo GTIN atual diverge do snapshot
    517416                        // gravado no momento do vínculo.
    518417                        $where[] = "i.wc_product_id IS NOT NULL AND (
    … …  
    528427                }
    529428
    530                 // price_variants / gtin_supplier_count alimentam os 3 estados do
    531                 // ícone de histórico na grid (cinza/âmbar/vermelho) — calculados
    532                 // 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 cruzando
    535                 // itens sem GTIN de fornecedores diferentes). ROUND(unit_value,2)
    536                 // na comparação de price_variants: `vUnCom` do XML às vezes vem
    537429                // com 10 casas decimais (resultado de divisão, ex:
    538                 // 5.8316666667) — sem arredondar, duas notas com o MESMO preço
    539                 // em reais/centavos podiam contar como "variou" por causa de
    540                 // ruído de precisão que o usuário nem vê na tela.
    541430                $sql = "SELECT i.*, n.note_number, n.series, n.emission_date, n.supplier_name,
    542431                                (
    … …  
    565454                        ORDER BY ' . $order_sql;
    566455
    567                 // join_params vem ANTES de params na string final (o JOIN aparece
    568                 // antes do WHERE no SQL), a ordem dos placeholders precisa bater.
    569456                $all_params = array_merge( $join_params, $params );
    570457
    571                 // Paginação — lista sem limite pesava com muitos itens (sem
    572                 // rolagem virtual, tudo no DOM de uma vez). 25/50/75/100,
    573                 // mesmas opções que a preferência salva no cliente oferece.
    574458                $per_page_options = array( 25, 50, 75, 100 );
    575459                if ( $ids_filter ) {
    576                         // Busca por ID explícita — devolve todos de uma vez, sem as
    577                         // opções fechadas de per_page (é uma seleção pontual, não
    578460                        // navegação de catálogo).
    579461                        $per_page = count( $ids_filter );
    … …  
    585467                }
    586468
    587                 // Total ANTES do LIMIT — mesmo WHERE/JOIN do SQL principal, sem os
    588                 // subselects de price_variants/gtin_supplier_count/linked_ncm
    589469                // (não afetam contagem, só custariam à toa).
    590470                $count_sql = "SELECT COUNT(*), COUNT(DISTINCT i.note_id)
    … …  
    598478                $note_count     = $count_row ? (int) $count_row[1] : 0;
    599479
    600                 // Skips the row fetch below — used by the per-product view to get
    601                 // the true item count for the "Items" stat without paying for the
    602                 // full row query (mirrors get_items_by_product()'s count_only).
    603480                if ( ! empty( $args['count_only'] ) ) {
    604481                        return array( 'total' => $total, 'note_count' => $note_count );
    … …  
    610487                $items        = $wpdb->get_results( $prepared, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    611488
    612                 // Apelido: troca supplier_name pelo apelido na grid, quando o
    613                 // fornecedor tem "Exibir apelido" marcado. Nada mais depende do
    614                 // nome legal aqui (filtro usa supplier_cnpj), seguro trocar direto.
    615489                self::apply_supplier_nicknames( $items );
    616490                self::apply_stale_flags( $items );
    … …  
    625499        }
    626500
    627         /**
    628          * Troca `supplier_name` pelo apelido, in-place, nas linhas que
    629          * tiverem `supplier_cnpj` batendo com o mapa de apelidos.
    630          * Helper comum entre get_items() e get_items_by_product() — mesma
    631          * regra, 2 formatos de linha diferentes.
    632          *
    633          * @param array[] $rows Alterado por referência.
    634          * @return void
    635          */
    636501        protected static function apply_supplier_nicknames( array &$rows ) {
    637502                if ( ! $rows || ! class_exists( 'SBNFEBR_Supplier_Service' ) ) {
    … …  
    650515        }
    651516
    652         /**
    653          * Agrega itens por identidade de produto (GTIN, ou fornecedor+código
    654          * quando não há GTIN) — visão "por produto" em vez de "por
    655          * lançamento de nota" — cada linha do resultado é 1 produto, não 1
    656          * ocorrência numa nota. Mesma noção de identidade de
    657          * 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 o
    661          * 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ão
    665          * por produto sempre esconde item ignorado, sem exceção). Os
    666          * filtros entram no WHERE ANTES do GROUP BY, então note_count/
    667          * supplier_count refletem só o escopo filtrado (comportamento
    668          * 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 array
    672          */
    673517        public static function get_items_by_product( array $args = array() ) {
    674518                global $wpdb;
    … …  
    683527                        $params[] = $args['supplier_cnpj'];
    684528                }
    685                 // Mesmo tratamento de get_items(): filtra as linhas ANTES do
    686                 // GROUP BY, então note_count/supplier_count também refletem só o
    687                 // escopo filtrado — mesmo comportamento esperado em qualquer
    688529                // outro filtro da grid.
    689530                if ( ! empty( $args['note_id'] ) ) {
    … …  
    693534                if ( ! empty( $args['search'] ) ) {
    694535                        $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)';
    696537                        $params[] = $like;
    697538                        $params[] = $like;
    698539                        $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
    704543                // desta mesma query.
    705544                $mode      = isset( $args['mode'] ) ? (string) $args['mode'] : '';
    … …  
    725564                        $join_params[] = $date_from;
    726565                        $join_params[] = $date_to;
     566                } elseif ( self::catalog_mode_clause( $mode ) ) {
     567                        $where[] = self::catalog_mode_clause( $mode );
    727568                } elseif ( 'linked' === $mode ) {
    728569                        $where[] = 'i.wc_product_id IS NOT NULL';
    … …  
    776617                $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";
    777618                $where_sql      = implode( ' AND ', $where );
    778                 // join_params vem ANTES de params (o JOIN aparece antes do WHERE
    779619                // no SQL final) — mesma ordem de get_items().
    780620                $count_join_params = array_merge( $join_params, $params );
    … …  
    792632                $total          = (int) $wpdb->get_var( $count_prepared ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    793633
    794                 // Badge "Produtos únicos" na barra de stats, visível nos 2 modos
    795634                // de visão. Só precisa do
    796                 // $total acima (já conta identidade com E sem GTIN, a expressão
    797                 // CASE cobre os 2 casos) — pula os 2 SELECTs pesados (grupo +
    798                 // linhas representantes) que só fazem sentido pra renderizar a
    799635                // grid de verdade.
    800636                if ( ! empty( $args['count_only'] ) ) {
    … …  
    807643                $page             = max( 1, (int) ( $args['page'] ?? 1 ) );
    808644
    809                 // MAX(i.id) como "linha representante" do grupo — mais barato que
    810                 // subquery correlacionada por data, e id crescente já é uma boa
    811                 // aproximação de "ocorrência mais recente" (inserção segue a
    812645                // ordem de import).
    813                 // COUNT(DISTINCT i.supplier_cnpj) sem CASE de propósito: no grupo
    814                 // sem GTIN, supplier_cnpj já É parte da chave de identidade (só
    815                 // pode dar 1); no grupo por GTIN, conta os fornecedores de
    816646                // verdade que já venderam esse mesmo GTIN.
    817                 // Ordenação por Descrição também na visão por produto (Fornecedor
    818                 // não existe aqui, é agregado — ver PRODUCT_COLS no front).
    819                 // MAX(i.description) como valor representante do grupo (mesmo
    820647                // raciocínio de rep_item_id).
    821648                $order_sql = self::resolve_order_by(
    … …  
    854681                }
    855682
    856                 // Dados completos das linhas representantes, mesmo formato de
    857                 // get_items() — grid/modal reaproveitam sem adaptação nenhuma.
    858683                $rep_ids          = array_map( function ( $g ) { return (int) $g['rep_item_id']; }, $groups );
    859684                $id_placeholders  = implode( ',', array_fill( 0, count( $rep_ids ), '%d' ) );
    860                 // price_variants: mesma noção de sempre, escopada ao
    861685                // fornecedor/código da LINHA REPRESENTANTE (mesmo
    862                 // critério já usado na visão por nota, sem inventar um novo).
    863686                $rows_sql         = "SELECT i.*, n.note_number, n.series, n.emission_date, n.supplier_name,
    864687                                (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,
    … …  
    889712                                continue;
    890713                        }
    891                         // wc_product_id agregado (MAX de todo o grupo) — a linha
    892714                        // representante já devia estar sincronizada por
    893                         // propagate_link(), mas usa o agregado por garantia (cobre
    894                         // uma eventual dessincronia sem precisar rodar migração).
    895715                        $row['wc_product_id']          = $g['wc_product_id'] ? (int) $g['wc_product_id'] : null;
    896716                        $row['product_note_count']     = (int) $g['note_count'];
    897717                        $row['product_supplier_count'] = (int) $g['supplier_count'];
    898                         // Data da nota mais recente do grupo inteiro, já calculada pra
    899                         // ordenar (latest_date); só devolve pro cliente em vez de descartar.
    900718                        $row['product_last_date']      = $g['latest_date'];
    901719                        if ( $row['wc_product_id'] ) {
    … …  
    905723                }
    906724
    907                 // Estoque atual — 1 query só pra todos os produtos
    908                 // 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 SELECT
    910725                // que já tem i.*).
    911726                if ( $linked_product_ids ) {
    … …  
    933748        }
    934749
    935         /**
    936          * Busca 1 item pelo ID — usado pra descobrir supplier_cnpj/product_code
    937          * 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|null
    941          */
    942750        public static function get_item( $item_id ) {
    943751                global $wpdb;
    … …  
    945753
    946754                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.InterpolatedTableName
     755                        $wpdb->prepare( "SELECT * FROM {$items_table} WHERE id = %d", (int) $item_id ),
    948756                        ARRAY_A
    949757                );
    950758        }
    951759
    952         /**
    953          * Marca/desmarca um ou mais itens como "ignorado" — item que o
    954          * usuário decidiu que nunca vai virar produto (amostra, brinde, uso
    955          * interno etc). Some da visão padrão (ver get_items()), só aparece
    956          * com o filtro "Ignored" ativo. Não mexe em `wc_product_id` nem em
    957          * 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          */
    963760        public static function set_ignored( array $item_ids, $ignored ) {
    964761                global $wpdb;
    … …  
    971768
    972769                $placeholders = implode( ',', array_fill( 0, count( $item_ids ), '%d' ) );
    973                 // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- placeholders montados acima, valores via prepare().
    974770                return (int) $wpdb->query(
    975771                        $wpdb->prepare(
    … …  
    980776        }
    981777
    982         /**
    983          * Checa se um produto já está vinculado a ALGUM outro item de nota
    984          * (diferente do informado) — base do aviso "este produto já está em
    985          * uso" antes de Link/Sync, evitando que 2 itens diferentes apontem
    986          * 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" (o
    990          *                             próprio item da ação em andamento).
    991          * @return array|null { id, description, note_number, series } ou null.
    992          */
    993778        public static function get_other_item_using_product( $product_id, $exclude_item_id ) {
    994779                global $wpdb;
    … …  
    1010795        }
    1011796
    1012         /**
    1013          * Busca 1 nota (cabeçalho) pelo ID — usado pelo Draft Service pra
    1014          * ler o CRT do fornecedor (decide CSOSN vs CST) na hora de criar o
    1015          * rascunho.
    1016          *
    1017          * @param int $note_id ID da linha em sbnfebr_notes.
    1018          * @return array|null
    1019          */
    1020797        public static function get_note( $note_id ) {
    1021798                global $wpdb;
    … …  
    1023800
    1024801                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.InterpolatedTableName
     802                        $wpdb->prepare( "SELECT * FROM {$notes_table} WHERE id = %d", (int) $note_id ),
    1026803                        ARRAY_A
    1027804                );
    1028805        }
    1029806
    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ão
    1033          * 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_Error
    1038          */
    1039807        public static function delete_note( $note_id ) {
    1040808                global $wpdb;
    … …  
    1078846        }
    1079847
    1080         /**
    1081          * Grava o `wc_product_id` numa linha de item — chamado depois que o
    1082          * 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 void
    1087          */
    1088848        public static function set_item_product_id( $item_id, $product_id ) {
    1089849                global $wpdb;
    … …  
    1100860        }
    1101861
    1102         /**
    1103          * Compara o snapshot gravado no vínculo contra o estado atual do
    1104          * produto. Só GTIN e existência — nome muda por motivos cosméticos
    1105          * o tempo todo, comparar geraria falso positivo constante. A UI oferece
    1106          * ações diferentes pra cada motivo (produto sumiu: só religar; GTIN
    1107          * 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          */
    1112862        public static function get_stale_reason( array $item ) {
    1113863                $product_id = (int) ( $item['wc_product_id'] ?? 0 );
    … …  
    1127877        }
    1128878
    1129         /**
    1130          * Preenche `stale`/`stale_reason` nas linhas, carregando posts e postmeta
    1131          * de todos os produtos vinculados em lote (2 queries no total) em vez de
    1132          * 1-2 por linha dentro de get_stale_reason().
    1133          *
    1134          * @param array $items Linhas de sbnfebr_note_items, por referência.
    1135          * @return void
    1136          */
    1137879        protected static function apply_stale_flags( array &$items ) {
    1138880                $product_ids = array();
    … …  
    1154896        }
    1155897
    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 void
    1163          */
    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.NotPrepared
    1169                         $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.InterpolatedNotPrepared
    1171                                 (string) get_post_meta( $product_id, '_global_unique_id', true ),
    1172                                 (string) get_the_title( $product_id ),
    1173                                 $product_id
    1174                         )
    1175                 );
    1176         }
    1177 
    1178         /**
    1179          * Acha um item vinculado a $product_id cuja identidade seja DIFERENTE
    1180          * da de $item (mesmo critério de propagate_link(): GTIN, ou
    1181          * fornecedor+código quando sem GTIN) — impõe "1 produto do cadastro
    1182          * = 1 identidade da NFE", usado por enforce_single_link() antes de
    1183          * 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          */
    1189898        public static function find_link_conflict( array $item, $product_id ) {
    1190899                global $wpdb;
    … …  
    1198907                                "SELECT i.*, n.note_number, n.series FROM {$items_table} i
    1199908                                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.InterpolatedTableName
     909                                WHERE i.wc_product_id = %d AND i.gtin <> %s LIMIT 1",
    1201910                                (int) $product_id,
    1202911                                $gtin
    … …  
    1206915                                "SELECT i.*, n.note_number, n.series FROM {$items_table} i
    1207916                                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.InterpolatedTableName
     917                                WHERE i.wc_product_id = %d AND ( i.supplier_cnpj <> %s OR i.product_code <> %s ) LIMIT 1",
    1209918                                (int) $product_id,
    1210919                                (string) ( $item['supplier_cnpj'] ?? '' ),
    … …  
    1216925        }
    1217926
    1218         /**
    1219          * Desvincula só a IDENTIDADE de $item (mesmo escopo de propagate_link:
    1220          * GTIN, ou fornecedor+código sem GTIN) — diferente de
    1221          * clear_product_link(), que limpa TODA linha apontando pro produto
    1222          * (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 void
    1226          */
    1227927        public static function unlink_identity( array $item ) {
    1228928                global $wpdb;
    … …  
    1252952        }
    1253953
    1254         /**
    1255          * Trava "1 produto do cadastro = 1 identidade da NFE" — chamado por
    1256          * todo caminho que grava
    1257          * wc_product_id num produto ESCOLHIDO pelo usuário (link manual,
    1258          * match automático, ou implícito via Estoque/Preço/Fiscal quando o
    1259          * item ainda não tinha vínculo). Sem $reassign, recusa e devolve os
    1260          * dados do conflito pro front alertar antes de deixar escolher; com
    1261          * $reassign=true, desvincula a identidade antiga primeiro (não o
    1262          * produto todo — outros itens de OUTRAS identidades continuam como
    1263          * 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_Error
    1269          */
    1270954        public static function enforce_single_link( array $item, $product_id, $reassign = false ) {
    1271955                $conflict = self::find_link_conflict( $item, $product_id );
    … …  
    1295979        }
    1296980
    1297         /**
    1298          * Identidade de produto: pra qualquer linha que
    1299          * compartilhe a MESMA identidade de outra já vinculada, "já tem
    1300          * 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); sem
    1303          * GTIN, fornecedor+código só é confiável DENTRO do mesmo fornecedor
    1304          * (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). */
    1310981        const META_IDENTITY_SCOPE = '_sbnfebr_identity_scope';
    1311982
    … …  
    1318989                        $pid = $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    1319990                                $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.InterpolatedTableName
     991                                        "SELECT wc_product_id FROM {$items_table} WHERE gtin = %s AND wc_product_id > 0 LIMIT 1",
    1321992                                        $gtin
    1322993                                )
    … …  
    1324995                        $pid = $pid ? (int) $pid : 0;
    1325996
    1326                         // Produto marcado "supplier_only" nunca aceita match por GTIN
    1327                         // vindo de fornecedor diferente do que
    1328                         // já está vinculado — só um "Ampliar identificação" explícito
    1329                         // (ver set_identity_scope()) libera isso.
    1330997                        if ( $pid && 'supplier_only' === get_post_meta( $pid, self::META_IDENTITY_SCOPE, true ) ) {
    1331998                                $same_supplier = $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    1332999                                        $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.InterpolatedTableName
     1000                                                "SELECT wc_product_id FROM {$items_table} WHERE gtin = %s AND supplier_cnpj = %s AND wc_product_id > 0 LIMIT 1",
    13341001                                                $gtin,
    13351002                                                (string) ( $item['supplier_cnpj'] ?? '' )
    … …  
    13471014                $pid = $wpdb->get_var( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    13481015                        $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.InterpolatedTableName
     1016                                "SELECT wc_product_id FROM {$items_table} WHERE supplier_cnpj = %s AND product_code = %s AND wc_product_id > 0 LIMIT 1",
    13501017                                $item['supplier_cnpj'],
    13511018                                $item['product_code']
    … …  
    13551022        }
    13561023
    1357         /**
    1358          * Grava a decisão do usuário (revisão pós-import) sobre um
    1359          * produto que ganhou GTIN novo: 'expand' remove a restrição (GTIN
    1360          * 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_id
    1365          * @param string $decision 'expand'|'restrict'.
    1366          * @return void
    1367          */
    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 mesma
    1378          * identidade do item vinculado — não só a linha que disparou a
    1379          * ação. Mesmo escopo de resolve_linked_product_id(): GTIN cruza
    1380          * 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 void
    1386          */
    13871024        public static function propagate_link( array $item, $product_id ) {
    13881025                global $wpdb;
    … …  
    14161053        }
    14171054
    1418         /**
    1419          * Limpa `wc_product_id` de toda linha que apontava pro produto —
    1420          * chamado quando o produto é excluído/apagado, e também pelo
    1421          * "Unlink": como propagate_link() garante que
    1422          * toda a família aponta pro MESMO produto, limpar por `wc_product_id`
    1423          * já É a propagação reversa correta — não precisa recalcular
    1424          * identidade de novo pra desvincular.
    1425          *
    1426          * @param int $product_id ID do produto WooCommerce removido/desvinculado.
    1427          * @return void
    1428          */
    14291055        public static function clear_product_link( $product_id ) {
    14301056                global $wpdb;
    … …  
    14401066        }
    14411067
    1442         /**
    1443          * Re-vincula toda linha que apontava pro post_id antigo pro post_id
    1444          * novo — mesma ideia de clear_product_link() (atualiza por
    1445          * `wc_product_id`, sem precisar recalcular identidade), só que troca
    1446          * em vez de zerar. Update direto, sem passar por link_existing()/
    1447          * enforce_single_link(): não é um vínculo NOVO sendo criado, é o
    1448          * 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 void
    1455          */
    14561068        public static function move_product_link( $old_product_id, $new_product_id ) {
    14571069                global $wpdb;
    … …  
    14681080        }
    14691081
    1470         /**
    1471          * "Deslinkar" — desfaz o vínculo de toda a família (não só a linha
    1472          * clicada, mantendo consistência com "GTIN é 1 produto só"). Não
    1473          * 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          */
    14781082        public static function unlink_item( $item_id ) {
    14791083                $item = self::get_item( $item_id );
    … …  
    14851089        }
    14861090
    1487         /**
    1488          * Price history of a product within one supplier — every occurrence
    1489          * 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          */
    14951091        public static function get_price_history( $supplier_cnpj, $product_code ) {
    14961092                global $wpdb;
    … …  
    15051101                                INNER JOIN {$notes_table} n ON n.id = i.note_id
    15061102                                WHERE i.supplier_cnpj = %s AND i.product_code = %s
    1507                                 ORDER BY n.emission_date ASC", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName
     1103                                ORDER BY n.emission_date ASC",
    15081104                                $supplier_cnpj,
    15091105                                $product_code
    … …  
    15131109        }
    15141110
    1515         /**
    1516          * Ocorrências do mesmo GTIN em fornecedores DIFERENTES do informado —
    1517          * alimenta a seção "Também comprado de outros fornecedores" do modal
    1518          * de histórico, só quando o ícone está no estado vermelho (GTIN visto
    1519          * 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          */
    15261111        public static function get_cross_supplier_history( $gtin, $exclude_supplier_cnpj ) {
    15271112                $gtin = trim( (string) $gtin );
    … …  
    15411126                                INNER JOIN {$notes_table} n ON n.id = i.note_id
    15421127                                WHERE i.gtin = %s AND i.supplier_cnpj <> %s
    1543                                 ORDER BY n.emission_date ASC", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName
     1128                                ORDER BY n.emission_date ASC",
    15441129                                $gtin,
    15451130                                $exclude_supplier_cnpj
    … …  
    15491134        }
    15501135
    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 = '' ) {
    16821137                $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 ) ) ) {
    16841140                        return array();
    16851141                }
    … …  
    16881144                $items_table = self::items_table();
    16891145                $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;
    16901150
    16911151                return $wpdb->get_results( // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    … …  
    16961156                                FROM {$items_table} i
    16971157                                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
    17021161                        ),
    17031162                        ARRAY_A
    … …  
    17051164        }
    17061165
    1707         /**
    1708          * Retorna o retrato mais recente (nota mais nova) dos dados do
    1709          * emitente pra um CNPJ — usado pra pré-preencher o cadastro de
    1710          * fornecedor (ícone "!" na toolbar) com nome/IE/telefone/endereço
    1711          * já capturados de alguma nota importada, sem o usuário digitar
    1712          * 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          */
    17171166        public static function get_supplier_snapshot( $supplier_cnpj ) {
    17181167                global $wpdb;
    … …  
    17251174                                        supplier_district, supplier_city, supplier_state
    17261175                                FROM {$notes_table} WHERE supplier_cnpj = %s
    1727                                 ORDER BY emission_date DESC LIMIT 1", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedTableName
     1176                                ORDER BY emission_date DESC LIMIT 1",
    17281177                                $supplier_cnpj
    17291178                        ),
    … …  
    17501199        }
    17511200
    1752         /**
    1753          * Lista fornecedores distintos já importados (pro seletor da toolbar).
    1754          *
    1755          * @return array[] Cada item: cnpj, name.
    1756          */
    17571201        public static function get_suppliers() {
    17581202                global $wpdb;
    … …  
    17671211                );
    17681212
    1769                 // Apelido: troca o nome exibido no seletor de fornecedor pelo
    17701213                // apelido, quando o fornecedor tem
    1771                 // "Exibir apelido" marcado. Reordena depois (a ordenação do SQL
    1772                 // usou o nome legal, apelido pode bagunçar a ordem alfabética).
    17731214                $nicknames = SBNFEBR_Supplier_Service::get_nickname_map();
    17741215                if ( $nicknames ) {
    … …  
    17871228        }
    17881229
    1789         /**
    1790          * Note/item counts per supplier CNPJ — used by the Suppliers Library
    1791          * to distinguish "has an active note" from "registered but no note
    1792          * currently linked" (only counts what exists now; a deleted note
    1793          * drops out on its own, no extra bookkeeping needed).
    1794          *
    1795          * @return array Map cnpj => { note_count, item_count }.
    1796          */
    17971230        public static function get_supplier_note_stats() {
    17981231                global $wpdb;
    … …  
    18181251        }
    18191252
    1820         /**
    1821          * Lista notas, opcionalmente filtradas por fornecedor (pro seletor
    1822          * de nota da toolbar, nível 2 da navegação, e pro Gerenciador de
    1823          * Notas). `items_count` e `total_value` vêm junto pra alimentar a
    1824          * 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          */
    18291253        public static function get_notes( $supplier_cnpj = '' ) {
    18301254                global $wpdb;
    … …  
    18431267                $rows = $wpdb->get_results( $sql, ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
    18441268
    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.
    18471269                foreach ( $rows as &$row ) {
    18481270                        $totals             = json_decode( (string) $row['totals_json'], true );
    … …  
    18551277        }
    18561278
    1857         /**
    1858          * Detalhe completo de 1 nota — dados que só existem no XML e nunca
    1859          * aparecem na tela normal (frete,
    1860          * base de cálculo, duplicatas, transporte). Nada novo é parseado
    1861          * 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_id
    1866          * @return array|null
    1867          */
    18681279        public static function get_note_detail( $note_id ) {
    18691280                global $wpdb;
    … …  
    18711282
    18721283                $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.InterpolatedTableName
     1284                        $wpdb->prepare( "SELECT * FROM {$notes_table} WHERE id = %d", (int) $note_id ),
    18741285                        ARRAY_A
    18751286                );
  • sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-supplier-service.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * Fornecedor (supplier) — integração com a taxonomia `sbs_supplier` da
    4  * SanBar EXPress Sheet (mesmo namespace de dado, mesmas chaves de term
    5  * meta). Registrada por QUALQUER um dos dois plugins que carregar
    6  * primeiro — a taxonomia e o term meta vivem nas tabelas nativas do
    7  * WordPress (`wp_terms`/`wp_term_taxonomy`/`wp_termmeta`), não
    8  * pertencem a nenhum plugin específico.
    9  *
    10  * Se a Sheet já registrou `sbs_supplier` nesta request, o SBNFEBR NÃO
    11  * registra de novo (evita duas declarações concorrentes) — só usa. Se
    12  * a Sheet não estiver ativa, o SBNFEBR registra a própria cópia (mesmo
    13  * slug, mesmos argumentos), pra funcionar 100% standalone. Nos dois
    14  * casos, os dados gravados são os mesmos — se a Sheet for instalada
    15  * depois, os fornecedores já cadastrados aparecem na Biblioteca dela
    16  * automaticamente.
    17  *
    18  * @package SBNFEBR
    19  * @since   0.3.0
    20  */
    212
    223defined( 'ABSPATH' ) || exit;
    … …  
    267        const TAXONOMY = 'sbs_supplier';
    278
    28         /* Meta keys match the SanBar EXPress Sheet plugin's, for shared supplier data. */
    299        const META_DOCUMENT   = 'sbs_supplier_document';
    3010        const META_CODE       = 'sbs_supplier_code';
    … …  
    4222        const META_STATE      = 'sbs_supplier_state';
    4323        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_name
    46         // (seletor, rodapé, grid) devem exibir o apelido no lugar.
    4724        const META_NICKNAME     = 'sbs_supplier_nickname';
    4825        const META_USE_NICKNAME = 'sbs_supplier_use_nickname';
    4926
    50         /** Contador do código interno auto-gerado (SB-0001...) — mesma option da Sheet, contador compartilhado. */
    5127        const OPTION_NEXT_CODE = 'sbs_supplier_next_code';
    5228
    … …  
    6036        }
    6137
    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 carregamento
    65          * dos plugins, mas o SBNFEBR usa prioridade 5 pra dar chance de a
    66          * Sheet (prioridade padrão 10) ainda não ter rodado; por isso o
    67          * `taxonomy_exists()` é a fonte de verdade, não a ordem).
    68          *
    69          * Na prática: se os dois plugins estiverem ativos, o primeiro a
    70          * rodar "vence" o registro — inofensivo, os argumentos são
    71          * idênticos nos dois lados.
    72          *
    73          * @return void
    74          */
    7538        public static function maybe_register_taxonomy() {
    7639                if ( taxonomy_exists( self::TAXONOMY ) ) {
    … …  
    9962                                'show_in_menu'      => true,
    10063                                'show_admin_column' => false,
    101                                 // Mesmo motivo da Sheet: endpoint genérico do WP não passa
    102                                 // pela validação própria (dígito verificador, duplicidade).
    10364                                'show_in_rest'      => false,
    10465                                'capabilities'      => array(
    … …  
    12586        }
    12687
    127         /**
    128          * Lista de todas as meta keys de fornecedor.
    129          *
    130          * @return string[]
    131          */
    13288        public static function meta_keys() {
    13389                return array(
    … …  
    152108        }
    153109
    154         /* ===========================================================
    155          * LEITURA
    156          * ========================================================= */
    157 
    158         /**
    159          * Lista/busca fornecedores (termos da taxonomia), no formato que o
    160          * modal da Biblioteca consome.
    161          *
    162          * @param string $search Termo de busca (nome, documento ou código).
    163          * @return array[]
    164          */
    165110        public static function list_suppliers( $search = '' ) {
    166111                $terms = get_terms(
    … …  
    180125                $out    = array();
    181126
    182                 // Note/item counts, keyed by normalized CNPJ — lets the Suppliers
    183                 // Library tell apart "has a note right now" from "registered but
    184                 // no note currently linked" (see get_supplier_note_stats()).
    185127                $note_stats = class_exists( 'SBNFEBR_Notes_Service' ) ? SBNFEBR_Notes_Service::get_supplier_note_stats() : array();
    186128
    … …  
    206148        }
    207149
    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 array
    213          */
    214150        protected static function term_to_row( $term ) {
    215151                $document     = get_term_meta( $term->term_id, self::META_DOCUMENT, true );
    … …  
    220156                        'id'               => $term->term_id,
    221157                        'name'             => $term->name,
    222                         // display_name: o que telas fora do cadastro (seletor, rodapé,
    223                         // grid) devem mostrar — resolvido aqui pra centralizar a
    224158                        // lógica "usa apelido só se marcado E preenchido".
    225159                        'display_name'     => ( $use_nickname && '' !== $nickname ) ? $nickname : $term->name,
    … …  
    246180        }
    247181
    248         /**
    249          * Mapa `documento (só dígitos) => apelido`, só dos fornecedores com
    250          * "Exibir apelido" marcado e apelido preenchido — usado por quem exibe
    251          * fornecedor fora do cadastro (seletor da toolbar, grid principal)
    252          * pra decidir nome legal vs apelido sem repetir leitura de term meta
    253          * por linha.
    254          *
    255          * @return array<string,string> documento => apelido.
    256          */
    257182        public static function get_nickname_map() {
    258183                global $wpdb;
    259184
    260                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    261185                $rows = $wpdb->get_results(
    262186                        $wpdb->prepare(
    … …  
    282206        }
    283207
    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          */
    291208        public static function find_by_document( $document ) {
    292209                $digits = preg_replace( '/\D/', '', (string) $document );
    … …  
    297214        }
    298215
    299         /* ===========================================================
    300          * ESCRITA
    301          * ========================================================= */
    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          */
    309216        public static function create( array $fields ) {
    310217                $name = trim( (string) ( $fields['name'] ?? '' ) );
    … …  
    330237        }
    331238
    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_Error
    338          */
    339239        public static function update( $term_id, array $fields ) {
    340240                $term_id = (int) $term_id;
    … …  
    360260        }
    361261
    362         /**
    363          * Remove um fornecedor.
    364          *
    365          * @param int $term_id Termo a remover.
    366          * @return bool|WP_Error
    367          */
    368262        public static function delete( $term_id ) {
    369263                return wp_delete_term( (int) $term_id, self::TAXONOMY );
    370264        }
    371265
    372         /**
    373          * Salva os campos extras (term meta) de um fornecedor. Chaves
    374          * 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          */
    380266        public static function save_fields( $term_id, array $fields ) {
    381267                $first_error = null;
    … …  
    420306                        }
    421307                }
    422                 // use_nickname é booleano, não string livre: grava '1' só quando
    423308                // truthy, senão apaga.
    424309                if ( array_key_exists( 'use_nickname', $fields ) && null !== $fields['use_nickname'] ) {
    … …  
    441326        }
    442327
    443         /**
    444          * Salva o documento (CNPJ/CPF) com validação de dígito verificador
    445          * e checagem de duplicidade. Vazio = permitido (limpa o campo).
    446          *
    447          * Escopo Brasil-only (conceito do plugin) — só CNPJ/CPF, diferente
    448          * da Sheet (multi-país). Documento fora desses dois formatos ainda
    449          * é aceito como texto livre (ex: fornecedor internacional), só não
    450          * valida dígito.
    451          *
    452          * @param int    $term_id
    453          * @param string $document
    454          * @return WP_Error|null
    455          */
    456328        public static function save_document( $term_id, $document ) {
    457329                $document = trim( (string) $document );
    … …  
    487359                                'sbnfebr_supplier_document_duplicate',
    488360                                sprintf(
    489                                         /* translators: 1: valor do documento, 2: nome do fornecedor. */
     361                                        /* translators: 1: value, 2: supplier. */
    490362                                        __( 'O CNPJ/CPF "%1$s" já pertence ao fornecedor "%2$s".', 'sanbar-express-nfe-xml-import-br' ),
    491363                                        self::format_document_for_display( $stored ),
    … …  
    500372        }
    501373
    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 string
    507          */
    508374        public static function format_document_for_display( $value ) {
    509375                $value  = (string) $value;
    … …  
    521387        }
    522388
    523         /**
    524          * Salva o código interno. Vazio = gera sequencial (SB-0001...).
    525          *
    526          * @param int    $term_id
    527          * @param string $code
    528          * @return WP_Error|null
    529          */
    530389        public static function save_code( $term_id, $code ) {
    531390                $code = trim( (string) $code );
    … …  
    555414        }
    556415
    557         /**
    558          * Gera o próximo código sequencial (SB-0001...) — contador
    559          * compartilhado com a Sheet (mesma option), pra nunca colidir
    560          * mesmo cadastrando fornecedor pelos dois lados.
    561          *
    562          * @return string
    563          */
    564416        public static function generate_internal_code() {
    565417                for ( $attempt = 0; $attempt < 10; $attempt++ ) {
    … …  
    575427        }
    576428
    577         /**
    578          * Dono de um valor num meta_key qualquer (documento ou código),
    579          * pra checagem de unicidade.
    580          *
    581          * @param string $meta_key
    582          * @param string $value
    583          * @param int    $exclude_term_id Termo a ignorar (o próprio, ao editar).
    584          * @return int Term ID dono, ou 0.
    585          */
    586429        protected static function find_meta_owner( $meta_key, $value, $exclude_term_id = 0 ) {
    587430                if ( '' === (string) $value ) {
    … …  
    590433                global $wpdb;
    591434
    592                 // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    593435                $row = $wpdb->get_var(
    594436                        $wpdb->prepare(
    … …  
    607449        }
    608450
    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 bool
    618          */
    619451        public static function validate_cpf( $value ) {
    620452                $d = preg_replace( '/\D/', '', (string) $value );
    … …  
    641473        }
    642474
    643         /**
    644          * Valida dígito verificador de CNPJ.
    645          *
    646          * @param string $value 14 dígitos.
    647          * @return bool
    648          */
    649475        public static function validate_cnpj( $value ) {
    650476                $d = preg_replace( '/\D/', '', (string) $value );
  • sanbar-express-nfe-xml-import-br/trunk/includes/services/class-sbnfebr-xml-parser-service.php

    r3725460 r3782421  
    11<?php
    2 /**
    3  * Parser de XML de NF-e (modelo 55, layout 4.00) — extrai cabeçalho e
    4  * itens pros campos mapeados a partir do DANFE.
    5  *
    6  * Não valida contra o XSD oficial da SEFAZ — assume XML já autorizado
    7  * (nfeProc) ou só o nó NFe isolado, e é tolerante a campos ausentes
    8  * (nem toda NF-e tem CEST, ICMS-ST, FCP etc.).
    9  *
    10  * @package SBNFEBR
    11  * @since   0.2.0
    12  */
    132
    143defined( 'ABSPATH' ) || exit;
    … …  
    165class SBNFEBR_Xml_Parser_Service {
    176
    18         /**
    19          * Teto de segurança contra XML fora do padrão/malicioso, evitando gastar
    20          * memória processando milhares de <det>. Distinto do aviso de 100+ itens
    21          * no preview (ver SBNFEBR_Import_Controller::WARN_ITEMS_THRESHOLD).
    22          */
    237        const MAX_ITEMS = 1000;
    248
    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          */
    359        public static function parse( $xml_string ) {
    3610                $xml_string = (string) $xml_string;
    3711
    38                 // XXE hardening: a legitimate NF-e never has DOCTYPE/ENTITY — reject
    39                 // before attempting to load, don't rely solely on libxml flags.
    4012                if ( preg_match( '/<!DOCTYPE|<!ENTITY/i', $xml_string ) ) {
    4113                        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' ) );
    4214                }
    4315
    44                 // NF-e XML uses a single default namespace throughout — stripping the
    45                 // xmlns declarations simplifies SimpleXML access without registering
    4616                // or prefixing the namespace on every call.
    4717                $clean = preg_replace( '/xmlns(:\w+)?="[^"]*"/', '', $xml_string );
    4818
    4919                libxml_use_internal_errors( true );
    50                 // LIBXML_NONET: never resolves an external (network) reference during
    51                 // parsing, even if an entity slips past the filter above.
    5220                $sx = simplexml_load_string( $clean, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NONET );
    5321                libxml_clear_errors();
    … …  
    6432                $header = self::parse_header( $inf_nfe );
    6533
    66                 // Authorization protocol (<protNFe><infProt>) only exists when the
    67                 // XML is the full "processo" (<nfeProc>), not a bare <NFe> node —
    68                 // empty fields in that case are expected, not an error.
    6934                $prot = isset( $sx->protNFe->infProt ) ? $sx->protNFe->infProt : null;
    7035                $header['protocol_status']  = (string) self::prop( $prot, 'cStat' );
    … …  
    7338                $header['protocol_date']    = self::datetime( self::prop( $prot, 'dhRecbto' ) );
    7439
    75                 // Model 55 (NF-e) only. Model 65 (NFC-e) and others share a similar
    76                 // layout but are not the document this plugin handles.
    7740                if ( '55' !== $header['model'] ) {
    7841                        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' ) );
    7942                }
    8043
    81                 // Access key is the note's permanent identity (UNIQUE KEY in the
    82                 // database) — reject before attempting to store it.
    8344                if ( ! preg_match( '/^\d{44}$/', $header['access_key'] ) ) {
    8445                        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' ) );
    … …  
    11576        }
    11677
    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 array
    123          */
    12478        protected static function parse_header( $inf_nfe ) {
    12579                $id_attr    = (string) $inf_nfe['Id'];
    … …  
    13286                $transp = isset( $inf_nfe->transp ) ? $inf_nfe->transp : null;
    13387
    134                 // $total may be null (malformed/partial NF-e) — avoid accessing a
    135                 // property on non-object, each key falls back to null via num().
    13688                $totals = array(
    13789                        'icms_base'       => self::num( $total ? $total->vBC : null ),
    … …  
    14698                        'products_value'  => self::num( $total ? $total->vProd : null ),
    14799                        '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 separately
    150100                        // charged tax.
    151101                        'approx_taxes'    => self::num( $total ? $total->vTotTrib : null ),
    … …  
    174124                }
    175125
    176                 // <pag><detPag> may repeat when payment is split across multiple
    177                 // methods; tPag is the raw XML payment-method code, translated only
    178126                // at display time (nfebr-note-info.js), not here.
    179127                $payments = array();
    … …  
    193141                        'access_key'         => $access_key,
    194142                        'model'              => (string) $ide->mod,
    195                         // tpNF: 0=Entrada, 1=Saída — standardized XML field, more
    196                         // reliable than natOp (free text typed by the issuer). Outbound
    197                         // notes are not blocked automatically, only flagged in the
    198143                        // preview; the decision is left to the user.
    199144                        '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 not
    202145                        // block import.
    203146                        'nfe_purpose'        => (string) self::prop( $ide, 'finNFe' ),
    … …  
    207150                        'emission_date'      => self::datetime( $ide->dhEmi ?? null ),
    208151                        'exit_entry_date'    => self::datetime( $ide->dhSaiEnt ?? null ),
    209                         // NF-e XSD already guarantees <CNPJ> is digits-only — this is a
    210                         // defensive second pass against malformed/tampered XML.
    211152                        'supplier_cnpj'      => preg_replace( '/\D/', '', (string) $emit->CNPJ ),
    212153                        'supplier_name'      => (string) $emit->xNome,
    213154                        'supplier_fantasy'   => (string) ( $emit->xFant ?? '' ),
    214155                        'supplier_ie'        => (string) ( $emit->IE ?? '' ),
    215                         // CRT (Código de Regime Tributário): 1/2 = Simples Nacional
    216                         // (product uses CSOSN), 3 = Regime Normal (product uses CST) —
    217                         // used when creating a draft to pick the item's tax code table.
    218156                        'supplier_crt'       => (string) ( $emit->CRT ?? '' ),
    219                         // <fone> lives inside <enderEmit>, not directly under <emit>.
    220157                        'supplier_phone'     => (string) self::prop( $ender_emit, 'fone' ),
    221                         // Supplier address, used to prefill supplier registration
    222                         // (toolbar "!" icon) from data the note already carries.
    223158                        'supplier_cep'       => (string) self::prop( $ender_emit, 'CEP' ),
    224159                        'supplier_street'    => (string) self::prop( $ender_emit, 'xLgr' ),
    … …  
    230165                        'dest_document'      => preg_replace( '/\D/', '', (string) ( $dest->CNPJ ?? $dest->CPF ?? '' ) ),
    231166                        'dest_name'          => (string) ( $dest->xNome ?? '' ),
    232                         // infCpl: supplier free text (order, terms, sales rep, etc.),
    233                         // lives under <infAdic>, not directly under <infNFe>.
    234167                        'additional_info'    => (string) self::prop( self::prop( $inf_nfe, 'infAdic' ), 'infCpl' ),
    235168                        'payments'           => $payments,
    … …  
    240173        }
    241174
    242         /**
    243          * Extrai um item (<det>) pros campos da grid fiscal (mesma ordem de
    244          * colunas do DANFE) + extras num JSON à parte.
    245          *
    246          * @param SimpleXMLElement $det Nó <det>.
    247          * @return array
    248          */
    249175        protected static function parse_item( $det ) {
    250176                $prod    = $det->prod;
    251177                $imposto = $det->imposto;
    252178
    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)
    255179                // child of <ICMS>, regardless of its name.
    256180                $icms_node = null;
    … …  
    264188                $ipi_trib = isset( $imposto->IPI->IPITrib ) ? $imposto->IPI->IPITrib : null;
    265189
    266                 // PIS/COFINS follow the same dynamic-child pattern as ICMS above
    267                 // (PISAliq/PISQtde/PISNT/PISSN/PISOutr depending on CST).
    268190                $pis_node = null;
    269191                if ( isset( $imposto->PIS ) ) {
    … …  
    281203                }
    282204
    283                 // cclasstrib/nfci/cbenef are promoted to a direct field in the
    284                 // fiscal_brasil group, so Make Draft can write them without
    285205                // decoding extra_fiscal_json.
    286206                $ibscbs_node = self::prop( $imposto, 'IBSCBS' );
    287207                $cclasstrib  = (string) self::prop( $ibscbs_node, 'cClassTrib' );
    288208
    289                 // gIBSCBS/gIBSUF/gIBSMun/gCBS are nested sub-groups, not direct
    290                 // children of IBSCBS. II and ICMSUFDest (DIFAL) are direct children
    291                 // of <imposto> with a fixed shape (no CST-based variation like
    292209                // ICMS/PIS/COFINS).
    293210                $gibscbs_node = self::prop( $ibscbs_node, 'gIBSCBS' );
    … …  
    297214                $ii_node      = self::prop( $imposto, 'II' );
    298215                $difal_node   = self::prop( $imposto, 'ICMSUFDest' );
    299                 // IS (Imposto Seletivo): its own separate group (not nested under
    300                 // IBSCBS), fixed shape like II/DIFAL. Applies only to specific
    301                 // products (cigarettes, alcoholic beverages, etc.), so its absence
    302216                // on most notes is expected.
    303217                $is_node      = self::prop( $imposto, 'IS' );
    … …  
    313227                                'icms_desoneracao'   => self::num( self::prop( $icms_node, 'vICMSDeson' ) ),
    314228                                'icms_st_desoneracao' => self::num( self::prop( $icms_node, 'vICMSSTDeson' ) ),
    315                                 // Always use pICMSST directly — do NOT derive it from
    316                                 // vICMSST/vBCST: vICMSST is a NET value (own ICMS already
    317                                 // deducted), so the simple division yields a much lower
    318229                                // effective rate than the real one.
    319230                                'icms_st_rate'       => self::num( self::prop( $icms_node, 'pICMSST' ) ),
    … …  
    324235                                'cofins_rate'        => self::num( self::prop( $cofins_node, 'pCOFINS' ) ),
    325236                                '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 there
    328                                 // is no credit/discount involved, so deriving the rate as
    329237                                // vII/vBC is mathematically correct here.
    330238                                'ii_base'            => self::num( self::prop( $ii_node, 'vBC' ) ),
    331239                                '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 a
    334240                                // non-contributor end consumer.
    335241                                'difal_rate'         => self::num( self::prop( $difal_node, 'pICMSUFDest' ) ),
    336242                                '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 single
    339                                 // rate to match the catalog's single 'ibs' kind. CBS is
    340243                                // federal, kept as a separate 'cbs' kind.
    341244                                'ibs_uf_rate'        => self::num( self::prop( $gibsuf_node, 'pIBSUF' ) ),
    342245                                'ibs_mun_rate'       => self::num( self::prop( $gibsmun_node, 'pIBSMun' ) ),
    343246                                'cbs_rate'           => self::num( self::prop( $gcbs_node, 'pCBS' ) ),
    344                                 // cEANTrib: GTIN of the TAXABLE unit, which can differ from
    345                                 // cEAN (commercial unit GTIN) when the sale unit differs
    346                                 // from the tax-calculation unit. 'gtin' stays as cEAN only.
    347247                                'gtin_taxable'       => (string) self::prop( $prod, 'cEANTrib' ),
    348248                                'info_adicional'     => (string) self::prop( $det, 'infAdProd' ),
    349249                                'ibscbs'             => isset( $imposto->IBSCBS ) ? self::xml_to_array( $imposto->IBSCBS ) : null,
    350                                 // Freight/insurance/other expenses allocated per item
    351250                                // (optional in the XSD, absent on most notes).
    352251                                'item_freight'       => self::num( self::prop( $prod, 'vFrete' ) ),
    353252                                'item_insurance'     => self::num( self::prop( $prod, 'vSeg' ) ),
    354253                                'item_other_expenses' => self::num( self::prop( $prod, 'vOutro' ) ),
    355                                 // rastro (lot/expiry): common for food/cosmetics/pharma, can
    356                                 // repeat (multiple lots per item). No dedicated UI yet.
    357254                                'rastro'             => self::parse_rastro( $prod ),
    358255                        ),
    … …  
    373270                        'origem'         => (string) self::prop( $icms_node, 'orig' ),
    374271                        'unit'           => (string) $prod->uCom,
    375                         // Taxable unit (uTrib) can differ from the commercial one
    376272                        // (uCom) for regulated NCMs.
    377273                        'unit_taxable'   => (string) self::prop( $prod, 'uTrib' ),
    … …  
    381277                        'ind_escala'     => (string) self::prop( $prod, 'indEscala' ),
    382278                        'cnpj_fabricante' => (string) self::prop( $prod, 'CNPJFab' ),
    383                         // Columns are NOT NULL DEFAULT 0 — an explicit null breaks the
    384                         // insert under strict MySQL mode (DEFAULT only applies to an
    385                         // OMITTED column, not an explicit NULL). A missing XML field
    386                         // means "not applicable", financially 0; extra_fiscal_json
    387                         // still distinguishes "0 reported" from "field absent".
    388279                        'quantity'       => self::num( $prod->qCom ) ?? 0,
    389280                        'unit_value'     => self::num( $prod->vUnCom ) ?? 0,
    … …  
    401292        }
    402293
    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); retorna
    406          * array vazio (nunca null) quando ausente.
    407          *
    408          * @param SimpleXMLElement $prod Nó <prod>.
    409          * @return array
    410          */
    411294        protected static function parse_rastro( $prod ) {
    412295                if ( ! isset( $prod->rastro ) ) {
    … …  
    425308        }
    426309
    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 da
    430          * direita pra esquerda (mesmo algoritmo do DV de CNPJ/CPF, só que
    431          * sobre a chave inteira). Pega XML corrompido/adulterado que por
    432          * acaso ainda bateria no formato de 44 dígitos.
    433          *
    434          * @param string $access_key 44 dígitos.
    435          * @return bool
    436          */
    437310        protected static function access_key_dv_valid( $access_key ) {
    438311                $digits       = str_split( substr( $access_key, 0, 43 ) );
    … …  
    455328        }
    456329
    457         /**
    458          * Leitura null-safe de propriedade de um SimpleXMLElement que pode
    459          * ser o próprio `null` (não um SimpleXMLElement "vazio") — evita
    460          * "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|null
    466          */
    467330        protected static function prop( $node, $name ) {
    468331                return null === $node ? null : $node->{$name};
    469332        }
    470333
    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|null
    476          */
    477334        protected static function num( $node ) {
    478335                if ( null === $node ) {
    … …  
    483340        }
    484341
    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 DAY
    492          * near midnight. Matching what the user sees on the note matters
    493          * 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          */
    498342        protected static function datetime( $node ) {
    499343                if ( null === $node ) {
    … …  
    507351                        return $matches[1] . ' ' . $matches[2];
    508352                }
    509                 // Fallback for formats without the expected "T" separator.
    510353                $ts = strtotime( $str );
    511354                return $ts ? gmdate( 'Y-m-d H:i:s', $ts ) : null;
    512355        }
    513356
    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 array
    520          */
    521357        protected static function xml_to_array( $node ) {
    522358                $result = array();
  • sanbar-express-nfe-xml-import-br/trunk/readme.txt

    r3725460 r3782421  
    11=== SanBar EXPress NF-e XML Import-BR ===
    22Contributors: sanbazar
    3 Tags: xml, nota fiscal, danfe, importar nfe, woocommerce
    4 Requires at least: 6.0
     3Tags: woocommerce, nfe, xml, fiscal, brazil
     4Requires at least: 6.2
    55Tested up to: 7.1
    66Requires PHP: 7.4
    7 Stable tag: 1.0
     7Stable tag: 2.0
    88License: GPLv2 or later
    99License URI: https://www.gnu.org/licenses/gpl-2.0.html
    1010
    11 Import Brazilian NF-e purchase invoice XML into WooCommerce with full fiscal data and automatic product creation.
     11Import Brazilian purchase NF-e XML into WooCommerce, with built-in fiscal checking, so products are created right the first time.
    1212
    1313== Description ==
    1414
    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.
    1616
    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
     19Standalone plugin: works on its own, with no dependency on any other plugin from the SanBar suite.
    1820
    1921= How it works =
    2022
    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.
     231. **Entry** — upload the purchase XML and review the summary (supplier, number, items, total, access key).
     242. **Review** — check each item with the fiscal checking: regime, NCM, CEST, CFOP/CSOSN and GTIN. Approve the review when it is right.
     253. **Sync** — create the product, link it to an existing one, or update cost/data — each action is independent and asks for confirmation.
    2526
    26 = Features =
     27= Features (all editions) =
    2728
    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
    4845
    4946= Fiscal security =
    … …  
    5249* Protection against XXE (external entities) and an upload size limit
    5350* 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
    5553
    5654== Installation ==
    … …  
    6462= Do I need another SanBar plugin installed? =
    6563
    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.
     64No. 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
     68Version 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.
    6769
    6870= Does the plugin also import sales NF-e? =
    … …  
    7274= Which taxes does the plugin capture from the invoice? =
    7375
    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.
     76ICMS, 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
     80No. Every change to cost, price or stock is a choice you confirm.
    7581
    7682= What is the difference from the Plus edition? =
    7783
    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.
     84This 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
     88Bundled 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
     94They 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/
    79104
    80105== Changelog ==
    81106
     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
    82120= 1.0 =
    83121* Initial release.
  • sanbar-express-nfe-xml-import-br/trunk/sanbar-express-nfe-xml-import-br.php

    r3725460 r3782421  
    44 * Plugin URI:        https://software.sanbazar.com.br
    55 * 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.0
    7  * Requires at least: 6.0
     6 * Version:           2.0
     7 * Requires at least: 6.2
    88 * Requires PHP:      7.4
    99 * Author:            SanBar (Sandro Barboza)
    … …  
    2020defined( 'ABSPATH' ) || exit;
    2121
    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  * ========================================================= */
     22if ( function_exists( 'sbnfebr_fs' ) ) {
     23        sbnfebr_fs()->set_basename( is_dir( __DIR__ . '/plus' ), __FILE__ );
     24        return;
     25}
    2826
    2927define( 'SBNFEBR_IS_PLUS', false );
    3028
    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' );
     29define( 'SBNFEBR_FREEMIUS_ENABLED', true );
     30
     31if ( 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
     84require_once __DIR__ . '/includes/class-sbnfebr-uninstall.php';
     85
     86if ( 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
     92if ( ! 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
     104define( 'SBNFEBR_VERSION', '2.0' );
    45105define( 'SBNFEBR_FILE', __FILE__ );
    46106define( 'SBNFEBR_DIR', plugin_dir_path( __FILE__ ) );
    47107define( 'SBNFEBR_URL', plugin_dir_url( __FILE__ ) );
    48 
    49 /* ===========================================================
    50  * Admin notice when WooCommerce is missing
    51  * ========================================================= */
    52108
    53109add_action(
    … …  
    64120        }
    65121);
    66 
    67 /* ===========================================================
    68  * HPOS / custom order tables compatibility
    69  * ========================================================= */
    70122
    71123add_action(
    … …  
    82134);
    83135
    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  * ========================================================= */
     136if ( ! 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}
    136179
    137180add_action(
    … …  
    145188
    146189                // dbDelta only runs when DB_VERSION changes.
     190                SBNFEBR_Workflow_Service::create_table();
     191                SBNFEBR_Fiscal_Tables::init();
     192                SBNFEBR_Fiscal_Settings::init();
    147193                SBNFEBR_Notes_Service::create_table();
     194                SBNFEBR_Workflow_Service::prepare_legacy_backfill();
    148195                SBNFEBR_Error_Log_Service::create_table();
    149196                SBNFEBR_Audit_Service::create_table();
    … …  
    158205);
    159206
    160 /* ===========================================================
    161  * Activation / Deactivation
    162  * ========================================================= */
    163 
    164207register_activation_hook(
    165208        __FILE__,
    166209        function () {
    167210                sbnfebr_load_modules();
     211                SBNFEBR_Workflow_Service::create_table();
     212                SBNFEBR_Fiscal_Tables::install();
    168213                SBNFEBR_Notes_Service::create_table();
     214                SBNFEBR_Workflow_Service::prepare_legacy_backfill();
    169215                SBNFEBR_Error_Log_Service::create_table();
    170216                SBNFEBR_Audit_Service::create_table();
    … …  
    175221        __FILE__,
    176222        function () {
     223                wp_clear_scheduled_hook( 'sbnfebr_ncm_refresh' );
    177224                flush_rewrite_rules( false );
    178225        }
Note: See TracChangeset for help on using the changeset viewer.