Legacy
1.x technical documentation
The complete documentation written for Splitmize 1.x, kept for reference. It describes code that no longer exists.
Optimized Sharing at Your Fingertips
Table of Contents
- Product Overview
- Slogan, Technologies, and Objectives
- Business Rules
- General Usage Flow
- Use Cases and Examples
- Technical and Logical Details
- Interface Specifications
- Code Architecture and Best Practices
- Component Documentation
- State Management
- Internationalization (i18n)
- Styling and Design System
- Data Persistence
- Export and Sharing Features
- Installation and Setup
- Development Tools and Scripts
- Deployment
- Contributing Guidelines
- Contact and Support
1. Product Overview
Splitmize is a feature-rich web application designed to revolutionize the process of splitting bills among groups of people. Whether it's for a casual dinner or a shared expense on a trip, the app simplifies calculations and ensures transparency for all participants.
Key Capabilities
- Register items and their values with dynamic calculations
- Associate individuals with consumed items
- Add service fees (e.g., 10%) with customizable rates
- Include extra charges (fixed or percentage-based)
- Generate comprehensive reports detailing amounts owed by each person
- Export reports as PDFs or share via WhatsApp, email, or clipboard
- Track payment status in real-time
- Persist session data for future reference
- Multi-language support (Portuguese, English, Spanish)
- Multi-currency support (BRL, USD)
Technology Stack
- Framework: Next.js 15.1.0 with React 18.2.0
- Language: TypeScript 5.1.6
- State Management: React Context API with useReducer
- Styling: SASS 1.83.0 with CSS Modules and BEM methodology
- Animations: Framer Motion 10.16.0
- Internationalization: i18next 23.5.0 with next-i18next 14.0.0
- PDF Generation: html2pdf.js 0.10.2
- ID Generation: uuid 11.0.3
- Email Integration: Nodemailer 6.9.16
- Analytics: Vercel Analytics 1.4.1
- Quality Control: ESLint with Next.js configuration
- Build Tools: Webpack 5.97.1
2. Slogan, Technologies, and Objectives
Slogan
"Optimized sharing at your fingertips."
Primary Objectives
- Simplify Bill Splitting: Make the process of dividing expenses between multiple people effortless and transparent
- Ensure Accuracy: Provide precise calculations for individual shares, service charges, and extra fees
- Enable Flexibility: Allow users to customize associations, fees, and charges according to their specific needs
- Maintain Transparency: Show clear breakdowns of how amounts are calculated
- Facilitate Sharing: Enable easy export and sharing of reports via multiple channels
- Preserve History: Store session data locally for future reference and reuse
- Support Global Usage: Provide multi-language and multi-currency support
Development Principles
- Mobile-First: Responsive design optimized for mobile devices
- Accessibility: WCAG AA compliant with proper ARIA labels and semantic HTML
- Performance: Optimized bundle size and lazy loading for fast page loads
- Maintainability: Clean code with TypeScript, ESLint, and modular architecture
- User Experience: Smooth animations and intuitive interface
3. Business Rules
3.1. Participant Management
Adding Participants:
- Users can add any number of participants by name
- Participant names are persisted in localStorage for future suggestions
- Each participant is automatically included in all calculations by default
- Participants can be removed at any time before finalizing the report
Participant Association:
- Each participant can be associated with specific items they consumed
- By default, all participants are linked to all items
- Users can uncheck items that specific participants did not consume
3.2. Item Registration
Item Properties:
- Each item has: name, quantity, unit price, and total price
- Users can input either unit price or total price; the other is calculated automatically
- Dynamic calculation:
totalPrice = quantity × unitPrice - All items are persisted in localStorage for future suggestions
Item Management:
- Items can be added, viewed, and removed before generating the report
- Items are displayed with full details (quantity, unit price, total)
- Currency formatting is applied based on the selected currency (BRL or USD)
3.3. Consumption Association
Default Behavior:
- All participants initially consume all items (checkboxes marked)
- Users customize by unchecking items that specific participants didn't consume
Calculation Logic:
- Each item's total price is divided equally among its consumers
- Formula:
personItemShare = itemTotalPrice / numberOfConsumers - Only active participants are included in calculations
3.4. Service Charges and Extra Fees
Service Charge:
- Default percentage: 10% (customizable)
- Can be applied to all or specific participants
- Calculated based on each participant's item subtotal
- Formula:
serviceCharge = itemsSubtotal × (percentage / 100)
Extra Fees:
- Two types: Fixed Value or Percentage
- Fixed Value: Divided equally among all participants
- Formula:
perPersonShare = fixedFee / numberOfParticipants
- Formula:
- Percentage: Applied to each participant's item subtotal
- Formula:
feeShare = itemsSubtotal × (percentage / 100)
- Formula:
- Multiple extra fees can be added
- Each extra fee has a description and value
3.5. Final Calculation
The total amount owed by each participant is calculated as:
Total = ItemsSubtotal + ServiceCharge + ExtraFeesShare
Where:
- ItemsSubtotal = Sum of all item shares consumed by the participant
- ServiceCharge = ItemsSubtotal × (servicePercentage / 100) [if applicable]
- ExtraFeesShare = Sum of all extra fee shares for the participant
3.6. Payment Tracking
- Each participant has a payment status: Paid or Unpaid
- Users can mark participants as paid using checkboxes
- The system displays:
- Total Paid: Sum of amounts from participants marked as paid
- Total Unpaid: Sum of amounts from participants not yet paid
- Payment status can be toggled at any time
3.7. Report Generation and Export
- PDF Export: Complete report with all details exported as a PDF file
- Share Options: WhatsApp, email, or clipboard copy
- Report Contents:
- Date and session name
- All consumed items with quantities and prices
- Service charges and extra fees
- Breakdown by participant with individual totals
- Grand total
- Payment status for each participant
4. General Usage Flow
The application follows a linear, step-by-step wizard-like flow:
Step 0: Introduction & Welcome
↓
Step 1: Add Participants
↓
Step 2: Register Items and Prices
↓
Step 3: Associate Participants with Items
↓
Step 4: Define Service Charges and Extra Fees
↓
Step 5: Review and Confirm Data
↓
Step 6: Final Report with Payment Tracking
Navigation Features
- Back Button: Navigate to previous steps (confirmation dialog on Step 1)
- Next/Continue Button: Advance to next step (disabled if required data is missing)
- Progress Bar: Visual indicator showing current step in the process
- Auto-save: Progress is automatically saved to localStorage
- Session Management: Users can load, save, and delete previous sessions
5. Use Cases and Examples
5.1. Adding Participants
Scenario: Three friends go out for dinner
User adds:
- Alice
- Bob
- Carol
These names are saved to localStorage for future sessions.
Each participant is automatically added to serviceCharge.applicablePeople array.
5.2. Registering Consumed Items
Scenario: The group orders food and drinks
Item 1: Pizza
- Quantity: 2
- Unit Price: $30.00
- Total Price: $60.00 (automatically calculated)
Item 2: Beer
- Quantity: 9
- Total Price: $45.00 (user enters this)
- Unit Price: $5.00 (automatically calculated)
Item 3: Dessert
- Quantity: 2
- Unit Price: $10.00
- Total Price: $20.00
5.3. Associating Items with Participants
Scenario: Not everyone consumed everything
Alice: Pizza ✓, Beer ✗, Dessert ✓
Bob: Pizza ✓, Beer ✓, Dessert ✗
Carol: Pizza ✓, Beer ✓, Dessert ✓
Calculations:
- Pizza ($60) → 3 consumers → $20 each
- Beer ($45) → 2 consumers (Bob, Carol) → $22.50 each
- Dessert ($20) → 2 consumers (Alice, Carol) → $10 each
Subtotals:
- Alice: $20 (pizza) + $10 (dessert) = $30
- Bob: $20 (pizza) + $22.50 (beer) = $42.50
- Carol: $20 (pizza) + $22.50 (beer) + $10 (dessert) = $52.50
5.4. Adding Service Charges and Extra Fees
Scenario: Restaurant charges 10% service fee, plus there's a parking fee
Service Charge: 10%
- Applied to: Bob and Carol only (Alice had a discount card)
- Bob: $42.50 × 10% = $4.25
- Carol: $52.50 × 10% = $5.25
Extra Fee: Parking
- Type: Fixed Value
- Amount: $15.00
- Divided equally: $15.00 / 3 = $5.00 each
5.5. Final Report
Scenario: Complete breakdown with totals
Alice's Total:
- Items: $30.00
- Service Charge: $0.00
- Extra Fees: $5.00
- TOTAL: $35.00 ⏳ (unpaid)
Bob's Total:
- Items: $42.50
- Service Charge: $4.25
- Extra Fees: $5.00
- TOTAL: $51.75 ✅ (paid)
Carol's Total:
- Items: $52.50
- Service Charge: $5.25
- Extra Fees: $5.00
- TOTAL: $62.75 ⏳ (unpaid)
Grand Total: $149.50
Total Paid: $51.75
Total Unpaid: $97.75
5.6. Session History and Persistence
Scenario: User returns later to view past bills
User opens Splitmize and clicks "History"
Sees saved sessions:
- Record #3 - 11/26/2025, 2:30 PM - Alice, Bob, Carol - $149.50
- Record #2 - 11/20/2025, 7:15 PM - John, Jane - $85.00
- Record #1 - 11/15/2025, 1:00 PM - Team Lunch - $320.00
User can:
- Load a session to view or edit
- Delete old sessions
- Rename sessions for better organization
5.7. Exporting and Sharing
Scenario: User wants to share the bill breakdown
PDF Export:
- Generates a formatted PDF with all details
- Filename: splitmize-report-11-26-2025.pdf
- Includes: items table, charges, breakdown by person, totals
Share via WhatsApp:
- Formats text message with emojis
- Includes totals and payment status
- Opens WhatsApp with pre-filled message
Copy to Clipboard:
- Copies formatted text
- Can be pasted anywhere
- Shows "Copied!" confirmation
6. Technical and Logical Details
6.1. Data Structure
The application state follows this TypeScript interface structure:
interface SplitmizeState {
// Participants in the bill split
people: Person[];
// Consumed items with pricing
items: Item[];
// Maps people to the items they consumed
consumptionMap: ConsumptionMap;
// Service charge configuration
serviceCharge: ServiceCharge;
// Additional fees (fixed or percentage)
extraFees: ExtraFee[];
// Payment status for each person
payments: {
[personName: string]: Payment;
};
// Current step in the wizard (0-6)
currentStep: number;
// Localization and currency
locale: string;
currency: "BRL" | "USD";
// Session metadata
name: string;
date: string;
sessionId: string;
}
Sub-interfaces:
interface Person {
name: string;
active: boolean;
}
interface Item {
name: string;
quantity: number;
unitPrice: number;
totalPrice: number;
}
interface ConsumptionMap {
[personName: string]: {
[itemName: string]: boolean;
};
}
interface ServiceCharge {
percentage: number;
applicablePeople: string[];
}
interface ExtraFee {
description: string;
value: number;
isPercentage: boolean;
}
interface Payment {
amountDue: number;
paid: boolean;
}
6.2. State Management Actions
The application uses a reducer pattern with these action types:
type SplitmizeAction =
| { type: "ADD_PERSON"; payload: string }
| { type: "REMOVE_PERSON"; payload: string }
| { type: "ADD_ITEM"; payload: Item }
| { type: "REMOVE_ITEM"; payload: string }
| { type: "UPDATE_CONSUMPTION"; payload: { person: string; item: string; consumed: boolean }}
| { type: "SET_SERVICE_CHARGE"; payload: ServiceCharge }
| { type: "ADD_EXTRA_FEE"; payload: ExtraFee }
| { type: "REMOVE_EXTRA_FEE"; payload: number }
| { type: "UPDATE_PAYMENT"; payload: { person: string; paid: boolean }}
| { type: "SET_STEP"; payload: number }
| { type: "SAVE_TO_STORAGE" }
| { type: "LOAD_STATE"; payload: SplitmizeState }
| { type: "SET_LOCALE"; payload: string }
| { type: "SET_CURRENCY"; payload: "BRL" | "USD" }
| { type: "START_NEW_SESSION" }
| { type: "SAVE_SESSION_PROGRESS" };
6.3. localStorage Storage Strategy
Keys Used:
splitmizeCurrency: Stores the user's preferred currencysplitmizeSession_{sessionId}: Stores individual session datasplitmizeCurrentSession: Stores the active session state (legacy, for compatibility)
Session Storage Format:
{
"sessionId": "uuid-v4-string",
"name": "Record #1",
"date": "11/26/2025, 2:30 PM",
"people": [
{ "name": "Alice", "active": true }
],
"items": [
{
"name": "Pizza",
"quantity": 2,
"unitPrice": 30,
"totalPrice": 60
}
],
"consumptionMap": {
"Alice": {
"Pizza": true
}
},
"serviceCharge": {
"percentage": 10,
"applicablePeople": ["Alice"]
},
"extraFees": [
{
"description": "Parking",
"value": 15,
"isPercentage": false
}
],
"payments": {
"Alice": {
"amountDue": 0,
"paid": false
}
},
"currentStep": 1,
"locale": "en",
"currency": "USD"
}
6.4. Calculation Algorithms
Individual Item Share:
function calculateItemShare(item: Item, person: Person, consumptionMap: ConsumptionMap, people: Person[]): number {
// Check if person consumed this item
if (!consumptionMap[person.name]?.[item.name]) {
return 0;
}
// Count how many people consumed this item
const consumers = people.filter(
p => consumptionMap[p.name]?.[item.name]
).length;
// Divide item price among consumers
return item.totalPrice / consumers;
}
Service Charge Calculation:
function calculateServiceCharge(
itemsSubtotal: number,
person: Person,
serviceCharge: ServiceCharge
): number {
// Check if person pays service charge
if (!serviceCharge.applicablePeople.includes(person.name)) {
return 0;
}
// Calculate percentage of subtotal
return itemsSubtotal * (serviceCharge.percentage / 100);
}
Extra Fees Calculation:
function calculateExtraFeesShare(
itemsSubtotal: number,
extraFees: ExtraFee[],
numberOfPeople: number
): number {
return extraFees.reduce((sum, fee) => {
if (fee.isPercentage) {
// Percentage-based fee
return sum + (itemsSubtotal * fee.value / 100);
} else {
// Fixed fee divided equally
return sum + (fee.value / numberOfPeople);
}
}, 0);
}
Total Per Person:
function calculatePersonTotal(
person: Person,
items: Item[],
consumptionMap: ConsumptionMap,
people: Person[],
serviceCharge: ServiceCharge,
extraFees: ExtraFee[]
): number {
// Calculate items subtotal
const itemsSubtotal = items.reduce((sum, item) => {
return sum + calculateItemShare(item, person, consumptionMap, people);
}, 0);
// Calculate service charge
const serviceChargeAmount = calculateServiceCharge(
itemsSubtotal,
person,
serviceCharge
);
// Calculate extra fees share
const extraFeesShare = calculateExtraFeesShare(
itemsSubtotal,
extraFees,
people.length
);
// Sum all components
return itemsSubtotal + serviceChargeAmount + extraFeesShare;
}
6.5. Currency Formatting
export function formatCurrency(value: number, currency: 'BRL' | 'USD'): string {
if (currency === 'BRL') {
// Brazilian Real format: R$ 10,50
return `R$ ${value.toFixed(2).replace('.', ',')}`;
}
// US Dollar format: $ 10.50
return `$ ${value.toFixed(2)}`;
}
6.6. Navigation and Flow Control
Step Validation:
function canProceed(state: SplitmizeState): boolean {
switch (state.currentStep) {
case 1: // PeopleManager
return state.people && state.people.length > 0;
case 2: // ItemManager
return state.items && state.items.length > 0;
case 3: // ConsumptionManager
return state.consumptionMap &&
Object.keys(state.consumptionMap).length > 0;
case 4: // ServiceChargeManager
case 5: // ReviewManager
return true; // Can always proceed
default:
return true;
}
}
7. Interface Specifications
7.1. Design System
Color Palette:
The application uses a carefully selected color palette defined in src/styles/base/_colors.scss:
- Primary Color: Used for main actions, buttons, and branding
- Secondary Color: Used for secondary actions and backgrounds
- Accent Color: Used for highlights and important indicators
- Neutral Palette:
- Text Primary: High contrast dark text
- Text Secondary: Medium gray for less prominent text
- Background: White base
- Dividers: Light gray borders
Typography:
Defined in src/styles/base/_typography.scss:
- Font Family: Sans-serif for optimal readability
- Base Size (Mobile): 16px for body text
- Heading Hierarchy:
- H1 (Page titles): 24px, bold
- H2 (Section titles): 20px, semi-bold
- H3 (Subsections): 18px, medium
- Line Height: 1.5 for comfortable reading
Spacing:
Following the 8px grid system (src/styles/base/_spacing.scss):
$spacing-xs: 4px;
$spacing-sm: 8px;
$spacing-md: 16px;
$spacing-lg: 24px;
$spacing-xl: 32px;
$spacing-2xl: 48px;
7.2. Responsive Breakpoints
$breakpoint-mobile: 320px;
$breakpoint-tablet: 768px;
$breakpoint-desktop: 1024px;
$breakpoint-wide: 1440px;
Mobile-First Approach:
- Default styles target mobile devices (320px+)
- Media queries add enhancements for larger screens
- Touch targets minimum 44x44px for accessibility
- Single-column layout on mobile
- Multi-column on tablet and desktop where appropriate
7.3. Component Specifications
Buttons:
// Primary Button
.button--primary {
background: $color-primary;
color: white;
padding: $spacing-sm $spacing-md;
border-radius: 4px;
border: none;
font-weight: 600;
cursor: pointer;
min-height: 44px; // Accessibility
&:hover {
background: darken($color-primary, 10%);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
// Secondary Button
.button--secondary {
background: transparent;
color: $color-primary;
border: 1px solid $color-primary;
padding: $spacing-sm $spacing-md;
border-radius: 4px;
&:hover {
background: rgba($color-primary, 0.1);
}
}
Input Fields:
.input {
width: 100%;
padding: $spacing-sm;
border: 1px solid $color-border;
border-radius: 4px;
font-size: 16px; // Prevent zoom on iOS
min-height: 44px;
&:focus {
outline: none;
border-color: $color-primary;
box-shadow: 0 0 0 3px rgba($color-primary, 0.1);
}
&::placeholder {
color: $color-text-secondary;
}
}
Cards:
.card {
background: white;
border-radius: 8px;
padding: $spacing-md;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
&:hover {
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
transform: translateY(-2px);
transition: all 0.2s ease;
}
}
7.4. Page-by-Page Specifications
Step 0: Introduction/Splash Screen
- Purpose: Welcome users and explain the app functionality
- Components:
- Logo and slogan
- Brief description
- Step-by-step overview with icons
- "Start New Bill" primary CTA button
- File:
src/components/SplitmizeIntro.tsx - Styles:
src/styles/components/SplitmizeIntro.module.scss
Step 1: People Manager
- Purpose: Add and manage participants
- Components:
- Input field for participant name
- "Add" button
- List of added participants with remove buttons
- Auto-save to localStorage
- File:
src/components/PeopleManager.tsx - Styles:
src/styles/components/PeopleManager.module.scss - Validation: At least one person required to proceed
Step 2: Item Manager
- Purpose: Register consumed items with prices
- Components:
- Item name input
- Quantity input (numeric)
- Unit price input (decimal with comma/period handling)
- Total price input (calculated or manual)
- "Add Item" button
- List of added items showing all details
- Remove button for each item
- File:
src/components/ItemManager.tsx - Styles:
src/styles/components/ItemManager.module.scss - Features:
- Dynamic calculation between unit price and total price
- Currency formatting based on selected currency
- Validation: At least one item required to proceed
Step 3: Consumption Manager
- Purpose: Associate participants with consumed items
- Components:
- "Mark All Items" global button
- Section per participant
- "Select all" toggle per participant
- Checkbox list of items per participant
- Item names with prices displayed
- File:
src/components/ConsumptionManager.tsx - Styles:
src/styles/components/ConsumptionManager.module.scss - Default Behavior: All items checked for all participants initially
Step 4: Service Charge Manager
- Purpose: Define service charges and extra fees
- Components:
- Service Charge Section:
- Percentage input
- Checkbox list of participants who pay it
- Extra Fees Section:
- Description input
- Value input
- Type selector (Fixed/Percentage)
- "Add" button
- List of added extra fees with remove buttons
- Service Charge Section:
- File:
src/components/ServiceChargeManager.tsx - Styles:
src/styles/components/ServiceChargeManager.module.scss
Step 5: Review Manager
- Purpose: Show comprehensive breakdown before finalizing
- Sections:
- Items Summary: Each item with consumers list
- Charges Summary: Service charge and extra fees
- Per-Person Summary: Detailed breakdown showing:
- Items consumed with individual shares
- Service charge (if applicable)
- Extra fees share
- Total amount
- Grand Total: Sum of all amounts
- File:
src/components/ReviewManager.tsx - Styles:
src/styles/components/ReviewManager.module.scss
Step 6: Final Report
- Purpose: Display final amounts and enable payment tracking
- Components:
- Summary Cards:
- Total Paid (green)
- Total Unpaid (red)
- Per-Person Cards:
- Name and amount
- "Paid" checkbox
- Export Section:
- PDF export button
- Share options (WhatsApp, Email, Copy)
- Action Buttons:
- "Split a New Bill" button
- Summary Cards:
- File:
src/components/FinalReport.tsx - Styles:
src/styles/components/FinalReport.module.scss - Features:
- Real-time update of totals when payments are marked
- Confirmation dialog before starting new session
7.5. Common UI Elements
Progress Bar
- Shows current step (1-6) with visual indicator
- Each step labeled with icon or text
- Completed steps marked differently than current/upcoming
- File:
src/components/ProgressBar.tsx
Navigation Bar
- Fixed at bottom of screen on mobile
- Contains "Back" and "Next/Continue/Finish" buttons
- "Next" button disabled when validation fails
- Hidden on introduction step
- File:
src/components/NavigationBar.tsx
Header
- App logo and name
- Language switcher (EN/ES/PT)
- Currency selector (BRL/USD)
- History button
- File:
src/components/SplitmizeHeader.tsx
Footer
- Copyright information
- Author attribution
- Social links (GitHub, LinkedIn, Instagram)
- File:
src/components/SplitmizeFooter.tsx
Confirm Dialog
- Modal overlay for important actions
- Title, message, confirm and cancel buttons
- Variants: info, warning, danger
- File:
src/components/ConfirmDialog.tsx
8. Code Architecture and Best Practices
8.1. Project Structure
splitmize/
├── public/ # Static assets
│ ├── assets/
│ │ ├── favicon.ico
│ │ └── images/ # App icons and logos
│ └── manifest.json # PWA manifest
│
├── src/
│ ├── assets/ # Source assets
│ │ └── images/ # Image imports
│ │
│ ├── components/ # React components
│ │ ├── ConsumptionManager.tsx
│ │ ├── FinalReport.tsx
│ │ ├── ItemManager.tsx
│ │ ├── PeopleManager.tsx
│ │ ├── ReviewManager.tsx
│ │ ├── ServiceChargeManager.tsx
│ │ ├── SplitmizeContent.tsx
│ │ ├── SplitmizeIntro.tsx
│ │ ├── PDFReport.tsx
│ │ ├── ShareReport.tsx
│ │ ├── SessionHistory.tsx
│ │ ├── NavigationBar.tsx
│ │ ├── ProgressBar.tsx
│ │ ├── ConfirmDialog.tsx
│ │ └── ... (other components)
│ │
│ ├── config/ # Configuration files
│ │ └── social.ts # Social media links
│ │
│ ├── contexts/ # React Context providers
│ │ └── SplitmizeContext.tsx
│ │
│ ├── i18n/ # Internationalization
│ │ ├── config.ts
│ │ ├── hooks.ts
│ │ ├── instance.ts
│ │ └── locales/
│ │ ├── en/
│ │ │ └── common.json
│ │ ├── es/
│ │ │ └── common.json
│ │ └── pt/
│ │ └── common.json
│ │
│ ├── pages/ # Next.js pages
│ │ ├── _app.tsx # App wrapper
│ │ ├── index.tsx # Home page
│ │ └── api/ # API routes
│ │ └── contact.ts
│ │
│ ├── styles/ # SASS styles
│ │ ├── base/ # Base styles
│ │ │ ├── _colors.scss
│ │ │ ├── _typography.scss
│ │ │ ├── _spacing.scss
│ │ │ ├── _mixins.scss
│ │ │ └── ...
│ │ ├── components/ # Component styles (CSS Modules)
│ │ ├── layouts/ # Layout styles
│ │ ├── themes/ # Theme definitions
│ │ ├── utils/ # Utility styles
│ │ └── main.scss # Main entry point
│ │
│ ├── types/ # TypeScript type definitions
│ │ └── env.d.ts
│ │
│ └── utils/ # Utility functions
│ └── currency.ts
│
├── .eslintrc.json # ESLint configuration
├── next.config.js # Next.js configuration
├── next-i18next.config.js # i18next configuration
├── package.json # Dependencies
├── tsconfig.json # TypeScript configuration
├── vercel.json # Vercel deployment config
└── webpack.config.js # Webpack configuration
8.2. Coding Standards
TypeScript Usage:
- All components use TypeScript for type safety
- Interfaces defined for all data structures
- Props interfaces for all components
- Avoid
anytype; use proper typing
Functional Components and Hooks:
// ✓ Good: Functional component with hooks
export default function PeopleManager() {
const { t } = useTranslation('common');
const { state, dispatch } = useSplitmize();
const [newPersonName, setNewPersonName] = useState('');
// Component logic
return (
// JSX
);
}
// ✗ Avoid: Class components
class PeopleManager extends React.Component {
// ...
}
State Management:
- Use Context API with useReducer for global state
- Use useState for local component state
- Actions are strongly typed
- Reducer handles all state mutations
Comments:
- All comments in English (per user requirements)
- Document complex logic
- JSDoc headers for functions:
/**
* Calculates the total amount owed by a specific person
*
* @param person - The person object containing name and active status
* @param items - Array of all consumed items
* @param consumptionMap - Mapping of people to their consumed items
* @param people - Array of all participants
* @param serviceCharge - Service charge configuration
* @param extraFees - Array of additional fees
* @returns The total amount owed by the person
*
* @example
* const total = calculatePersonTotal(alice, items, map, people, charge, fees);
* // Returns: 45.50
*/
function calculatePersonTotal(
person: Person,
items: Item[],
consumptionMap: ConsumptionMap,
people: Person[],
serviceCharge: ServiceCharge,
extraFees: ExtraFee[]
): number {
// Implementation
}
CSS/SASS:
- Use CSS Modules for component styles
- Follow BEM (Block Element Modifier) naming convention:
// Block
.peopleManager {
// Block styles
// Element
&__input {
// Element styles
}
// Modifier
&--disabled {
// Modifier styles
}
}
- Use SASS variables for colors, spacing, and breakpoints
- Mobile-first media queries:
.component {
// Mobile styles (default)
@media (min-width: $breakpoint-tablet) {
// Tablet styles
}
@media (min-width: $breakpoint-desktop) {
// Desktop styles
}
}
Accessibility:
- Use semantic HTML elements
- Provide ARIA labels for interactive elements
- Ensure keyboard navigation
- Maintain color contrast ratios (WCAG AA minimum)
- Use
htmlForwith labels - Provide alternative text for images
// Good accessibility example
<label htmlFor="personName" className={styles.label}>
{t('people.inputLabel')}
</label>
<input
id="personName"
type="text"
className={styles.input}
value={newPersonName}
onChange={(e) => setNewPersonName(e.target.value)}
placeholder={t('people.inputPlaceholder')}
aria-label={t('people.inputLabel')}
/>
8.3. Error Handling
Reducer Error Handling:
function splitmizeReducer(
state: SplitmizeState,
action: SplitmizeAction
): SplitmizeState {
try {
// Validate state
if (!state || typeof state !== "object") {
console.error("Invalid state:", state);
return createInitialState();
}
// Handle actions
switch (action.type) {
case "ADD_PERSON":
// Validate payload
if (!action.payload || typeof action.payload !== "string") {
console.error("Invalid payload for ADD_PERSON:", action.payload);
return state;
}
// Process action
return { ...state, /* updated state */ };
// Other cases...
}
} catch (error) {
console.error("Error in reducer:", error);
return createInitialState();
}
}
localStorage Error Handling:
React.useEffect(() => {
if (!isClient) return;
try {
const savedState = localStorage.getItem("splitmizeCurrentSession");
if (!savedState) return;
const parsedState = JSON.parse(savedState);
// Validate before loading
if (isValidSplitmizeState(parsedState)) {
dispatch({ type: "LOAD_STATE", payload: parsedState });
}
} catch (error) {
console.error("Error loading saved state:", error);
if (isClient) {
localStorage.removeItem("splitmizeCurrentSession");
}
}
}, [dispatch, isClient]);
8.4. Performance Optimizations
Code Splitting:
- Dynamic imports for heavy components
- Lazy loading of non-critical features
import dynamic from 'next/dynamic';
const SplitmizeWrapper = dynamic(
() => import('./SplitmizeWrapper'),
{
ssr: false,
loading: () => <Spinner size="large" />
}
);
Memoization:
const safeDispatch = React.useCallback((action) => {
// Validation and dispatch logic
}, []);
const value = React.useMemo(
() => ({
state: state || createInitialState(),
dispatch: safeDispatch,
}),
[state, safeDispatch]
);
Bundle Optimization:
- Webpack configuration for optimal bundling
- Tree shaking to remove unused code
- Image optimization
- CSS extraction and minification
9. Component Documentation
9.1. Core Components
SplitmizeContext
Purpose: Provides global state management for the entire application
File: src/contexts/SplitmizeContext.tsx
Exports:
SplitmizeProvider: Context provider componentuseSplitmize: Custom hook to access state and dispatch
Usage:
// In _app.tsx
<SplitmizeProvider>
<Component {...pageProps} />
</SplitmizeProvider>
// In any component
const { state, dispatch } = useSplitmize();
State Properties:
people: Array of participantsitems: Array of consumed itemsconsumptionMap: Mapping of people to itemsserviceCharge: Service charge configurationextraFees: Array of extra feespayments: Payment status for each personcurrentStep: Current step in the wizard (0-6)locale: Current language (pt/en/es)currency: Current currency (BRL/USD)name: Session namedate: Session creation datesessionId: Unique session identifier (UUID)
Actions: See section 6.2 for complete action list
SplitmizeContent
Purpose: Main container managing the wizard flow and navigation
File: src/components/SplitmizeContent.tsx
Features:
- Renders current step based on
state.currentStep - Handles navigation between steps
- Validates step completion before allowing progression
- Auto-saves progress to localStorage
- Loads saved state on mount
Step Routing:
const renderCurrentStep = () => {
switch (state.currentStep) {
case 0: return <SplitmizeIntro />;
case 1: return <PeopleManager />;
case 2: return <ItemManager />;
case 3: return <ConsumptionManager />;
case 4: return <ServiceChargeManager />;
case 5: return <ReviewManager />;
case 6: return <FinalReport />;
default: return <SplitmizeIntro />;
}
};
PeopleManager
Purpose: Manage participants in the bill split
File: src/components/PeopleManager.tsx
Features:
- Add new participants by name
- Display list of added participants
- Remove participants
- Enter key support for quick addition
- Confirmation dialog before returning to intro
- Auto-focus on input after adding
State Updates:
- Dispatches
ADD_PERSONwhen adding - Dispatches
REMOVE_PERSONwhen removing
Validation: At least one person required to proceed to next step
ItemManager
Purpose: Register consumed items with pricing information
File: src/components/ItemManager.tsx
Features:
- Add items with name, quantity, and price
- Dynamic calculation:
- Enter quantity and unit price → total price calculated
- Enter quantity and total price → unit price calculated
- Number input validation (comma and period handling)
- Display list of items with full details
- Currency formatting based on selected currency
- Remove items functionality
Input Validation:
- Quantity: Integer only
- Prices: Decimal with comma or period
- Name: Required, non-empty
State Updates:
- Dispatches
ADD_ITEMwith complete item object - Dispatches
REMOVE_ITEMby item name
ConsumptionManager
Purpose: Associate participants with the items they consumed
File: src/components/ConsumptionManager.tsx
Features:
- "Mark All Items" button to select all items for all people
- Per-person sections with expandable details
- "Select all" toggle per person
- Checkbox for each item per person
- Shows item prices for reference
- Default: all items checked for all people
State Updates:
- Dispatches
UPDATE_CONSUMPTIONfor each checkbox change
UI Pattern:
[Mark All Items] (global button)
┌─ Alice ──────────────────┐
│ ☑ Select all │
│ ☑ Pizza - $60.00 │
│ ☑ Beer - $45.00 │
│ ☑ Dessert - $20.00 │
└──────────────────────────┘
┌─ Bob ────────────────────┐
│ ☑ Select all │
│ ☑ Pizza - $60.00 │
│ ☐ Beer - $45.00 │
│ ☑ Dessert - $20.00 │
└──────────────────────────┘
ServiceChargeManager
Purpose: Configure service charges and extra fees
File: src/components/ServiceChargeManager.tsx
Features:
Service Charge Section:
- Percentage input (0-100)
- Checkbox list of participants who pay the charge
- Default: 10%, all participants selected
Extra Fees Section:
- Description input
- Value input
- Type selector (Fixed Value / Percentage)
- Add button
- List of added extra fees with remove buttons
State Updates:
- Dispatches
SET_SERVICE_CHARGEwhen percentage or applicable people change - Dispatches
ADD_EXTRA_FEEwhen adding fee - Dispatches
REMOVE_EXTRA_FEEwhen removing fee
ReviewManager
Purpose: Display comprehensive breakdown before finalizing
File: src/components/ReviewManager.tsx
Sections:
Items Summary:
- Each item with total price
- List of consumers for each item
Charges Summary:
- Service charge percentage
- Each extra fee with description and value
Per-Person Summary:
- Name
- Items consumed with individual shares
- Service charge (if applicable)
- Extra fees share
- Total amount
Grand Total:
- Sum of all individual totals
Calculations:
- Performs all calculations for display
- Does not modify state
- Read-only view for confirmation
FinalReport
Purpose: Display final amounts and track payments
File: src/components/FinalReport.tsx
Features:
Payment Summary:
- Total Paid (sum of amounts from people marked as paid)
- Total Unpaid (sum of amounts from people not yet paid)
Per-Person Cards:
- Name
- Amount owed
- "Paid" checkbox
- Visual distinction between paid/unpaid
Export Options:
- PDF export via
PDFReportcomponent - Share via
ShareReportcomponent
Actions:
- "Split a New Bill" button (with confirmation)
- Dispatches
UPDATE_PAYMENTwhen payment status changes - Dispatches
START_NEW_SESSIONfor new bill
Real-time Updates:
- Totals recalculate immediately when payment status changes
- Visual feedback for paid vs unpaid
PDFReport
Purpose: Generate and export PDF reports
File: src/components/PDFReport.tsx
Dependencies: html2pdf.js
Features:
- Renders complete bill breakdown
- Generates PDF file with formatted layout
- Filename:
splitmize-report-{date}.pdf - Includes:
- Items table
- Charges section
- Per-person breakdown
- Grand total
Usage:
<PDFReport data={reportData} />
ShareReport
Purpose: Share bill information via multiple channels
File: src/components/ShareReport.tsx
Features:
Share Methods:
- WhatsApp: Opens WhatsApp with pre-filled message
- Email: Opens email client with subject and body
- Copy to Clipboard: Copies formatted text
Message Format:
🧾 Share Report - 11/26/2025
💰 Total Bill: $149.50
👥 Amounts by Person:
Alice: $35.00 ⏳
Bob: $51.75 ✅
Carol: $62.75 ⏳
Generated by Splitmize - https://splitmize.com
Features:
- Uses emojis for visual appeal
- Shows payment status with checkmarks
- Includes currency formatting
- Copy confirmation message
SessionHistory
Purpose: View, load, and manage saved sessions
File: src/components/SessionHistory.tsx
Features:
- Lists all saved sessions from localStorage
- Shows session metadata:
- Name (editable)
- Date
- Participants
- Total amount
- Actions per session:
- Load: Loads session into current state
- Delete: Removes session from localStorage (with confirmation)
- Edit session name inline
- Empty state when no sessions exist
- Sorted by date (newest first)
Usage:
<SessionHistory onClose={() => setShowHistory(false)} />
9.2. UI Components
NavigationBar
Purpose: Provides Back/Next navigation controls
File: src/components/NavigationBar.tsx
Props:
onBack: Callback for back buttononNext: Callback for next buttoncanProceed: Boolean indicating if next button should be enabledshowNavigation: Boolean to show/hide the navigation barisFirstStep: Boolean indicating if on first stepisLastStep: Boolean indicating if on last step
Behavior:
- Shows "Back" button (except on first step)
- Shows "Next"/"Continue"/"Finish" button
- Next button disabled when
canProceedis false - Fixed at bottom on mobile
- Centered on desktop
ProgressBar
Purpose: Visual indicator of current step in the wizard
File: src/components/ProgressBar.tsx
Features:
- Shows steps 1-6 (excluding intro step 0)
- Highlights current step
- Shows completed steps differently
- Responsive design (labels on desktop, icons on mobile)
- Step labels:
- People
- Items
- Consumption
- Fees
- Review
- Report
ConfirmDialog
Purpose: Modal dialog for confirmations
File: src/components/ConfirmDialog/index.tsx
Props:
isOpen: Boolean to show/hide dialogtitle: Dialog titlemessage: Dialog message/descriptionconfirmLabel: Text for confirm buttoncancelLabel: Text for cancel buttononConfirm: Callback when confirmedonCancel: Callback when cancelledvariant: Visual variant ('info' | 'warning' | 'danger')
Variants:
- info: Blue theme for informational confirmations
- warning: Yellow theme for warnings
- danger: Red theme for destructive actions
Usage:
<ConfirmDialog
isOpen={showConfirm}
title="Delete Session"
message="Are you sure you want to delete this session?"
confirmLabel="Delete"
cancelLabel="Cancel"
onConfirm={handleDelete}
onCancel={() => setShowConfirm(false)}
variant="danger"
/>
LanguageSwitcher
Purpose: Switch between available languages
File: src/components/LanguageSwitcher/LanguageSwitcher.tsx
Features:
- Dropdown or button group with language options
- Available languages: English (en), Español (es), Português (pt)
- Shows flag icons for each language
- Updates i18next locale
- Persists selection
Spinner
Purpose: Loading indicator
File: src/components/Spinner.tsx
Props:
size: 'small' | 'medium' | 'large'
Usage: Shown during dynamic imports or async operations
Logo
Purpose: Display application logo
File: src/components/Logo/Logo.tsx
Variants:
- Small: For header
- Large: For intro/splash screen
SplitmizeHeader
Purpose: Main application header
File: src/components/SplitmizeHeader.tsx
Contents:
- Logo
- Language switcher
- Currency selector
- History button
- Mobile menu toggle
SplitmizeFooter
Purpose: Application footer
File: src/components/SplitmizeFooter.tsx
Contents:
- Copyright notice
- Author attribution: "Created and maintained by Denner Parreiras"
- Social media links (GitHub, LinkedIn, Instagram)
10. State Management
10.1. Context Architecture
The application uses React Context API with the useReducer hook for predictable state management.
Provider Hierarchy:
<SplitmizeProvider>
<App>
{/* All components have access to state and dispatch */}
</App>
</SplitmizeProvider>
10.2. State Updates
All state modifications go through the reducer:
// Correct way to update state
dispatch({ type: 'ADD_PERSON', payload: 'Alice' });
// Incorrect - never mutate state directly
state.people.push({ name: 'Alice', active: true }); // ✗
10.3. Action Patterns
Adding an Item:
const handleAddItem = () => {
dispatch({
type: 'ADD_ITEM',
payload: {
name: itemName,
quantity: quantity,
unitPrice: unitPrice,
totalPrice: totalPrice
}
});
};
Updating Consumption:
const handleConsumptionChange = (person: string, item: string, consumed: boolean) => {
dispatch({
type: 'UPDATE_CONSUMPTION',
payload: { person, item, consumed }
});
};
Setting Service Charge:
const handlePercentageChange = (percentage: number) => {
dispatch({
type: 'SET_SERVICE_CHARGE',
payload: {
...state.serviceCharge,
percentage
}
});
};
10.4. State Persistence
Auto-save:
React.useEffect(() => {
if (state.sessionId && state.currentStep > 0) {
dispatch({ type: 'SAVE_SESSION_PROGRESS' });
}
}, [state, dispatch]);
Manual save:
const handleSave = () => {
dispatch({ type: 'SAVE_TO_STORAGE' });
};
Load saved state:
React.useEffect(() => {
const savedState = localStorage.getItem('splitmizeCurrentSession');
if (savedState) {
dispatch({ type: 'LOAD_STATE', payload: JSON.parse(savedState) });
}
}, []);
10.5. State Validation
Reducer-level validation:
case "ADD_PERSON": {
// Validate payload
if (!action.payload || typeof action.payload !== "string") {
console.error("Invalid payload for ADD_PERSON:", action.payload);
return state;
}
// Process action
return {
...state,
people: [...state.people, { name: action.payload, active: true }]
};
}
State validation function:
function isValidSplitmizeState(obj: any): obj is SplitmizeState {
return (
obj &&
typeof obj === "object" &&
Array.isArray(obj.people) &&
Array.isArray(obj.items) &&
typeof obj.consumptionMap === "object" &&
typeof obj.serviceCharge === "object" &&
Array.isArray(obj.extraFees) &&
typeof obj.payments === "object" &&
typeof obj.currentStep === "number"
);
}
11. Internationalization (i18n)
11.1. Configuration
The application uses i18next with next-i18next for internationalization.
Configuration file: next-i18next.config.js
module.exports = {
i18n: {
defaultLocale: 'pt',
locales: ['en', 'pt', 'es'],
},
localePath: './src/i18n/locales',
};
11.2. Available Languages
- Portuguese (pt) - Default
- English (en)
- Spanish (es)
11.3. Translation Files
Location: src/i18n/locales/{locale}/common.json
Structure:
{
"slogan": "Optimized splitting at your fingertips",
"intro": {
"description": "Divide bills simply and transparently",
"startButton": "Start a New Bill"
},
"people": {
"title": "Add Participants",
"inputLabel": "Participant's name",
"addButton": "Add"
},
"items": {
"title": "Add Items",
"nameLabel": "Item name"
}
}
11.4. Usage in Components
Hook usage:
import { useTranslation } from 'next-i18next';
export default function MyComponent() {
const { t } = useTranslation('common');
return (
<div>
<h1>{t('people.title')}</h1>
<button>{t('people.addButton')}</button>
</div>
);
}
With interpolation:
// Translation file
{
"welcome": "Welcome, {{name}}!"
}
// Component
<h1>{t('welcome', { name: 'Alice' })}</h1>
// Renders: Welcome, Alice!
With fallback:
<span>{t('items.total', 'Total')}</span>
// If 'items.total' doesn't exist, displays 'Total'
11.5. Language Switching
Programmatic change:
import { useRouter } from 'next/router';
const router = useRouter();
const changeLanguage = (locale: string) => {
router.push(router.pathname, router.asPath, { locale });
};
Via LanguageSwitcher component:
Users can click on language options in the header to switch languages. The entire UI updates immediately.
12. Styling and Design System
12.1. SASS Architecture
Main entry point: src/styles/main.scss
// Base styles (reset, typography, colors, etc.)
@import 'base/index';
// Layout styles (grid, container, spacing)
@import 'layouts/index';
// Component styles
@import 'components/index';
// Utility styles (helpers, animations, mixins)
@import 'utils/index';
// Theme styles (light, dark)
@import 'themes/index';
12.2. CSS Modules with BEM
File naming: ComponentName.module.scss
BEM structure:
// Block
.peopleManager {
padding: $spacing-md;
// Element
&__input {
width: 100%;
padding: $spacing-sm;
}
&__button {
background: $color-primary;
}
// Modifier
&--disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
Usage in component:
import styles from './PeopleManager.module.scss';
<div className={styles.peopleManager}>
<input className={styles.peopleManager__input} />
<button className={styles.peopleManager__button}>
Add
</button>
</div>
12.3. Design Tokens
Colors (_colors.scss):
// Primary brand colors
$color-primary: #3B82F6;
$color-secondary: #F3F4F6;
$color-accent: #EF4444;
// Text colors
$color-text-primary: #111827;
$color-text-secondary: #6B7280;
// Background colors
$color-background: #FFFFFF;
$color-background-alt: #F9FAFB;
// Border colors
$color-border: #D1D5DB;
Spacing (_spacing.scss):
$spacing-xs: 4px;
$spacing-sm: 8px;
$spacing-md: 16px;
$spacing-lg: 24px;
$spacing-xl: 32px;
$spacing-2xl: 48px;
Typography (_typography.scss):
$font-family-base: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
$font-size-base: 16px;
$font-size-sm: 14px;
$font-size-lg: 18px;
$font-size-xl: 20px;
$font-size-2xl: 24px;
$font-weight-normal: 400;
$font-weight-medium: 500;
$font-weight-semibold: 600;
$font-weight-bold: 700;
$line-height-base: 1.5;
$line-height-tight: 1.25;
$line-height-relaxed: 1.75;
12.4. Responsive Design
Breakpoints (_variables.scss):
$breakpoint-mobile: 320px;
$breakpoint-tablet: 768px;
$breakpoint-desktop: 1024px;
$breakpoint-wide: 1440px;
Mixin usage:
@import 'base/mixins';
.component {
// Mobile (default)
padding: $spacing-sm;
// Tablet
@include respond-to('tablet') {
padding: $spacing-md;
}
// Desktop
@include respond-to('desktop') {
padding: $spacing-lg;
max-width: 1200px;
margin: 0 auto;
}
}
12.5. Animations
Framer Motion usage:
import { motion } from 'framer-motion';
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -20 }}
transition={{ duration: 0.3 }}
>
{content}
</motion.div>
CSS transitions:
.button {
transition: all 0.2s ease;
&:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
}
13. Data Persistence
13.1. localStorage Strategy
The application uses localStorage extensively for data persistence:
Keys:
splitmizeCurrency: User's preferred currency (BRL or USD)splitmizeSession_{uuid}: Individual saved sessionssplitmizeCurrentSession: Legacy key for current session
13.2. Session Management
Creating a new session:
case "START_NEW_SESSION": {
const sessionId = uuidv4();
const sessionNumber = Object.keys(localStorage)
.filter(key => key.startsWith("splitmizeSession_"))
.length + 1;
const name = `Record #${sessionNumber}`;
const date = new Intl.DateTimeFormat(locale, {
dateStyle: 'short',
timeStyle: 'short',
}).format(new Date());
const newState = {
...createInitialState(),
sessionId,
name,
date,
locale
};
localStorage.setItem(
`splitmizeSession_${sessionId}`,
JSON.stringify(newState)
);
return newState;
}
Saving progress:
case "SAVE_SESSION_PROGRESS": {
if (!state.sessionId) return state;
localStorage.setItem(
`splitmizeSession_${state.sessionId}`,
JSON.stringify(state)
);
return state;
}
Loading a session:
const handleLoadSession = (sessionId: string) => {
const savedState = localStorage.getItem(sessionId);
if (savedState) {
const parsedState = JSON.parse(savedState);
dispatch({ type: 'LOAD_STATE', payload: parsedState });
}
};
Deleting a session:
const handleDeleteSession = (sessionId: string) => {
localStorage.removeItem(sessionId);
loadSavedSessions(); // Refresh list
};
13.3. Data Validation
Before loading:
function isValidSplitmizeState(obj: any): obj is SplitmizeState {
try {
return (
obj &&
typeof obj === "object" &&
Array.isArray(obj.people) &&
obj.people.every(p =>
typeof p.name === "string" &&
typeof p.active === "boolean"
) &&
Array.isArray(obj.items) &&
// ... more validations
);
} catch {
return false;
}
}
Safe loading:
try {
const savedState = localStorage.getItem(key);
if (!savedState) return;
const parsedState = JSON.parse(savedState);
if (!isValidSplitmizeState(parsedState)) {
console.error("Invalid saved state");
localStorage.removeItem(key);
return;
}
// Use validated state
dispatch({ type: 'LOAD_STATE', payload: parsedState });
} catch (error) {
console.error("Error loading state:", error);
localStorage.removeItem(key);
}
13.4. Auto-save Implementation
Effect hook for auto-save:
React.useEffect(() => {
// Only save if session exists and we're past intro
if (state.sessionId && state.currentStep > 0) {
dispatch({ type: 'SAVE_SESSION_PROGRESS' });
}
}, [state, dispatch]);
This automatically saves progress whenever the state changes.
14. Export and Sharing Features
14.1. PDF Export
Library: html2pdf.js
Implementation:
const generatePDF = () => {
const element = reportRef.current;
if (!element) return;
const options = {
margin: 1,
filename: `splitmize-report-${date}.pdf`,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'a4', orientation: 'portrait' }
};
html2pdf().set(options).from(element).save();
};
PDF Contents:
- Header with logo and date
- Items table with quantities and prices
- Charges section (service charge and extra fees)
- Per-person breakdown with totals
- Grand total
- Payment status indicators
14.2. WhatsApp Sharing
const handleWhatsAppShare = () => {
const text = generateShareText();
const encoded = encodeURIComponent(text);
window.open(`https://wa.me/?text=${encoded}`, '_blank');
};
Message Format:
🧾 Share Report - 11/26/2025
💰 Total Bill: $149.50
👥 Amounts by Person:
Alice: $35.00 ⏳
Bob: $51.75 ✅
Carol: $62.75 ⏳
Generated by Splitmize - https://splitmize.com
14.3. Email Sharing
const handleEmailShare = () => {
const subject = encodeURIComponent('Bill Split - Splitmize');
const body = encodeURIComponent(generateShareText());
window.open(`mailto:?subject=${subject}&body=${body}`);
};
Opens default email client with pre-filled subject and body.
14.4. Copy to Clipboard
const handleCopyToClipboard = async () => {
try {
await navigator.clipboard.writeText(generateShareText());
setShowCopiedMessage(true);
setTimeout(() => setShowCopiedMessage(false), 2000);
} catch (error) {
console.error('Error copying to clipboard:', error);
}
};
Features:
- Uses modern Clipboard API
- Shows confirmation message
- Fallback error handling
15. Installation and Setup
15.1. Prerequisites
- Node.js: >= 16.x
- npm: >= 7.x (or yarn/pnpm equivalent)
- Git: For cloning the repository
15.2. Installation Steps
1. Clone the repository:
git clone https://github.com/dennerparreiras/splitmize.git
2. Navigate to project directory:
cd splitmize
3. Install dependencies:
npm install
4. Start development server:
npm run dev
5. Open in browser:
http://localhost:3000
15.3. Environment Variables
Optional .env.local file:
# Analytics (optional)
NEXT_PUBLIC_VERCEL_ANALYTICS_ID=your-analytics-id
# Email configuration (if using contact form)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-email@example.com
SMTP_PASS=your-password
15.4. Build for Production
Create optimized build:
npm run build
Start production server:
npm run start
Build output: .next/ directory
16. Development Tools and Scripts
16.1. Available Scripts
Development:
npm run dev
# Starts Next.js development server on http://localhost:3000
# Includes hot reload, fast refresh, and source maps
Production Build:
npm run build
# Creates optimized production build
# Includes code splitting, minification, and optimization
Production Server:
npm run start
# Starts production server
# Must run 'npm run build' first
Linting:
npm run lint
# Runs ESLint to check code quality
# Configuration in .eslintrc.json
16.2. Development Workflow
Recommended workflow:
Create feature branch from
main:git checkout -b feature/new-featureMake changes and test locally:
npm run devRun linter before committing:
npm run lintCommit changes:
git commit -m "Add feature: description"Push and create pull request:
git push origin feature/new-feature
16.3. Code Quality Tools
ESLint Configuration (.eslintrc.json):
{
"extends": "next/core-web-vitals",
"rules": {
// Custom rules here
}
}
TypeScript Configuration (tsconfig.json):
{
"compilerOptions": {
"target": "ES2020",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
16.4. Debugging
VS Code launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Next.js: debug server-side",
"type": "node-terminal",
"request": "launch",
"command": "npm run dev"
},
{
"name": "Next.js: debug client-side",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000"
}
]
}
Browser DevTools:
- React Developer Tools extension recommended
- Redux DevTools for state inspection (if needed)
17. Deployment
17.1. Vercel Deployment (Recommended)
Splitmize is optimized for deployment on Vercel:
Steps:
Push to GitHub:
git push origin mainConnect to Vercel:
- Go to vercel.com
- Click "New Project"
- Import your GitHub repository
- Vercel auto-detects Next.js configuration
Configure (if needed):
- Set environment variables in Vercel dashboard
- Configure custom domain (optional)
Deploy:
- Click "Deploy"
- Vercel builds and deploys automatically
- Each push to main triggers new deployment
Vercel Configuration (vercel.json):
{
"buildCommand": "npm run build",
"devCommand": "npm run dev",
"installCommand": "npm install",
"framework": "nextjs"
}
17.2. Other Deployment Options
Netlify:
npm run build
# Deploy .next folder to Netlify
Docker:
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
Static Export (if applicable):
npm run build
# Deploy .next/static to any static hosting
17.3. Performance Optimization
Next.js Optimizations:
- Automatic code splitting
- Image optimization with Next/Image
- Font optimization
- Script optimization
Vercel Edge Network:
- Global CDN distribution
- Automatic SSL/HTTPS
- DDoS protection
- Automatic caching
17.4. Monitoring and Analytics
Vercel Analytics:
// Already configured in the application
import { Analytics } from '@vercel/analytics/react';
<Analytics />
Metrics tracked:
- Page views
- User engagement
- Core Web Vitals (LCP, FID, CLS)
- Custom events
18. Contributing Guidelines
18.1. How to Contribute
We welcome contributions! To contribute:
1. Fork the Repository:
# Fork via GitHub UI, then clone
git clone https://github.com/YOUR_USERNAME/splitmize.git
2. Create Feature Branch:
git checkout -b feature/your-feature-name
3. Make Changes:
- Follow coding standards (see section 8.2)
- Write clear, descriptive commit messages
- Add comments in English
- Update documentation if needed
4. Test Your Changes:
npm run dev
# Test all affected functionality
npm run lint
# Fix any linting issues
5. Commit:
git add .
git commit -m "Add feature: clear description of changes"
6. Push:
git push origin feature/your-feature-name
7. Create Pull Request:
- Go to GitHub repository
- Click "New Pull Request"
- Provide clear description of changes
- Reference any related issues
18.2. Coding Standards
Follow these principles:
- Use TypeScript for type safety
- Follow BEM methodology for CSS
- All comments in English
- Use functional components with hooks
- Avoid any type; use proper typing
- Write descriptive variable and function names
- Keep functions small and focused
- Use meaningful commit messages
Example commit messages:
✓ Good:
Add currency selector to header
Fix calculation bug in service charge
Update Portuguese translations for new features
✗ Bad:
Update
Fix bug
Changes
18.3. Pull Request Guidelines
PR should include:
- Clear Title: Describe what the PR does
- Description: Explain the changes and why
- Screenshots: If UI changes, include before/after
- Testing: Describe how you tested
- Related Issues: Link to any related issues
PR checklist:
- Code follows project style guidelines
- Comments added in English where necessary
- No linting errors
- Tested on mobile and desktop
- Documentation updated if needed
- No console errors or warnings
18.4. Code Review Process
What reviewers look for:
- Functionality: Does it work as intended?
- Code Quality: Is it clean, readable, maintainable?
- Performance: Any performance implications?
- Security: Any security concerns?
- Accessibility: Is it accessible?
- Testing: Adequately tested?
After approval:
- Maintainer will merge PR
- Your contribution will be credited
19. Contact and Support
19.1. Author
Denner Parreiras
- Email: contact@dennerparreiras.com
- GitHub: @dennerparreiras
- LinkedIn: Denner Parreiras
19.2. Support Channels
GitHub Issues:
For bug reports and feature requests:
- Go to: GitHub Issues
- Choose appropriate template
- Provide detailed description
Bug Report Template:
**Describe the bug**
A clear description of the bug
**To Reproduce**
Steps to reproduce:
1. Go to '...'
2. Click on '...'
3. See error
**Expected behavior**
What you expected to happen
**Screenshots**
If applicable, add screenshots
**Environment**
- Browser: [e.g., Chrome 96]
- Device: [e.g., iPhone 12]
- OS: [e.g., iOS 15]
Feature Request Template:
**Feature Description**
Clear description of the feature
**Use Case**
Why is this feature needed?
**Proposed Solution**
How should it work?
**Alternatives**
Any alternative solutions considered?
19.3. Community
Contributing:
- Read Contributing Guidelines
- Join discussions in GitHub Issues
- Submit pull requests
Feedback:
- Feature suggestions welcome
- UI/UX improvement ideas
- Translation contributions
- Documentation improvements
19.4. License
This project is developed and maintained by Denner Parreiras. All rights reserved.
Appendix A: Glossary
Terms used in this documentation:
- Participant/Person: Individual who will share the bill
- Item: Product or service consumed (e.g., Pizza, Beer)
- Consumption Map: Data structure mapping people to items they consumed
- Service Charge: Percentage-based fee (typically 10% tip/service fee)
- Extra Fee: Additional charge, either fixed value or percentage
- Session: A complete bill-splitting instance with all data
- Step: Stage in the wizard flow (0-6)
- localStorage: Browser storage API for persisting data
- Context: React Context API for state management
- Reducer: Function that handles state updates
- Action: Object describing a state change
- Dispatch: Function to send actions to reducer
- BEM: Block Element Modifier (CSS naming methodology)
- i18n: Internationalization (multi-language support)
- UUID: Universally Unique Identifier
Appendix B: Troubleshooting
Common Issues:
Issue: State not persisting
// Check if localStorage is available
if (typeof window !== 'undefined' && window.localStorage) {
// localStorage available
}
// Clear corrupted data
localStorage.clear();
Issue: Calculation errors
- Verify all numbers are properly parsed (parseFloat, parseInt)
- Check for division by zero
- Ensure currency formatting doesn't interfere with calculations
Issue: Translation not working
- Verify locale is correctly set
- Check translation key exists in JSON file
- Ensure
useTranslationhook is used correctly
Issue: Build errors
# Clear cache and rebuild
rm -rf .next
rm -rf node_modules
npm install
npm run build
Appendix C: Future Enhancements
Potential features for future versions:
- Multi-currency conversion: Real-time currency conversion API
- Split by percentage: Allow custom percentage splits
- Item categories: Group items by categories (food, drinks, etc.)
- Recurring bills: Save bill templates for recurring expenses
- Payment integration: Direct payment links (PayPal, Venmo, etc.)
- QR code sharing: Generate QR codes for easy sharing
- Advanced reports: Charts and visualizations
- Dark mode: Theme switcher
- Progressive Web App: Offline support, install to home screen
- Backend sync: Optional cloud storage for cross-device sync
Appendix D: API Reference
Currency Utility
Function: formatCurrency
/**
* Formats a number as currency based on the specified currency type
*
* @param value - The numeric value to format
* @param currency - The currency type ('BRL' or 'USD')
* @returns Formatted currency string
*
* @example
* formatCurrency(10.5, 'BRL'); // Returns: "R$ 10,50"
* formatCurrency(10.5, 'USD'); // Returns: "$ 10.50"
*/
export function formatCurrency(
value: number,
currency: 'BRL' | 'USD'
): string
Custom Hooks
Hook: useSplitmize
/**
* Custom hook to access Splitmize context
* Must be used within SplitmizeProvider
*
* @returns Object containing state and dispatch
* @throws Error if used outside provider
*
* @example
* const { state, dispatch } = useSplitmize();
* dispatch({ type: 'ADD_PERSON', payload: 'Alice' });
*/
export function useSplitmize(): {
state: SplitmizeState;
dispatch: React.Dispatch<SplitmizeAction>;
}
End of Documentation
Document Version: 1.0.0
Last Updated: November 26, 2025
Author: Denner Parreiras
Project: Splitmize
Repository: https://github.com/dennerparreiras/splitmize
This documentation is maintained alongside the codebase. For the most up-to-date information, refer to the source code and inline comments.