# AGENTS.md — NexStock Development Guide

## Project Overview

**NexStock** is a POS + Inventory Management System built for small and medium-sized retail businesses by **Nexgen Technology Services**. It is a SaaS product focused on three core workflows: **Sell**, **Buy**, and **Control Stock** — with business insights derived from that data.

## Technology Stack

| Layer | Technology |
|-------|-----------|
| Backend Framework | Laravel 12 |
| PHP Version | 8.3+ (minimum 8.2) |
| Database | MySQL 8.x |
| Frontend Framework | Vue 3 (Composition API) |
| Language | TypeScript |
| SPA Bridge | Inertia.js |
| CSS Framework | Tailwind CSS v4 |
| UI Components | shadcn-vue |
| Build Tool | Vite+ |
| Charts | Apache ECharts |
| WebSockets | Laravel Reverb |
| Queue | Redis + Laravel Horizon |
| Testing | Pest (PHP), Vitest (Vue) |
| Code Style | Laravel Pint |
| Static Analysis | PHPStan / Larastan |
| Containerization | Docker |

## Project Structure

```
app/
├── Actions/            # Single-purpose business actions
├── Console/            # Artisan commands
├── DTOs/               # Data Transfer Objects
├── Enums/              # PHP enums
├── Events/             # Domain events
├── Exceptions/         # Custom exceptions
├── Http/
│   ├── Controllers/    # Thin controllers (delegate to Actions)
│   ├── Middleware/      # Request middleware
│   └── Requests/       # Form request validation
├── Jobs/               # Queued jobs
├── Listeners/          # Event listeners
├── Mail/               # Mailable classes
├── Models/             # Eloquent models
│   ├── Concerns/       # Model traits (BelongsToTenant, etc.)
│   └── Scopes/         # Query scopes
├── Notifications/      # Notification classes
├── Observers/          # Model observers
├── Policies/           # Authorization policies
├── Providers/          # Service providers
├── Rules/              # Custom validation rules
├── Services/           # Complex orchestration services
└── ValueObjects/       # Immutable value objects

config/                 # Laravel configuration
database/
├── factories/          # Model factories for testing
├── migrations/         # Database migrations
└── seeders/            # Database seeders (including sample data)

resources/
├── js/
│   ├── Components/     # Reusable Vue components
│   ├── Composables/    # Vue composables (shared logic)
│   ├── Layouts/        # Page layouts
│   ├── Pages/          # Inertia page components
│   ├── Stores/         # Pinia stores (if needed)
│   ├── Types/          # TypeScript type definitions
│   └── Utils/          # Utility functions
├── css/                # Tailwind CSS entry
└── views/              # Blade views (app shell only)

routes/
├── web.php             # Web routes
├── api.php             # API routes (if needed)
├── channels.php        # Broadcast channels
└── console.php         # Console routes

tests/
├── Feature/            # Feature/integration tests
├── Unit/               # Unit tests
├── Browser/            # Browser/E2E tests
└── Pest.php            # Pest configuration
```

## Coding Conventions

### PHP / Laravel

- **Actions over fat controllers**: Business logic lives in Action classes (`app/Actions/`), not controllers
- **Single Responsibility**: Each Action class does one thing
- **Form Requests**: All input validation in Form Request classes
- **Policies**: All authorization through Policy classes
- **Enums**: Use PHP enums for status types, payment methods, etc.
- **DTOs**: Use for passing structured data between layers
- **Type declarations**: Full type hints on all methods
- **Strict types**: `declare(strict_types=1);` on every file
- **Named arguments**: Use where it improves readability
- **Laravel Pint**: Follow Laravel preset code style
- **No business logic in**: controllers, models, migrations, or views

### Vue / TypeScript

- **Composition API**: Use `<script setup lang="ts">` exclusively
- **TypeScript strict mode**: No `any` types unless absolutely necessary
- **Props interface**: Define typed props interfaces
- **Composables**: Extract shared logic into composables
- **Component naming**: PascalCase, descriptive names
- **Page components**: One per route, in `Pages/` directory

### Database

- **Migrations**: Descriptive names, reversible, include indexes
- **Soft deletes**: On transaction records (sales, purchases, returns)
- **tenant_id**: Required on every business-owned table
- **UUIDs**: Use UUIDs for public-facing IDs, auto-increment for internal
- **Indexes**: Always index foreign keys, tenant_id, and frequently queried columns
- **Composite unique**: Include tenant_id in unique constraints

### Testing

- **Pest**: All tests use Pest syntax
- **Naming**: `it('does something specific')` format
- **Datasets**: Use Pest datasets for parameterized tests
- **Factories**: Every model has a factory
- **Assertions**: Test behavior, not implementation
- **Cross-tenant tests**: Every feature test must verify tenant isolation

### Multi-Tenancy Rules

1. **Never trust tenant_id from the client** — resolve from authenticated user's membership
2. **Global Scope** on all tenant models via `BelongsToTenant` trait
3. **Auto-populate tenant_id** on model creating event
4. **Composite unique indexes** include tenant_id
5. **Queue jobs** must carry and restore tenant context
6. **Cache keys** must include tenant_id prefix
7. **File paths** must include tenant_id
8. **Broadcast channels** must verify tenant membership

## Key Architectural Decisions

1. **Shared database multi-tenancy** — single database, `tenant_id` column isolation
2. **Modular monolith** — domain boundaries enforced by convention, not microservices
3. **Weighted-average costing** — simplest correct approach for retail
4. **Immutable inventory movements** — corrections create new entries, never modify history
5. **Atomic sales transactions** — sale + lines + payment + stock in single DB transaction
6. **Rule-based insights** — no AI/ML in V1, just smart queries and thresholds
7. **Entitlement-based billing** — `canUse()` / `limitFor()` pattern, not plan name checks

## Running the Project

```bash
# Install dependencies
composer install
npm install

# Environment setup
cp .env.example .env
php artisan key:generate

# Database
php artisan migrate --seed

# Development server
composer dev
# (runs: php artisan serve, queue:listen, reverb:start, vite dev)

# Tests
php artisan test
# or
./vendor/bin/pest

# Code quality
./vendor/bin/pint
./vendor/bin/phpstan analyse
```

## Important Warnings

- **NEVER** bypass tenant scoping — every query must be tenant-aware
- **NEVER** modify posted inventory movements — create corrections instead
- **NEVER** allow sales without atomic transactions (sale + stock + payment)
- **NEVER** store raw card numbers
- **NEVER** use `$plan === 'business'` — use the entitlement system
- **NEVER** hard-delete transaction records — use soft deletes
- **NEVER** trust authorization from the frontend — always verify server-side
