Merge branch 'feature/sprint-01-barcode-print' into develop

This commit is contained in:
2025-09-14 22:46:21 +02:00
17 changed files with 2377 additions and 9 deletions

View File

@@ -0,0 +1,6 @@
import { NotFoundPage } from '@/app/ui/NotFoundPage';
const PrintPageNotFound = () =>
<NotFoundPage title="404 Print Page Not Found" description="Could not find the requested print preview page." />;
export default PrintPageNotFound;

View File

@@ -0,0 +1,63 @@
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: {
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();
}
// 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"),
barcodeSingular: t("barcode-singular"),
printButton: t("print-button"),
printFooter: t("print-footer", { date: new Date().toLocaleDateString() }),
tableHeaderIndex: t("table-header-index"),
tableHeaderBillInfo: t("table-header-bill-info"),
tableHeaderBarcode: t("table-header-barcode"),
emptyStateTitle: t("empty-state-title"),
emptyStateMessage: t("empty-state-message", { yearMonth })
};
// If no barcode data found, show empty state
if (!printData || printData.length === 0) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<h1 className="text-2xl font-bold mb-4">{translations.emptyStateTitle}</h1>
<p className="text-gray-600">
{translations.emptyStateMessage}
</p>
</div>
</div>
);
}
return <PrintPreview data={printData} year={year} month={month} translations={translations} />;
}

View File

@@ -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,

View File

@@ -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<PrintBarcodeData[]> => {
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<BillingLocation>("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;
});

View File

@@ -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<MonthLocationListProps > = ({
locations.map((location, ix) => <LocationCard key={`location-${location._id}`} location={location} />)
: null
}
<AddLocationButton yearMonth={yearMonth} />
<div className="flex gap-2 justify-center">
<AddLocationButton yearMonth={yearMonth} />
<PrintButton yearMonth={yearMonth} />
</div>
</MonthCard>
)
}

32
app/ui/PrintButton.tsx Normal file
View File

@@ -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<PrintButtonProps> = ({ yearMonth }) => {
const t = useTranslations("home-page.month-card");
const handlePrintClick = () => {
window.open(`/print/${yearMonth.year}/${yearMonth.month}`, '_blank');
};
return (
<div className="card card-compact card-bordered bg-base-100 shadow-s my-1">
<button
className="card-body tooltip self-center cursor-pointer"
onClick={handlePrintClick}
data-tip={t("print-codes-tooltip")}
>
<span className='flex self-center mr-[-3em]'>
<PrinterIcon className="h-[1em] w-[1em] cursor-pointer text-4xl" />
<span className="ml-1 mt-[.4em] text-xs text-left leading-[1.2em] w-[6em]">{t("print-codes-label")}</span>
</span>
</button>
</div>
);
};

154
app/ui/PrintPreview.tsx Normal file
View File

@@ -0,0 +1,154 @@
'use client';
import { PrintBarcodeData } from '../lib/actions/printActions';
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<PrintPreviewProps> = ({ data, year, month, translations }) => {
return (
<>
{/* Print-specific CSS styles */}
<style jsx>{`
@media print {
@page {
size: A4;
margin: 1in;
}
body {
-webkit-print-color-adjust: exact !important;
color-adjust: exact !important;
print-color-adjust: exact !important;
}
.print-barcode-img {
width: 69.6mm !important;
max-width: 69.6mm !important;
height: auto !important;
max-height: none !important;
}
.print-table {
page-break-inside: avoid;
}
.print-table tr {
page-break-inside: avoid;
page-break-after: auto;
}
.print-table thead {
display: table-header-group;
}
/* Optimize for B&W printing */
* {
color: black !important;
background: white !important;
box-shadow: none !important;
text-shadow: none !important;
}
.print-table th,
.print-table td {
border: 2px solid black !important;
background: white !important;
}
.print-table thead tr {
background: #f5f5f5 !important;
}
}
`}</style>
<div className="min-h-screen bg-white">
{/* Header section - hidden in print */}
<div className="p-6 border-b border-gray-200 print:hidden">
<h1 className="text-3xl font-bold text-gray-900 mb-2">
{translations.title}
</h1>
<p className="text-lg text-gray-600 mb-4">
{year}-{month.toString().padStart(2, '0')} {data.length} {data.length === 1 ? translations.barcodeSingular : translations.barcodesFound}
</p>
<button
onClick={() => window.print()}
className="btn btn-primary"
>
🖨 {translations.printButton}
</button>
</div>
{/* Print content */}
<div className="p-0">
<table className="w-full border-collapse border-2 border-gray-800 print-table">
<thead>
<tr className="bg-gray-100">
<th className="border-2 border-gray-800 px-3 py-2 text-center font-bold text-sm w-16">
{translations.tableHeaderIndex}
</th>
<th className="border-2 border-gray-800 px-3 py-2 text-left font-bold text-sm">
{translations.tableHeaderBillInfo}
</th>
<th className="border-2 border-gray-800 px-3 py-2 text-center font-bold text-sm w-64">
{translations.tableHeaderBarcode}
</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => (
<tr key={`${item.locationName}-${item.billName}`} className="hover:bg-gray-50">
<td className="border-2 border-gray-800 px-3 py-4 text-center font-mono text-sm font-medium">
{(index + 1).toString().padStart(2, '0')}
</td>
<td className="border-2 border-gray-800 px-3 py-4">
<div className="space-y-1">
<div className="font-bold text-sm text-gray-900">
📅 {item.yearMonth}
</div>
<div className="font-medium text-sm text-gray-800">
🏠 {item.locationName}
</div>
<div className="text-sm text-gray-700">
📋 {item.billName}
</div>
</div>
</td>
<td className="border-2 border-gray-800 px-3 py-1.5 text-center">
<div className="flex justify-center items-center">
<img
src={item.barcodeImage.startsWith('data:') ? item.barcodeImage : `data:image/png;base64,${item.barcodeImage}`}
alt={`Barcode for ${item.billName}`}
className="max-h-28 w-auto border border-gray-300 rounded print-barcode-img"
style={{ maxWidth: '270px' }}
/>
</div>
</td>
</tr>
))}
</tbody>
</table>
{/* Print footer - only visible when printing */}
<div className="mt-6 text-center text-xs text-gray-500 hidden print:block">
<p>{translations.printFooter}</p>
</div>
</div>
</div>
</>
);
};

View File

@@ -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<T, E> 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.
---

View File

@@ -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 users 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 users 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-<id>]`
* [ ] 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.

View File

@@ -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:**
```
<type>(scope): <subject>
<body>
<footer>
```
**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-<id>-<goal-slug>
```
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.
---

View File

@@ -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:
```
<type>(<scope>): <subject>
<body>
Refs: <Story-ID(s)>
```
* Example:
```
feat(auth): add JWT middleware
Introduces HS256 verification for protected routes.
Returns 401 for missing/invalid/expired tokens.
Refs: US-3
```
* Allowed `<type>`: `feat`, `fix`, `refactor`, `perf`, `test`, `docs`, `build`, `ci`, `style`, `chore`, `revert`.
### 1.3 Branching Strategy
* Use **one dedicated branch per Sprint**:
* Naming: `feature/sprint-<id>-<short-goal>`
* 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 AIs 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 storys `Status` field (`🔲 todo` → `🚧 in progress` → `✅ done`).
* Mark `✅ done` only when the storys **DoD** is fully satisfied.
### 2.2 Sprint Status (Top-Level)
* Keep the top-level Sprint status current:
```
Status: [🔲 not started | 🚧 in progress | 🛠️ implementing <user story id> | ✅ 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-<id>.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 projects 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.

View File

@@ -0,0 +1,232 @@
# 📑 Sprint Playbook Template (Improved)
## 0. Sprint Status
```
Status: [🔲 not started | 🚧 in progress | 🛠️ implementing <user story id> | ✅ 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-<id>-<short-description>]
* **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<ResultType> => {
// 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-<id>`
* [ ] 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]
---

View File

@@ -0,0 +1,94 @@
# 📑 Sprint Playbook Template
## 0. Sprint Status
```
Status: [🔲 not started | 🚧 in progress | 🛠️ implementing <user story id> | ✅ 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-<id>]
---
## 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-<id>]`.
* [ ] Documentation is updated.
* [ ] Sprint status updated to `✅ done`.
**User-Only Items** (Only user can verify and tick):
* [ ] Branch is merged into main.
---

View File

@@ -0,0 +1,196 @@
# 📑 Sprint Playbook: Barcode Print Support
## 0. Sprint Status
```
Status: ✅ completed
```
---
## 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 | ✅ 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`
---
## 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');
};
<button
className="btn btn-ghost btn-sm"
onClick={handlePrintClick}
title={t("print-codes-tooltip")}
>
<PrinterIcon className="h-4 w-4" />
{t("print-codes-label")}
</button>
```
```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):
* [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
* [ ] Print functionality tested across target browsers
* [ ] Print output quality validated on physical printer
---

View File

@@ -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

View File

@@ -58,7 +58,21 @@
"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"
},
"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",
"empty-state-title": "No Barcode Data Found",
"empty-state-message": "No bills with 2D barcodes found for {yearMonth}"
}
},
"bill-delete-form": {

View File

@@ -58,7 +58,21 @@
"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"
},
"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",
"empty-state-title": "Nema Podataka o Barkodovima",
"empty-state-message": "Nema računa s 2D barkodovima za {yearMonth}"
}
},
"bill-delete-form": {