# Service Layer

## Tong quan

Service layer (`src/app/service/`) chua business logic xu ly nghiep vu chinh cua AutoShopee Kit. Cac service duoc thiet ke de tach biet logic xu ly khoi components va store, giup tai su dung va bao tri de dang hon.

## Cau truc thu muc

```
src/app/service/
├── print/                          # In don hang da nen tang
│   ├── service.js                  # Logic chung cho in don
│   ├── shopee.js                   # In don Shopee
│   ├── lazada.js                   # In don Lazada
│   ├── tiktok.js                   # In don TikTok
│   └── log.js                      # Queue xu ly print job
│
├── shop/                           # Quan ly shop
│   └── order/
│       └── fetch.js                # Lay danh sach don hang (stub)
│
├── shopee/                         # Nghiep vu rieng Shopee
│   ├── index.js                    # Entry point (chua implement)
│   ├── product.js                  # Clone san pham (stub)
│   └── flashsale/                  # Tu dong Flash Sale
│       ├── get.js                  # Truy van du lieu Flash Sale
│       ├── campaign.js             # Tao lich tu campaign
│       └── scheduler.js            # Thuc thi Flash Sale tu scheduler
│
└── user/
    └── index.js                    # Entry point (chua implement)
```

---

## 1. Print Service - In don hang

### Muc dich

Quan ly viec luu tru va xu ly PDF in don hang cho tat ca cac nen tang (Shopee, Lazada, TikTok). Khi nguoi ban in don hang tren trang seller, service se:
1. Tai PDF tu API cua nen tang
2. Phan tich noi dung PDF de trich xuat ma don hang va ma van don
3. Upload PDF len Amazon S3 de luu tru
4. Luu metadata vao PouchDB

### 1.1 `print/service.js` - Logic chung

File nay chua cac ham dung chung cho tat ca nen tang.

#### Hang so

| Ten | Gia tri | Mo ta |
|-----|---------|-------|
| `RETRY_PRINT_PDF` | `{ retries: 5, minTimeout: 5000 }` | Cau hinh retry khi tai PDF that bai |

#### Ham

**`extractOrderIdFromHtml(html, regexPatterns)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `html` | `string` | Noi dung HTML can trich xuat |
| `regexPatterns` | `Record<string, RegExp>` | Cac pattern regex de tim ma don/van don |
| **Tra ve** | `string[]` | Danh sach ma don hang/van don (da loai trung) |

Loai bo the script/style, xoa HTML tags, sau do ap dung regex de tim ma don hang va ma van chuyen.

**`saveLogPrintJob(printId, shopId, shopName, platform, OrderPdfPrintJobModel, getPdfBuffer, regexPatterns)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `printId` | `string` | ID cua print job |
| `shopId` | `string` | ID shop |
| `shopName` | `string` | Ten shop |
| `platform` | `string` | Nen tang (`shopee`, `lazada`, `tiktok`) |
| `OrderPdfPrintJobModel` | `ModelApiLoader` | PouchDB model tuong ung |
| `getPdfBuffer` | `() => Promise<ArrayBuffer>` | Ham tai PDF buffer |
| `regexPatterns` | `Record<string, RegExp>` | Regex trich xuat ma don |
| **Tra ve** | `Promise<OrderPdfBucket>` | Ket qua print job da luu |

Luong xu ly:
1. Kiem tra `printId` da ton tai trong DB chua (tranh trung lap)
2. Tai PDF buffer voi retry (toi da 5 lan, moi lan cach 5 giay)
3. Kiem tra kich thuoc PDF >= 5KB (loai bo PDF loi)
4. Phan tich PDF de trich xuat ma don hang
5. Upload len S3 theo duong dan `{platform}/{ngay}/{shopId}/{printId}.pdf`
6. Luu metadata vao PouchDB

**Dependencies:**
- `@/api/autoshopee/service/s3` - Upload S3
- `@/api/autoshopee/service/pdf` - Phan tich PDF
- `@/plugins/logger` - Ghi log
- `async-retry` - Retry mechanism
- `moment` - Xu ly ngay gio

### 1.2 `print/shopee.js` - In don Shopee

**`shopeeSaveLogPrintJob(printId, shopId, shopName)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `printId` | `string` | ID print job tu Shopee |
| `shopId` | `string` | ID shop Shopee |
| `shopName` | `string` | Ten shop |
| **Tra ve** | `Promise<OrderPdfBucket>` | Ket qua print job |

Regex trich xuat:
- Ma van don: `/\bSPX[A-Z0-9]{5,}\b/g` (vi du: `SPXVN12345678`)
- Ma don hang: `/\b\d{8}[A-Z0-9]{6}\b/g`

**Dependencies:**
- `@/models/orderPdf` - Model `ShopeeOrderPdfPrintJob`
- `@/api/shopee/seller/order/print` - API tai PDF tu Shopee

### 1.3 `print/lazada.js` - In don Lazada

**`lazadaSaveLogPrintJob(pdfUrl, shopId, shopName)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `pdfUrl` | `string` | URL truc tiep den file PDF |
| `shopId` | `string` | ID shop Lazada |
| `shopName` | `string` | Ten shop |
| **Tra ve** | `Promise<OrderPdfBucket>` | Ket qua print job |

Khac voi Shopee (dung `printId`), Lazada su dung URL truc tiep den PDF. `printId` duoc tao bang SHA256 hash cua URL.

Regex trich xuat:
- Ma van don: `/\bLMP[A-Z0-9]{10,20}\b/g`
- Ma don hang: `/\b\d{11,15}\b/g`

**Dependencies:**
- `@/models/orderPdf` - Model `LazadaOrderPdfPrintJob`
- `@/api/utils/get` - Ham `getPdfFromUrl` tai PDF tu URL
- `crypto-js` - Tao SHA256 hash cho printId

### 1.4 `print/tiktok.js` - In don TikTok

**`tiktokSaveLogPrintJob(pdfUrl, shopId, shopName)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `pdfUrl` | `string` | URL truc tiep den file PDF |
| `shopId` | `string` | ID shop TikTok |
| `shopName` | `string` | Ten shop |
| **Tra ve** | `Promise<OrderPdfBucket>` | Ket qua print job |

Tuong tu Lazada, su dung URL va SHA256 hash lam printId.

Regex trich xuat:
- Ma van don: `/\b\d{12}\b/g`
- Ma don hang: `/\b\d{18}\b/g`

**Dependencies:**
- `@/models/orderPdf` - Model `TiktokOrderPdfPrintJob`
- `@/api/utils/get` - Ham `getPdfFromUrl`
- `crypto-js` - Tao SHA256 hash

### 1.5 `print/log.js` - Queue xu ly Print Job

Quan ly hang doi (queue) cho viec xu ly print job, dam bao moi nen tang chi xu ly 1 job tai mot thoi diem (concurrency = 1) de tranh xung dot.

**`pushShopeePrintLogJob(printId, shopId, shopName)`**

Day print job Shopee vao hang doi xu ly.

**`pushTiktokPrintLogJob(pdfUrl, shopId, shopName)`**

Day print job TikTok vao hang doi xu ly.

**`pushLazadaPrintLogJob(pdfUrl, shopId, shopName)`**

Day print job Lazada vao hang doi xu ly.

Moi ham tra ve `Promise<OrderPdfBucket>`.

**Dependencies:**
- `p-queue` - Thu vien queue voi gioi han concurrency

### Noi su dung Print Service

| File | Ham su dung |
|------|-------------|
| `src/background/bridge/listener/shopee/print.js` | `pushShopeePrintLogJob` |
| `src/background/bridge/listener/tiktok/print.js` | `pushTiktokPrintLogJob` |
| `src/background/bridge/listener/lazada/print.js` | `pushLazadaPrintLogJob` |

Tat ca deu duoc goi tu **background bridge listener** - nghia la khi content script gui message in don hang den background, cac listener nay se day job vao queue xu ly.

---

## 2. Shopee Flash Sale Service - Tu dong Flash Sale

### Muc dich

Tu dong hoa quy trinh dang ky va tao Flash Sale tren Shopee. He thong hoat dong theo 2 buoc:
1. **Campaign** - Tao lich dang ky (scheduler) tu cau hinh campaign
2. **Scheduler** - Thuc thi dang ky Flash Sale tu scheduler da len lich

### 2.1 `shopee/flashsale/get.js` - Truy van du lieu

#### Ham

**`unixTime(num)`**

Chuyen doi Unix timestamp (giay) sang doi tuong `Date`.

**`getFlashSaleDataTimeId(timeId)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `timeId` | `number` | ID khung gio Flash Sale |
| **Tra ve** | `Promise<Object>` | Du lieu Flash Sale tuong ung voi khung gio |

Lay danh sach Flash Sale sap toi (100 items) va tim Flash Sale khop voi `timeId`.

**`getListSlotTimeAll()`**

| **Tra ve** | `Promise<Array<{timeSlotId, timeStart, timeEnd}>>` | Tat ca khung gio Flash Sale kha dung |

Lay danh sach khung gio Flash Sale tu API Shopee va chuyen doi sang dinh dang noi bo.

**`getKvLockApi(type, id, ttl)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `type` | `string` | Loai khoa (vi du: `create`, `shop`, `create-from-campaign`) |
| `id` | `string` | ID doi tuong can khoa |
| `ttl` | `number` | Thoi gian song (giay), mac dinh 30 |
| **Tra ve** | `Promise<{KvLocker}>` | Doi tuong khoa, `null` neu da bi khoa |

Co che khoa (lock) bang KV storage de tranh xu ly dong thoi (race condition). Neu key da bi khoa, tra ve `KvLocker: null`.

**Dependencies:**
- `@/api/shopee/seller/flashsale` - API Flash Sale Shopee
- `@/plugins/kv` - KV storage (lock mechanism)

### 2.2 `shopee/flashsale/campaign.js` - Tao lich tu Campaign

#### Ham

**`createScheduleFromCampaignId(campaignId, callbackScheduler)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `campaignId` | `string` | ID campaign |
| `callbackScheduler` | `Function\|null` | Callback sau moi scheduler duoc tao |
| **Tra ve** | `Promise<FlashSaleScheduler[]>` | Danh sach scheduler da tao |

Luong xu ly:
1. Khoa campaign bang KV lock (TTL 60 giay)
2. Lay thong tin campaign tu API AutoShopee
3. Lay tat ca khung gio Flash Sale kha dung
4. Loc khung gio phu hop (chua co scheduler, nam trong khoang thoi gian cho phep, dung khung gio cau hinh)
5. Tao scheduler cho tung khung gio khop (tuan tu, delay 500ms giua moi lan)
6. Goi callback (neu co) voi thong tin tien trinh
7. Giai phong khoa

**`createScheduleFlashsaleFromCampaignShopId(shopId, callbackScheduler)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `shopId` | `string` | ID shop Shopee |
| `callbackScheduler` | `Function\|null` | Callback theo doi tien trinh |
| **Tra ve** | `Promise<FlashSaleCampaignScheduler[]>` | Danh sach campaign da xu ly |

Xu ly tat ca campaign dang hoat dong cua shop:
1. Khoa shop bang KV lock (TTL 120 giay)
2. Lay danh sach campaign tu API
3. Loc campaign con hoat dong (active, trong khoang thoi gian hien tai)
4. Goi `createScheduleFromCampaignId` cho tung campaign

**Dependencies:**
- `@/api/autoshopee/shopee/flashsale` - API AutoShopee (campaign list, scheduler create, scheduler slot)
- `@/plugins/logger` - Ghi log
- `p-map` - Xu ly promise tuan tu
- `delay` - Delay giua cac request
- `moment` - Xu ly thoi gian

### 2.3 `shopee/flashsale/scheduler.js` - Thuc thi Flash Sale

#### Ham

**`createFlashsaleFromSchedulerId(schedulerId, isForce)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `schedulerId` | `string` | ID scheduler |
| `isForce` | `boolean` | Bat buoc kiem tra khoa (mac dinh `false`) |
| **Tra ve** | `Promise<number>` | ID Flash Sale da tao |

Luong xu ly:
1. Khoa scheduler bang KV lock (TTL 20 giay)
2. Lay thong tin scheduler tu API AutoShopee
3. Kiem tra da hoan thanh chua (neu `isDone && isSuccess` thi tra ve ngay)
4. Kiem tra khung gio chua qua
5. Kiem tra Flash Sale da ton tai cho khung gio nay chua
6. Neu chua co, tao Flash Sale moi qua API Shopee
7. Cap nhat danh sach san pham (set + index)
8. Luu Flash Sale ID vao scheduler

**`createFlashsaleFromSchedulerShopId(shopId, callbackFlashsale)`**

| Tham so | Kieu | Mo ta |
|---------|------|-------|
| `shopId` | `string` | ID shop Shopee |
| `callbackFlashsale` | `Function\|null` | Callback theo doi tien trinh |
| **Tra ve** | `Promise<number[]>` | Danh sach Flash Sale ID da tao |

Xu ly tat ca scheduler dang cho cua shop:
1. Khoa shop bang KV lock (TTL 30 giay)
2. Lay danh sach scheduler tu API AutoShopee
3. Loc scheduler phu hop: chua co `flashsaleId`, dang `active`, da den gio schedule nhung chua qua gio Flash Sale
4. Thuc thi tung scheduler tuan tu (delay 1 giay giua moi lan)

**Dependencies:**
- `@/api/shopee/seller/flashsale` - API Shopee (tao Flash Sale, cap nhat san pham)
- `@/api/autoshopee/shopee/flashsale` - API AutoShopee (quan ly scheduler)
- `@/plugins/i18n` - Da ngon ngu cho thong bao loi
- `@/plugins/logger` - Ghi log

### Noi su dung Flash Sale Service

| File | Ham su dung |
|------|-------------|
| `src/background/shopee/task.js` | `createScheduleFlashsaleFromCampaignShopId`, `createFlashsaleFromSchedulerShopId` |
| `src/app/store/modules/shopee/flashsale.js` | `createFlashsaleFromSchedulerShopId`, `createScheduleFlashsaleFromCampaignShopId` |
| `src/app/components/Shopee/Seller/FlashSale/mixin/List.js` | `createFlashsaleFromSchedulerId` |
| `src/app/components/Shopee/Seller/FlashSale/mixin/Campaign.js` | `createScheduleFromCampaignId` |

Duoc su dung boi:
- **Background task** - Chay tu dong theo lich (alarm/cron)
- **Vuex store** - Goi tu UI khi nguoi dung thao tac
- **Vue mixin** - Goi truc tiep tu component Flash Sale

---

## 3. Shop Order Service (Stub)

**File:** `src/app/service/shop/order/fetch.js`

Chua cac ham stub (chua implement) cho viec lay danh sach don hang:

- `fetchListOrderShopee()` - Lay don hang Shopee
- `fetchListOrderTiktok()` - Lay don hang TikTok
- `fetchListOrderLazada()` - Lay don hang Lazada

Hien tai cac ham nay chua co logic xu ly, du kien se duoc implement trong tuong lai.

---

## 4. Shopee Product Service (Stub)

**File:** `src/app/service/shopee/product.js`

- `cloneProduct()` - Clone san pham Shopee (chua implement)

---

## So do luong xu ly

### Luong in don hang

```
Content Script (trang in don)
    │
    ▼ webext-bridge message
Background Bridge Listener
    │
    ▼ pushXxxPrintLogJob()
Print Queue (p-queue, concurrency=1)
    │
    ▼ xxxSaveLogPrintJob()
saveLogPrintJob()
    │
    ├── Tai PDF (retry 5 lan)
    ├── Phan tich PDF (trich xuat ma don)
    ├── Upload S3
    └── Luu PouchDB
```

### Luong tu dong Flash Sale

```
Background Task (alarm dinh ky)
    │
    ▼ createScheduleFlashsaleFromCampaignShopId()
Lay danh sach Campaign dang hoat dong
    │
    ▼ createScheduleFromCampaignId()
Tao Scheduler cho tung khung gio phu hop
    │
    ▼ (doi den gio schedule)
    │
    ▼ createFlashsaleFromSchedulerShopId()
Lay danh sach Scheduler da den gio
    │
    ▼ createFlashsaleFromSchedulerId()
    │
    ├── Tao Flash Sale ID tren Shopee
    ├── Cap nhat danh sach san pham
    └── Luu ket qua vao API AutoShopee
```

## Co che chung

### KV Lock (chong xu ly dong thoi)

Tat ca cac service Flash Sale su dung `KVCheckLock` tu `@/plugins/kv` de dam bao moi thao tac chi chay 1 lan tai mot thoi diem. Lock co TTL (time-to-live) tu 20-120 giay tuy theo loai thao tac.

### Queue (hang doi xu ly)

Print service su dung `p-queue` voi `concurrency: 1` de dam bao moi nen tang chi xu ly 1 print job tai mot thoi diem, tranh tinh trang qua tai API.

### Retry (thu lai khi loi)

Print service su dung `async-retry` voi cau hinh 5 lan thu lai, moi lan cach 5 giay, de xu ly truong hop API khong pha hoi hoac PDF chua san sang.
