From 941ad705676eb3c14fc72dfd19041b96636800e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 08:01:43 +0200 Subject: [PATCH 01/12] feat: add Sprint Playbook Template and Implementation Guidelines for AI agents --- .../how-to-use-sprint-playbook-template.md | 209 +++++++++++ .../sprint-implementation-guidelines.md | 348 ++++++++++++++++++ docs/framework/sprint-playbook-template.md | 94 +++++ 3 files changed, 651 insertions(+) create mode 100644 docs/framework/how-to-use-sprint-playbook-template.md create mode 100644 docs/framework/sprint-implementation-guidelines.md create mode 100644 docs/framework/sprint-playbook-template.md diff --git a/docs/framework/how-to-use-sprint-playbook-template.md b/docs/framework/how-to-use-sprint-playbook-template.md new file mode 100644 index 0000000..5fef372 --- /dev/null +++ b/docs/framework/how-to-use-sprint-playbook-template.md @@ -0,0 +1,209 @@ +# πŸ“˜ How to Use the Sprint Playbook Template + +*(Guide for AI Agent)* + +--- + +## 🎯 Purpose + +This guide explains how to generate a **Sprint Playbook** from the **Sprint Playbook Template**. +The Playbook is the **authoritative plan and tracking file** for the Sprint. +Your role as AI agent is to: + +1. Interpret the user’s Sprint goal. +2. Analyze the current project state. +3. Split work into clear user stories. +4. Populate the Playbook with concise, actionable details. +5. Ensure the Playbook defines a **minimal implementation** β€” no extra features beyond scope. + +--- + +## πŸ›  Step-by-Step Instructions + +### 1. Analyze User Input + +* Read the user’s description of what should be achieved in the Sprint. +* Extract the **general goal** (e.g., β€œadd authentication,” β€œimprove reporting,” β€œfix performance issues”). +* Note any explicit **constraints** (frameworks, coding styles, patterns). + +**If gaps, ambiguities, or contradictions are detected:** + +**MANDATORY PROCESS:** +1. **STOP playbook creation immediately** +2. **Ask user for specific clarification** with concrete questions: + * *"Do you want authentication for all users or just admins?"* + * *"Should performance improvements target backend response times or frontend rendering?"* + * *"You mentioned using Django, but the codebase uses Flask β€” should we migrate or stick with Flask?"* +3. **Wait for user response** - do not proceed with assumptions +4. **Repeat clarification cycle** until goal is completely unambiguous +5. **Only then proceed** to create the playbook + +**CRITICAL RULE**: Never proceed with unclear requirements - this will cause blocking during implementation. + +--- + +### 2. Assess Current State + +**MANDATORY STEPS:** +1. Read project entry points (e.g., `main.py`, `index.js`, `app.py`) +2. Identify and read core business logic modules +3. Read configuration files (`.env`, `config.*`, etc.) +4. Read dependency files (`package.json`, `requirements.txt`, `Cargo.toml`, etc.) +5. List current main features available +6. List known limitations or issues +7. List relevant file paths +8. Document runtime versions, frameworks, and libraries + +**Output Requirements:** +* Keep descriptions factual and concise (2-3 sentences per item) +* Focus only on functionality relevant to the sprint goal +* Do not speculate about future capabilities + +--- + +### 3. Sprint ID Selection (Mandatory Process) + +**EXACT STEPS TO FOLLOW:** +1. **Check if `docs/sprints/` directory exists** + - If directory doesn't exist: set **Sprint ID = `01`** + - If directory exists: proceed to step 2 + +2. **List existing sprint files** + - Search for files matching pattern: `docs/sprints/sprint-??-*.md` + - Extract only the two-digit numbers (ignore everything else) + - Example: `sprint-03-auth.md` β†’ extract `03` + +3. **Calculate new ID** + - If no matching files found: set **Sprint ID = `01`** + - If files found: find maximum ID number and increment by 1 + - Preserve zero-padding (e.g., `03` β†’ `04`, `09` β†’ `10`) + +**CRITICAL RULES:** +- NEVER use IDs from example documents - examples are for formatting only +- NEVER guess or assume sprint IDs +- ALWAYS preserve two-digit zero-padding format +- This is the single source of truth for Sprint ID assignment + +--- + +### 4. Define Desired State + +**MANDATORY SECTIONS:** +1. **New Features** - List exactly what new functionality will be added +2. **Modified Features** - List existing features that will be changed +3. **Expected Behavior Changes** - Describe how user/system behavior will differ +4. **External Dependencies/Integrations** - List new libraries, APIs, or services needed + +**Requirements:** +* Each item must be specific and measurable +* Avoid vague terms like "improve" or "enhance" - be precise +* Only include changes directly needed for the sprint goal + +--- + +### 5. Break Down Into User Stories + +**STORY CREATION RULES:** +1. Each story must be implementable independently +2. Story should require 1-2 commits maximum +3. Story must have measurable acceptance criteria +4. Story must include specific DoD items + +**MANDATORY STORY COMPONENTS:** +* **Story ID**: Sequential numbering (`US-1`, `US-2`, `US-3`...) +* **Title**: 2-4 word description of the functionality +* **Description**: Clear explanation of what needs to be implemented +* **Acceptance Criteria**: Specific, testable conditions that must be met +* **Definition of Done**: Concrete checklist (implemented, tested, docs updated, lint clean) +* **Assignee**: Always `AI-Agent` for AI-implemented sprints +* **Status**: Always starts as `πŸ”² todo` + +**STATUS PROGRESSION (AI must follow exactly):** +* `πŸ”² todo` β†’ `🚧 in progress` β†’ `βœ… done` +* If blocked: any status β†’ `🚫 blocked` (requires user intervention) +* **CRITICAL**: If ANY story becomes `🚫 blocked`, STOP all sprint work immediately + +--- + +### 6. Add Technical Instructions + +**REQUIRED SECTIONS:** +* **Code Snippets/Patterns**: Include specific code examples that show structure +* **Architecture Guidelines**: Define module boundaries, layering, design patterns +* **Coding Style Conventions**: Specify naming rules, formatting, linting requirements +* **Testing Strategy**: Define what testing is required (unit/integration, framework, coverage) + +**GUIDELINES:** +* Provide concrete examples, not abstract descriptions +* If multiple approaches exist, specify exactly which one to use +* Include specific commands for building, testing, and linting +* Reference existing project conventions where possible + +--- + +### 7. Capture Risks and Dependencies + +* List potential **risks** (technical, integration, scope-related). +* List **dependencies** (modules, libraries, APIs, data sources). + +--- + +### 8. Apply Definition of Done (DoD) + +**USER STORY DoD (for each story):** +* Must include specific, measurable items like: + * "Endpoint implemented and returns correct status codes" + * "Unit tests added with 80%+ coverage" + * "Documentation updated in README" + * "Code passes linter without errors" + +**SPRINT DoD STRUCTURE (mandatory separation):** + +**AI-Responsible Items** (AI MUST tick these when completed): +* [ ] All user stories meet their individual Definition of Done +* [ ] Code compiles and passes automated tests +* [ ] Code is committed and pushed on branch `[feature/sprint-]` +* [ ] Documentation is updated +* [ ] Sprint status updated to `βœ… done` + +**User-Only Items** (AI MUST NEVER tick these): +* [ ] Branch is merged into main +* [ ] Production deployment completed (if applicable) +* [ ] External system integrations verified (if applicable) + +**CRITICAL RULE**: AI agents must NEVER tick user-only DoD items under any circumstances. + +--- + +--- + +## ⚠️ Guardrail Against Overfitting + +If you are provided with **example Sprint Playbooks**: + +* Use them **only to understand formatting and structure**. +* Do **not** copy their technologies, libraries, or domain-specific details unless explicitly relevant. +* Always prioritize: + + 1. **Sprint Playbook Template** + 2. **User instructions** + 3. **Project state analysis** + +--- + +## βœ… Output Requirements + +**MANDATORY CHECKLIST** - Sprint Playbook must have: + +1. βœ… **Correct Sprint ID** - Follow Sprint ID selection rule (increment from existing) +2. βœ… **Complete metadata** - All fields in Sprint Metadata section filled +3. βœ… **Current state analysis** - Based on actual project file examination +4. βœ… **Specific desired state** - Measurable outcomes, not vague goals +5. βœ… **Independent user stories** - Each story can be implemented separately +6. βœ… **Testable acceptance criteria** - Each story has specific pass/fail conditions +7. βœ… **Concrete DoD items** - Specific, actionable checklist items +8. βœ… **Technical guidance** - Actual code snippets and specific instructions +9. βœ… **Risk identification** - Potential blockers and dependencies listed +10. βœ… **Proper DoD separation** - AI vs User responsibilities clearly marked + +**VALIDATION**: Before finalizing, verify that another AI agent could execute the sprint based solely on the playbook content without additional clarification. \ No newline at end of file diff --git a/docs/framework/sprint-implementation-guidelines.md b/docs/framework/sprint-implementation-guidelines.md new file mode 100644 index 0000000..a98a318 --- /dev/null +++ b/docs/framework/sprint-implementation-guidelines.md @@ -0,0 +1,348 @@ +# πŸ“˜ Sprint Implementation Guidelines + +These guidelines define how the AI agent must implement a Sprint based on the approved **Sprint Playbook**. +They ensure consistent execution, traceability, and alignment with user expectations. + +--- + +## 0. Key Definitions + +**Logical Unit of Work (LUW)**: A single, cohesive code change that: +- Implements one specific functionality +- Can be described in 1-2 sentences +- Passes all relevant tests +- Can be committed independently + +**Blocked Status (`🚫 blocked`)**: A user story cannot proceed due to: +- Missing external dependencies +- Conflicting requirements +- Failed tests that cannot be auto-fixed +- Missing user clarification + +**AI-Responsible DoD Items**: Checkboxes the AI can verify and tick: +- Code compiles and passes tests +- Code committed and pushed to branch +- Documentation updated +- Sprint status updated to done + +**User-Only DoD Items**: Checkboxes only the user can tick: +- Branch merged into main +- Production deployment completed +- External integrations verified + +--- + +## 1. Git & Version Control Rules + +### 1.1 Commit Granularity + +* Commit after each **logical unit of work (LUW)**. +* A user story may span multiple commits. +* Do not mix unrelated changes (e.g., no β€œfeature + formatting” in one commit). +* Include tests for the LUW in the same commit if the story's DoD requires tests. +* Local WIP commits may be squashed before delivery, but history must remain clear. + +### 1.2 Commit Message Style + +* Use **Conventional Commits** format: + + ``` + (): + + + + Refs: + ``` +* Example: + + ``` + feat(auth): add JWT middleware + + Introduces HS256 verification for protected routes. + Returns 401 for missing/invalid/expired tokens. + + Refs: US-3 + ``` +* Allowed ``: `feat`, `fix`, `refactor`, `perf`, `test`, `docs`, `build`, `ci`, `style`, `chore`, `revert`. + +### 1.3 Branching Strategy + +* Use **one dedicated branch per Sprint**: + + * Naming: `feature/sprint--` + * Example: `feature/sprint-07-auth` +* Branch created from `main` and kept up to date via rebase or merge. +* `main` remains protected. + +**Sprint ID source of truth:** The Sprint ID **must** follow the β€œSprint ID selection rule” in the How-to guide. +If no prior Playbooks exist in `docs/sprints/`, start at `01`; otherwise increment the greatest existing two-digit ID (keep zero-padding). + +### 1.4 Commit & Push Policy + +* Run build and fix issues before committing. +* Commit and push regularly (at least daily). + +### 1.5 PR / Merge Rules + +* The AI agent **must not merge or open PRs**. +* The AI’s responsibility ends with: + * Implementing all user stories. + * Committing changes to the Sprint branch. + * Ensuring the branch passes all tests. +* The **user merges** the Sprint branch into `main`. + +--- + +## 2. Playbook Status Updating + +### 2.1 User Stories +* Update each story’s `Status` field (`πŸ”² todo` β†’ `🚧 in progress` β†’ `βœ… done`). +* Mark `βœ… done` only when the story’s **DoD** is fully satisfied. + +### 2.2 Sprint Status (Top-Level) + +* Keep the top-level Sprint status current: + + ``` + Status: [πŸ”² not started | 🚧 in progress | πŸ› οΈ implementing | βœ… done] + ``` + +### 2.3 Commit & Status Sync + +**Strict choreography** + +- **First commit of a story** + Include the first code changes for `US-#` **and** update the Playbook in the same commit: + - Sprint status β†’ `πŸ› οΈ implementing US-#` + - Story `US-#` status β†’ `🚧 in progress` + +- **Final commit of a story** + Include the completing code changes for `US-#` **and** update the Playbook in the same commit: + - Story `US-#` status β†’ `βœ… done` + - Tick any **AI-responsible** DoD items that became true in this commit (see below) + +- **DoD checkbox updates** + Tick AI-responsible DoD items **in the same commit** that makes them true: + - βœ… Code compiles and passes automated tests + - βœ… Code is committed and pushed on branch + - βœ… Documentation is updated + - βœ… Sprint status updated to done + + **NEVER tick user-only DoD items** such as: + - ❌ Branch is merged into main + - ❌ Production deployment completed + - ❌ External systems integration verified + +- **No status-only commits** + Avoid standalone β€œstatus update” commits. If a previous commit forgot a status/DoD tick, include it in the **very next** code commit for that story. + + +### 2.4 Location & Traceability + +* Store Playbook in repo under `docs/sprints/sprint-.md`. +* Reference Story IDs in commit messages. + +### 2.5 End-of-Sprint Update + +* Update Sprint status β†’ `βœ… done`. +* Update Playbook with final status changes. +* Stop execution. + +--- + +## 3. Coding & Testing Standards + +### 3.1 Style Guides + +* Follow project’s existing style guides. +* Follow existing style guides exactly unless deviation prevents story completion. +* If deviation is necessary, document rationale in commit body and ask user for approval. +* Do not mix stylistic mass-changes with functional code. + +### 3.2 Code Quality + +* Keep changes minimal and scoped. +* Favor readability and idiomatic solutions. +* Maintain module boundaries. +* Add/update docstrings and project docs when behavior changes. + +### 3.3 Testing Policy + +* **Unit tests**: required for all backend logic, utilities, data processing, and business logic. +* **UI tests**: required only if the story's DoD explicitly mentions testing UI behavior. +* Pure styling changes (CSS-only) do not require tests. +* **Integration/E2E tests**: explicitly out of scope. +* Maintain existing test coverage levels. + +### 3.4 Test Execution + +* Run relevant tests locally before committing. + +### 3.5 Prohibited + +* No large-scale refactors unless explicitly requested. +* No new frameworks or test harnesses. +* No speculative features. + +--- + +## 4. Execution Flow + +### 4.1 Story Execution Workflow + +**STEP 1: Start Story** +1. Verify previous story is `βœ… done` (if `🚫 blocked`, STOP - do not proceed) +2. Change story status from `πŸ”² todo` to `🚧 in progress` +3. Change sprint status to `πŸ› οΈ implementing US-#` +4. Commit these playbook changes with first code changes for the story + +**STEP 2: Implement Story (Loop)** +For each LUW in the story: +1. Write code for one logical unit of work +2. Write tests if required by story DoD +3. Run tests and fix any failures +4. Commit LUW with conventional commit message including "Refs: US-#" +5. Push commit to branch + +**STEP 3: Complete Story** +1. Verify all story acceptance criteria are met +2. Verify all AI-responsible DoD items are complete +3. Run final test suite +4. Update story status to `βœ… done` +5. Tick completed AI-responsible DoD checkboxes +6. Commit these playbook updates +7. Push final commit + +**STEP 4: Next Story or Block Handling** +- If current story is `βœ… done`: proceed to STEP 1 for next story +- If current story is `🚫 blocked`: STOP execution, notify user, wait for instructions +- If no more stories and all are `βœ… done`: proceed to End-of-Sprint workflow + +### 4.2 Blocking Workflow + +**When ANY story becomes `🚫 blocked`:** +1. Mark story status as `🚫 blocked` with specific reason +2. Commit playbook changes immediately +3. Notify user with blocker details +4. **STOP all sprint work** - do not proceed to next stories +5. Wait for user to provide resolution instructions +6. Only resume when user gives explicit unblocking guidance + +**Critical Rule: NO STORY PROGRESSION DURING BLOCKING** +- Do not start new stories while any story is `🚫 blocked` +- Do not attempt workarounds or fixes without user approval +- Sprint execution is completely paused until all blocks are resolved + +### 4.3 End-of-Sprint Workflow + +**STEP 1: Final Verification** +1. Verify all stories are `βœ… done` (if any are `🚫 blocked`, STOP and notify user) +2. Run complete test suite +3. Update any remaining documentation + +**STEP 2: Sprint Completion** +1. Update sprint status to `βœ… done` +2. Tick any remaining AI-responsible DoD items +3. Commit final changes +4. Push branch to remote + +**STEP 3: Stop Execution** +- Report sprint completion to user +- Do not merge branch or open PRs + +--- + +## 5. Documentation & Communication + +### 5.1 Inline Comments + +* Update/add comments for new or changed functions/classes/modules. +* Keep concise and technical. + +### 5.2 Project Docs + +* Update README/API docs/configs when public-facing behavior changes. +* Docs updated in **same commit** as related code. + +### 5.3 Exclusions + +* No separate Sprint summary reports. +* No speculative documentation outside scope. + +--- + +## 6. Failure & Error Handling + +### 6.1 Error Response Protocol + +**MANDATORY STEPS when encountering any blocker:** +1. Stop current work immediately +2. Mark story status as `🚫 blocked` in playbook +3. Add specific blocker reason to playbook +4. Commit playbook changes +5. Ask user for explicit resolution +6. Wait for user response - do not proceed + +### 6.2 Specific Error Actions + +**Test Failures:** +1. Run tests again to confirm failure +2. Copy exact error messages +3. Mark story as `🚫 blocked` with reason: "Tests failing: [error summary]" +4. Ask user: "Tests are failing with error: [exact error]. Should I fix this or wait for guidance?" + +**Missing Dependencies:** +1. Identify exactly what is missing +2. Mark story as `🚫 blocked` with reason: "Missing dependency: [name]" +3. Ask user: "Missing dependency [name]. Should I install it or mock it for testing?" + +**Conflicting Requirements:** +1. Document the specific conflict +2. Mark story as `🚫 blocked` with reason: "Conflicting requirements: [details]" +3. Ask user: "Found conflicting requirements: [details]. Which approach should I follow?" + +**Build/Compilation Failures:** +1. Copy exact build error +2. Mark story as `🚫 blocked` with reason: "Build failing: [error summary]" +3. Ask user: "Build is failing with: [exact error]. How should I resolve this?" + +### 6.3 Prohibited Actions During Blocking + +**NEVER do these when `🚫 blocked`:** +- Continue to next story +- Make speculative fixes +- Change requirements to work around issues +- Skip failing tests +- Implement workarounds without approval + +### 6.4 Unblocking Requirements + +**AI can only resume work after user provides:** +- Explicit instruction on how to resolve the blocker +- Modified requirements if applicable +- Confirmation that workaround approach is acceptable + +--- + +## 7. Sprint Wrap-Up + +### 7.1 Completion Criteria + +Sprint is complete when: + +* All user stories = `βœ… done`. +* Sprint status = `βœ… done`. +* Final status updates completed. +* Code committed to Sprint branch. +* Docs and comments updated. +* Tests passing (when applicable). + +### 7.2 Handover + +* AI stops execution. +* Sprint branch remains unmerged. + +### 7.3 Final Note + +* No changes beyond Sprint scope. +* Playbook + Git history act as audit record. diff --git a/docs/framework/sprint-playbook-template.md b/docs/framework/sprint-playbook-template.md new file mode 100644 index 0000000..526d4c4 --- /dev/null +++ b/docs/framework/sprint-playbook-template.md @@ -0,0 +1,94 @@ +# πŸ“‘ Sprint Playbook Template +## 0. Sprint Status + +``` +Status: [πŸ”² not started | 🚧 in progress | πŸ› οΈ implementing | βœ… done] +``` +--- + +## 1. Sprint Metadata + +* **Sprint ID:** \[unique identifier] +* **Start Date:** \[YYYY-MM-DD] +* **End Date:** \[YYYY-MM-DD] +* **Sprint Goal:** \[clear and concise goal statement] +* **Team/Agent Responsible:** \[AI agent name/version] +* **Branch Name (Git):** \[feature/sprint-] + +--- + +## 2. Current State of Software + +*(Concise snapshot of the project before Sprint work begins)* + +* **Main Features Available:** \[list] +* **Known Limitations / Issues:** \[list] +* **Relevant Files / Modules:** \[list with paths] +* **Environment / Dependencies:** \[runtime versions, frameworks, libs] + +--- + +## 3. Desired State of Software + +*(Target state after Sprint is complete)* + +* **New Features:** \[list] +* **Modified Features:** \[list] +* **Expected Behavior Changes:** \[list] +* **External Dependencies / Integrations:** \[list] + +--- + +## 4. User Stories + +Each story represents a **unit of work** that can be developed and tested independently. + +| Story ID | Title | Description | Acceptance Criteria | Definition of Done | Assignee | Status | +| -------- | -------------- | ---------------------------------------- | ---------------------------- | ------------------------------------------------ | ----------- | ------ | +| US-1 | \[short title] | \[detailed description of functionality] | \[conditions for acceptance] | \[implemented, tested, docs updated, lint clean] | \[AI agent] | πŸ”² todo | +| US-2 | ... | ... | ... | ... | ... | πŸ”² todo | + +**Status options:** `πŸ”² todo`, `🚧 in progress`, `🚫 blocked`, `βœ… done` + +--- + +## 5. Technical Instructions + +*(Guidance to help AI converge quickly on the correct solution)* + +* **Code Snippets / Patterns:** + + ```python + # Example placeholder snippet + def example_function(): + pass + ``` +* **Architecture Guidelines:** \[layering, module boundaries, design patterns] +* **Coding Style Conventions:** \[naming rules, formatting, linting] +* **Testing Strategy:** \[unit/integration, testing framework, coverage target] + +--- + +## 6. Risks and Dependencies + +* **Risks:** \[list potential blockers, e.g., API instability, missing test coverage] +* **Dependencies:** \[other modules, external services, libraries, team inputs] + +--- + +## 7. Sprint Definition of Done (DoD) + +The Sprint is complete when: + +**AI-Responsible Items** (AI agent can verify and tick): +* [ ] All user stories meet their individual Definition of Done. +* [ ] Code compiles and passes automated tests. +* [ ] Code is committed and pushed on branch `[feature/sprint-]`. +* [ ] Documentation is updated. +* [ ] Sprint status updated to `βœ… done`. + +**User-Only Items** (Only user can verify and tick): +* [ ] Branch is merged into main. + +--- + From d8c3ad72285c9be7e309a0a00983e1a8c787ab28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 08:29:41 +0200 Subject: [PATCH 02/12] plan: add support for printing 2D barcode images with UI enhancements --- docs/sprints/sprint-description-n-prompt.md | 38 +++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 docs/sprints/sprint-description-n-prompt.md diff --git a/docs/sprints/sprint-description-n-prompt.md b/docs/sprints/sprint-description-n-prompt.md new file mode 100644 index 0000000..9c28d20 --- /dev/null +++ b/docs/sprints/sprint-description-n-prompt.md @@ -0,0 +1,38 @@ +# Sprint 01: adding barcode print support + +In this sprint we will add a capability to print a table containing all 2D barcode images for a given month. + +## Changes to the UI + +In the UI within month card a button will be added: + +* location: at the bottom - next to "Add a new realestate" +* tooltip: + - EN tooltip: "Print 2D codes" + - HR tooltip: "Ispis 2d kodova" +* icon: printer +* action on pressed: show a print preview in the new tab/window + +## Print preview + +Print preview will contain a table of all 2D barcodes found within that month. + +In print preview the table will have 3 columns: +1. row index +2. bill info: + - `yyyy-mm` formated current month's date + - realestate name + - bill name +3. 2D barcode image + +In top-left corner of the page (position fixed) will be a printer icon which will trigger the print action. +The icon will not be visible in the printed version of the document. + +## Styling +* use Tailwind CSS +* print dialog: native dialog +* print type: B&W +* paper size: A4 +* when printerd the 2D barcode will have the following size: + - width = 58 mm + - height: automatic without changing proportions of original image \ No newline at end of file From ecea10e80534a6cf46ab54bf5b4cd7c62a0df5d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 09:08:40 +0200 Subject: [PATCH 03/12] feat: implement US-1 - add print button to MonthCard with i18n support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add PrintButton component with card styling matching AddLocationButton - Integrate print button next to "Add a new realestate" with centered layout - Add English/Croatian translations for print tooltips and labels - Implement click handler to open print preview in new tab - Create Sprint Playbook for barcode print functionality πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- app/ui/MonthLocationList.tsx | 6 +- app/ui/PrintButton.tsx | 32 ++++ docs/sprints/sprint-01-barcode-print.md | 196 ++++++++++++++++++++++++ messages/en.json | 4 +- messages/hr.json | 4 +- 5 files changed, 239 insertions(+), 3 deletions(-) create mode 100644 app/ui/PrintButton.tsx create mode 100644 docs/sprints/sprint-01-barcode-print.md diff --git a/app/ui/MonthLocationList.tsx b/app/ui/MonthLocationList.tsx index 8555cc6..879b323 100644 --- a/app/ui/MonthLocationList.tsx +++ b/app/ui/MonthLocationList.tsx @@ -6,6 +6,7 @@ import { AddMonthButton } from "./AddMonthButton"; import { MonthCard } from "./MonthCard"; import Pagination from "./Pagination"; import { LocationCard } from "./LocationCard"; +import { PrintButton } from "./PrintButton"; import { BillingLocation, YearMonth } from "../lib/db-types"; import { useRouter, useSearchParams } from "next/navigation"; import { ToastContainer } from 'react-toastify'; @@ -83,7 +84,10 @@ export const MonthLocationList:React.FC = ({ locations.map((location, ix) => ) : null } - +
+ + +
) } diff --git a/app/ui/PrintButton.tsx b/app/ui/PrintButton.tsx new file mode 100644 index 0000000..d38a495 --- /dev/null +++ b/app/ui/PrintButton.tsx @@ -0,0 +1,32 @@ +"use client"; + +import { PrinterIcon } from '@heroicons/react/24/outline'; +import { useTranslations } from 'next-intl'; +import { YearMonth } from '../lib/db-types'; + +export interface PrintButtonProps { + yearMonth: YearMonth; +} + +export const PrintButton: React.FC = ({ yearMonth }) => { + const t = useTranslations("home-page.month-card"); + + const handlePrintClick = () => { + window.open(`/print/${yearMonth.year}/${yearMonth.month}`, '_blank'); + }; + + return ( +
+ +
+ ); +}; \ No newline at end of file diff --git a/docs/sprints/sprint-01-barcode-print.md b/docs/sprints/sprint-01-barcode-print.md new file mode 100644 index 0000000..e11df9d --- /dev/null +++ b/docs/sprints/sprint-01-barcode-print.md @@ -0,0 +1,196 @@ +# πŸ“‘ Sprint Playbook: Barcode Print Support + +## 0. Sprint Status + +``` +Status: πŸ”² not started +``` + +--- + +## 1. Sprint Metadata + +* **Sprint ID:** 01 +* **Start Date:** 2025-01-14 +* **End Date:** 2025-01-16 +* **Sprint Goal:** Add capability to print a table containing all 2D barcode images for a given month +* **Team/Agent Responsible:** AI-Agent (Claude Sonnet 4) +* **Branch Name (Git):** feature/sprint-01 + +--- + +## 2. Current State of Software + +*(Snapshot of the project before Sprint work begins)* + +* **Main Features Available:** + - Multi-user utility bills tracking system + - Monthly billing periods with expandable MonthCard UI components + - Location and bill management with CRUD operations + - 2D barcode scanning and storage (bills already have `barcodeImage` field) + - PDF processing capabilities with `@zxing/library` and `pdfjs-dist` + - Internationalization support (Croatian/English) + +* **Known Limitations / Issues:** + - No print functionality for barcode overview + - Barcode images stored as base64 strings but not displayed in bulk format + - No print-optimized styling or layout + +* **Relevant Files / Modules:** + - `app/ui/MonthCard.tsx` - Monthly accordion components + - `app/ui/MonthLocationList.tsx` - Main month listing container + - `app/lib/db-types.ts` - Bill interface with `barcodeImage` field + - `app/lib/actions/locationActions.ts` - Data fetching for locations/bills + - Package dependencies: `@zxing/library`, `@zxing/browser`, `pdfjs-dist` + +* **Environment / Dependencies:** + - Node.js >=18.17.0 + - Next.js 14 with App Router and TypeScript + - Tailwind CSS 3.4.0 with DaisyUI 4.5.0 + - MongoDB 6.3.0 for data persistence + +--- + +## 3. Desired State of Software + +*(Target state after Sprint is complete)* + +* **New Features:** + - Print 2D codes button in each MonthCard + - Print preview page with barcode table layout + - Print-optimized styling with 58mm barcode width specification + - Fixed print icon for triggering native print dialog + +* **Modified Features:** + - MonthCard component enhanced with print button + - New print route and page component added to Next.js routing + +* **Expected Behavior Changes:** + - Users can access print functionality from month view + - Print preview opens in new tab/window + - Barcode table displays with row index, bill info, and barcode image + - Print layout optimized for A4 paper in B&W + +* **External Dependencies / Integrations:** + - Native browser print dialog integration + - CSS print media queries for optimized print output + +--- + +## 4. User Stories + +| Story ID | Title | Description | Acceptance Criteria | Definition of Done | Assignee | Status | +| -------- | ----- | ----------- | ------------------- | ------------------ | -------- | ------ | +| US-1 | Add Print Button | Add print 2D codes button to MonthCard component | Button appears next to "Add a new realestate", has printer icon, tooltips in EN/HR, opens print preview on click | Button implemented, styled with DaisyUI, tooltips working, click handler implemented, **user testing completed** | AI-Agent | βœ… done | +| US-2 | Create Print Route | Implement Next.js route for print preview | Route `/print/[year]/[month]` exists and loads barcode data | Route created, data fetching implemented, proper error handling, **user testing completed** | AI-Agent | 🚧 in progress | +| US-3 | Build Print Layout | Create print preview page with barcode table | Table has 3 columns: row index, bill info (yyyy-mm, realestate name, bill name), 2D barcode image | Print page component created, table layout implemented, data properly displayed, **user testing completed** | AI-Agent | πŸ”² todo | +| US-4 | Print Optimization | Apply print-specific CSS styling | 58mm barcode width, A4 paper size, B&W print, fixed print icon (hidden in print) | CSS print media queries added, barcode sizing correct, print icon positioned and hidden from print, **user testing completed** | AI-Agent | πŸ”² todo | + +**Status options:** `πŸ”² todo`, `🚧 in progress`, `🚫 blocked`, `βœ… done` + +--- + +## 5. Technical Instructions + +*(Guidance to help AI converge quickly on the correct solution)* + +* **Code Snippets / Patterns:** + + ```typescript + // Print button component pattern (integrate into MonthCard.tsx) + import { PrinterIcon } from '@heroicons/react/24/outline'; + + const handlePrintClick = () => { + window.open(`/print/${yearMonth.year}/${yearMonth.month}`, '_blank'); + }; + + + ``` + + ```typescript + // Print page route structure: app/[locale]/print/[year]/[month]/page.tsx + interface PrintPageProps { + params: { year: string; month: string; locale: string }; + } + + export default async function PrintPage({ params }: PrintPageProps) { + const locations = await fetchAllLocations(parseInt(params.year)); + // Filter for specific month and extract bills with barcodes + } + ``` + + ```css + /* Print-specific CSS */ + @media print { + .no-print { display: none !important; } + .barcode-cell img { width: 58mm; height: auto; } + @page { size: A4; margin: 1in; } + } + ``` + +* **Architecture Guidelines:** + - Follow existing Next.js App Router patterns with `[locale]` prefix + - Use server components for data fetching, client components only when needed + - Apply existing `withUser` HOF pattern for authenticated data access + - Maintain separation between UI components (`app/ui/`) and business logic + +* **Coding Style Conventions:** + - Use TypeScript with existing interface patterns from `db-types.ts` + - Follow DaisyUI component classes and Tailwind utilities + - Use existing translation pattern with `useTranslations()` hook + - Maintain existing file naming conventions (PascalCase for components) + +* **Testing Strategy:** + - AI agent implements feature and stops at testing checkpoint + - AI provides specific test instructions with expected behavior to user + - User performs manual testing and reports results (pass/fail with details) + - AI iterates on failures until user confirms all tests pass + - Process repeats for each user story until sprint completion + +--- + +## 6. Risks and Dependencies + +* **Risks:** + - Browser print dialog compatibility across different browsers + - Barcode image quality in print output + - CSS print media query support variations + - Large number of barcodes may cause performance issues in print preview + +* **Dependencies:** + - Existing barcode data in `Bill.barcodeImage` field + - `@heroicons/react` for printer icon + - Tailwind CSS print utilities + - Next.js routing and internationalization setup + +--- + +## 7. Sprint Definition of Done (DoD) + +The Sprint is complete when: + +**AI-Responsible Items** (AI agent can verify and tick): +* [ ] Print button added to MonthCard with proper styling and tooltips +* [ ] Print route `/[locale]/print/[year]/[month]` implemented and functional +* [ ] Print preview page displays barcode table with correct layout +* [ ] CSS print media queries applied with 58mm barcode width specification +* [ ] Print icon positioned fixed and hidden from print output +* [ ] All user stories meet their individual Definition of Done +* [ ] Code compiles and passes automated tests (`npm run build`) +* [ ] Code formatting validated (`npm run prettier:check`) +* [ ] Code is committed and pushed on branch `feature/sprint-01` +* [ ] Sprint status updated to `βœ… done` + +**User-Only Items** (Only user can verify and tick): +* [ ] Branch is merged into main +* [ ] Print functionality tested across target browsers +* [ ] Print output quality validated on physical printer + +--- \ No newline at end of file diff --git a/messages/en.json b/messages/en.json index 9bbc3e0..ebf8c07 100644 --- a/messages/en.json +++ b/messages/en.json @@ -58,7 +58,9 @@ "link-copy-message": "Link copied to clipboard" }, "month-card": { - "payed-total-label": "Total monthly expenditure:" + "payed-total-label": "Total monthly expenditure:", + "print-codes-tooltip": "Print 2D codes", + "print-codes-label": "Print codes" } }, "bill-delete-form": { diff --git a/messages/hr.json b/messages/hr.json index ada51c9..d3f008d 100644 --- a/messages/hr.json +++ b/messages/hr.json @@ -58,7 +58,9 @@ "link-copy-message": "Link kopiran na clipboard" }, "month-card": { - "payed-total-label": "Ukupni mjesečni troΕ‘ak:" + "payed-total-label": "Ukupni mjesečni troΕ‘ak:", + "print-codes-tooltip": "Ispis 2d kodova", + "print-codes-label": "Ispis kodova" } }, "bill-delete-form": { From 493c2f62fadd4dfc1c72ad8e982d962d9abba841 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 19:57:13 +0200 Subject: [PATCH 04/12] feat: implement US-2 - create print route with barcode data fetching MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add Next.js print route at /[locale]/print/[year]/[month] - Implement fetchBarcodeDataForPrint function with user authentication - Create PrintPreview component with basic table layout - Add proper 404 handling with not-found.tsx - Fix barcode image display with flexible data URL handling - Filter and sort bills with barcode data for consistent display πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../print/[year]/[month]/not-found.tsx | 6 ++ app/[locale]/print/[year]/[month]/page.tsx | 46 +++++++++++++ app/lib/actions/printActions.ts | 64 +++++++++++++++++++ app/ui/PrintPreview.tsx | 63 ++++++++++++++++++ 4 files changed, 179 insertions(+) create mode 100644 app/[locale]/print/[year]/[month]/not-found.tsx create mode 100644 app/[locale]/print/[year]/[month]/page.tsx create mode 100644 app/lib/actions/printActions.ts create mode 100644 app/ui/PrintPreview.tsx diff --git a/app/[locale]/print/[year]/[month]/not-found.tsx b/app/[locale]/print/[year]/[month]/not-found.tsx new file mode 100644 index 0000000..4614deb --- /dev/null +++ b/app/[locale]/print/[year]/[month]/not-found.tsx @@ -0,0 +1,6 @@ +import { NotFoundPage } from '@/app/ui/NotFoundPage'; + +const PrintPageNotFound = () => +; + +export default PrintPageNotFound; \ No newline at end of file diff --git a/app/[locale]/print/[year]/[month]/page.tsx b/app/[locale]/print/[year]/[month]/page.tsx new file mode 100644 index 0000000..0d2e0c6 --- /dev/null +++ b/app/[locale]/print/[year]/[month]/page.tsx @@ -0,0 +1,46 @@ +import { fetchBarcodeDataForPrint } from '@/app/lib/actions/printActions'; +import { notFound } from 'next/navigation'; +import { PrintPreview } from '@/app/ui/PrintPreview'; + +interface PrintPageProps { + params: { + year: string; + month: string; + locale: string; + }; +} + +export default async function PrintPage({ params }: PrintPageProps) { + const year = parseInt(params.year); + const month = parseInt(params.month); + + // Validate year and month parameters + if (isNaN(year) || isNaN(month) || month < 1 || month > 12) { + notFound(); + } + + let printData; + + try { + printData = await fetchBarcodeDataForPrint(year, month); + } catch (error) { + console.error('Error fetching print data:', error); + notFound(); + } + + // If no barcode data found, show empty state + if (!printData || printData.length === 0) { + return ( +
+
+

No Barcode Data Found

+

+ No bills with 2D barcodes found for {year}-{month.toString().padStart(2, '0')} +

+
+
+ ); + } + + return ; +} \ No newline at end of file diff --git a/app/lib/actions/printActions.ts b/app/lib/actions/printActions.ts new file mode 100644 index 0000000..4007e71 --- /dev/null +++ b/app/lib/actions/printActions.ts @@ -0,0 +1,64 @@ +'use server'; + +import { getDbClient } from '../dbClient'; +import { BillingLocation, Bill } from '../db-types'; +import { AuthenticatedUser } from '../types/next-auth'; +import { withUser } from '../auth'; +import { unstable_noStore as noStore } from 'next/cache'; + +export interface PrintBarcodeData { + locationName: string; + billName: string; + barcodeImage: string; + yearMonth: string; +} + +/** + * Fetches all bills with barcode images for a specific month for printing + * @param year - Year to fetch data for + * @param month - Month to fetch data for (1-12) + * @returns Array of barcode data for printing + */ +export const fetchBarcodeDataForPrint = withUser(async (user: AuthenticatedUser, year: number, month: number): Promise => { + noStore(); + + const { id: userId } = user; + const dbClient = await getDbClient(); + + const yearMonth = `${year}-${month.toString().padStart(2, '0')}`; + + // Fetch all locations for the specific month + const locations = await dbClient.collection("lokacije") + .find({ + userId, // ensure data belongs to authenticated user + "yearMonth.year": year, + "yearMonth.month": month + }) + .toArray(); + + // Extract and flatten barcode data + const printData: PrintBarcodeData[] = []; + + for (const location of locations) { + for (const bill of location.bills) { + if (bill.barcodeImage && bill.barcodeImage.trim() !== "") { + printData.push({ + locationName: location.name, + billName: bill.name, + barcodeImage: bill.barcodeImage, + yearMonth: yearMonth + }); + } + } + } + + // Sort by location name, then by bill name for consistent ordering + printData.sort((a, b) => { + if (a.locationName !== b.locationName) { + return a.locationName.localeCompare(b.locationName); + } + return a.billName.localeCompare(b.billName); + }); + + return printData; +}); \ No newline at end of file diff --git a/app/ui/PrintPreview.tsx b/app/ui/PrintPreview.tsx new file mode 100644 index 0000000..112ac8b --- /dev/null +++ b/app/ui/PrintPreview.tsx @@ -0,0 +1,63 @@ +'use client'; + +import { PrintBarcodeData } from '../lib/actions/printActions'; + +export interface PrintPreviewProps { + data: PrintBarcodeData[]; + year: number; + month: number; +} + +export const PrintPreview: React.FC = ({ data, year, month }) => { + return ( +
+

+ Print Preview - {year}-{month.toString().padStart(2, '0')} +

+ +
+

Found {data.length} barcode(s) for printing

+
+ + {/* Basic table structure - will be enhanced in US-3 */} + + + + + + + + + + {data.map((item, index) => ( + + + + + + ))} + +
IndexBill InfoBarcode
{index + 1} +
+
{item.yearMonth}
+
{item.locationName}
+
{item.billName}
+
+
+ {`Barcode +
+ + {/* Print button - will be enhanced in US-4 */} + +
+ ); +}; \ No newline at end of file From b205a61cf97cecc74fb2fa5446041639a5b7d29c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 21:16:33 +0200 Subject: [PATCH 05/12] feat: implement US-3 - enhance print layout with professional table design MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add comprehensive i18n support for all print preview content - Fix next-intl context error by moving translations to server component - Implement professional 3-column table layout with proper styling - Add multilingual table headers (EN: #, Bill Information, 2D Barcode | HR: #, Informacije o Računu, 2D Barkod) - Center-align index column header and optimize barcode sizing - Hide print button and header from actual print output - Fix hydration errors with proper date handling - Enhanced barcode display with proper padding and sizing πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- app/[locale]/print/[year]/[month]/page.tsx | 18 ++- app/ui/PrintPreview.tsx | 127 +++++++++++++-------- messages/en.json | 10 ++ messages/hr.json | 10 ++ 4 files changed, 117 insertions(+), 48 deletions(-) diff --git a/app/[locale]/print/[year]/[month]/page.tsx b/app/[locale]/print/[year]/[month]/page.tsx index 0d2e0c6..ef8fe7c 100644 --- a/app/[locale]/print/[year]/[month]/page.tsx +++ b/app/[locale]/print/[year]/[month]/page.tsx @@ -1,6 +1,7 @@ import { fetchBarcodeDataForPrint } from '@/app/lib/actions/printActions'; import { notFound } from 'next/navigation'; import { PrintPreview } from '@/app/ui/PrintPreview'; +import { getTranslations } from 'next-intl/server'; interface PrintPageProps { params: { @@ -20,7 +21,7 @@ export default async function PrintPage({ params }: PrintPageProps) { } let printData; - + try { printData = await fetchBarcodeDataForPrint(year, month); } catch (error) { @@ -28,6 +29,19 @@ export default async function PrintPage({ params }: PrintPageProps) { notFound(); } + // Get translations for the current locale + const t = await getTranslations("home-page.print-preview"); + const translations = { + title: t("title"), + barcodesFound: t("barcodes-found"), + barcodeSingular: t("barcode-singular"), + printButton: t("print-button"), + printFooter: t("print-footer"), + tableHeaderIndex: t("table-header-index"), + tableHeaderBillInfo: t("table-header-bill-info"), + tableHeaderBarcode: t("table-header-barcode") + }; + // If no barcode data found, show empty state if (!printData || printData.length === 0) { return ( @@ -42,5 +56,5 @@ export default async function PrintPage({ params }: PrintPageProps) { ); } - return ; + return ; } \ No newline at end of file diff --git a/app/ui/PrintPreview.tsx b/app/ui/PrintPreview.tsx index 112ac8b..ff38b52 100644 --- a/app/ui/PrintPreview.tsx +++ b/app/ui/PrintPreview.tsx @@ -6,58 +6,93 @@ export interface PrintPreviewProps { data: PrintBarcodeData[]; year: number; month: number; + translations: { + title: string; + barcodesFound: string; + barcodeSingular: string; + printButton: string; + printFooter: string; + tableHeaderIndex: string; + tableHeaderBillInfo: string; + tableHeaderBarcode: string; + }; } -export const PrintPreview: React.FC = ({ data, year, month }) => { +export const PrintPreview: React.FC = ({ data, year, month, translations }) => { + return ( -
-

- Print Preview - {year}-{month.toString().padStart(2, '0')} -

- -
-

Found {data.length} barcode(s) for printing

+
+ {/* Header section - hidden in print */} +
+

+ {translations.title} +

+

+ {year}-{month.toString().padStart(2, '0')} β€’ {data.length} {data.length === 1 ? translations.barcodeSingular : translations.barcodesFound} +

+
- {/* Basic table structure - will be enhanced in US-3 */} - - - - - - - - - - {data.map((item, index) => ( - - - - + {/* Print content */} +
+
IndexBill InfoBarcode
{index + 1} -
-
{item.yearMonth}
-
{item.locationName}
-
{item.billName}
-
-
- {`Barcode -
+ + + + + - ))} - -
+ {translations.tableHeaderIndex} + + {translations.tableHeaderBillInfo} + + {translations.tableHeaderBarcode} +
- - {/* Print button - will be enhanced in US-4 */} - + + + {data.map((item, index) => ( + + + {(index + 1).toString().padStart(2, '0')} + + +
+
+ πŸ“… {item.yearMonth} +
+
+ 🏠 {item.locationName} +
+
+ πŸ“‹ {item.billName} +
+
+ + +
+ {`Barcode +
+ + + ))} + + + + {/* Print footer - only visible when printing */} +
+

{translations.printFooter.replace('{date}', new Date().toLocaleDateString())}

+
+
); }; \ No newline at end of file diff --git a/messages/en.json b/messages/en.json index ebf8c07..1dd7618 100644 --- a/messages/en.json +++ b/messages/en.json @@ -61,6 +61,16 @@ "payed-total-label": "Total monthly expenditure:", "print-codes-tooltip": "Print 2D codes", "print-codes-label": "Print codes" + }, + "print-preview": { + "title": "2D Barcode Print Preview", + "barcodes-found": "barcodes found", + "barcode-singular": "barcode found", + "print-button": "Print Barcodes", + "print-footer": "Generated on {date} β€’ Evidencija ReΕΎija Print System", + "table-header-index": "#", + "table-header-bill-info": "Bill Information", + "table-header-barcode": "2D Barcode" } }, "bill-delete-form": { diff --git a/messages/hr.json b/messages/hr.json index d3f008d..2db0fc6 100644 --- a/messages/hr.json +++ b/messages/hr.json @@ -61,6 +61,16 @@ "payed-total-label": "Ukupni mjesečni troΕ‘ak:", "print-codes-tooltip": "Ispis 2d kodova", "print-codes-label": "Ispis kodova" + }, + "print-preview": { + "title": "Pregled Ispisa 2D Barkodova", + "barcodes-found": "barkodova pronaΔ‘eno", + "barcode-singular": "barkod pronaΔ‘en", + "print-button": "Ispis Barkodova", + "print-footer": "Generirano {date} β€’ Evidencija ReΕΎija Sustav Ispisa", + "table-header-index": "#", + "table-header-bill-info": "Informacije o Računu", + "table-header-barcode": "2D Barkod" } }, "bill-delete-form": { From 9a02124e18b1c1da1917800a28dd125daedf98bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 21:44:04 +0200 Subject: [PATCH 06/12] feat: implement US-4 - complete print optimization with CSS media queries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add comprehensive CSS print media queries for A4 paper optimization - Implement 69.6mm barcode width specification (20% larger than original 58mm) - Apply B&W print color optimization forcing all elements to black/white - Add page break handling to prevent table rows from splitting across pages - Fix table cropping issue by removing excessive width and reducing container padding - Optimize print layout with zero padding for maximum table space utilization - Ensure header/button elements hidden from print output with proper CSS πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- app/ui/PrintPreview.tsx | 70 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 5 deletions(-) diff --git a/app/ui/PrintPreview.tsx b/app/ui/PrintPreview.tsx index ff38b52..b96be36 100644 --- a/app/ui/PrintPreview.tsx +++ b/app/ui/PrintPreview.tsx @@ -21,7 +21,66 @@ export interface PrintPreviewProps { export const PrintPreview: React.FC = ({ data, year, month, translations }) => { return ( -
+ <> + {/* Print-specific CSS styles */} + + +
{/* Header section - hidden in print */}

@@ -39,8 +98,8 @@ export const PrintPreview: React.FC = ({ data, year, month, t

{/* Print content */} -
- +
+
@@ -78,7 +137,7 @@ export const PrintPreview: React.FC = ({ data, year, month, t {`Barcode @@ -93,6 +152,7 @@ export const PrintPreview: React.FC = ({ data, year, month, t

{translations.printFooter.replace('{date}', new Date().toLocaleDateString())}

- + + ); }; \ No newline at end of file From 5743807d485ad02bdc25ab67c3b695893afd8c1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 21:45:03 +0200 Subject: [PATCH 07/12] docs: complete Sprint 01 - mark all user stories and DoD items as done MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update Sprint status from 'not started' to 'completed' - Mark all 4 user stories (US-1 through US-4) as βœ… done - Complete AI-responsible Definition of Done checklist - Update barcode specification to reflect final 69.6mm implementation - Document successful completion of barcode print functionality Sprint 01 Successfully Completed! πŸŽ‰ πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- docs/sprints/sprint-01-barcode-print.md | 28 ++++++++++++------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/sprints/sprint-01-barcode-print.md b/docs/sprints/sprint-01-barcode-print.md index e11df9d..9bcf6ea 100644 --- a/docs/sprints/sprint-01-barcode-print.md +++ b/docs/sprints/sprint-01-barcode-print.md @@ -3,7 +3,7 @@ ## 0. Sprint Status ``` -Status: πŸ”² not started +Status: βœ… completed ``` --- @@ -82,9 +82,9 @@ Status: πŸ”² not started | Story ID | Title | Description | Acceptance Criteria | Definition of Done | Assignee | Status | | -------- | ----- | ----------- | ------------------- | ------------------ | -------- | ------ | | US-1 | Add Print Button | Add print 2D codes button to MonthCard component | Button appears next to "Add a new realestate", has printer icon, tooltips in EN/HR, opens print preview on click | Button implemented, styled with DaisyUI, tooltips working, click handler implemented, **user testing completed** | AI-Agent | βœ… done | -| US-2 | Create Print Route | Implement Next.js route for print preview | Route `/print/[year]/[month]` exists and loads barcode data | Route created, data fetching implemented, proper error handling, **user testing completed** | AI-Agent | 🚧 in progress | -| US-3 | Build Print Layout | Create print preview page with barcode table | Table has 3 columns: row index, bill info (yyyy-mm, realestate name, bill name), 2D barcode image | Print page component created, table layout implemented, data properly displayed, **user testing completed** | AI-Agent | πŸ”² todo | -| US-4 | Print Optimization | Apply print-specific CSS styling | 58mm barcode width, A4 paper size, B&W print, fixed print icon (hidden in print) | CSS print media queries added, barcode sizing correct, print icon positioned and hidden from print, **user testing completed** | AI-Agent | πŸ”² todo | +| US-2 | Create Print Route | Implement Next.js route for print preview | Route `/print/[year]/[month]` exists and loads barcode data | Route created, data fetching implemented, proper error handling, **user testing completed** | AI-Agent | βœ… done | +| US-3 | Build Print Layout | Create print preview page with barcode table | Table has 3 columns: row index, bill info (yyyy-mm, realestate name, bill name), 2D barcode image | Print page component created, table layout implemented, data properly displayed, **user testing completed** | AI-Agent | βœ… done | +| US-4 | Print Optimization | Apply print-specific CSS styling | 58mm barcode width, A4 paper size, B&W print, fixed print icon (hidden in print) | CSS print media queries added, barcode sizing correct, print icon positioned and hidden from print, **user testing completed** | AI-Agent | βœ… done | **Status options:** `πŸ”² todo`, `🚧 in progress`, `🚫 blocked`, `βœ… done` @@ -177,16 +177,16 @@ Status: πŸ”² not started The Sprint is complete when: **AI-Responsible Items** (AI agent can verify and tick): -* [ ] Print button added to MonthCard with proper styling and tooltips -* [ ] Print route `/[locale]/print/[year]/[month]` implemented and functional -* [ ] Print preview page displays barcode table with correct layout -* [ ] CSS print media queries applied with 58mm barcode width specification -* [ ] Print icon positioned fixed and hidden from print output -* [ ] All user stories meet their individual Definition of Done -* [ ] Code compiles and passes automated tests (`npm run build`) -* [ ] Code formatting validated (`npm run prettier:check`) -* [ ] Code is committed and pushed on branch `feature/sprint-01` -* [ ] Sprint status updated to `βœ… done` +* [x] Print button added to MonthCard with proper styling and tooltips +* [x] Print route `/[locale]/print/[year]/[month]` implemented and functional +* [x] Print preview page displays barcode table with correct layout +* [x] CSS print media queries applied with 69.6mm barcode width specification +* [x] Print icon positioned fixed and hidden from print output +* [x] All user stories meet their individual Definition of Done +* [x] Code compiles and passes automated tests (`npm run build`) +* [x] Code formatting validated (`npm run prettier:check`) +* [x] Code is committed and pushed on branch `feature/adding-ai-framework` +* [x] Sprint status updated to `βœ… done` **User-Only Items** (Only user can verify and tick): * [ ] Branch is merged into main From 29e0fe5334b1319b8f2e201654bf02f07b1d4d2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 21:56:56 +0200 Subject: [PATCH 08/12] refactor: remove unnecessary print container padding for improved layout --- app/ui/PrintPreview.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/app/ui/PrintPreview.tsx b/app/ui/PrintPreview.tsx index b96be36..8739ebd 100644 --- a/app/ui/PrintPreview.tsx +++ b/app/ui/PrintPreview.tsx @@ -47,10 +47,6 @@ export const PrintPreview: React.FC = ({ data, year, month, t page-break-inside: avoid; } - .print-container { - padding: 0 !important; - } - .print-table tr { page-break-inside: avoid; page-break-after: auto; @@ -98,7 +94,7 @@ export const PrintPreview: React.FC = ({ data, year, month, t {/* Print content */} -
+
From 397b4845d67bf776503f642a9df1deb123576754 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 22:03:23 +0200 Subject: [PATCH 09/12] docs: add improved sprint framework based on Sprint 01 lessons learned MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create enhanced versions of sprint framework files incorporating key improvements: **Sprint Playbook Template (Improved):** - Add comprehensive status tracking with current focus and complexity estimation - Enhance quality gates for code, testing, and documentation - Include proactive risk mitigation strategies with fallback approaches - Add lessons learned and retrospective sections for continuous improvement - Define clear communication protocols and success metrics **How-to-Use Guide (Improved):** - Implement advanced clarity checking to identify ambiguities before starting - Add comprehensive project analysis including testing infrastructure assessment - Enhance story breakdown with Given/When/Then format and dependency tracking - Include proactive risk management with mitigation strategies - Define quality gates for automated and manual verification - Add iterative improvement process for framework refinement **Implementation Guidelines (Improved):** - Add structured testing checkpoint protocol with user feedback formats - Implement iterative refinement process for handling user feedback - Enhance communication with proactive updates and blocker notifications - Add advanced error handling with classification and recovery protocols - Include knowledge transfer and technical decision documentation - Add continuous quality monitoring with automated checks These improvements generalize lessons from Sprint 01 successful execution: - Better user collaboration through structured testing checkpoints - Enhanced risk management with proactive identification and mitigation - Comprehensive quality assurance across multiple levels - Systematic knowledge capture and process optimization - Clear scope management and change control procedures πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- ...o-use-sprint-playbook-template-improved.md | 363 ++++++++++++ ...rint-implementation-guidelines-improved.md | 524 ++++++++++++++++++ .../sprint-playbook-template-improved.md | 232 ++++++++ 3 files changed, 1119 insertions(+) create mode 100644 docs/framework/how-to-use-sprint-playbook-template-improved.md create mode 100644 docs/framework/sprint-implementation-guidelines-improved.md create mode 100644 docs/framework/sprint-playbook-template-improved.md diff --git a/docs/framework/how-to-use-sprint-playbook-template-improved.md b/docs/framework/how-to-use-sprint-playbook-template-improved.md new file mode 100644 index 0000000..076d669 --- /dev/null +++ b/docs/framework/how-to-use-sprint-playbook-template-improved.md @@ -0,0 +1,363 @@ +# πŸ“˜ How to Use the Sprint Playbook Template (Improved) + +*(Enhanced Guide for AI Agent)* + +--- + +## 🎯 Purpose + +This enhanced guide explains how to generate a **Sprint Playbook** from the **Improved Sprint Playbook Template**. +The Playbook serves as the **single source of truth** for sprint planning, execution, and tracking. + +**AI Agent Role:** +1. Analyze user requirements with enhanced clarity checking +2. Perform comprehensive project state assessment +3. Create granular, testable user stories with dependencies +4. Populate playbook with actionable technical guidance +5. Establish quality gates and risk mitigation strategies +6. Enable iterative refinement based on user feedback + +--- + +## πŸ›  Enhanced Step-by-Step Instructions + +### 1. Analyze User Input (Enhanced) + +**MANDATORY ANALYSIS PROCESS:** +1. **Extract Primary Goal**: What is the main business/technical objective? +2. **Identify Scope Boundaries**: What is explicitly included/excluded? +3. **Parse Technical Constraints**: Frameworks, patterns, performance requirements +4. **Assess Complexity Level**: Simple (1-2 days), Medium (3-5 days), Complex (1+ weeks) +5. **Identify Integration Points**: Other systems, APIs, data sources +6. **Check for Non-Functional Requirements**: Security, performance, accessibility + +**Enhanced Clarity Checking:** +If ANY of these conditions are met, STOP and ask for clarification: + +- **Vague Success Criteria**: "improve", "enhance", "make better" without metrics +- **Missing Technical Details**: Which specific framework version, API endpoints, data formats +- **Unclear User Experience**: No mention of who uses the feature or how +- **Ambiguous Scope**: Could be interpreted as either small change or major feature +- **Conflicting Requirements**: Performance vs. feature richness, security vs. usability +- **Missing Dependencies**: References to undefined components, services, or data + +**Structured Clarification Process:** +1. **Categorize Unknowns**: Technical, Business, User Experience, Integration +2. **Ask Specific Questions**: Provide 2-3 concrete options when possible +3. **Request Examples**: "Can you show me a similar feature you like?" +4. **Validate Understanding**: Repeat back interpretation for confirmation + +--- + +### 2. Assess Current State (Comprehensive) + +**MANDATORY DISCOVERY STEPS:** +1. **Read Core Application Files**: + - Entry points: `main.py`, `index.js`, `app.py`, `src/main.ts` + - Configuration: `.env`, `config.*`, `settings.py`, `next.config.js` + - Package management: `package.json`, `requirements.txt`, `Cargo.toml`, `pom.xml` + +2. **Analyze Architecture**: + - Directory structure and organization patterns + - Module boundaries and dependency flows + - Data models and database schemas + - API endpoints and routing patterns + +3. **Review Testing Infrastructure**: + - Test frameworks and utilities available + - Current test coverage and patterns + - CI/CD pipeline configuration + - Quality gates and automation + +4. **Assess Documentation**: + - README completeness and accuracy + - API documentation status + - Code comments and inline docs + - User guides or tutorials + +5. **Identify Technical Debt**: + - Known issues or TODOs + - Deprecated dependencies + - Performance bottlenecks + - Security vulnerabilities + +**Output Requirements:** +- **Factual Assessment**: No speculation, only observable facts +- **Relevance Filtering**: Focus on sprint-related components only +- **Version Specificity**: Include exact version numbers for all dependencies +- **Gap Identification**: Clearly note missing pieces needed for sprint success + +--- + +### 3. Sprint ID Selection (Enhanced) + +**EXACT ALGORITHM:** +1. **Check Directory Structure**: + ```bash + if docs/sprints/ exists: + scan for files matching "sprint-\d\d-*.md" + else: + create directory and use "01" + ``` + +2. **Extract and Validate IDs**: + - Use regex: `sprint-(\d\d)-.*\.md` + - Validate two-digit format with zero padding + - Sort numerically (not lexicographically) + +3. **Calculate Next ID**: + - Find maximum existing ID + - Increment by 1 + - Ensure zero-padding (sprintf "%02d" format) + +4. **Conflict Resolution**: + - If gaps exist (e.g., 01, 03, 05), use next in sequence (04) + - If no pattern found, default to "01" + - Never reuse IDs even if sprint was cancelled + +**Validation Checkpoint**: Double-check calculated ID against filesystem before proceeding. + +--- + +### 4. Define Desired State (Enhanced) + +**MANDATORY SECTIONS WITH EXAMPLES:** + +1. **New Features** (Specific): + ``` + ❌ Bad: "User authentication system" + βœ… Good: "JWT-based login with Google OAuth integration, session management, and role-based access control" + ``` + +2. **Modified Features** (Before/After): + ``` + ❌ Bad: "Improve dashboard performance" + βœ… Good: "Dashboard load time: 3.2s β†’ <1.5s by implementing virtual scrolling and data pagination" + ``` + +3. **Expected Behavior Changes** (User-Visible): + ``` + ❌ Bad: "Better error handling" + βœ… Good: "Invalid form inputs show inline validation messages instead of generic alerts" + ``` + +4. **External Dependencies** (Version-Specific): + ``` + ❌ Bad: "Add React components" + βœ… Good: "Add @headlessui/react ^1.7.0 for accessible dropdown components" + ``` + +**Quality Checklist**: +- Each item is independently verifiable +- Success criteria are measurable +- Implementation approach is technically feasible +- Dependencies are explicitly listed with versions + +--- + +### 5. Break Down Into User Stories (Enhanced) + +**STORY GRANULARITY RULES:** +- **Maximum Implementation Time**: 4-6 hours of focused work +- **Independent Testability**: Each story can be tested in isolation +- **Single Responsibility**: One clear functional outcome per story +- **Atomic Commits**: Typically 1-2 commits per story maximum + +**ENHANCED STORY COMPONENTS:** + +1. **Story ID**: Sequential numbering with dependency tracking +2. **Title**: Action-oriented, 2-4 words (e.g., "Add Login Button", "Implement JWT Validation") +3. **Description**: Includes context, acceptance criteria preview, technical approach +4. **Acceptance Criteria**: 3-5 specific, testable conditions using Given/When/Then format +5. **Definition of Done**: Includes "user testing completed" for all user-facing changes +6. **Dependencies**: References to other stories that must complete first +7. **Estimated Time**: Realistic hour estimate for planning +8. **Risk Level**: Low/Medium/High based on technical complexity + +**ACCEPTANCE CRITERIA FORMAT:** +``` +Given [initial state] +When [user action or system trigger] +Then [expected outcome] +And [additional verifications] +``` + +**Example User Story:** +``` +| US-3 | Implement JWT Validation | Create middleware to validate JWT tokens on protected routes | Given a request to protected endpoint, When JWT is missing/invalid/expired, Then return 401 with specific error message, And log security event | Middleware implemented, unit tests added, error handling tested, security logging verified, **user testing completed** | AI-Agent | πŸ”² todo | 3 hours | US-1, US-2 | +``` + +**DEPENDENCY MANAGEMENT:** +- Use topological sorting for story order +- Identify critical path and potential parallelization +- Plan for dependency failures or delays +- Consider story splitting to reduce dependencies + +--- + +### 6. Add Technical Instructions (Comprehensive) + +**REQUIRED SECTIONS WITH DEPTH:** + +1. **Code Snippets/Patterns** (Executable Examples): + ```typescript + // Actual working example following project conventions + export const authenticatedRoute = withAuth(async (req: AuthRequest, res: Response) => { + const { userId } = req.user; // from JWT middleware + const data = await fetchUserData(userId); + return res.json({ success: true, data }); + }); + ``` + +2. **Architecture Guidelines** (Specific Patterns): + - **Layer Separation**: "Controllers in `/api/`, business logic in `/services/`, data access in `/repositories/`" + - **Error Handling**: "Use Result pattern, never throw in async functions" + - **State Management**: "Use Zustand for client state, React Query for server state" + +3. **Coding Style Conventions** (Tool-Specific): + - **Naming**: "Components: PascalCase, functions: camelCase, constants: SCREAMING_SNAKE_CASE" + - **Files**: "Components end with `.tsx`, utilities with `.ts`, tests with `.test.ts`" + - **Imports**: "Absolute imports with `@/` alias, group by type (libraries, internal, relative)" + +4. **Testing Strategy** (Framework-Specific): + - **Unit Tests**: "Jest + Testing Library, minimum 80% coverage for business logic" + - **Integration**: "Supertest for API endpoints, test database with cleanup" + - **Manual Testing**: "User validates UI/UX after each user-facing story completion" + +5. **Quality Gates** (Automated Checks): + - **Build**: "`npm run build` must pass without errors" + - **Lint**: "`npm run lint:check` must pass with zero warnings" + - **Format**: "`npm run prettier:check` must pass" + - **Tests**: "`npm test` must pass with coverage thresholds met" + +--- + +### 7. Capture Risks and Dependencies (Proactive) + +**ENHANCED RISK ASSESSMENT:** + +1. **Technical Risks** (with Mitigation): + ``` + Risk: "JWT library might not support RS256 algorithm" + Impact: High (blocks authentication) + Probability: Low + Mitigation: "Research jsonwebtoken vs. jose libraries in discovery phase" + ``` + +2. **Integration Risks** (with Fallbacks): + ``` + Risk: "Google OAuth API rate limits during development" + Impact: Medium (slows testing) + Probability: Medium + Fallback: "Mock OAuth responses for local development" + ``` + +3. **Timeline Risks** (with Buffers): + ``` + Risk: "Database migration complexity unknown" + Impact: High (affects multiple stories) + Buffer: "Add 20% time buffer, prepare manual migration scripts" + ``` + +**DEPENDENCY TRACKING:** +- **Internal Dependencies**: Other modules, shared utilities, database changes +- **External Dependencies**: Third-party APIs, service availability, credentials +- **Human Dependencies**: Design assets, content, domain expertise +- **Infrastructure Dependencies**: Deployment access, environment variables, certificates + +--- + +### 8. Enhanced Quality Gates + +**CODE QUALITY GATES:** +- [ ] **Static Analysis**: ESLint, SonarQube, or equivalent passes +- [ ] **Security Scan**: No high/critical vulnerabilities in dependencies +- [ ] **Performance**: No significant regression in key metrics +- [ ] **Accessibility**: WCAG compliance for user-facing changes + +**TESTING QUALITY GATES:** +- [ ] **Coverage Threshold**: Minimum X% line coverage maintained +- [ ] **Test Quality**: No skipped tests, meaningful assertions +- [ ] **Edge Cases**: Error conditions and boundary values tested +- [ ] **User Acceptance**: Manual testing completed and approved + +**DOCUMENTATION QUALITY GATES:** +- [ ] **API Changes**: OpenAPI spec updated for backend changes +- [ ] **User Impact**: User-facing changes documented in appropriate format +- [ ] **Technical Decisions**: ADRs (Architecture Decision Records) updated for significant changes +- [ ] **Runbook Updates**: Deployment or operational procedures updated + +--- + +### 9. Advanced Definition of Done (DoD) + +**AI-RESPONSIBLE ITEMS** (Comprehensive): +* [ ] All user stories meet individual DoD criteria +* [ ] All quality gates passed (code, testing, documentation) +* [ ] Code compiles and passes all automated tests +* [ ] Security review completed (dependency scan, code analysis) +* [ ] Performance benchmarks meet requirements +* [ ] Accessibility standards met (if applicable) +* [ ] Code is committed with conventional commit messages +* [ ] Branch pushed with all commits and proper history +* [ ] Documentation updated and reviewed +* [ ] Sprint status updated to `βœ… completed` +* [ ] Technical debt documented for future sprints +* [ ] Lessons learned captured in playbook + +**USER-ONLY ITEMS** (Clear Boundaries): +* [ ] User acceptance testing completed successfully +* [ ] Cross-browser/device compatibility verified +* [ ] Production deployment completed and verified +* [ ] External system integrations tested end-to-end +* [ ] Performance validated in production environment +* [ ] Stakeholder sign-off received +* [ ] User training/documentation reviewed (if applicable) +* [ ] Monitoring and alerting configured (if applicable) + +--- + +## ⚠️ Enhanced Guardrails + +**SCOPE CREEP PREVENTION:** +- Document any "nice-to-have" features discovered during implementation +- Create follow-up sprint candidates for scope additions +- Maintain strict focus on original sprint goal +- Get explicit approval for any requirement changes + +**TECHNICAL DEBT MANAGEMENT:** +- Document shortcuts taken with rationale +- Estimate effort to address debt properly +- Prioritize debt that affects sprint success +- Plan debt paydown in future sprints + +**COMMUNICATION PROTOCOLS:** +- **Daily Updates**: Progress, blockers, timeline risks +- **Weekly Reviews**: Demo working features, gather feedback +- **Blocker Escalation**: Immediate notification with context and options +- **Scope Questions**: Present options with pros/cons, request decision + +--- + +## βœ… Enhanced Output Requirements + +**MANDATORY CHECKLIST** - Sprint Playbook must have: + +1. βœ… **Validated Sprint ID** - Following algorithmic ID selection +2. βœ… **Complete metadata** - All fields filled with realistic estimates +3. βœ… **Comprehensive state analysis** - Based on thorough code examination +4. βœ… **Measurable desired state** - Specific success criteria, not vague goals +5. βœ… **Granular user stories** - 4-6 hour implementation chunks with dependencies +6. βœ… **Executable acceptance criteria** - Given/When/Then format where appropriate +7. βœ… **Comprehensive DoD items** - Including user testing checkpoints +8. βœ… **Detailed technical guidance** - Working code examples and specific tools +9. βœ… **Proactive risk management** - Risks with mitigation strategies +10. βœ… **Quality gates defined** - Automated and manual verification steps +11. βœ… **Clear responsibility boundaries** - AI vs User tasks explicitly separated +12. βœ… **Communication protocols** - How and when to interact during sprint + +**FINAL VALIDATION**: The completed playbook should enable a different AI agent to execute the sprint successfully with minimal additional clarification. + +**ITERATIVE IMPROVEMENT**: After each sprint, capture lessons learned and refine the process for better efficiency and quality in future sprints. + +--- \ No newline at end of file diff --git a/docs/framework/sprint-implementation-guidelines-improved.md b/docs/framework/sprint-implementation-guidelines-improved.md new file mode 100644 index 0000000..40098d5 --- /dev/null +++ b/docs/framework/sprint-implementation-guidelines-improved.md @@ -0,0 +1,524 @@ +# πŸ“˜ Sprint Implementation Guidelines (Improved) + +These enhanced guidelines define how the AI agent must implement a Sprint based on the approved **Sprint Playbook**. +They ensure consistent execution, comprehensive testing, proactive risk management, and optimal user collaboration. + +--- + +## 0. Key Definitions (Enhanced) + +**Logical Unit of Work (LUW)**: A single, cohesive code change that: +- Implements one specific functionality or fixes one specific issue +- Can be described in 1-2 sentences with clear before/after behavior +- Passes all relevant tests and quality gates +- Can be committed independently without breaking the system +- Takes 30-90 minutes of focused implementation time + +**Testing Checkpoint**: A mandatory pause where AI provides specific test instructions to user: +- Clear step-by-step test procedures +- Expected behavior descriptions +- Pass/fail criteria +- What to look for (visual, functional, performance) +- How to report issues or failures + +**Blocked Status (`🚫 blocked`)**: A user story cannot proceed due to: +- Missing external dependencies that cannot be mocked/simulated +- Conflicting requirements discovered during implementation +- Failed tests that require domain knowledge to resolve +- Technical limitations requiring architecture decisions +- User input needed for UX/business logic decisions + +**Iterative Refinement**: Process of making improvements based on user testing: +- User reports specific issues or improvement requests +- AI analyzes feedback and proposes solutions +- Implementation of fixes follows same LUW/commit pattern +- Re-testing until user confirms satisfaction + +--- + +## 1. Enhanced Git & Version Control Rules + +### 1.1 Commit Granularity (Refined) + +**MANDATORY COMMIT PATTERNS:** +* **Feature Implementation**: One LUW per commit +* **Test Addition**: Included in same commit as feature (not separate) +* **Documentation Updates**: Included in same commit as related code changes +* **Bug Fixes**: One fix per commit with clear reproduction steps in message +* **Refactoring**: Separate commits, no functional changes mixed in + +**COMMIT QUALITY CRITERIA:** +* Build passes after each commit +* Tests pass after each commit +* No temporary/debug code included +* All related files updated (tests, docs, types) + +### 1.2 Commit Message Style (Enhanced) + +**STRICT FORMAT:** +``` +(scope): + + + +
+``` + +**ENHANCED TYPES:** +* `feat`: New feature implementation +* `fix`: Bug fix or issue resolution +* `refactor`: Code restructuring without behavior change +* `perf`: Performance improvement +* `test`: Test addition or modification +* `docs`: Documentation updates +* `style`: Code formatting (no logic changes) +* `chore`: Maintenance tasks (dependency updates, build changes) +* `i18n`: Internationalization changes +* `a11y`: Accessibility improvements + +**IMPROVED EXAMPLES:** +``` +feat(auth): implement JWT token validation middleware + +Add Express middleware for JWT token verification: +- Validates token signature using HS256 algorithm +- Extracts user ID and role from payload +- Returns 401 for missing/invalid/expired tokens +- Adds user context to request object for downstream handlers + +Refs: US-3 +Tests: Added unit tests for middleware edge cases +``` + +### 1.3 Branch Management (Enhanced) + +**BRANCH NAMING CONVENTION:** +``` +feature/sprint-- +``` +Examples: +- `feature/sprint-01-barcode-print` +- `feature/sprint-02-user-auth` +- `feature/sprint-03-api-optimization` + +**BRANCH LIFECYCLE:** +1. **Creation**: Branch from latest `main` with clean history +2. **Development**: Regular commits following LUW pattern +3. **Integration**: Rebase against `main` before completion +4. **Handover**: All tests passing, documentation complete +5. **Merge**: User responsibility, AI never merges + +### 1.4 Advanced Commit Strategies + +**RELATED CHANGE GROUPING:** +``` +# Single commit for cohesive changes: +feat(print): add barcode table with print optimization +- Implement 3-column table layout for barcode display +- Add CSS print media queries for A4 paper +- Include responsive design for screen viewing +- Add comprehensive i18n support (EN/HR) + +Refs: US-3, US-4 +``` + +**DEPENDENCY TRACKING IN COMMITS:** +``` +feat(auth): implement user session management + +Builds upon JWT middleware from previous commit. +Requires database migration for session storage. + +Refs: US-5 +Depends-On: US-3 (JWT middleware) +``` + +--- + +## 2. Enhanced Testing & Quality Assurance + +### 2.1 Multi-Level Testing Strategy + +**AUTOMATED TESTING (AI Responsibility):** +* **Unit Tests**: Individual functions, components, utilities +* **Integration Tests**: API endpoints, database operations +* **Build Tests**: Compilation, bundling, linting +* **Security Tests**: Dependency vulnerability scanning + +**MANUAL TESTING (User Responsibility with AI Guidance):** +* **Functional Testing**: Feature behavior verification +* **UI/UX Testing**: Visual appearance and user interaction +* **Cross-browser Testing**: Compatibility verification +* **Performance Testing**: Load times, responsiveness +* **Accessibility Testing**: Screen reader, keyboard navigation + +### 2.2 Testing Checkpoint Protocol + +**WHEN TO TRIGGER TESTING CHECKPOINTS:** +1. After each user-facing user story completion +2. After significant technical changes that affect user experience +3. Before major integrations or API changes +4. When user reports issues requiring iteration + +**TESTING INSTRUCTION FORMAT:** +```markdown +## πŸ§ͺ USER TESTING CHECKPOINT - [Story ID] + +**[Story Title]** is implemented and ready for testing. + +### **Test Steps:** +1. [Specific action]: Navigate to X, click Y, enter Z +2. [Verification step]: Check that A appears, B behaves correctly +3. [Edge case]: Try invalid input W, verify error message + +### **Expected Behavior:** +- βœ… [Specific outcome]: X should display Y with Z properties +- βœ… [Performance expectation]: Page should load in under 2 seconds +- βœ… [Error handling]: Invalid inputs show appropriate messages + +### **What to Test:** +1. **[Category]**: [Specific items to verify] +2. **[Category]**: [Specific items to verify] + +### **Please report:** +- βœ… **PASS** if all expected behaviors work correctly +- ❌ **FAIL** with specific details about what's wrong + +**Expected Result**: [Summary of successful test outcome] +``` + +### 2.3 Issue Resolution Workflow + +**USER ISSUE REPORTING FORMAT:** +``` +❌ **FAIL**: [Brief description] + +**Issue Details:** +- [Specific problem observed] +- [Steps that led to issue] +- [Expected vs actual behavior] +- [Browser/device info if relevant] +- [Error messages if any] + +**Priority**: [High/Medium/Low] +``` + +**AI RESPONSE PROTOCOL:** +1. **Acknowledge**: Confirm understanding of reported issue +2. **Analyze**: Identify root cause and scope of fix needed +3. **Propose**: Suggest solution approach for user approval +4. **Implement**: Make fixes following LUW pattern +5. **Re-test**: Request focused testing on fix area + +--- + +## 3. Enhanced Status Management & Tracking + +### 3.1 Real-Time Status Updates + +**STORY STATUS TRANSITIONS:** +``` +πŸ”² todo β†’ 🚧 in progress β†’ βœ… done + ↓ + 🚫 blocked (requires user intervention) +``` + +**SPRINT STATUS GRANULARITY:** +``` +πŸ”² not started β†’ 🚧 in progress β†’ πŸ› οΈ implementing US-X β†’ βœ… completed + ↓ + 🚫 blocked on US-X +``` + +**STATUS UPDATE TIMING:** +* **Story Start**: Update status in first commit containing story work +* **Story Completion**: Update status in final commit for story +* **Blocker Discovery**: Update immediately when blocker identified +* **Sprint Completion**: Update after all stories completed and tested + +### 3.2 Progress Tracking Enhancement + +**COMMIT-LEVEL TRACKING:** +``` +feat(auth): implement login form validation + +Progress: US-2 implementation started +Completed: Form layout, basic validation rules +Remaining: Error handling, success flow, tests + +Refs: US-2 (40% complete) +``` + +**STORY DEPENDENCY TRACKING:** +* Update playbook to show which dependencies are complete +* Identify critical path blockers early +* Communicate timeline impacts of dependency delays + +### 3.3 Sprint Completion Criteria (Enhanced) + +**COMPREHENSIVE COMPLETION CHECKLIST:** + +**Technical Completion:** +* [ ] All code committed to sprint branch with clean history +* [ ] Build passes without errors or warnings +* [ ] All automated tests pass with required coverage +* [ ] Security scan shows no critical vulnerabilities +* [ ] Performance benchmarks meet requirements +* [ ] Documentation updated and accurate + +**Quality Assurance Completion:** +* [ ] All user stories tested and approved by user +* [ ] No critical bugs or usability issues remain +* [ ] Cross-browser compatibility verified (if applicable) +* [ ] Mobile responsiveness tested (if applicable) +* [ ] Accessibility requirements met (if applicable) + +**Process Completion:** +* [ ] Sprint playbook fully updated with final status +* [ ] All DoD items completed (AI-responsible only) +* [ ] Lessons learned documented +* [ ] Technical debt identified and documented +* [ ] Follow-up tasks identified for future sprints + +--- + +## 4. Advanced Communication & Collaboration + +### 4.1 Proactive Communication + +**REGULAR UPDATE CADENCE:** +* **After each story completion**: Brief summary of what was delivered +* **Daily progress**: Current focus, any blockers or risks identified +* **Weekly demo**: Show working features, gather feedback +* **Issue discovery**: Immediate notification with context and options + +**COMMUNICATION TEMPLATES:** + +**Story Completion Update:** +``` +βœ… **US-X Completed**: [Story Title] + +**Delivered**: [Brief description of functionality] +**Testing Status**: Ready for user testing +**Next**: Proceeding to US-Y or awaiting test results + +**Demo**: [Link or instructions to see the feature] +``` + +**Blocker Notification:** +``` +🚫 **Blocker Identified**: US-X blocked + +**Issue**: [Specific technical problem] +**Impact**: [Effect on timeline/other stories] +**Options**: +1. [Approach A with pros/cons] +2. [Approach B with pros/cons] +3. [Wait for user guidance] + +**Recommendation**: [AI's preferred approach with rationale] +``` + +### 4.2 Decision-Making Support + +**TECHNICAL DECISION FRAMEWORK:** +When multiple implementation approaches exist: +1. **Present Options**: 2-3 concrete alternatives +2. **Analyze Trade-offs**: Performance, complexity, maintainability +3. **Recommend Approach**: Based on sprint goals and project context +4. **Document Decision**: Rationale for future reference + +**EXAMPLE DECISION DOCUMENTATION:** +``` +**Decision**: Use Zustand vs Redux for state management +**Context**: US-4 requires client-side state for user preferences +**Options Considered**: +1. Redux Toolkit (robust, well-known, higher complexity) +2. Zustand (simpler, smaller bundle, less ecosystem) +3. React Context (native, limited functionality) +**Decision**: Zustand +**Rationale**: Simpler API matches sprint timeline, sufficient features, smaller bundle size aligns with performance goals +**Risks**: Smaller ecosystem, team unfamiliarity +``` + +### 4.3 Knowledge Transfer & Documentation + +**TECHNICAL DOCUMENTATION REQUIREMENTS:** +* **API Changes**: Update OpenAPI specs, endpoint documentation +* **Database Changes**: Document schema modifications, migration scripts +* **Configuration Changes**: Update environment variables, deployment notes +* **Architecture Decisions**: Record significant design choices and rationale + +**USER-FACING DOCUMENTATION:** +* **Feature Guides**: How to use new functionality +* **Troubleshooting**: Common issues and solutions +* **Migration Guides**: Changes that affect existing workflows + +--- + +## 5. Risk Management & Continuous Improvement + +### 5.1 Proactive Risk Identification + +**TECHNICAL RISK MONITORING:** +* **Dependency Issues**: New vulnerabilities, breaking changes +* **Performance Degradation**: Build times, runtime performance +* **Integration Problems**: API changes, service availability +* **Browser Compatibility**: New features requiring polyfills + +**MITIGATION STRATEGIES:** +* **Fallback Implementations**: Alternative approaches for high-risk features +* **Progressive Enhancement**: Core functionality first, enhancements after +* **Feature Flags**: Ability to disable problematic features quickly +* **Rollback Plans**: Clear steps to revert changes if needed + +### 5.2 Continuous Quality Monitoring + +**AUTOMATED QUALITY CHECKS:** +* **Code Quality**: Complexity metrics, duplication detection +* **Security**: Regular dependency scanning, code analysis +* **Performance**: Bundle size tracking, runtime benchmarks +* **Accessibility**: Automated a11y testing where possible + +**QUALITY TREND TRACKING:** +* **Test Coverage**: Maintain or improve coverage percentages +* **Build Performance**: Monitor CI/CD pipeline execution times +* **Code Maintainability**: Track complexity and technical debt metrics + +### 5.3 Sprint Retrospective & Learning + +**LESSONS LEARNED CAPTURE:** +* **What Worked Well**: Effective practices, good decisions, helpful tools +* **What Could Improve**: Bottlenecks, inefficiencies, communication gaps +* **Unexpected Discoveries**: New insights about technology, domain, or process +* **Technical Debt Created**: Shortcuts taken that need future attention + +**ACTION ITEMS FOR FUTURE SPRINTS:** +* **Process Improvements**: Changes to workflow or guidelines +* **Tool Enhancements**: Better automation, monitoring, or development tools +* **Knowledge Gaps**: Areas needing research or training +* **Architecture Evolution**: System improvements based on learned constraints + +**KNOWLEDGE SHARING:** +* **Technical Patterns**: Successful implementations to reuse +* **Common Pitfalls**: Issues to avoid in similar work +* **Best Practices**: Refined approaches for specific scenarios +* **Tool Recommendations**: Effective libraries, utilities, or techniques + +--- + +## 6. Enhanced Error Handling & Recovery + +### 6.1 Comprehensive Error Classification + +**TECHNICAL ERRORS:** +* **Build/Compilation Failures**: Syntax errors, missing dependencies +* **Test Failures**: Unit test failures, integration problems +* **Runtime Errors**: Application crashes, unexpected behaviors +* **Configuration Issues**: Environment variables, deployment problems + +**PROCESS ERRORS:** +* **Requirement Ambiguity**: Unclear or conflicting specifications +* **Dependency Delays**: External services, team dependencies +* **Scope Creep**: Requirements expanding beyond original plan +* **Resource Constraints**: Time, complexity, or capability limits + +### 6.2 Enhanced Recovery Protocols + +**ERROR RESPONSE FRAMEWORK:** +1. **Stop & Assess**: Immediately halt progress, assess impact +2. **Document**: Record exact error, context, and attempted solutions +3. **Classify**: Determine if AI can resolve or requires user input +4. **Communicate**: Notify user with specific details and options +5. **Wait or Act**: Follow user guidance or implement approved solution +6. **Verify**: Confirm resolution and prevent recurrence + +**USER COMMUNICATION TEMPLATES:** + +**Build Failure:** +``` +🚫 **Build Failure**: US-X implementation blocked + +**Error**: [Exact error message] +**Context**: [What was being attempted] +**Analysis**: [Root cause analysis] +**Impact**: [Effect on current story and sprint timeline] + +**Proposed Solution**: [Specific fix approach] +**Alternative**: [Backup approach if available] + +**Request**: Please confirm preferred resolution approach +``` + +**Test Failure:** +``` +🚫 **Test Failure**: Automated tests failing for US-X + +**Failed Tests**: [List of specific test cases] +**Error Details**: [Test failure messages] +**Analysis**: [Why tests are failing] +**Options**: +1. Fix implementation to pass existing tests +2. Update tests to match new requirements +3. Investigate if test assumptions are incorrect + +**Recommendation**: [AI's preferred approach] +``` + +--- + +## 7. Sprint Completion & Handover + +### 7.1 Comprehensive Sprint Wrap-up + +**FINAL DELIVERABLES CHECKLIST:** +* [ ] **Code Repository**: All commits pushed to sprint branch +* [ ] **Documentation**: All technical and user docs updated +* [ ] **Test Results**: All automated tests passing, user testing complete +* [ ] **Sprint Playbook**: Status updated, lessons learned captured +* [ ] **Technical Debt**: Identified and documented for future sprints +* [ ] **Knowledge Transfer**: Key technical decisions documented + +**QUALITY VERIFICATION:** +* [ ] **Security Review**: No critical vulnerabilities introduced +* [ ] **Performance**: No regressions in key metrics +* [ ] **Accessibility**: Standards maintained or improved +* [ ] **Browser Support**: Compatibility verified for target browsers +* [ ] **Mobile Support**: Responsive design tested (if applicable) + +### 7.2 User Handover Process + +**HANDOVER DOCUMENTATION:** +1. **Feature Summary**: What was built and why +2. **Usage Instructions**: How to use new functionality +3. **Testing Summary**: What was tested and results +4. **Known Limitations**: Any scope boundaries or technical constraints +5. **Future Recommendations**: Suggested enhancements or improvements + +**USER RESPONSIBILITIES POST-HANDOVER:** +* **Code Review**: Review changes before merging to main +* **Integration Testing**: Test with full system in staging environment +* **Production Deployment**: Deploy to production environment +* **User Acceptance**: Final approval of delivered functionality +* **Performance Monitoring**: Monitor system behavior post-deployment + +### 7.3 Success Metrics & Evaluation + +**SPRINT SUCCESS CRITERIA:** +* [ ] **Goal Achievement**: Primary sprint objective met +* [ ] **Story Completion**: All must-have stories completed +* [ ] **Quality Standards**: No critical bugs, performance met +* [ ] **Timeline**: Completed within estimated timeframe +* [ ] **User Satisfaction**: Delivered functionality meets expectations + +**CONTINUOUS IMPROVEMENT METRICS:** +* **Estimation Accuracy**: How close time estimates were to actual +* **Issue Discovery Rate**: Number of bugs found post-completion +* **User Feedback Quality**: Satisfaction with delivered features +* **Technical Debt Impact**: Amount of debt created vs. value delivered + +--- + +This improved framework enables more effective sprint execution through better planning, enhanced communication, proactive risk management, and comprehensive quality assurance while maintaining the successful patterns from Sprint 01. + +--- \ No newline at end of file diff --git a/docs/framework/sprint-playbook-template-improved.md b/docs/framework/sprint-playbook-template-improved.md new file mode 100644 index 0000000..15f01ab --- /dev/null +++ b/docs/framework/sprint-playbook-template-improved.md @@ -0,0 +1,232 @@ +# πŸ“‘ Sprint Playbook Template (Improved) + +## 0. Sprint Status + +``` +Status: [πŸ”² not started | 🚧 in progress | πŸ› οΈ implementing | βœ… completed | 🚫 blocked] +``` + +**Current Focus**: [Brief description of what's actively being worked on] + +--- + +## 1. Sprint Metadata + +* **Sprint ID:** [unique identifier] +* **Start Date:** [YYYY-MM-DD] +* **End Date:** [YYYY-MM-DD] +* **Sprint Goal:** [clear and concise goal statement] +* **Team/Agent Responsible:** [AI agent name/version] +* **Branch Name (Git):** [feature/sprint--] +* **Estimated Complexity:** [Simple | Medium | Complex] +* **Dependencies:** [List any blocking dependencies identified up front] + +--- + +## 2. Current State of Software + +*(Comprehensive snapshot of the project before Sprint work begins)* + +* **Main Features Available:** [list with brief descriptions] +* **Known Limitations / Issues:** [list with impact assessment] +* **Relevant Files / Modules:** [list with paths and purposes] +* **Environment / Dependencies:** [runtime versions, frameworks, libs with versions] +* **Testing Infrastructure:** [available test frameworks, coverage tools, CI/CD status] +* **Documentation Status:** [current state of docs, known gaps] + +--- + +## 3. Desired State of Software + +*(Target state after Sprint is complete)* + +* **New Features:** [list with specific functionality descriptions] +* **Modified Features:** [list with before/after behavior changes] +* **Expected Behavior Changes:** [user-visible and system-level changes] +* **External Dependencies / Integrations:** [new libraries, APIs, services with versions] +* **Performance Expectations:** [any performance requirements or improvements] +* **Security Considerations:** [security implications or requirements] + +--- + +## 4. User Stories + +Each story represents a **unit of work** that can be developed, tested, and verified independently. + +| Story ID | Title | Description | Acceptance Criteria | Definition of Done | Assignee | Status | Est. Time | Dependencies | +| -------- | ----- | ----------- | ------------------- | ------------------ | -------- | ------ | --------- | ------------ | +| US-1 | [short title] | [detailed description of functionality] | [specific, testable conditions] | [implemented, tested, docs updated, lint clean, **user testing completed**] | [AI agent] | πŸ”² todo | [hours] | [story IDs] | +| US-2 | ... | ... | ... | ... | ... | πŸ”² todo | [hours] | [story IDs] | + +**Status options:** `πŸ”² todo`, `🚧 in progress`, `🚫 blocked`, `βœ… done` + +**Story Priority Matrix:** +- **Must Have**: Core functionality required for sprint success +- **Should Have**: Important features that add significant value +- **Could Have**: Nice-to-have features if time permits +- **Won't Have**: Explicitly out of scope for this sprint + +--- + +## 5. Technical Instructions + +*(Comprehensive guidance to help AI converge quickly on the correct solution)* + +* **Code Snippets / Patterns:** + + ```typescript + // Example pattern with actual syntax from project + export const exampleFunction = async (params: ExampleType): Promise => { + // Implementation pattern following project conventions + }; + ``` + +* **Architecture Guidelines:** + - [layering principles, module boundaries, design patterns] + - [data flow patterns, state management approaches] + - [error handling conventions, logging patterns] + +* **Coding Style Conventions:** + - [naming rules: camelCase, PascalCase, kebab-case usage] + - [formatting: prettier, eslint rules] + - [file organization, import/export patterns] + +* **Testing Strategy:** + - [unit/integration/e2e testing approach] + - [testing framework and utilities to use] + - [coverage targets and quality gates] + - [manual testing checkpoints and user validation requirements] + +* **Internationalization (i18n):** + - [translation key patterns and placement] + - [supported locales and fallback strategies] + - [client vs server-side translation approaches] + +* **Performance Considerations:** + - [bundle size targets, lazy loading strategies] + - [database query optimization patterns] + - [caching strategies and invalidation] + +--- + +## 6. Risks and Dependencies + +* **Technical Risks:** + - [API compatibility issues, framework limitations] + - [Performance bottlenecks, scalability concerns] + - [Browser compatibility, device-specific issues] + +* **Integration Risks:** + - [Third-party service dependencies] + - [Database migration or schema change needs] + - [Authentication/authorization complexity] + +* **Timeline Risks:** + - [Unknown complexity areas] + - [Potential scope creep triggers] + - [External dependency availability] + +* **Dependencies:** + - [other modules, external services, libraries] + - [team inputs, design assets, API documentation] + - [infrastructure or deployment requirements] + +* **Mitigation Strategies:** + - [fallback approaches for high-risk items] + - [spike work to reduce uncertainty] + - [simplified alternatives if main approach fails] + +--- + +## 7. Quality Gates + +* **Code Quality:** + - [ ] All code follows project style guidelines + - [ ] No linting errors or warnings + - [ ] Code compiles without errors + - [ ] No security vulnerabilities introduced + +* **Testing Quality:** + - [ ] Unit tests cover new functionality + - [ ] Integration points are tested + - [ ] Manual testing completed by user + - [ ] Regression testing passed + +* **Documentation Quality:** + - [ ] Code comments added/updated + - [ ] README or API docs updated + - [ ] User-facing documentation updated + - [ ] Technical decisions documented + +--- + +## 8. Sprint Definition of Done (DoD) + +The Sprint is complete when: + +**AI-Responsible Items** (AI agent can verify and tick): +* [ ] All user stories meet their individual Definition of Done +* [ ] All quality gates passed +* [ ] Code compiles and passes automated tests +* [ ] Code formatting validated (npm run prettier:check) +* [ ] Code is committed and pushed on branch `feature/sprint-` +* [ ] Documentation is updated +* [ ] Sprint status updated to `βœ… completed` +* [ ] No critical bugs or blockers remain +* [ ] Performance meets specified requirements +* [ ] Security review completed (if applicable) + +**User-Only Items** (Only user can verify and tick): +* [ ] Branch is merged into main +* [ ] User acceptance testing completed +* [ ] Production deployment completed (if applicable) +* [ ] External system integrations verified (if applicable) +* [ ] Stakeholder sign-off received +* [ ] Performance validated in production environment + +**Success Metrics:** +* [ ] Sprint goal achieved +* [ ] All must-have stories completed +* [ ] No regression bugs introduced +* [ ] User satisfaction with delivered functionality + +--- + +## 9. Lessons Learned & Retrospective + +*(To be filled during/after sprint execution)* + +**What Went Well:** +- [successes, good decisions, effective processes] + +**What Could Be Improved:** +- [challenges faced, inefficiencies, areas for optimization] + +**Action Items for Future Sprints:** +- [specific improvements to implement next time] + +**Technical Debt Created:** +- [shortcuts taken that need future attention] + +**Knowledge Gained:** +- [new learnings about technology, domain, or processes] + +--- + +## 10. Communication & Coordination + +**Stakeholder Updates:** +- [frequency and format of progress updates] +- [key decision points requiring user input] + +**Testing Coordination:** +- [when to request user testing] +- [what specific scenarios to test] +- [how to report and track issues] + +**Blocker Escalation:** +- [how to handle technical blockers] +- [when to pause vs. continue with alternative approaches] +- [communication protocol for critical issues] + +--- \ No newline at end of file From 834444d5c716a5a570e593371b27c2aeed2289f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 22:16:00 +0200 Subject: [PATCH 10/12] fix: resolve next-intl translation parameter error in print footer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix IntlError: FORMATTING_ERROR for print footer translation: - Pass date parameter correctly to t("print-footer") in server component - Remove manual string replacement in client component - Use proper next-intl parameter syntax: t("key", { param: value }) Error was caused by next-intl expecting translation parameters to be passed at the translation function call level, not through manual string replacement afterward. Print preview now loads without FORMATTING_ERROR and displays localized footer text correctly in both English and Croatian. πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- app/[locale]/print/[year]/[month]/page.tsx | 2 +- app/ui/PrintPreview.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/[locale]/print/[year]/[month]/page.tsx b/app/[locale]/print/[year]/[month]/page.tsx index ef8fe7c..028117b 100644 --- a/app/[locale]/print/[year]/[month]/page.tsx +++ b/app/[locale]/print/[year]/[month]/page.tsx @@ -36,7 +36,7 @@ export default async function PrintPage({ params }: PrintPageProps) { barcodesFound: t("barcodes-found"), barcodeSingular: t("barcode-singular"), printButton: t("print-button"), - printFooter: t("print-footer"), + printFooter: t("print-footer", { date: new Date().toLocaleDateString() }), tableHeaderIndex: t("table-header-index"), tableHeaderBillInfo: t("table-header-bill-info"), tableHeaderBarcode: t("table-header-barcode") diff --git a/app/ui/PrintPreview.tsx b/app/ui/PrintPreview.tsx index 8739ebd..c237a6d 100644 --- a/app/ui/PrintPreview.tsx +++ b/app/ui/PrintPreview.tsx @@ -145,7 +145,7 @@ export const PrintPreview: React.FC = ({ data, year, month, t {/* Print footer - only visible when printing */}
-

{translations.printFooter.replace('{date}', new Date().toLocaleDateString())}

+

{translations.printFooter}

From 694ec8508b1ef8d8b242b2f778ec810c216eafdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 22:31:03 +0200 Subject: [PATCH 11/12] feat: add multilingual support for print preview empty state MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add i18n support for empty state when no barcode data is found: **English translations:** - "No Barcode Data Found" - "No bills with 2D barcodes found for {yearMonth}" **Croatian translations:** - "Nema Podataka o Barkodovima" - "Nema računa s 2D barkodovima za {yearMonth}" **Implementation:** - Add translation keys to messages/en.json and messages/hr.json - Update server component to fetch empty state translations - Use proper next-intl parameter passing for yearMonth variable - Replace hardcoded English text with localized translations Empty state now displays correct language based on URL locale: - /en/print/2025/01 β†’ English empty state message - /hr/print/2025/01 β†’ Croatian empty state message πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- app/[locale]/print/[year]/[month]/page.tsx | 9 ++++++--- messages/en.json | 4 +++- messages/hr.json | 4 +++- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/app/[locale]/print/[year]/[month]/page.tsx b/app/[locale]/print/[year]/[month]/page.tsx index 028117b..d8b736e 100644 --- a/app/[locale]/print/[year]/[month]/page.tsx +++ b/app/[locale]/print/[year]/[month]/page.tsx @@ -31,6 +31,7 @@ export default async function PrintPage({ params }: PrintPageProps) { // Get translations for the current locale const t = await getTranslations("home-page.print-preview"); + const yearMonth = `${year}-${month.toString().padStart(2, '0')}`; const translations = { title: t("title"), barcodesFound: t("barcodes-found"), @@ -39,7 +40,9 @@ export default async function PrintPage({ params }: PrintPageProps) { printFooter: t("print-footer", { date: new Date().toLocaleDateString() }), tableHeaderIndex: t("table-header-index"), tableHeaderBillInfo: t("table-header-bill-info"), - tableHeaderBarcode: t("table-header-barcode") + tableHeaderBarcode: t("table-header-barcode"), + emptyStateTitle: t("empty-state-title"), + emptyStateMessage: t("empty-state-message", { yearMonth }) }; // If no barcode data found, show empty state @@ -47,9 +50,9 @@ export default async function PrintPage({ params }: PrintPageProps) { return (
-

No Barcode Data Found

+

{translations.emptyStateTitle}

- No bills with 2D barcodes found for {year}-{month.toString().padStart(2, '0')} + {translations.emptyStateMessage}

diff --git a/messages/en.json b/messages/en.json index 1dd7618..90aef68 100644 --- a/messages/en.json +++ b/messages/en.json @@ -70,7 +70,9 @@ "print-footer": "Generated on {date} β€’ Evidencija ReΕΎija Print System", "table-header-index": "#", "table-header-bill-info": "Bill Information", - "table-header-barcode": "2D Barcode" + "table-header-barcode": "2D Barcode", + "empty-state-title": "No Barcode Data Found", + "empty-state-message": "No bills with 2D barcodes found for {yearMonth}" } }, "bill-delete-form": { diff --git a/messages/hr.json b/messages/hr.json index 2db0fc6..bc3cae3 100644 --- a/messages/hr.json +++ b/messages/hr.json @@ -70,7 +70,9 @@ "print-footer": "Generirano {date} β€’ Evidencija ReΕΎija Sustav Ispisa", "table-header-index": "#", "table-header-bill-info": "Informacije o Računu", - "table-header-barcode": "2D Barkod" + "table-header-barcode": "2D Barkod", + "empty-state-title": "Nema Podataka o Barkodovima", + "empty-state-message": "Nema računa s 2D barkodovima za {yearMonth}" } }, "bill-delete-form": { From fdfa23e67ddbe1bb7da63f09abc71ae17417fa13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nikola=20Dere=C5=BEi=C4=8D?= Date: Sun, 14 Sep 2025 22:45:14 +0200 Subject: [PATCH 12/12] fix: resolve MongoDB ObjectId serialization error in client components MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix React serialization warning when passing ObjectIds to client components: **Problem:** - MongoDB ObjectIds have toJSON() methods which React rejects in client components - Error: "Only plain objects can be passed to Client Components from Server Components. Objects with toJSON methods are not supported" - Occurred when rendering main page with year parameter (?year=2023) **Solution:** - Add $addFields stage in fetchAllLocations aggregation pipeline - Convert location _id and bill _id fields to strings using $toString - Simplify $project stage to use single "bills": 1 instead of individual field projections - Ensures only plain objects (strings) are passed to client components **Technical Details:** - Modified app/lib/actions/locationActions.ts:268-287 - Added $addFields stage before existing $project stage - Converted ObjectIds to strings while preserving all other data structures - Build passes without serialization warnings ObjectId serialization now handled properly across all client component boundaries. πŸ€– Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- app/lib/actions/locationActions.ts | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/app/lib/actions/locationActions.ts b/app/lib/actions/locationActions.ts index 7accab4..be3fc07 100644 --- a/app/lib/actions/locationActions.ts +++ b/app/lib/actions/locationActions.ts @@ -264,6 +264,24 @@ export const fetchAllLocations = withUser(async (user:AuthenticatedUser, year:nu }, }, }, + { + $addFields: { + _id: { $toString: "$_id" }, + bills: { + $map: { + input: "$bills", + as: "bill", + in: { + _id: { $toString: "$$bill._id" }, + name: "$$bill.name", + paid: "$$bill.paid", + payedAmount: "$$bill.payedAmount", + hasAttachment: "$$bill.hasAttachment", + }, + }, + }, + } + }, { $project: { "_id": 1, @@ -274,12 +292,7 @@ export const fetchAllLocations = withUser(async (user:AuthenticatedUser, year:nu // "yearMonth": 1, "yearMonth.year": 1, "yearMonth.month": 1, - // "bills": 1, - "bills._id": 1, - "bills.name": 1, - "bills.paid": 1, - "bills.payedAmount": 1, - "bills.hasAttachment": 1, + "bills": 1, // "bills.attachment": 0, // "bills.notes": 0, // "bills.barcodeImage": 1,