a966e0b2c7c732e85f9eecdddcde3b513b6c0c2d
6 Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
113610ea8f |
feat: WO apply_margin at fișă level + full RO/RU i18n on client portal
Two changes in one commit:
== 1. Moved apply_margin toggle from line-level to Fișă-level ==
The per-manoperă apply_margin toggle is gone from the Manopere tab.
In its place: a single "Aplică marjă internă" toggle in Fișa's
"Plată & total" section (next to override_margin_pct). One decision
per Fișă instead of per line — cleaner mental model, matches how the
shop actually thinks about at-cost vs. billable work.
Migration: work_orders.apply_margin boolean default true (idempotent).
WorkOrderWork::saving now reads WO.apply_margin from DB directly (not
via belongsTo cache) to determine salary_base:
- WO.apply_margin=false → every line gets salary_base=total, applied_margin_pct=0
- WO.apply_margin=true → resolver chain (WO.override → user margin → tenant default)
Old wo_works.apply_margin column stays untouched (backward-compat with
existing rows), but no longer exposed in UI. Tests updated to new
semantic. All existing tests green.
== 2. Full i18n audit on client-facing portal — RO/RU separated ==
Problem: user selecting Russian saw Romanian mixed into headings,
buttons, labels. Every client-facing Blade file was 100% hardcoded
Romanian — zero __() calls.
Fix: created lang/ro/portal.php + lang/ru/portal.php with 131 keys
across 3 namespaces:
- portal.common (email, phone, save, total, powered_by, ...)
- portal.invitation (welcome_name, activate_account, expired_body, ...)
- portal.tracking (title_fisa, approve, approval_needed_title,
ready_estimated, hours, unit_pcs, ...)
- portal.shop (catalog, cart, checkout_title, order_number, vin_title,
signin_title, add_to_cart, in_stock, ...)
Converted 15 Blade files to __() calls:
- resources/views/invitations/{accept,expired,invalid}.blade.php
- resources/views/tracking/show.blade.php
- resources/views/shop/{layout,catalog,cart,checkout,order,account,part,vin}.blade.php
- resources/views/shop/auth/{login,register,forgot,reset}.blade.php
Each view's <html lang="{{ app()->getLocale() }}"> now reflects the
resolved locale (was hardcoded lang="ro").
SetLocale middleware resolves locale in this order:
1. session locale (user picked via language switcher)
2. authenticated user.locale
3. tenant.settings.language
4. app.locale default (now 'ro')
Config change: config/app.php default locale + fallback both = 'ro'
(was 'en'). English falls back to Romanian for portal.* keys since
we don't ship English portal translations — a Romanian shop that
switches to English shows Romanian text, which is safer than showing
"portal.invitation.activate_account" literals.
phpunit.xml sets APP_LOCALE=ro so test assertSee() calls that look
for Romanian text pass.
Verified via portal.* grep: 131 __() calls across 15 files. Zero
hardcoded Romanian nouns/verbs left in any client-facing view.
Suite: 303 passed (840 assertions). Unchanged count — refactor,
not new tests.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
f4ccc306dc |
feat: marjă internă — Settings % + toggle per manoperă + visibility flag
Adds three usability improvements to the marja internă feature: 1. Settings UI section "Marjă internă (nu TVA)" — configurable at tenant level 2. Per-line toggle "Aplică marjă" on each manoperă 3. Global visibility flag to hide margin details in-session == 1. Settings page == New section on /app/settings (gated by FINANCE_VIEW_INTERNAL_MARGIN): - "% marjă implicit" numeric input with % suffix, 0–90 range - "Afișează detalii marjă la procesele calculate" toggle (default on) - Explicit label "Marjă internă (nu TVA)" plus helper text explaining it's not the Moldovan tax — feeds into MarginResolver as the tenant default, applied only when the mechanic has no per-user margin. Persists as company.settings.default_internal_margin_pct and company.settings.show_internal_margin_details. == 2. Per-line "Aplică marjă" toggle == New wo_works.apply_margin boolean, default true. When false: applied_margin_pct = 0 salary_base = total (mechanic gets salaried on the full amount) Use case: oil change, tire mount, and similar "at-cost" services where the shop doesn't want to hold back part of the labor rate. The owner can flag those specific lines while keeping margin on diagnostic and premium labor. WorksRelationManager form gains a Toggle field (gated by FINANCE_VIEW_INTERNAL_MARGIN); table gains a ToggleColumn for quick inline flipping without opening the row. Booted hook now recomputes salary_base when apply_margin is dirtied, so toggling live in the table takes effect immediately. == 3. Show internal margin details flag == Global tenant flag (default on): when off, the gray subtitle line "Bază salariu: 200 · marjă 20%" under the Total column disappears for everyone, even users with FINANCE_VIEW_INTERNAL_MARGIN. Practical use: when reviewing a Fișă face-to-face with the client on the manager's screen, flip the flag off from Settings for the day → no risk of the client accidentally seeing internal numbers. Flip back when done. The flag lives in company.settings.show_internal_margin_details. == Description text on the Total column == Now shows either: - "Bază salariu: 200.00 MDL · marjă 20%" when apply_margin=true - "Fără marjă · bază salariu = Total" when apply_margin=false - nothing when show_internal_margin_details=false or role lacks permission == Tests == InternalMarginToggleTest (5): - apply_margin=false → salary_base equals total, applied_margin_pct=0 - apply_margin=true (default) still applies 20% margin - Toggling apply_margin recomputes salary_base bidirectionally - Company default margin resolves when mechanic has no per-user setting - show_internal_margin_details flag persists correctly in Company.settings Suite: 303 passed (845 assertions). Was 298. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> |
||
|
|
70ca2fa74a |
feat: marjă internă per mechanic — hidden margin on labor
Client sees only Total. Salary is calculated from salary_base = client_price
× (1 − margin/100). Margin never appears in customer-facing surfaces (PDF,
tracking JSON, portal).
Terminology: "marjă internă" — internal profit margin. NOT VAT/TVA. Never
called NDS/TVA anywhere in the code to avoid confusion with real Moldova
tax reporting (Doc 19/1C integration).
== Configuration ==
Fallback chain (in MarginResolver::resolve):
1. WorkOrder.override_margin_pct — per-Fișă for special contracts/VIP
2. User.internal_margin_pct — per-mechanic (main setting)
3. Company.settings.default_internal_margin_pct — tenant default
4. 0.0 — no margin
Example (mechanic Andrei with 20% margin):
User enters price_per_hour = 250 for 1h diagnosis
→ total = 250 (what client sees, goes into PDF)
→ salary_base = 250 × 0.80 = 200 (what mechanic gets salaried on)
→ applied_margin_pct = 20 (frozen)
If admin later changes Andrei's margin to 40%, the row's salary_base does
NOT change — history is immutable. Only new rows use the new margin.
Solves the retroactive-recompute problem for closed payroll periods.
== salary_base freeze semantics ==
wo_works gains 2 columns:
salary_base decimal(10,2) nullable
applied_margin_pct decimal(5,2) nullable
Frozen at save time by WorkOrderWork::saving hook. Recomputes only if
total OR master_id changes (i.e., someone actively edits the price or
reassigns the mechanic — in those cases we WANT the salary_base to
follow). Legacy rows (before this feature) have null salary_base;
PayrollCalculator falls back to total for them.
== PayrollCalculator uses salary_base ==
Previously: sum(wo_works.total) × works_pct → gave the mechanic a cut
of the price INCLUDING margin.
Now: sum(salary_base ?? total) × works_pct → the cut is from the
labor rate excluding margin.
Impact: for a 250 lei diagnosis at 20% margin with 50% payroll cut, the
mechanic gets 200 × 50% = 100 lei (was 250 × 50% = 125 lei). The shop
keeps the 50 lei margin regardless of the payroll %.
== RBAC gate ==
New permission FINANCE_VIEW_INTERNAL_MARGIN. Assigned to owner + admin +
manager + accountant in seed matrix. Not granted to mechanic,
receptionist, or viewer — those roles never see the "Bază salariu"
disclosure line or the margin % fields.
== UI surfaces ==
UserResource — new "Salariu & marjă" section (visible only with
FINANCE_VIEW_INTERNAL_MARGIN):
- Tarif orar (MDL)
- Marjă internă (%) with helper text explaining the -X% semantics
- Placeholder tells manager the exact formula
WorkOrderResource form — new override_margin_pct field in the "Plată &
total" section, gated by same permission. Helper text: "Doar pentru
cazuri speciale. Lasă gol pentru a folosi marja mecanicului."
WorksRelationManager (WO edit page) — Total column now shows a gray
subtitle line "Bază salariu: 200.00 MDL · marjă 20%" ONLY for users
with FINANCE_VIEW_INTERNAL_MARGIN. Everyone else sees just Total.
== Contract tests: NO leak ==
InternalMarginTest verifies with black-box grepping that:
- WorkOrderPdfService::generate output contains NONE of
{salary_base, internal_margin, applied_margin_pct, marja intern,
Bază salariu}
- /api/track/{token} JSON payload contains NONE of the same terms
- wo_parts table has no salary_base column (margin ONLY on labor)
- Changing mechanic.internal_margin_pct after work is saved does NOT
rewrite the historical salary_base (frozen)
- WO override wins over mechanic margin (contract-priced clients)
- Fallback chain: WO → mechanic → company default → 0
== Suite ==
298 passed (828 assertions). Was 285. +13 InternalMarginTest.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
cbcf08b28c |
feat: tier 2 — M12 Pricing UI + M13 mechanic granular workflow
Closes "Important pentru produs complet" tier from CONFORMITY-12-15.md.
== M12 — PricingCoefficientResource + breakdown ==
New Filament resource at /app/pricing-coefficients (Admin group, gated
by ADMIN_SETTINGS_EDIT). Replaces the previous "edit JSON in DB"
configuration workflow.
Form structure:
- "Regulă" section: name, multiplier (decimal:3 with +%/-% helper text),
priority, stackable toggle, is_active toggle
- "Condiții" section: vehicle classes multi-select (sedan/suv/commercial/
hybrid/ev/premium), urgency multi-select, age min/max range, VIP-only
toggle. Empty = applies to everything.
Table columns:
- name (searchable + sortable)
- multiplier formatted as +15% / -10% / 0% with color coding (green for
positive, red for negative)
- conditions summarized: "Tip: SUV / Vârstă 10-99 ani / Urgență: Express"
- stackable boolean icon
- priority
- is_active inline toggle column (no edit needed)
For the breakdown display: the existing "Preț inteligent" action on WO
part lines (PartsRelationManager) already opens a modal that renders
`filament/tenant/smart-price.blade.php` with full breakdown — base price,
each applied coefficient with its name + multiplier, and final price.
Confirmed working; no change needed.
== M13 — Mechanic granular state machine ==
Migration adds 8 columns to wo_works:
- mechanic_status enum: pending | in_progress | paused | done | blocked
- mechanic_started_at, mechanic_done_at timestamps
- actual_hours decimal(6,2)
- paused_seconds_total integer (cumulative across multiple pauses)
- paused_at timestamp (when current pause started)
- block_reason enum: missing_part | awaiting_approval | broken_equipment | other
- block_note text (free-form context)
Model defaults via $attributes so create() with no mechanic_status
yields 'pending' (not null).
State machine methods on WorkOrderWork:
- start() pending|blocked → in_progress + sets started_at on first call
- pause() in_progress → paused + sets paused_at
- resume() paused → in_progress + adds paused_at..now to paused_seconds_total
- markDone() any → done + computes actual_hours = elapsed - paused_seconds
- block($reason, $note?) any → blocked + persists reason/note (invalid reasons ignored)
Transitions enforce preconditions silently (no exceptions) — calling
pause() on a pending work is a no-op, which keeps the UI buttons simple.
Efficiency indicator:
- efficiencyClass(): 'green' (actual <= norm), 'amber' (1.0 < ratio <= 1.3),
'red' (ratio > 1.3). null when no actual data.
- efficiencyPct(): integer percentage of norm time used.
== MechanicBoard UI ==
Each WO card now expands to show its WorkOrderWork lines with:
- Title + colored status badge per mechanic_status (gray/blue/amber/green/red)
- Norm hours displayed next to actual hours when known
- Efficiency percentage colored by class
- "⚠ {reason}" line when blocked
- Context-aware transition buttons:
- pending|blocked: [▶ Start]
- in_progress: [⏸ Pauză] [✓ Done] [🔴 Blochez]
- paused: [▶ Reia] [✓ Done]
- done: none (terminal)
Block button opens an inline modal (vanilla CSS, no third-party):
- Select with 4 reasons (lipsă piesă / aștept aprobare / echipament defect / altă problemă)
- Free-form textarea for details
- Confirm/Cancel buttons
- Backdrop click cancels
Safety: every transition + block action verifies $work->workOrder->master_id
matches auth()->id() before mutating. Other mechanics' works are silently
refused (no error leak).
== Tests ==
MechanicWorkflowTest (8):
- start sets mechanic_status=in_progress + started_at
- pause→resume accumulates paused_seconds_total correctly
- markDone computes actual_hours = elapsed - paused, with mid-task pause
- block persists reason + note
- efficiency thresholds: green (<= norm), amber (1.0-1.3x), red (>1.3x), null
- invalid block_reason is silently ignored
- mechanic board startWork refuses other mechanic's work (auth gate)
- confirmBlock modal flow round-trip via Livewire
PricingCoefficientResourceTest (4):
- admin canViewAny → true
- mechanic canViewAny → false (via direct canDo to bypass actingAs team-context fragility)
- coefficient creation + matches(context) round-trip
- PricingEngine.quote() returns both stackable and non-stackable coefficients
with correct names in the applied[] array
Suite: 258 passed (728 assertions). Was 246.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
0e3119a6e2 |
feat: M14 Excel import wizard + M15 client approval via tracking link
Top-ROI items from CONFORMITY-12-15.md. Together: ~40h of TZ work
delivered in one pass.
== M14 — Excel/CSV invoice import wizard ==
phpoffice/phpspreadsheet ^5.7 added as composer dep — parses both XLSX
and CSV cleanly.
ExcelInvoiceImportService (app/Services/ExcelInvoiceImportService.php):
- headersPreview($path) → first 5 rows + detected column letters
- preview($path, $mapping) → all rows classified as found/new/no_article
- import($supplier, $rows, $createNew=true) → creates Purchase + items,
auto-creates Parts for "new" rows
- rememberMapping / rememberedMappingFor($supplier) — round-trips JSON
config (article_col / name_col / qty_col / price_col / brand_col? /
header_row / sheet_name?) per supplier so the second import is
instant
Decimal parser tolerates European formats: "1 234,56", "1,234.56",
non-breaking spaces (U+00A0 NBSP common in copy-pastes from PDF).
Article matching uses single batch query (Part::whereIn) — O(1) for
the whole sheet, not O(rows).
ExcelImportWizard Filament page (/app/excel-import-wizard) — 4-step
Livewire wizard:
1. Upload + supplier select (saved mapping auto-loads if exists)
2. Column mapping with first-3-rows preview table + per-column
dropdowns
3. Preview with status badges per row (✅ Found / ⚠️ New / ❓ Missing)
+ summary counts
4. Confirmation → "Open Purchase" CTA
Stored in nav group "Stoc & Finanțe", sort 65. Width Full.
Migration: supplier_invoice_mappings (id, company_id, supplier_id UNIQUE,
mapping_config JSON, sample_file_name, last_used_at, timestamps).
Per-tenant scope via BelongsToTenant.
== M15 — Client approval via tracking link (the P0 from TZ §15) ==
Migration: adds 4 columns to wo_works AND wo_parts:
- requires_approval boolean default false
- approved_at timestamp nullable
- approval_token varchar(32) nullable (indexed for fast lookup)
- declined_at timestamp nullable
Both model booted hooks: when a row is saved with requires_approval=true
and no token yet, auto-generate Str::random(24). Models gain
isPendingApproval() helper returning true only while not yet approved
nor declined.
Public route: POST /t/{token}/approve/{kind}/{lineToken}
kind = 'work' | 'part'
body: decision = 'approve' | 'decline'
The line's approval_token IS the credential — anyone with the URL can
act. No CSRF token required since this is the unauthed public tracking
flow (the tracking_token + line approval_token combo functions as
shared-secret). Form-encoded POST with csrf_field() on the public form
keeps Laravel happy.
TrackingController::show() now eager-loads works + parts, computes
pendingWorks and pendingParts collections, passes them to the view.
TrackingController::approve() validates kind, locates the line by
(work_order_id, approval_token), idempotently marks approved_at or
declined_at, redirects back to /t/{token} with a flash status.
UI banner (tracking/show.blade.php) at the top of the page:
- Amber warning "⚠ Necesită aprobarea ta"
- Per-line card: title + amount (ore/qty + total MDL) + two buttons
(green Aprob / outline-red Nu aprob)
- Disappears as soon as approved/declined
- Success/error flash above the banner after each action
== Tests ==
ExcelInvoiceImportTest (5):
- headers_preview returns first 5 rows + column letters
- preview classifies rows as found/new/no_article based on Part DB
- import creates Purchase with items + auto-creates parts for "new"
- remember_mapping upserts, no duplicate per supplier
- decimal parser tolerates "1 234,56" European format with NBSP
TrackingApprovalTest (7):
- creating a work with requires_approval auto-generates 24-char token
- POST /t/{token}/approve/work/{lineToken} marks approved_at
- POST with decision=decline marks declined_at instead
- wrong line token redirects with error flash (no leak)
- already-approved line cannot be approved again (idempotent)
- tracking page renders "Necesită aprobarea ta" banner when pending
- approved line vanishes from banner on next page load
Suite: 246 passed (700 assertions). Was 234.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
||
|
|
51a0bab39e |
Faza 3.2: Service modules — Norme-ore, Tehnicieni, Fișe lucru
Schema:
- users + specialization, color, hourly_rate (pentru maistri)
- labors: catalog manopere standard cu category/ore/preț (RO+RU)
- work_orders: nr unique per tenant, status workflow (9 stări),
pay_status (3 stări), client/vehicle/master/deal/appointment refs,
complaint/diagnosis/recommendations, total auto-calculat
- wo_works: manopere per fișă, recalc auto la save/delete
- wo_parts: piese per fișă (free-text deocamdată), discount/total auto
Filament resources (group Service):
- LaborResource: CRUD + grupare pe categorie + filter active
- WorkOrderResource: form complex în 4 secțiuni (antet, diagnostic, plată)
+ 2 RelationManagers (Works, Parts)
- MasterResource: vedere User filtrată role=mechanic, edit specializare/
culoare calendar/tarif oră
Conversie auto: la adaugare manoperă din catalog Labor,
form populează numele + ore + preț/oră derivat (price/hours).
Number generator pentru WO: format WO-{YY}-{NNNN} per tenant per an,
calculat în CreateWorkOrder via WorkOrder::generateNumber().
Seed extins:
- 3 mecanici (Vasile/Andrei/Nicolae) cu culori + specializări
- 10 manopere standard din prototipul AutoCRM.html
- 1 fișă demo (BMW X5 plăcuțe Brembo) cu 1 manoperă + 1 piesă, total auto
|