# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview
 **Project name**: Lme, sns-line
is a Laravel-based LINE bot management platform. It provides LINE chatbot creation, customer messaging, campaign management, calendar booking, landing pages, rich menus, affiliate tracking, and payment processing.

**Stack**: Laravel 5.5 (PHP 7.0+), Vue.js 2.6.12 (embedded via script tag, not SPA), Laravel Mix (Webpack), Redis, MySQL (multiple connections), Node.js WebSocket server (Socket.IO + Express).

## Common Commands

```bash
# Database
php artisan migrate

# WebSocket server (Node.js)
pm2 start ecosystem.config.js                     # Start via PM2
node node_serve/server.js                         # Direct run
```

## Architecture

### Backend (Laravel)

**Controllers** are organized by access level/context:
- `app/Http/Controllers/Admin/` — Admin panel
- `app/Http/Controllers/Basic/` — User-facing web
- `app/Http/Controllers/Api/` — REST API endpoints
- `app/Http/Controllers/V2/` — API v2
- `app/Http/Controllers/Mobile/` — Mobile app endpoints
- `app/Http/Controllers/Ajax/` — AJAX handlers
- `app/Http/Controllers/ChatGPT/` — ChatGPT integration
- `app/Http/Controllers/Aff/`, `Affiliate/` — Affiliate system

**Business logic** lives in `app/Services/`, not in controllers. Key services:
- `ChatService` — Chat/messaging logic
- `MessageService` — Message creation and storage
- `HelperService` — Shared utility functions
- `BookingService` — Calendar/appointment management
- `ConversationService` — Conversation flow handling
- Subdirectories: `CalendarManagement/`, `CalendarSalon/`, `ChatGPT/`, `Landing/`, `Filters/`, `FormAnswer/`, `EventBooking/`, `Notify/`

**Models** — legacy Eloquent models sit directly under `app/` (e.g. `app/User.php`, `app/Bot.php`). For new code, create models under `app/Models/` with namespace `App\Models\` instead. Don't move legacy models unless the task specifically asks for it — just follow the new convention for anything new.

**Repositories** live in `app/Repositories/` — Eloquent implementations under `app/Repositories/Eloquents/`, all extending `BaseRepositories`. All DB access in **new code** MUST go through a repository; Services call repositories instead of querying Eloquent models directly. Legacy code still queries models directly in many places — leave it as-is when touching unrelated areas, but do NOT follow that pattern for new features. When adding a new entity, create a matching `FooRepository extends BaseRepositories` and inject it into the Service that needs it.

**Global helper functions** are in `app/Helpers/functions.php` (autoloaded via composer.json). Other helpers: `ChatMessages.php`, `UnivapayPayment.php`, `StripePayment.php`, `GoogleSheetService.php`.

**Routes** are split across multiple files:
- `routes/web.php` — Main web routes (very large file)
- `routes/api.php` — API routes
- `routes/layout.php` — Layout routes
- `routes/shorten.php` — URL shortener routes

### Database

Multiple MySQL connections are configured in `config/database.php`:
- `mysql` — Primary database
- `mysql_callback` — Callbacks
- `mysql_message` — Messages
- `mysql_db_replicate` — Read replicas
- `mysql_db_package` — Package data
- `mysql_url` — URL management

Message tables are sharded by year (e.g., `Messages2020`, `Messages2021`, ..., `Messages2025`).

### Frontend

- **Vue.js 2.6.12** is loaded via `<script>` tag (not npm/CLI SPA)
- Multiple page application — each Blade template mounts its own Vue instance
- User feature pages: `resources/views/basic/[feature]/`
- Admin pages: `resources/views/admin/`
- Don't use Laravel Mix compiles React (`resources/assets/js/app.jsx` → `public/js/app.js`):
- **Two UI component systems**:
  1. **Legacy Blade components** 
  2. **lme-ui** (`public/lme-ui/`, git submodule): Vue 2 component library with `<lme-*>` tags (`lme-table`, `lme-select`, `lme-modal`, etc.). Used in newer pages. See below for details

### lme-ui (Git Submodule)

**Path**: `public/lme-ui/` — submodule from `WTML-2023/lme-ui.git` (branch `lgram-main`)

**What it is**: A standalone Vue 2 UI component library. Raw JS files that register globally via `Vue.component()`, consumed via `<script>` tags (no ES module imports, no build step).

**Docs location** (readable from this project):
- `public/lme-ui/docs/component-summary.md` — all components with CSS/JS paths
- `public/lme-ui/docs/components/{name}.md` — detailed props, events, slots per component
- `public/lme-ui/docs/design-tokens.md` — CSS variables, spacing, colors, typography
- `public/lme-ui/docs/layout-summary.md` — layout patterns (Table A/B, Pattern C–M)

**Using lme-ui in Blade templates**: import with `/lme-ui/` prefix:
```blade
@push('css')
    <link rel="stylesheet" href="/lme-ui/src/css/reset.css">
    <link rel="stylesheet" href="/lme-ui/src/css/base.css">
    <link rel="stylesheet" href="/lme-ui/src/css/{component}/{component}.css">
@endpush
@push('js')
    <script src="/lme-ui/src/js/{component}/lme-{component}.js"></script>
@endpush
```

**CRITICAL — When editing Blade files that contain `<lme-*>` tags**:
Before modifying any `<lme-*>` component (fix bug, adjust props, add/remove components, change behavior), you MUST:
1. Read `.claude/docs/lme-ui-rules.md` — single source of truth for all lme-ui rules and docs paths
2. Read `public/lme-ui/docs/components/{name}.md` for the specific component's props, events, slots, and data format
3. Do NOT guess props or events — lme-ui components have specific APIs (e.g., `lme-select` uses `options=[{label,value}]` not `options=['a','b']`, `lme-table` uses `columns=[{key,title,width}]`)

**Skills & workflow** (see `.claude/workflow/figma-to-laravel-page.md`):
- `/gen-ui-blade` — Figma/screenshot/description → Blade view with lme-ui components (supports both new and edit). All runs in this project, no need to switch to lme-ui directory
- `/implement-logic-fe` — takes a Blade file with lme-ui HTML → generates Vue JS logic, backend dummy data (Controller → Service → Repository), and routes. Supports fresh and update mode
- When lme-ui submodule updates its rules → sync changes to `.claude/docs/lme-ui-rules.md`


### Authentication

- Session-based auth for web (admin + basic users)
- JWT auth (`tymon/jwt-auth`) for API/mobile
- Middleware: `admin_access`, `basic_access`, `mobile-auth`, `affiliater`, `supper_admin`

### Key Integrations

- **LINE Bot SDK**: Line Messaging API, Line Liffapp API
- **Payments**: Stripe, Univapay, Telecom
- **Google**: Calendar sync, Sheets integration, Gmail
- **Firebase**: Push notifications
- **FFmpeg**: Video processing (`pbmedia/laravel-ffmpeg`)
- **Backblaze B2**: for object storage using S3 API


### Configuration
- project constants: `config/sns-line.php` (large config file with platform-specific constants)
- Helpers auto-loaded from `app/Helpers/functions.php`

## Conventions

### Coding Rules (MANDATORY for all new code)
Before writing ANY new code (controller, service, repository, model, migration, FE logic) — whether via a skill or an ad-hoc prompt — you MUST read `.claude/docs/BE-coding-rules.md`. It is the single source of truth for:
- Architecture layering (Controller → Service → Repository)
- Log requirements (CRUD log fields, update before/after, payment log detail)
- Error handling & transaction policy (no try/catch in controllers; `DB::transaction` only for multi-write consistency)
- Security (ownership check `bot_id`/`user_id` inside Repository queries; payment amount must be server-recomputed; webhook signature verify; idempotency)
- Performance (eager load, pagination, sharded `Messages{year}` tables, required indexes, queue for heavy tasks, no `float` for money)

When an endpoint returns JSON or renders an error page, you MUST also read `.claude/docs/api-error-code-rules.md` — the single source of truth for HTTP status codes (400/401/402/403/404/409/410/422/500/502), response shape for errors, and the enduser-specific rules (Japanese `msg`, never leak `getMessage()`).

### Backend
- Keep controllers thin — delegate to Services for business logic
- Access DB through repositories, not directly in controllers
- Use Eloquent relationships and eager loading over raw query builder
- Form validation via Form Request classes in `app/Http/Requests/`
- API responses formatted via Resource classes in `app/Http/Resources/`
- Use Laravel Events, Jobs, and Notifications where appropriate
- **Repository binding rule**: When creating a new Repository + Interface pair, you MUST register the binding in `app/Providers/RepositoryServiceProvider.php` using `$this->app->singleton('Interface', 'Implementation')`. Without this binding, Laravel cannot resolve the interface and will throw "not instantiable" errors.

## Sprint Task Implementation
Sprint task specs live at `sprints/{sprint-id}/{task-id}/dev/` (technical-design, spec-dev-BE, spec-dev-FE, optional spec-dev-Job).

**Workflow chuẩn**: spec → real DB-backed implementation
- Skill: `/implement-logic-spec <task-id>` — runs 5-phase pipeline (load context → gap analysis → plan with approval gate → layered implementation → self review)
- Workflow doc: `.claude/workflow/implement-logic-spec.md` (rationale, phase mapping)
- Convention doc: `.claude/docs/implement-logic-spec-conventions.md` (layer location, naming, response shape, anti-patterns) — single source of truth

**Tiền đề input** mỗi task khi chạy `/implement-logic-spec`:
1. UI Blade lme-ui đã có (sinh trước bởi `/gen-ui-blade`)
2. Spec docs đầy đủ trong `sprints/{sprint}/{task}/dev/`

**Output**: migration thật, model, repo query thật, service hết dummy, FE wire AJAX thật, Job/Command nếu spec yêu cầu.

**Hard rules** khi implement sprint task (skill enforce, nhưng cũng áp dụng nếu user gọi tay):
- Không invent field/column/validation rule ngoài spec
- Không skip Phase 2 plan approval gate
- Q&A trong `qa/` còn `OPEN` block schema/validation/contract → dừng và báo

## Sprint Specs (Task & Spec Reading Skills)

Task specifications are stored in `sprints/` folder. Use these skills to read specs before implementing or reviewing code:

| Skill | Purpose | Usage |
|-------|---------|-------|
| `/read-task` | Read task status, progress, available spec files | `/read-task mypage` or `/read-task 34630` |
| `/read-spec` | Read common/BA spec — business rules, feature flow, validation | `/read-spec mypage` |
| `/read-ui-spec` | Read FE dev spec — client validation, API interfaces, routing, permissions | `/read-ui-spec mypage` |
| `/read-be-spec` | Read BE dev spec — DB entities, API logic, access control, integrations | `/read-be-spec backup` |
| `/review-task` | Review implementation — kiểm tra code đã implement đủ theo spec chưa | `/review-task mypage` |
| `/review-code` | Pre-release checklist — kiểm tra security, migration, conventions, config/env trước khi merge vào release | `/review-code ai-feature-36409 release_step_18032026` |

**Workflow**: When implementing or reviewing a feature, use `/read-task` first to see task overview, then read the relevant spec (common, FE, or BE) based on the work you're doing.

**Review workflow**: Dùng `/review-task {name}` để review — skill sẽ hỏi release branch, chạy 4 sub-agents (BE, FE, Spec Coverage, Checklist) song song, ghi report vào `sprints/reviews/`. Re-review sẽ update report cũ, đánh dấu items đã fix. Checklist tích lũy ở `sprints/helpers/dev-review-checklist.md`.

**Pre-release checklist**: Dùng `/review-code {feature_branch} {release_branch}` trước khi merge hàng tháng — 4 agents kiểm tra security/migration, BE conventions, FE conventions, config/env song song. Ghi report vào `sprints/reviews/pre-release-{branch}.md`.
