Skip to content

joi_s4 - #62

Merged
CasperGamingOne merged 4 commits into
new-tui-frontendfrom
day_4-andreea
Jul 17, 2026
Merged

joi_s4#62
CasperGamingOne merged 4 commits into
new-tui-frontendfrom
day_4-andreea

Conversation

@CasperGamingOne

Copy link
Copy Markdown
Owner

No description provided.

Ganea Andreea and others added 3 commits July 16, 2026 15:23
… estimate, UI & persistence refinements

  ──────
  ### Summary
  Implemented a realistic degradation model where a part can degrade to Good or jump directly to Critical, updated the maintenance‑days estimation to match the new 20 % degradation chance, fixed the direct‑assignment bug by
  using BreakDown(), and incorporated several earlier quality‑of‑life improvements (persistence, menu restructuring, production‑flow realism, batch handling, and localisation) that were completed in previous checkpoints.
  ──────
  ──────
  ### Detailed Changes
   File            | Change                                                                                                                                                 | Reason
  -----------------|--------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------
   File            | Change                                                                                                                         | Reason
  -----------------|----------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------
   Core/Machine.cs     | • Updated GetEstimatedDaysUntilMaintenance comment and divisor from 0.8 → 0.2 to reflect 20 % wear probability.•       | Provides the logical model the user requested and fixes accessibility errors.
                           | Adjusted the calculation: expectedCycles = minSteps * N / 0.2.• Re‑implemented ApplyProductionWearAndTear:  -      |
                           | ApplyProductionWearAndTear:  - Added explanatory comments describing the 20 % overall chance and the 10 %/10 |
                           | % split for Excellent parts.  - When the part is Excellent, a second random roll decides Good (10 %) or a    |
                               | direct Critical (10 %) using selectedPart.BreakDown().  - When the part is Good, it degrades to Critical (20 |
                               | %).  - Kept Critical parts unchanged.• Replaced direct Condition = PartCondition.Critical with the           |
                               | encapsulated selectedPart.BreakDown() to respect the part’s API.                                             |
   Core/MachinePart.cs         | No code changes, but referenced to clarify that BreakDown() is now the proper way to force a part to      | Needed for the new degradation path.
                               | Critical.                                                                                                    |
   Core/ProductionOrder.cs     | Added BatchId property to track a production batch across interruptions.                                     | Allows reuse of an existing batch instead of creating duplicates on a machine
                               |                                                                                                              | trip.
   UI/ProductionMenuHandler.cs | • Integrated batch‑reuse logic using BatchId.• Ensured the live‑feed UI updates to the final progress count  | Improves user experience and matches the “final number before price”
                               | before prompting for pricing.• Suppressed pricing prompts on intermediate trips; now only shown when an      | requirement.
                                  | order finishes.                                                                                              |
                                                         | final progress count before prompting for pricing.• Suppressed pricing prompts on      | requirement.
                                                         | intermediate trips; now only shown when an order finishes.                             |
   UI/SalesMenuHandler.cs                                | Implemented UseConverter to filter unsold batches and present only relevant batch      | Aligns sales view with the new batch handling.
                                                         | choices.                                                                               |
   UI/AccountingMenuHandler.cs                           | Propagated reportRequestsRepo and added state‑saving for accounting data.              | Guarantees persistence of accounting reports.
   UI/Program.cs                                         | Removed the now‑obsolete “Factory Information” menu entry and cleaned the switch‑case   | Reflects the user’s decision to drop that menu.
                                                         | handling.                                                                               |
   Text/Machines.cs                                      | Added localisation strings for the new degradation messages and spinner updates.        | Keeps UI text externalised and consistent.
   Text/Sales.cs (reference)                             | No changes, but used as a source for localisation patterns.                             | Supporting consistency.
   UI/FactoryReportMenuHandler.cs                        | Deleted file (obsolete after menu removal).                                             | Eliminates dead code.
   Persistence files (orders.json, report_requests.json) | Not code files, but now the system writes pending orders and report requests here via   | Guarantees data survives crashes.
                                                         | the new JSON repositories.                                                              |
   Project metadata                                      | Updated README / comments where applicable to note the 20 % degradation configuration.  | Documentation consistency.
  ──────
  ### Why These Changes Matter
  • Realistic wear‑and‑tear – The machine now mirrors the user‑specified 20 % chance with a split between gradual degradation and sudden failure, making the simulation more believable.
  • Accurate maintenance forecasting – The GetEstimatedDaysUntilMaintenance method now returns values that align with the new probability, eliminating the previous 5/10‑day confusion.
  • Robust API usage – Using BreakDown() respects encapsulation and resolves the earlier compile‑time access error.
  • Batch integrity – Introducing BatchId prevents duplicate batch creation when a machine trips, fixing the “price each time it trips” bug.
  • UI polish – Live‑feed now shows the final production count before prompting for price, and menus have been trimmed to the requested set.
  • Persistence – JSON repositories ensure orders and report requests survive application restarts.
  • Localization – All user‑visible strings live in the Text project, simplifying future translations.

Signed-off-by: CasperGamingOne <caspergamingone@outlook.dk>
@github-actions

github-actions Bot commented Jul 17, 2026

Copy link
Copy Markdown

Qodana Community for .NET

113 new problems were found

Inspection name Severity Problems
Method return value is never used: Private accessibility 🔶 Warning 1
Unused local variable 🔶 Warning 1
Type member is never used: Non-private accessibility ◽️ Notice 66
Member can be made private: Non-private accessibility ◽️ Notice 17
Auto-property can be made get-only: Non-private accessibility ◽️ Notice 9
Property can be made init-only: Non-private accessibility ◽️ Notice 7
Type member is never accessed via base type: Non-private accessibility ◽️ Notice 5
Merge null/pattern checks into complex pattern ◽️ Notice 2
Unused parameter: Non-private accessibility ◽️ Notice 2
'if' statement can be rewritten as '?:' expression ◽️ Notice 1
Replace with 'field' keyword ◽️ Notice 1
Simplify LINQ expression (use 'All') ◽️ Notice 1
View the detailed Qodana report

To be able to view the detailed Qodana report, you can either:

To get *.log files or any other Qodana artifacts, run the action with upload-result option set to true,
so that the action will upload the files as the job artifacts:

      - name: 'Qodana Scan'
        uses: JetBrains/qodana-action@v2026.1.3
        with:
          upload-result: true
Contact Qodana team

Contact us at qodana-support@jetbrains.com

@CasperGamingOne

Copy link
Copy Markdown
Owner Author

Summary by Jules

This branch (day_4-andreea) builds on top of new-tui-frontend with four major themes: a realistic 20 % split-severity machine wear-and-tear model, a live production-line dashboard with batch-reuse, a full Employee removal flow with undo support, and a richer Accounting / Report experience (financial summary, export-destination picker, persisted report requests). Alongside these features, the entire codebase received systematic housekeeping: JSON serialisation compatibility fixes, naming-convention clean-ups, and thorough localisation of every raw string into the Text/ layer.


New Features

  • Realistic wear-and-tear degradation model (Core/Machine.cs)

    • Implemented a 20 % overall per-cycle degradation chance with a 10 %/10 % split for Excellent parts: one random roll decides between a graceful step down to Good (10 %) or a direct jump to Critical (10 %). Good parts degrade straight to Critical on a separate 20 % roll. Critical parts are left untouched.
    • Replaced direct Condition = PartCondition.Critical assignments with the encapsulated selectedPart.BreakDown() API to honour the part's invariants.
    • Updated GetEstimatedDaysUntilMaintenance comment and divisor (0.8 → 0.2) and recalculated the formula (expectedCycles = minSteps * N / 0.2) to match the new probability.
  • Live Production-Line Dashboard (UI/ProductionMenuHandler.cs)

    • Replaced the old step-by-step text dump with a AnsiConsole.Live rendering loop that redraws a full status table (machine name, RUNNING/TRIPPED/IDLE state, progress bar, unit count) on every produced board.
    • Added a Unicode block progress bar helper GetProgressBar(completed, total) that renders (green filled) and (grey empty) segments at a fixed 20-character width.
    • Introduced a Machine.SilentMode flag: when true, per-machine Spectre status spinners and individual success/failure messages are suppressed so the live panel is the only output. A 500 ms Thread.Sleep is still inserted to simulate machine latency.
    • After a fully complete run the operator is prompted for the actual unit production cost (with validation) which is retroactively written back to every product in the batch as well as the batch record itself — giving an accurate cost figure that accounts for any repairs or downtime during the cycle.
  • Batch-reuse across machine trips (Core/ProductionOrder.cs, UI/ProductionMenuHandler.cs, Core/ProductionBatch.cs)

    • ProductionOrder now carries a nullable BatchId property. When production is interrupted and the technician returns to resume, StartProductionBatch looks up the existing ProductionBatch by that ID and resumes from the same object instead of creating a duplicate entry in Factory.Batches.
    • ProductionBatch constructor now accepts an optional batchId parameter so that externally assigned IDs (e.g. reloaded from disk) are honoured.
  • Employee Removal with Undo (UI/EmployeeMenuHandler.cs, Services/UndoService.cs, Text/Employees.cs)

    • Directors can now remove any employee (except themselves) through a confirmation-guarded flow.
    • The removal is wrapped in a new RemoveEmployeeCommand (implements ICommand) that stores the removed Employee object and can re-add it to both the in-memory Factory and the persisted employees.json on undo.
    • A new EmployeeRemoved log event is emitted on successful removal.
  • Export-Destination picker for Printable Reports (UI/ReportMenuHandler.cs, Text/Reports.cs)

    • Directors requesting a printable report are now prompted to choose between Desktop or Program Reports Folder as the export target before the request is submitted.
    • The selected destination is stored in ReportRequest.ExportDestination and persisted immediately to report_requests.json via the newly injected IJsonRepository<ReportRequest>.
  • Accounting Menu: View Production Summary shortcut (UI/AccountingMenuHandler.cs)

    • Accountants now have a direct "View Production Summary" option inside the Accounting menu which delegates to ReportMenuHandler.ShowProductionSummary (now internal static instead of private static).
  • Inventory Alert Banner (UI/ProductMenuHandler.cs, Core/Factory.cs)

    • If the total number of unsold units falls below Factory.MinStockThreshold (200 units), the product-management header panel switches its border from blue to red and displays a blinking bold red ⚠️ INVENTORY ALERT banner prompting the user to start production.
    • Warehouse stats now show totalUnits / maxUnits (activeBatches / maxBatches) instead of the old raw inventory-list count.
  • Low-stock helper on Product (Core/Product.cs)

    • Added MinStockThreshold { get; set; } = 5 and IsLowStock() helper method to the Product base class for per-item threshold checks.
  • Seeded demo data expanded (Services/DataSeeder.cs)

    • Seed now populates six unsold inventory batches (3 CPU models + 3 motherboard models, total 70 units — deliberately below the 200-unit alert threshold to make the alert visible on first run) plus three pre-sold historical batches for the financial dashboard demonstration.
  • New MenuOptions static class (Text/MenuOptions.cs)

    • Centralised all menu string arrays (MainMenu, MachineMenu, ProductMenu, ReportMenu, SalesMenu, AccountingMenu, EmployeeManagementMenu, EmployeeRoles, FormFactors, TechAssignChoices, ProductTypes) into a single file, eliminating scattered inline string literals across multiple UI handlers.

Bug Fixes

  • Employee ID counter inflation on load (Core/Factory.cs)

    • LoadFromRepository now calls Employee.InitializeIdCounter(0) and Machine.InitializeIdCounter(0) before materialising the deserialized lists. Previously, the JSON deserializer triggered the normal constructor for each entity (incrementing the static counter), causing subsequent new entities to receive IDs offset by the number of loaded records. This was the root-cause of the "fixed an issue with employee ID" commit.
  • SellFromInventoryCommand undo batch restoration (Services/UndoService.cs)

    • After undoing a sale, the undo handler now also looks up the original ProductionBatch by BatchId, increments its Quantity, and calls MarkAsUnsold() — previously the batch remained marked as sold even after the inventory item was restored.
  • Logger WriteToFile called with enum value instead of string (Services/LoggerService.cs)

    • WriteToFile signature changed from (string level, LogOrigin origin, ...) to (string level, string origin, ...). Call sites use nameof(origin).ToUpper() / nameof(LogOrigin.System).ToUpper() to produce a stable string regardless of future enum renames, fixing a previous oversight where the enum .ToString() could change.
  • FactoryReportMenuHandler removed (UI/FactoryReportMenuHandler.cs)

    • The entire file was deleted (169 lines). Its functionality is now covered directly by ReportMenuHandler and AccountingMenuHandler, removing a redundant handler that was causing confusion.
  • ProductionBatch.Quantity and UnitProductionCost mutability (Core/ProductionBatch.cs)

    • Changed from init-only to set so that the actual cost entered by the operator after a run can be written back to the batch.
  • MachinePart.Name accessor narrowed (Core/MachinePart.cs)

    • Changed public string? Name { get; private protected set; }public string? Name { get; } to prevent accidental mutation from derived classes.
  • Technician menu trimmed (Core/Employee.cs)

    • Removed "Reports" and "Factory Information" from Technician.GetMenuOptions() — technicians no longer see menu items that were never properly implemented or authorised for their role.
  • Accountant quick-action and menu restored (Core/Employee.cs)

    • QuickActionName changed from "N/A" to "Quick Actions" and "Quick Actions" re-added as the first entry in GetMenuOptions(), so the Accountant role actually shows its quick-action shortcut.
  • Markup typo in Products.PortfolioTitle (Text/Products.cs)

    • Removed a stray trailing [/] markup tag that was not opened, which would have caused Spectre.Console to throw a markup parse error when rendering the analytics panel.

Enhancements

  • Production-order and report-request persistence (UI/Program.cs, UI/ProductionMenuHandler.cs, UI/ReportMenuHandler.cs)

    • Program.cs now instantiates JsonRepository<ProductionOrder> (orders.json) and JsonRepository<ReportRequest> (report_requests.json) and passes them through the call chain.
    • Factory.LoadFromRepository signature extended to accept IEnumerable<ProductionOrder> and IEnumerable<ReportRequest>, which are hydrated into their respective queues on startup.
    • ProductionMenuHandler saves the order queue after every production run; ReportMenuHandler saves the report-request queue immediately after submission.
  • Batch reconstruction on load (Core/Factory.cs)

    • On startup, LoadFromRepository groups the loaded Product list by BatchId and reconstructs ProductionBatch objects (quantity, weighted average unit cost, sell price if already priced, sold status). This means batch data survives a restart without a separate batch file.
  • Production Summary merged into Financial Dashboard (UI/ReportMenuHandler.cs, Text/Reports.cs)

    • The standalone "Batch Revenue Summary" report option was retired. Its content is now merged into an expanded "Production Summary" that shows: a snapshot panel (generated by, timestamp, item types, total units, estimated value, headcount, machine count), a full batch table (all batches, produced vs. sold status), and a colour-coded Financial Summary panel (Total Expenses in red, Total Income in green, Net Profit/Loss in green/red based on sign).
    • ShowProductionSummary is now internal static to allow the Accounting menu to reuse it directly.
  • Report-request export-destination captured (Core/ReportRequest.cs)

    • ExportDestination { get; set; } = "ReportsFolder" added to ReportRequest. AccountingMenuHandler.ProcessReportRequests can now honour the chosen folder when fulfilling a request.
  • Repair spinner text localised (Text/Machines.cs)

    • Three new string constants for machine repair spinner phases added (RepairSpinnerOpeningPanels, RepairSpinnerServicingPart, RepairSpinnerDiagnostics) so the MachineMenuHandler can display human-readable repair progress.
  • Production alert strings added (Text/Production.cs)

    • CostAdvice, CostPrompt, CostValidationInvalidNumber, CostValidationNegative, ProductionLineTitle, MachineTrippedAlert, CompletedUnitsStatus, MotherboardLineTitle, WorkflowTrippedAlert, StepSmt, StepPap, StepOven — all new constants extracted from inline strings in ProductionMenuHandler.
  • Reports strings extended (Text/Reports.cs)

    • ChooseExportFolderPrompt, ExportDestDesktop, ExportDestReportsFolder, ExportDestSelected, ProductionSummaryHeader, BatchesDetailsHeader, column header constants, StatusSold, StatusProduced, NoBatchesProduced, financial label constants, FinanceHeader, OrderBacklogSummaryHeader, ColumnOrderId.
  • Accounting strings added (Text/Accounting.cs)

    • Added QuickActionViewBatches, QuickActionProcessReportRequests, QuickActionViewProductionSummary, QuickActionReturnToMainMenu for the accountant's numbered quick-action menu.
  • Employee removal strings added (Text/Employees.cs)

    • RemoveTitle, NoEmployeesToRemove, SelectEmployeeToRemove, RemoveConfirmPrompt, RemoveSuccess, RemoveCancelled.
  • Sales strings extended (Text/Sales.cs)

    • Added a string constant for the auto-assignment acknowledgment prompt.
  • LogOrigin enum naming aligned to C# conventions (Services/LoggerService.cs)

    • SYSTEM → System, USER → User, UNDO → Undo. All 30+ call sites updated throughout UI/.
  • UndoService private field renamed (Services/UndoService.cs)

    • _commands → Commands (PascalCase static field) to satisfy the project's naming-convention linter.
  • ProductionOrder constructor and property mutability (Core/ProductionOrder.cs)

    • Added a parameterless constructor alongside the existing primary constructor so that System.Text.Json can deserialise persisted orders without reflection hacks. All init-only properties changed to set for the same reason. IsNotifiedComplete default value removed (now relies on the CLR default false).
  • ReportRequest constructor and property mutability (Core/ReportRequest.cs)

    • Same pattern: added parameterless constructor, changed initset, changed private set on Statusset for JSON round-tripping.
  • Product property mutability (Core/Product.cs)

    • ProductionCost: private initset (needed by the post-run cost update).
    • SellingPrice and Quantity backing fields replaced with C# 13 field keyword expressions.
    • Name: initget-only (prevents post-construction name mutation).
    • Microprocessor.Architecture property removed (unused).
    • Microprocessor.Cores, ClockSpeed, Motherboard.SocketStandard, PhysicalForm: initget-only.
  • Employee.Id mutability (Core/Employee.cs)

    • Changed from init to set to allow JSON deserializer to round-trip employee IDs correctly without the primary constructor.
  • DataSeeder: Employee constructor call simplified (Services/DataSeeder.cs)

    • Removed the explicit false argument for isFirstTimeLogin from all four seed employees (relies on default parameter value), reducing noise in the seed file.

Refactoring

  • MenuOptions.cs extracted to Text/ layer ({UI → Text}/MenuOptions.cs)

    • The file was moved from UI/ to Text/ to respect the strict layering rule (UI must not contain data that belongs in the localisation/text layer). Six references (menu string arrays) updated accordingly.
  • FactoryReportMenuHandler deleted (UI/FactoryReportMenuHandler.cs)

    • 169-line file removed; responsibilities consolidated into existing handlers.
  • Factory capacity model replaced (Core/Factory.cs)

    • InventoryCapacity (backed by _inventory.Capacity, a List<T> internal capacity — meaningless as a business value) replaced with computed business constants: MaxBatches = 20, MaxUnitsPerBatch = 100, MaxCapacity = 2000, MinStockThreshold = 200, and GetTotalUnsoldUnits().

Files Changed

File Lines ±
Core/Employee.cs +7 / -1
Core/Factory.cs +80 / -4
Core/Machine.cs +157 / -117
Core/MachinePart.cs +1 / -1
Core/Product.cs +20 / -15
Core/ProductionBatch.cs +4 / -4
Core/ProductionOrder.cs +22 / -6
Core/ReportRequest.cs +18 / -5
Services/DataSeeder.cs +18 / -10
Services/LoggerService.cs +8 / -9
Services/UndoService.cs +37 / -6
Text/Accounting.cs +6
Text/Employees.cs +7
Text/Machines.cs +3
Text/MenuOptions.cs (moved from UI/) +6 / -0
Text/Production.cs +22
Text/Products.cs +1 / -1
Text/Reports.cs +29
Text/Sales.cs +1
UI/AccountSettingsMenuHandler.cs +3 / -3
UI/AccountingMenuHandler.cs +120 / -48
UI/EmployeeMenuHandler.cs +50 / -9
UI/FactoryReportMenuHandler.cs deleted (−169)
UI/LoginMenuHandler.cs +2 / -2
UI/MachineMenuHandler.cs +5 / -5
UI/PasswordChangeHandler.cs +1 / -1
UI/ProductMenuHandler.cs +27 / -12
UI/ProductionMenuHandler.cs +330 / -111
UI/Program.cs +25 / -15
UI/ReportMenuHandler.cs +80 / -56
UI/SalesMenuHandler.cs +30 / -34
UI/TUIHelpers.cs +1 / -1
UI/UndoMenuHandler.cs +2 / -2
.idea/encodings.xml +7

Total: 34 files changed, +1 184 insertions, −590 deletions

@CasperGamingOne

Copy link
Copy Markdown
Owner Author

@ganeaandreea701-crypto ⬆️ ⬆️

@CasperGamingOne
CasperGamingOne merged commit 59f8555 into new-tui-frontend Jul 17, 2026
5 checks passed
@CasperGamingOne
CasperGamingOne deleted the day_4-andreea branch July 17, 2026 03:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant