Compare commits

...

22 Commits

Author SHA1 Message Date
Misaka_Company
b2f2c536cb feat(registration): merge shelf overview into registration 2026-05-15 08:45:22 +08:00
Misaka_Company
ce80e1a1f6 feat(boxing): support editing assigned box records 2026-05-15 08:19:34 +08:00
Misaka_Company
a165bfeabe feat(boxing): handle multi-code paichan switches 2026-05-14 14:04:25 +08:00
Misaka_Company
28871eb21f feat(boxing): support v2.5 dual modes 2026-05-14 12:29:33 +08:00
Misaka_Company
077a1ab1b9 fix(settings): save all config atomically and strip trailing slash from API URL
- Save API URL and sound paths in a single load-modify-write cycle to
  prevent race conditions that wiped previously saved config
- Strip trailing slashes from API URL to avoid double-slash 404 errors
- Make AppConfigService.saveConfig public for batch config writes

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-13 16:58:39 +08:00
Misaka_Company
42a9cc7204 feat(boxing): update detail page quantity display and paichan_no style
- Change quantity display from "数量:N" to "N/total" format (boxed/total)
- Enlarge paichan_no font to 18px bold and right-align

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-13 15:51:41 +08:00
Misaka_Company
396a19ff43 feat(boxing): update many-to-one packing flow 2026-05-13 15:14:14 +08:00
Misaka_Company
b32c9c5aad feat: handle off-shelf registration results 2026-05-13 12:43:22 +08:00
Misaka_Company
b975b15ba7 feat: improve one-to-many boxing workflow 2026-05-13 11:22:49 +08:00
Misaka_Company
e4a8816b98 chore: ignore agent workspace 2026-05-13 09:52:23 +08:00
Misaka_Company
c2fc884b66 feat(boxing): show work order numbers in boxing views 2026-05-13 09:48:08 +08:00
Misaka_Company
62583510b2 docs: add CLAUDE.md with app installation rules
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-12 17:33:41 +08:00
Misaka_Company
1417c8baf9 refactor: unify error feedback system with FeedbackService and StatusBar widget
- Create FeedbackService as centralized sound/vibration dispatcher
- Create reusable StatusBar widget with StatusDotColor enum (blue/orange/green/red/yellow/amber)
- Extend SoundService with beep/error/alert sound types and loop playback
- Remove top feedback banners from both registration and boxing pages
- Route all feedback through bottom status bar per PRD requirements
- Add sound and vibration feedback to boxing module (was completely missing)
- Handle network errors with yellow status, general errors with red
- Enhance duplicate dialog with alert loop sound that stops on close
- Add beep/error/alert sound file selectors in settings page

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-12 17:15:28 +08:00
Misaka_Company
ac77294ecb feat: enhance boxing module with box mode support and fix Android build
- Add box_mode parameter to box submission API for one-to-one/one-to-many/many-to-one modes
- Allow re-scan override in one2one mode without clearing state
- Improve duplicate detection messages per boxing mode
- Disable Kotlin incremental compilation to fix cross-drive build failure

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-12 15:42:43 +08:00
Misaka
2937efdefd chore: ignore android/build directory
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
2026-05-11 20:43:13 +08:00
Misaka
732befb2a0 merge: integrate boxing module from remote with sound/vibration feedback
Merge remote boxing module (one2one, one2many, many2one modes) with
local sound and vibration feedback feature. Migrate SharedPreferences
to AppConfigService across all services including SoundService.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-11 20:18:47 +08:00
Misaka
230e6ee07a feat: add sound and vibration feedback for registration actions
Integrate audioplayers, vibration, and file_picker packages to provide
audio/haptic feedback on registration success/failure. Add sound
settings UI in SettingsPage for customizing notification sounds.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-11 20:13:03 +08:00
Misaka_Company
5bae60cc82 feat: implement boxing module with three modes (one2one, one2many, many2one)
- Add BoxInfoResult/BoxSaveResult data classes and API methods to ApiService
- Create BoxingPage with mode switching, auto-fill rules, duplicate detection
- Create BoxingDetailPage for read-only box detail view
- Activate boxing module in HomePage navigation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-11 17:38:16 +08:00
Misaka_Company
cdc64bf82f feat: replace SharedPreferences with file-based AppConfigService and add HomePage navigation
- Implement AppConfigService using path_provider to store settings in a local JSON file,\n   ensuring configuration survives app updates/reinstalls.\n - Replace shared_preferences with AppConfigService in HomePage, SettingsPage,\n   and RegistrationPage.\n - Replace shared_preferences with AppConfigService in HomePage, SettingsPage,\n   and RegistrationPage.\n - Add HomePage.dart as the main navigation hub with feature cards (Registration,\n   Boxing, Shelf Query) and dynamic connection status bar.\n - Remove Settings entry from RegistrationPage; Settings are only accessible from\n   the Home page. Use 'flutter analyze' to verify the code.
2026-05-11 16:24:16 +08:00
Misaka_Company
3f70049292 test: add unit tests for ApiService.registerLocation
Cover success (200), duplicate (409), validation error (400), and
network failure paths using a MockClient.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-11 12:58:33 +08:00
Misaka_Company
9e18ed4b8c feat: handle 400 status code with unified error format
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-11 12:47:21 +08:00
Misaka
28006f19a5 docs: add sound settings design document
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-09 20:50:35 +08:00
27 changed files with 5913 additions and 436 deletions

5
.gitignore vendored
View File

@@ -32,6 +32,7 @@ migrate_working_dir/
.pub-cache/
.pub/
/build/
android/build/
# Symbolication related
app.*.symbols
@@ -43,6 +44,8 @@ app.*.map.json
/android/app/debug
/android/app/profile
/android/app/release
/android/build/
# AI Agents
.claude/
.claude/
.agents/

17
CLAUDE.md Normal file
View File

@@ -0,0 +1,17 @@
# pad_scanner CLAUDE.md
## App Installation Rules
**Always use `adb install -r` to install the app. Never use `flutter install`.**
`flutter install` uninstalls the old version first, which wipes app configuration (API URL, sound file paths, etc.). `adb install -r` performs an in-place upgrade that preserves all app data.
### Installation Steps
```bash
# 1. Build
flutter build apk --release
# 2. Install (in-place upgrade, preserves config)
adb install -r build/app/outputs/flutter-apk/app-release.apk
```

View File

@@ -1,4 +1,5 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
kotlin.incremental=false
android.useAndroidX=true
android.enableJetifier=true
systemProp.http.proxyHost=127.0.0.1

View File

@@ -0,0 +1,261 @@
# 错误反馈机制重构计划
> 版本v1.0
> 日期2026-05-12
> 状态:已完成
---
## 1. 背景与目标
### 1.1 当前问题
对照 PRD上架登记模块 v1.0 + 装箱编号模块 v1.3)的要求,当前 Flutter 应用在错误反馈方面存在以下差距:
| # | 问题 | 影响范围 |
|---|------|---------|
| 1 | **装箱模块完全没有声音和振动反馈**`boxing_page.dart` 未引入 `SoundService``Vibration` | 装箱编号 |
| 2 | **反馈横幅位置错误** — 当前在页面顶部显示反馈横幅PRD 要求统一由底部状态栏承载所有反馈文案 | 上架登记、装箱编号 |
| 3 | **底部状态栏缺少黄色(网络异常)和红色(错误)状态** — 注册页状态栏圆点仅使用蓝/橙/绿三色,错误信息只出现在顶部横幅 | 上架登记 |
| 4 | **反馈信息重复显示** — 顶部横幅和底部状态栏同时显示类似内容,造成冗余 | 上架登记、装箱编号 |
| 5 | **声音类型不足**`SoundService` 只有 success/failure 两种PRD 要求区分"扫描提示音"、"错误音"、"成功音"、"连续错误音" | 全局 |
| 6 | **重复上架弹窗缺少声音差异化** — PRD 要求"连续错误音"+"连续振动",当前只是普通失败音 | 上架登记 |
> LED 反馈暂时不实现,后续单独处理。
### 1.2 重构目标
- **统一反馈入口**:创建集中的 `FeedbackService`,管理声音/振动三通道反馈
- **消除重复**:移除顶部反馈横幅,所有反馈文案统一由底部状态栏显示
- **补全缺失**:为装箱模块补齐声音/振动反馈
- **符合 PRD**:状态栏圆点颜色、文案、持续时间与 PRD 表格一一对应
---
## 2. PRD 反馈要求汇总
### 2.1 上架登记模块PRD 第 7 节)
| 事件 | 屏幕(底部状态栏) | 声音 | 振动 |
|------|-------------------|------|------|
| 扫入有效总排号 | 总排号字段填入,绿色高亮 | 短促提示音 | 短震 |
| 扫入有效货位号 | 货位号字段填入,绿色高亮 | 短促提示音 | 短震 |
| 扫入无效码 | 红色提示 2 秒:"无效码:{值}" | 错误音 | 短震 |
| 提交成功 | 绿色提示 1.5 秒 | 成功音 | 长震 |
| 提交失败 | 红色提示 2 秒 | 失败音 | 短震 |
| 重复上架错误 | 红色错误弹窗(需手动关闭) | 连续错误音 | 连续震 |
| 网络异常 | 黄色提示:"网络异常,请检查网络连接" | 失败音 | 短震 |
### 2.2 装箱编号模块PRD 第 9 节)
| 事件 | 屏幕(底部状态栏) | 声音 | 振动 |
|------|-------------------|------|------|
| 扫入有效总排号 | 显示排产号信息,绿色对勾 | 短促提示音 | 短震 |
| 扫入无效码 | 红色提示:"无效码,请重新扫描" | 错误音 | 短震 |
| 提交成功 | 绿色提示 1.5 秒 | 成功音 | 长震 |
| 重复箱号 | amber 提示 + 输入框 amber 边框 | 失败音 | 短震 |
| 网络异常 | 黄色提示:"网络异常,请检查网络连接" | 失败音 | 短震 |
| 切换装箱模式 | 模式控件高亮切换 | 短促提示音 | — |
### 2.3 底部状态栏圆点颜色规范
| 状态 | 圆点颜色 |
|------|---------|
| 空闲等待 | 蓝色 |
| 提交中 | 橙色 |
| 成功 | 绿色 |
| 错误(无效码/提交失败/重复) | 红色 |
| 网络异常 | 黄色 |
| 警告(重复箱号) | amber |
---
## 3. 架构设计
### 3.1 新增 `FeedbackService`
创建 `lib/services/feedback_service.dart`,作为**唯一的反馈调度中心**。
```
FeedbackService
├── trigger(FeedbackEvent event) ← 统一入口
├── _playSound(SoundType type) ← 声音通道
├── _vibrate(VibrationPattern p) ← 振动通道
└── 底部状态栏状态由各 Page State 管理FeedbackService 不直接操控 Widget
```
**FeedbackEvent 枚举:**
```dart
enum FeedbackEvent {
scanValid, // 扫入有效码 → 短促提示音 + 短震
scanInvalid, // 扫入无效码 → 错误音 + 短震
submitSuccess, // 提交成功 → 成功音 + 长震
submitFailure, // 提交失败 → 失败音 + 短震
duplicateError, // 重复上架 → 连续错误音 + 连续震
networkError, // 网络异常 → 失败音 + 短震
duplicateBoxNo, // 重复箱号 → 失败音 + 短震
modeSwitch, // 模式切换 → 短促提示音
}
```
### 3.2 声音扩展
扩展 `SoundService`,增加声音类型:
| 声音类型 | 方法名 | 用途 |
|---------|--------|------|
| 短促提示音 | `playBeep()` | 有效扫码、模式切换 |
| 错误音 | `playError()` | 无效码 |
| 成功音 | `playSuccess()` | 提交成功(保留现有) |
| 失败音 | `playFailure()` | 提交失败、网络异常(保留现有) |
| 连续错误音 | `playAlertLoop()` | 重复上架弹窗(循环播放直到弹窗关闭) |
**实现策略**
-`SoundService` 中增加 `beep``error``alert` 三个可配置路径
- 设置页面增加对应的文件选择器
- 若路径未配置则静默跳过(不阻塞业务)
### 3.3 底部状态栏组件化
抽取 `lib/widgets/status_bar.dart` 为独立 Widget
```dart
enum StatusDotColor { blue, orange, green, red, yellow, amber }
class StatusBar extends StatelessWidget {
final StatusDotColor dotColor;
final String text;
// ...
}
```
所有页面统一使用此组件,消除重复代码。
---
## 4. 文件变更清单
### 4.1 新增文件
| 文件路径 | 说明 |
|---------|------|
| `lib/services/feedback_service.dart` | 反馈调度中心,管理声音/振动 |
| `lib/widgets/status_bar.dart` | 底部状态栏可复用组件 |
### 4.2 修改文件
| 文件路径 | 变更内容 |
|---------|---------|
| `lib/services/sound_service.dart` | 增加 `beep`/`error`/`alert` 声音类型和配置 |
| `lib/pages/registration_page.dart` | ① 移除顶部反馈横幅 ② 状态栏增加红/黄颜色 ③ 引入 FeedbackService ④ 重复上架弹窗调用连续错误音 |
| `lib/pages/boxing_page.dart` | ① 移除顶部反馈横幅 ② 引入 FeedbackService ③ 增加声音/振动反馈 ④ 状态栏统一使用 StatusBar 组件 |
| `lib/pages/settings_page.dart` | 增加声音文件配置项beep/error/alert |
### 4.3 不变文件
| 文件路径 | 原因 |
|---------|------|
| `lib/services/api_service.dart` | API 层只负责数据传输,不涉及反馈 |
| `lib/services/code_parser.dart` | 解析逻辑不变 |
| `lib/services/scanner_service.dart` | 扫码硬件层不变 |
| `lib/pages/home_page.dart` | 不涉及作业反馈 |
| `lib/pages/boxing_detail_page.dart` | 只读展示页,无反馈交互 |
---
## 5. 实施步骤
### 步骤 1创建 `FeedbackService`(核心)
**文件**`lib/services/feedback_service.dart`
- 定义 `FeedbackEvent` 枚举
- 根据 event 映射声音类型、振动模式
- 调用 `SoundService``Vibration`
**预估改动**~70 行新代码
### 步骤 2扩展 `SoundService`
**文件**`lib/services/sound_service.dart`
- 新增 `playBeep()``playError()``playAlertLoop()``stopAlert()` 方法
- 新增 `beep_path``error_path``alert_path` 配置存取
- 所有播放方法在路径未配置时静默返回
**预估改动**~40 行新增
### 步骤 3创建 `StatusBar` 组件
**文件**`lib/widgets/status_bar.dart`
- 抽取底部状态栏为独立 Widget
- 接收 `dotColor`(枚举)和 `text` 参数
- 统一样式:圆点 + 文字,背景色使用 `surfaceContainerHighest`
**预估改动**~40 行新代码
### 步骤 4重构上架登记页
**文件**`lib/pages/registration_page.dart`
变更清单:
1. **删除**顶部反馈横幅相关代码(`_snackbarMessage``_snackbarColor``_showFeedback()` 方法中的横幅渲染)
2. **引入** `FeedbackService`,在以下时机调用 `trigger()`
- `_onScan` 无效码 → `scanInvalid`
- `_onScan` 有效码 → `scanValid`
- `_submitOne` 成功 → `submitSuccess`
- `_submitOne` 失败 → `submitFailure`
- `_submitOne` 重复 → `duplicateError`
- catch 网络异常 → `networkError`
3. **修改**底部状态栏:
- 状态栏圆点颜色增加红色和黄色
- 错误文案在状态栏中显示(不再在横幅中)
- 移除 `_successMessage` 单独字段,统一由状态栏管理
4. **替换** 内联状态栏 Widget 为 `StatusBar` 组件
5. **修改** `_showDuplicateDialog`:打开时触发 `duplicateError`(连续音/震),关闭时停止
**预估改动**:净减 ~30 行(移除横幅 > 新增 trigger 调用)
### 步骤 5重构装箱编号页
**文件**`lib/pages/boxing_page.dart`
变更清单:
1. **删除**顶部反馈横幅相关代码
2. **删除** 内联底部状态栏代码,替换为 `StatusBar` 组件
3. **引入** `FeedbackService`,在以下时机调用 `trigger()`
- `_onScan` 无效码 → `scanInvalid`
- `_queryBoxInfo` 成功 → `scanValid`
- `_submit` 成功 → `submitSuccess`
- `_submit` 失败 → `submitFailure`
- `_submit` 重复箱号 → `duplicateBoxNo`
- catch 网络异常 → `networkError`
- `_cycleMode``modeSwitch`
4. **修改**状态栏颜色逻辑,增加红色/黄色/amber
**预估改动**:净减 ~20 行
### 步骤 6设置页扩展**文件**`lib/pages/settings_page.dart`- 新增三个声音文件选择器提示音beep、错误音error、警报音alert- 保持与现有 success/failure 选择器一致的 UI 风格**预估改动**~60 行新增
---
## 6. 风险与约束
| 风险 | 缓解措施 |
|------|---------|
| LED 功能依赖设备硬件 | `LedService` 全面包裹 try-catch不支持时静默降级 |
| 声音文件路径未配置 | 所有 `play*()` 方法在路径为空时静默返回 |
| 连续错误音循环播放 | `playAlertLoop()` 使用循环计数或时长上限,`stopAlert()` 确保可停止 |
| 振动权限 | Android 需要 `VIBRATE` 权限,检查 `AndroidManifest.xml` 是否已声明 |
---
## 7. 不在本次范围内
- 后端 API 错误格式调整PRD 已定义,后端自行对齐)
- 操作日志与操作人员记录
- 离线缓存与联网同步
- 新模块开发
- LED 反馈(后续单独处理)

View File

@@ -0,0 +1,38 @@
# 铃声配置功能设计
## 概述
在设置页新增铃声配置入口,用户可以为"上架成功"和"上架失败"分别指定本地音频文件作为提示铃声。
## 依赖
- `file_picker` — 从设备选择音频文件(支持 mp3/wav/ogg/aac/m4a/flac
- `audioplayers` — 播放本地音频文件
## 数据存储
使用 `SharedPreferences`
- `sound_success` — 上架成功铃声文件路径
- `sound_failure` — 上架失败铃声文件路径
## UI 设计
设置页新增"铃声设置"分区API 地址下方:
```
铃声设置
─────────────────────────────
上架成功铃声
[当前文件名或"未设置"] [选择] [试听] [清除]
上架失败铃声
[当前文件名或"未设置"] [选择] [试听] [清除]
```
## 音频播放逻辑
- 封装为 `SoundService`,统一管理播放
- 通过 `DeviceFileSource` 播放本地文件
- 上架成功/失败时检查是否配置了铃声,有则播放
- 保留现有震动反馈,铃声与震动并行
## 涉及文件
1. `pubspec.yaml` — 添加依赖
2. `lib/services/sound_service.dart` — 新建,封装音频播放
3. `lib/pages/settings_page.dart` — 新增铃声配置 UI
4. `lib/pages/registration_page.dart` — 集成铃声播放

View File

@@ -0,0 +1,519 @@
# 装箱编号模块 Implementation Plan — Flutter
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** 实现 PRD v1.3 中定义的装箱编号模块 Flutter 页面,支持三种装箱模式(一码一箱、一码多箱、多码一箱),包含扫码识别、信息查询、自动填充、重复校验和提交功能。
**Architecture:** 在现有 Flutter 应用基础上扩展,使用 setState 管理 UI 状态EventChannel 接收扫码数据http 包调用后端 API。新增 BoxingPage 和 BoxingDetailPage 两个页面。
**Tech Stack:** Flutter 3.x, Dart, http, shared_preferences, Android native EventChannel (SEUIC scanner)
---
## 页面结构
```
HomePage
├── 上架登记 (RegistrationPage) ← 已完成
├── 装箱编号 (BoxingPage) ← 本次实现
│ └── 装箱详情 (BoxingDetailPage) ← 子页面
└── 货架查询 ← 规划中
```
## 状态机设计
三种装箱模式对应不同的状态流转:
```
一码一箱: 等待扫码 → 扫码后自动填充箱号+数量 → 确认 → 成功(1.5s) → 重置等待扫码
一码多箱: 等待扫码 → 扫码后自动填充箱号 → 手动填数量 → 确认 → 成功
→ "继续添加": 预填箱号+1、预填上次数量 → 确认 → ...
→ "返回": 重置等待扫码
多码一箱: 等待扫码 → 扫码后填充+锁定箱号+数量 → 确认 → 成功
→ 自动等待下一个扫码 → 箱号锁定 → 自动填充新数量 → 确认 → ...
→ "返回": 重置等待扫码
```
---
### Task 1: ApiService 扩展 — 装箱 API 方法
**Files:**
- Modify: `lib/services/api_service.dart`
**Step 1: 添加装箱相关的数据类和 API 方法**
在文件末尾(`ApiService` 类内部)新增以下方法,在文件顶部新增数据类:
```dart
// === 装箱模块数据类 ===
/// 装箱信息查询结果
class BoxInfoResult {
final bool success;
final String? errorMessage;
final String? errorCode;
final String? zongpaiNo;
final String? paichanNo;
final int? quantity;
final List<BoxDetailData> existingBoxes;
final int maxBoxNo;
final int suggestedBoxNo;
BoxInfoResult({
required this.success,
this.errorMessage,
this.errorCode,
this.zongpaiNo,
this.paichanNo,
this.quantity,
this.existingBoxes = const [],
this.maxBoxNo = 0,
this.suggestedBoxNo = 1,
});
factory BoxInfoResult.ok(Map<String, dynamic> json) {
final boxes = (json['existing_boxes'] as List<dynamic>?)
?.map((b) => BoxDetailData.fromJson(b as Map<String, dynamic>))
.toList() ??
[];
return BoxInfoResult(
success: true,
zongpaiNo: json['zongpai_no'] as String?,
paichanNo: json['paichan_no'] as String?,
quantity: json['quantity'] as int?,
existingBoxes: boxes,
maxBoxNo: json['max_box_no'] as int? ?? 0,
suggestedBoxNo: json['suggested_box_no'] as int? ?? 1,
);
}
factory BoxInfoResult.error(String message, {String? errorCode}) {
return BoxInfoResult(success: false, errorMessage: message, errorCode: errorCode);
}
}
/// 箱号明细
class BoxDetailData {
final int boxNo;
final List<BoxItemData> items;
BoxDetailData({required this.boxNo, required this.items});
factory BoxDetailData.fromJson(Map<String, dynamic> json) {
final items = (json['items'] as List<dynamic>?)
?.map((i) => BoxItemData.fromJson(i as Map<String, dynamic>))
.toList() ??
[];
return BoxDetailData(boxNo: json['box_no'] as int, items: items);
}
}
/// 箱号内单个总排号明细
class BoxItemData {
final String zongpaiNo;
final int quantity;
BoxItemData({required this.zongpaiNo, required this.quantity});
factory BoxItemData.fromJson(Map<String, dynamic> json) {
return BoxItemData(
zongpaiNo: json['zongpai_no'] as String,
quantity: json['quantity'] as int,
);
}
}
/// 装箱保存结果
class BoxSaveResult {
final bool success;
final bool isDuplicate;
final String? errorMessage;
final String? paichanNo;
final int? boxNo;
BoxSaveResult({
required this.success,
this.isDuplicate = false,
this.errorMessage,
this.paichanNo,
this.boxNo,
});
factory BoxSaveResult.ok(Map<String, dynamic> json) {
return BoxSaveResult(
success: true,
paichanNo: json['paichan_no'] as String?,
boxNo: json['box_no'] as int?,
);
}
factory BoxSaveResult.duplicate(Map<String, dynamic> json) {
return BoxSaveResult(
success: false,
isDuplicate: true,
paichanNo: json['paichan_no'] as String?,
boxNo: json['box_no'] as int?,
);
}
factory BoxSaveResult.error(String message) {
return BoxSaveResult(success: false, errorMessage: message);
}
}
```
`ApiService` 类内新增两个方法:
```dart
/// 查询装箱信息 — GET /CargoTrace/box/info
Future<BoxInfoResult> fetchBoxInfo({
required String baseUrl,
required String zongpaiNo,
}) async {
final uri = Uri.parse('$baseUrl/CargoTrace/box/info').replace(
queryParameters: {'zongpai_no': zongpaiNo},
);
try {
final response = await _client.get(uri, headers: {
'Content-Type': 'application/json',
}).timeout(timeout);
switch (response.statusCode) {
case 200:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxInfoResult.ok(body);
case 400:
final body = jsonDecode(response.body) as Map<String, dynamic>;
final errorCode = body['error_code']?.toString() ?? '';
return BoxInfoResult.error(
_errorMessage(errorCode),
errorCode: errorCode,
);
case 404:
return BoxInfoResult.error('未找到该总排号对应的排产号信息');
default:
return BoxInfoResult.error('查询失败 (${response.statusCode})');
}
} catch (e) {
return BoxInfoResult.error('网络异常,请检查网络连接');
}
}
/// 保存装箱记录 — POST /CargoTrace/box
Future<BoxSaveResult> saveBoxRecord({
required String baseUrl,
required String zongpaiNo,
required int boxNo,
required int quantity,
}) async {
final uri = Uri.parse('$baseUrl/CargoTrace/box');
try {
final response = await _client
.post(
uri,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'zongpai_no': zongpaiNo,
'box_no': boxNo,
'quantity': quantity,
}),
)
.timeout(timeout);
switch (response.statusCode) {
case 200:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxSaveResult.ok(body);
case 400:
final body = jsonDecode(response.body) as Map<String, dynamic>;
final msg = body['message']?.toString() ?? '请求参数错误';
return BoxSaveResult.error(msg);
case 409:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxSaveResult.duplicate(body);
case 404:
return BoxSaveResult.error('未找到该总排号对应的排产号信息');
default:
return BoxSaveResult.error('提交失败 (${response.statusCode})');
}
} catch (e) {
return BoxSaveResult.error('网络异常,请检查网络连接');
}
}
String _errorMessage(String errorCode) {
switch (errorCode) {
case 'INVALID_ZONGPAI':
return '无效的总排号格式';
default:
return '请求参数错误';
}
}
```
**Step 2: 验证编译**
Run: `flutter analyze lib/services/api_service.dart`
**Step 3: Commit**
```bash
git add lib/services/api_service.dart
git commit -m "feat: add box info query and save methods to ApiService"
```
---
### Task 2: BoxingDetailPage — 装箱详情页
**Files:**
- Create: `lib/pages/boxing_detail_page.dart`
**Step 1: 实现详情页**
只读页面展示排产号下的完整装箱明细PRD §7.3)。
```dart
import 'package:flutter/material.dart';
import 'package:pad_scanner/services/api_service.dart';
class BoxingDetailPage extends StatelessWidget {
final String paichanNo;
final List<BoxDetailData> existingBoxes;
const BoxingDetailPage({
super.key,
required this.paichanNo,
required this.existingBoxes,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
children: [
const Text('装箱详情'),
const SizedBox(width: 12),
Text(
paichanNo,
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.normal),
),
],
),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
padding: const EdgeInsets.all(12),
itemCount: existingBoxes.length,
itemBuilder: (context, index) {
final box = existingBoxes[index];
return _buildBoxGroup(context, box);
},
),
),
// 底部汇总
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Text(
'${existingBoxes.length}',
style: const TextStyle(fontSize: 14),
),
),
],
),
);
}
Widget _buildBoxGroup(BuildContext context, BoxDetailData box) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'箱号 ${box.boxNo}',
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(6),
),
child: Column(
children: box.items.map((item) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(item.zongpaiNo, style: const TextStyle(fontSize: 14)),
Text('数量:${item.quantity}', style: const TextStyle(fontSize: 14)),
],
),
);
}).toList(),
),
),
],
),
);
}
}
```
**Step 2: 验证编译**
Run: `flutter analyze lib/pages/boxing_detail_page.dart`
**Step 3: Commit**
```bash
git add lib/pages/boxing_detail_page.dart
git commit -m "feat: add BoxingDetailPage for boxing record details"
```
---
### Task 3: BoxingPage — 装箱编号主页面
**Files:**
- Create: `lib/pages/boxing_page.dart`
这是核心页面,实现 PRD §7 中的所有交互逻辑。
**Step 1: 实现装箱模式枚举和页面**
核心状态变量:
- `BoxingMode _mode` — 当前装箱模式
- `_BoxingPhase _phase` — 当前阶段waiting / scanned / submitted
- `String? _zongpaiNo` — 当前总排号
- `String? _paichanNo` — 排产号
- `int? _erpQuantity` — ERP 中的数量
- `List<BoxDetailData> _existingBoxes` — 已有箱号明细
- `int _maxBoxNo` — 最大箱号
- `TextEditingController _boxNoController` — 箱号输入
- `TextEditingController _quantityController` — 数量输入
- `bool _boxNoLocked` — 箱号是否锁定(多码一箱)
- `int? _lastBoxNo` / `int? _lastQuantity` — 上次提交的值(一码多箱用)
页面结构:
```
┌──────────────────────────────────┐
│ 装箱编号 [一码一箱 ○] │ ← AppBar + 模式切换
├──────────────────────────────────┤
│ 提示条区域 (错误/警告) │ ← 红色/amber/yellow 提示条
├──────────────────────────────────┤
│ ✓ 26BW0011 已识别 │ ← 扫码区
│ │
│ 排产号: W00009 │ ← 信息区
│ 已有箱数3箱 最大箱号3 │
│ [详情 →] │
│ ─────────────────────────────── │
│ 箱号[ 4 ] 数量[ 80 ] [确认] │ ← 输入区
│ │
├──────────────────────────────────┤
│ [返回] [继续添加] │ ← 操作栏(一码多箱/多码一箱)
├──────────────────────────────────┤
│ ● 等待扫码 │ ← 状态栏
└──────────────────────────────────┘
```
**扫码处理逻辑_onScan**
1. 解析码值 → 只接受 `CodeType.zongpaiNo`
2. 调用 `fetchBoxInfo` 查询后端
3. 成功后根据模式填充:
- 一码一箱:箱号 = suggested_box_no数量 = erp_quantity
- 一码多箱:箱号 = suggested_box_no数量为空
- 多码一箱(首次):箱号 = suggested_box_no数量 = erp_quantity箱号锁定
- 多码一箱(后续):箱号保持锁定,数量 = 新总排号的 erp_quantity
**重复箱号检测(本地):**
- 当箱号值变化时,比对 `_existingBoxes` 中是否已存在该箱号
- 重复时amber 边框 + 警告条 + 禁用确认按钮
**提交逻辑_submit**
1. 调用 `saveBoxRecord` 保存
2. 成功后根据模式处理后续:
- 一码一箱:显示成功 1.5s → 重置
- 一码多箱:记录 lastBoxNo/lastQuantity → 等待"继续添加"
- 多码一箱:保留箱号锁定 → 等待下一个扫码
**Step 2: 验证编译**
Run: `flutter analyze lib/pages/boxing_page.dart`
**Step 3: Commit**
```bash
git add lib/pages/boxing_page.dart
git commit -m "feat: add BoxingPage with three boxing modes"
```
---
### Task 4: HomePage 更新 — 接入装箱模块
**Files:**
- Modify: `lib/pages/home_page.dart`
**Step 1: 更新装箱模块状态**
`boxing` FeatureCard 的 `status``ModuleStatus.developing` 改为 `ModuleStatus.online`,设置 `version: 'v1.0'`
**Step 2: 更新导航逻辑**
`_navigateToModule``ModuleType.boxing` case 中:
- 添加 `import 'package:pad_scanner/pages/boxing_page.dart';`
- 替换 placeholder 为 `targetPage = const BoxingPage();`
**Step 3: 验证编译**
Run: `flutter analyze`
**Step 4: Commit**
```bash
git add lib/pages/home_page.dart
git commit -m "feat: activate boxing module in HomePage"
```
---
### Task 5: 最终验证
**Step 1: 全量分析**
Run: `flutter analyze`
Expected: No issues found
**Step 2: 运行测试**
Run: `flutter test`
Expected: All tests pass
**Step 3: 检查无遗漏引用**
确认 `BoxingPage` 已正确从 `HomePage` 导航访问。
---
## 文件变更汇总
| 操作 | 文件 | 说明 |
|------|------|------|
| Modify | `lib/services/api_service.dart` | 新增装箱 API 方法和数据类 |
| Create | `lib/pages/boxing_detail_page.dart` | 装箱详情只读页 |
| Create | `lib/pages/boxing_page.dart` | 装箱编号主页面(三种模式) |
| Modify | `lib/pages/home_page.dart` | 激活装箱模块导航 |

View File

@@ -1,5 +1,5 @@
import 'package:flutter/material.dart';
import 'package:pad_scanner/pages/registration_page.dart';
import 'package:pad_scanner/pages/home_page.dart';
void main() {
runApp(const PadScannerApp());
@@ -11,12 +11,12 @@ class PadScannerApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: '上架登记',
title: 'CargoTrace',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
useMaterial3: true,
),
home: const RegistrationPage(),
home: const HomePage(),
);
}
}

View File

@@ -0,0 +1,142 @@
import 'package:flutter/material.dart';
import 'package:pad_scanner/services/api_service.dart';
class BoxingDetailPage extends StatelessWidget {
final String paichanNo;
final List<BoxDetailData> existingBoxes;
const BoxingDetailPage({
super.key,
required this.paichanNo,
required this.existingBoxes,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Row(
children: [
const Text('装箱详情'),
const SizedBox(width: 12),
Expanded(
child: Text(
paichanNo,
textAlign: TextAlign.end,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
overflow: TextOverflow.ellipsis,
),
),
],
),
),
body: Column(
children: [
Expanded(
child: existingBoxes.isEmpty
? const Center(child: Text('暂无装箱记录'))
: ListView.builder(
padding: const EdgeInsets.all(12),
itemCount: existingBoxes.length,
itemBuilder: (context, index) {
return _buildBoxGroup(context, existingBoxes[index]);
},
),
),
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
color: Theme.of(context).colorScheme.surfaceContainerHighest,
child: Text(
'${existingBoxes.length}',
style: const TextStyle(fontSize: 14),
),
),
],
),
);
}
Widget _buildBoxGroup(BuildContext context, BoxDetailData box) {
final boxTotalQuantity = box.items.fold<int>(
0,
(sum, item) => sum + item.quantity,
);
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
'箱号 ${box.boxNo}',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
),
Text(
'$boxTotalQuantity',
textAlign: TextAlign.right,
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.primary,
),
),
],
),
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(6),
),
child: Column(
children: box.items.map((item) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
children: [
Expanded(
flex: 3,
child: Text(
item.zongpaiNo,
style: const TextStyle(fontSize: 14),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
Expanded(
flex: 2,
child: Text(
item.workOrderNo ?? '--',
style: const TextStyle(fontSize: 14),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 8),
Text(
'${item.quantity}/${item.totalQuantity ?? '--'}',
style: const TextStyle(fontSize: 14),
),
],
),
);
}).toList(),
),
),
],
),
);
}
}

2088
lib/pages/boxing_page.dart Normal file

File diff suppressed because it is too large Load Diff

341
lib/pages/home_page.dart Normal file
View File

@@ -0,0 +1,341 @@
import 'package:flutter/material.dart';
import 'package:pad_scanner/services/app_config_service.dart';
import 'package:pad_scanner/pages/settings_page.dart';
import 'package:pad_scanner/pages/registration_page.dart';
import 'package:pad_scanner/pages/boxing_page.dart';
import 'package:pad_scanner/services/api_service.dart';
/// Module type enum for each available feature card
enum ModuleType { registration, boxing, shelfQuery }
/// Module status for PRD state tracking
enum ModuleStatus { online, developing, planning }
/// Function card data model per PRD §3.3
class FeatureCard {
final ModuleType type;
final IconData icon;
final String title;
final String description;
final ModuleStatus status;
final String? version;
final String route;
const FeatureCard({
required this.type,
required this.icon,
required this.title,
required this.description,
required this.status,
this.version,
required this.route,
});
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _apiService = ApiService();
bool _isCheckingConnection = false;
bool _isConnected = false;
String _apiAddress = '';
/// Module registry from PRD §3.4
static const _modules = [
FeatureCard(
type: ModuleType.registration,
icon: Icons.local_shipping_outlined,
title: '上架登记',
description: '扫码绑定总排号与货位',
status: ModuleStatus.online,
version: 'v1.0',
route: '/registration',
),
FeatureCard(
type: ModuleType.boxing,
icon: Icons.view_list_outlined,
title: '装箱编号',
description: '查询箱号、录入装箱明细',
status: ModuleStatus.online,
version: 'v1.0',
route: '/boxing',
),
FeatureCard(
type: ModuleType.shelfQuery,
icon: Icons.search_outlined,
title: '货架查询',
description: '按合同查询货架库存',
status: ModuleStatus.planning,
version: null,
route: '',
),
];
@override
void initState() {
super.initState();
_checkConnection();
}
Future<void> _checkConnection() async {
final configService = AppConfigService();
final url = await configService.getString('api_url') ?? '';
if (url.isEmpty) {
setState(() {
_isConnected = false;
_apiAddress = '';
_isCheckingConnection = false;
});
return;
}
setState(() => _isCheckingConnection = true);
final ok = await _apiService.testConnection(url);
if (!mounted) return;
setState(() {
_isConnected = ok;
_apiAddress = url;
_isCheckingConnection = false;
});
}
void _onCardTap(FeatureCard card) {
switch (card.status) {
case ModuleStatus.online:
_navigateToModule(card.type);
case ModuleStatus.developing:
_showToast('该功能正在开发中');
case ModuleStatus.planning:
_showToast('该功能规划中');
}
}
void _showToast(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message), duration: const Duration(seconds: 2)),
);
}
void _navigateToModule(ModuleType type) {
late Widget targetPage;
switch (type) {
case ModuleType.registration:
targetPage = const RegistrationPage();
break;
case ModuleType.boxing:
targetPage = const BoxingPage();
break;
case ModuleType.shelfQuery:
return; // 规划中,不导航
}
Navigator.push(
context,
MaterialPageRoute(builder: (_) => targetPage),
).then((_) => _checkConnection());
}
void _navigateToSettings() {
Navigator.push(
context,
MaterialPageRoute(builder: (_) => const SettingsPage()),
).then((_) => _checkConnection());
}
Color _getConnectionStatusColor() {
if (_isCheckingConnection) return Colors.orange;
return _isConnected ? Colors.green : Colors.red;
}
String _getConnectionStatusText() {
if (_isCheckingConnection) return '● 正在检测连接...';
if (!_isConnected || _apiAddress.isEmpty) return '● 未连接,请检查设置';
return '● 已连接 $_apiAddress';
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Scaffold(
appBar: AppBar(
title: const Text('CargoTrace'),
actions: [
Padding(
padding: const EdgeInsets.only(right: 8),
child: IconButton(
icon: const Icon(Icons.settings),
onPressed: _navigateToSettings,
),
),
],
),
body: Column(
children: [
// Function cards area
Expanded(
child: ListView.builder(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
itemCount: _modules.length,
itemBuilder: (context, index) {
final card = _modules[index];
return _buildFeatureCard(context, card);
},
),
),
// Bottom connection status bar
Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
color: colorScheme.surfaceContainerHighest,
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: _getConnectionStatusColor(),
shape: BoxShape.circle,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
_getConnectionStatusText(),
style: const TextStyle(fontSize: 13),
overflow: TextOverflow.ellipsis,
),
),
],
),
),
],
),
);
}
Widget _buildFeatureCard(BuildContext context, FeatureCard card) {
final Color statusBgColor;
final TextStyle statusTextStyle;
final String statusText;
switch (card.status) {
case ModuleStatus.online:
statusBgColor = Colors.green.shade700;
statusTextStyle = const TextStyle(color: Colors.white, fontSize: 12);
statusText = card.version ?? '已上线';
break;
case ModuleStatus.developing:
statusBgColor = Colors.blue.shade700;
statusTextStyle = const TextStyle(color: Colors.white, fontSize: 12);
statusText = '开发中';
break;
case ModuleStatus.planning:
statusBgColor = Colors.grey.shade500;
statusTextStyle = const TextStyle(color: Colors.white, fontSize: 12);
statusText = '规划中';
break;
}
final canNavigate = card.status == ModuleStatus.online;
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: InkWell(
onTap: () => _onCardTap(card),
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: canNavigate ? Colors.white : Colors.grey.shade200,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.black.withValues(alpha: 0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// First row: icon + module name
Row(
children: [
Icon(
card.icon,
size: 22,
color: canNavigate ? Colors.blue : Colors.grey,
),
const SizedBox(width: 8),
Text(
card.title,
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: canNavigate ? Colors.black87 : Colors.grey,
),
),
],
),
const SizedBox(height: 6),
// Second row: description
Text(
card.description,
style: TextStyle(fontSize: 13, color: Colors.grey.shade600),
),
const SizedBox(height: 10),
// Third row: status badge (right aligned)
Align(
alignment: Alignment.centerRight,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 3,
),
decoration: BoxDecoration(
color: statusBgColor,
borderRadius: BorderRadius.circular(4),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(statusText, style: statusTextStyle),
if (card.status == ModuleStatus.online) ...[
const SizedBox(width: 6),
Container(
width: 6,
height: 6,
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
),
] else ...[
const SizedBox(width: 6),
Container(
width: 6,
height: 6,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.5),
shape: BoxShape.circle,
),
),
],
],
),
),
),
],
),
),
),
);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,8 @@
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:pad_scanner/services/app_config_service.dart';
import 'package:file_picker/file_picker.dart';
import 'package:pad_scanner/services/api_service.dart';
import 'package:pad_scanner/services/sound_service.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@@ -12,30 +14,70 @@ class SettingsPage extends StatefulWidget {
class _SettingsPageState extends State<SettingsPage> {
final _controller = TextEditingController();
final _apiService = ApiService();
final _soundService = SoundService();
bool _saving = false;
bool _testing = false;
String? _successPath;
String? _failurePath;
String? _beepPath;
String? _errorPath;
String? _alertPath;
@override
void initState() {
super.initState();
_loadUrl();
_loadSoundPaths();
}
Future<void> _loadUrl() async {
final prefs = await SharedPreferences.getInstance();
final url = prefs.getString('api_url') ?? '';
final configService = AppConfigService();
final url = await configService.getString('api_url') ?? '';
_controller.text = url;
}
Future<void> _loadSoundPaths() async {
final results = await Future.wait([
_soundService.getSuccessPath(),
_soundService.getFailurePath(),
_soundService.getBeepPath(),
_soundService.getErrorPath(),
_soundService.getAlertPath(),
]);
if (mounted) {
setState(() {
_successPath = results[0];
_failurePath = results[1];
_beepPath = results[2];
_errorPath = results[3];
_alertPath = results[4];
});
}
}
Future<void> _saveUrl() async {
final url = _controller.text.trim();
final url = _controller.text.trim().replaceAll(RegExp(r'/+$'), '');
if (url.isEmpty) {
_showSnackBar('请输入 API 地址', isError: true);
return;
}
setState(() => _saving = true);
final prefs = await SharedPreferences.getInstance();
await prefs.setString('api_url', url);
// Load config once, apply all changes, then save once to avoid race conditions
final configService = AppConfigService();
final config = await configService.loadConfig();
config['api_url'] = url;
if (_successPath != null) config['sound_success'] = _successPath;
else config.remove('sound_success');
if (_failurePath != null) config['sound_failure'] = _failurePath;
else config.remove('sound_failure');
if (_beepPath != null) config['sound_beep'] = _beepPath;
else config.remove('sound_beep');
if (_errorPath != null) config['sound_error'] = _errorPath;
else config.remove('sound_error');
if (_alertPath != null) config['sound_alert'] = _alertPath;
else config.remove('sound_alert');
await configService.saveConfig(config);
setState(() => _saving = false);
if (mounted) {
_showSnackBar('设置已保存');
@@ -52,18 +94,65 @@ class _SettingsPageState extends State<SettingsPage> {
final ok = await _apiService.testConnection(url);
setState(() => _testing = false);
if (mounted) {
_showSnackBar(
ok ? '连接成功' : '连接失败,请检查地址和网络',
isError: !ok,
);
_showSnackBar(ok ? '连接成功' : '连接失败,请检查地址和网络', isError: !ok);
}
}
Future<void> _pickSound(String key) async {
final result = await FilePicker.pickFiles(
type: FileType.audio,
);
if (result != null && result.files.single.path != null) {
final path = result.files.single.path!;
setState(() {
switch (key) {
case 'success':
_successPath = path;
case 'failure':
_failurePath = path;
case 'beep':
_beepPath = path;
case 'error':
_errorPath = path;
case 'alert':
_alertPath = path;
}
});
}
}
Future<void> _clearSound(String key) async {
setState(() {
switch (key) {
case 'success':
_successPath = null;
case 'failure':
_failurePath = null;
case 'beep':
_beepPath = null;
case 'error':
_errorPath = null;
case 'alert':
_alertPath = null;
}
});
}
Future<void> _previewSound(String path) async {
await _soundService.play(path);
}
String _fileName(String? path) {
if (path == null) return '未设置';
return path.split('/').last;
}
void _showSnackBar(String message, {bool isError = false}) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: isError ? Colors.red.shade700 : Colors.green.shade700,
backgroundColor:
isError ? Colors.red.shade700 : Colors.green.shade700,
duration: const Duration(seconds: 2),
),
);
@@ -72,6 +161,7 @@ class _SettingsPageState extends State<SettingsPage> {
@override
void dispose() {
_controller.dispose();
_soundService.dispose();
super.dispose();
}
@@ -79,11 +169,12 @@ class _SettingsPageState extends State<SettingsPage> {
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('设置')),
body: Padding(
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ---- API 地址 ----
const Text('API 服务器地址', style: TextStyle(fontSize: 14)),
const SizedBox(height: 8),
TextField(
@@ -118,9 +209,137 @@ class _SettingsPageState extends State<SettingsPage> {
: const Icon(Icons.wifi),
label: const Text('测试连接'),
),
const SizedBox(height: 24),
// ---- 铃声设置 ----
const Divider(),
const SizedBox(height: 8),
const Text('铃声设置',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
const SizedBox(height: 16),
// 扫码提示音
_buildSoundRow(
label: '扫码提示音',
path: _beepPath,
onPick: () => _pickSound('beep'),
onPreview: _beepPath != null
? () => _previewSound(_beepPath!)
: null,
onClear: _beepPath != null ? () => _clearSound('beep') : null,
),
const SizedBox(height: 12),
// 成功铃声
_buildSoundRow(
label: '成功铃声',
path: _successPath,
onPick: () => _pickSound('success'),
onPreview: _successPath != null
? () => _previewSound(_successPath!)
: null,
onClear: _successPath != null ? () => _clearSound('success') : null,
),
const SizedBox(height: 12),
// 失败铃声
_buildSoundRow(
label: '失败铃声',
path: _failurePath,
onPick: () => _pickSound('failure'),
onPreview: _failurePath != null
? () => _previewSound(_failurePath!)
: null,
onClear: _failurePath != null ? () => _clearSound('failure') : null,
),
const SizedBox(height: 12),
// 错误铃声(无效码)
_buildSoundRow(
label: '错误铃声(无效码)',
path: _errorPath,
onPick: () => _pickSound('error'),
onPreview: _errorPath != null
? () => _previewSound(_errorPath!)
: null,
onClear: _errorPath != null ? () => _clearSound('error') : null,
),
const SizedBox(height: 12),
// 警报铃声(重复上架)
_buildSoundRow(
label: '警报铃声(重复上架)',
path: _alertPath,
onPick: () => _pickSound('alert'),
onPreview: _alertPath != null
? () => _previewSound(_alertPath!)
: null,
onClear: _alertPath != null ? () => _clearSound('alert') : null,
),
],
),
),
);
}
Widget _buildSoundRow({
required String label,
required String? path,
required VoidCallback onPick,
required VoidCallback? onPreview,
required VoidCallback? onClear,
}) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: const TextStyle(fontSize: 14)),
const SizedBox(height: 6),
Row(
children: [
Expanded(
child: Container(
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400),
borderRadius: BorderRadius.circular(8),
),
child: Text(
_fileName(path),
style: TextStyle(
fontSize: 13,
color: path != null ? Colors.black87 : Colors.grey,
),
overflow: TextOverflow.ellipsis,
),
),
),
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.folder_open),
tooltip: '选择文件',
onPressed: onPick,
),
if (onPreview != null)
IconButton(
icon: const Icon(Icons.play_arrow),
tooltip: '试听',
onPressed: onPreview,
),
if (onClear != null)
IconButton(
icon: const Icon(Icons.clear, size: 20),
tooltip: '清除',
onPressed: onClear,
),
],
),
],
);
}
}

View File

@@ -5,32 +5,306 @@ import 'package:http/http.dart' as http;
class RegistrationResult {
final bool success;
final bool isDuplicate;
final bool isAlreadyOffShelf;
final bool isOffShelfSuccess;
final String? errorMessage;
final Map<String, dynamic>? duplicateInfo;
final Map<String, dynamic>? conflictInfo;
RegistrationResult({
required this.success,
this.isDuplicate = false,
this.isAlreadyOffShelf = false,
this.isOffShelfSuccess = false,
this.errorMessage,
this.duplicateInfo,
this.conflictInfo,
});
factory RegistrationResult.ok() =>
RegistrationResult(success: true);
factory RegistrationResult.ok() => RegistrationResult(success: true);
factory RegistrationResult.offShelfSuccess() =>
RegistrationResult(success: true, isOffShelfSuccess: true);
factory RegistrationResult.duplicate(Map<String, dynamic> info) =>
RegistrationResult(success: false, isDuplicate: true, duplicateInfo: info);
RegistrationResult(
success: false,
isDuplicate: true,
duplicateInfo: info,
conflictInfo: info,
);
factory RegistrationResult.alreadyOffShelf(Map<String, dynamic> info) =>
RegistrationResult(
success: false,
isAlreadyOffShelf: true,
errorMessage: info['message']?.toString() ?? '该总排号已下架至转运区域,不可重新上架',
conflictInfo: info,
);
factory RegistrationResult.error(String message) =>
RegistrationResult(success: false, errorMessage: message);
}
class PaichaOverviewItem {
final String zongpaiNo;
final String? workOrderNo;
final int quantity;
final String? locationCode;
final String status;
PaichaOverviewItem({
required this.zongpaiNo,
this.workOrderNo,
required this.quantity,
this.locationCode,
required this.status,
});
factory PaichaOverviewItem.fromJson(Map<String, dynamic> json) {
return PaichaOverviewItem(
zongpaiNo: json['zongpai_no'] as String,
workOrderNo: json['work_order_no']?.toString(),
quantity: json['quantity'] as int? ?? 0,
locationCode: json['location_code']?.toString(),
status: json['status']?.toString() ?? 'not_shelved',
);
}
}
class PaichaOverviewResult {
final bool success;
final bool notFound;
final String? errorMessage;
final String? paichaNo;
final int totalCount;
final List<PaichaOverviewItem> items;
PaichaOverviewResult({
required this.success,
this.notFound = false,
this.errorMessage,
this.paichaNo,
this.totalCount = 0,
this.items = const [],
});
factory PaichaOverviewResult.ok(Map<String, dynamic> json) {
final items =
(json['items'] as List<dynamic>?)
?.map(
(item) =>
PaichaOverviewItem.fromJson(item as Map<String, dynamic>),
)
.toList() ??
[];
return PaichaOverviewResult(
success: true,
paichaNo: json['paicha_no'] as String?,
totalCount: json['total_count'] as int? ?? items.length,
items: items,
);
}
factory PaichaOverviewResult.notFoundResult() => PaichaOverviewResult(
success: false,
notFound: true,
errorMessage: '暂无排产信息',
);
factory PaichaOverviewResult.error(String message) =>
PaichaOverviewResult(success: false, errorMessage: message);
}
// === 装箱模块数据类 ===
/// 箱号内单个总排号明细
class BoxItemData {
final int? boxItemId;
final String zongpaiNo;
final String? workOrderNo;
final int quantity;
final int? totalQuantity;
BoxItemData({
this.boxItemId,
required this.zongpaiNo,
this.workOrderNo,
required this.quantity,
this.totalQuantity,
});
factory BoxItemData.fromJson(Map<String, dynamic> json) {
return BoxItemData(
boxItemId: json['box_item_id'] as int?,
zongpaiNo: json['zongpai_no'] as String,
workOrderNo: json['work_order_no']?.toString(),
quantity: json['quantity'] as int,
totalQuantity: json['total_quantity'] as int?,
);
}
}
/// 箱号明细
class BoxDetailData {
final int boxNo;
final List<BoxItemData> items;
BoxDetailData({required this.boxNo, required this.items});
factory BoxDetailData.fromJson(Map<String, dynamic> json) {
final items =
(json['items'] as List<dynamic>?)
?.map((i) => BoxItemData.fromJson(i as Map<String, dynamic>))
.toList() ??
[];
return BoxDetailData(boxNo: json['box_no'] as int, items: items);
}
}
/// 当前总排号已分配的装箱明细
class CurrentZongpaiBoxData {
final int boxItemId;
final int boxNo;
final int quantity;
CurrentZongpaiBoxData({
required this.boxItemId,
required this.boxNo,
required this.quantity,
});
factory CurrentZongpaiBoxData.fromJson(Map<String, dynamic> json) {
return CurrentZongpaiBoxData(
boxItemId: json['box_item_id'] as int,
boxNo: json['box_no'] as int,
quantity: json['quantity'] as int,
);
}
}
/// 装箱信息查询结果
class BoxInfoResult {
final bool success;
final String? errorMessage;
final String? zongpaiNo;
final String? paichanNo;
final String? workOrderNo;
final int? quantity;
final List<CurrentZongpaiBoxData> currentZongpaiBoxes;
final List<BoxDetailData> existingBoxes;
final int maxBoxNo;
final int suggestedBoxNo;
BoxInfoResult({
required this.success,
this.errorMessage,
this.zongpaiNo,
this.paichanNo,
this.workOrderNo,
this.quantity,
this.currentZongpaiBoxes = const [],
this.existingBoxes = const [],
this.maxBoxNo = 0,
this.suggestedBoxNo = 1,
});
factory BoxInfoResult.ok(Map<String, dynamic> json) {
final boxes =
(json['existing_boxes'] as List<dynamic>?)
?.map((b) => BoxDetailData.fromJson(b as Map<String, dynamic>))
.toList() ??
[];
final currentBoxes =
(json['current_zongpai_boxes'] as List<dynamic>?)
?.map(
(b) => CurrentZongpaiBoxData.fromJson(b as Map<String, dynamic>),
)
.toList() ??
[];
return BoxInfoResult(
success: true,
zongpaiNo: json['zongpai_no'] as String?,
paichanNo: json['paichan_no'] as String?,
workOrderNo: json['work_order_no']?.toString(),
quantity: json['quantity'] as int?,
currentZongpaiBoxes: currentBoxes,
existingBoxes: boxes,
maxBoxNo: json['max_box_no'] as int? ?? 0,
suggestedBoxNo: json['suggested_box_no'] as int? ?? 1,
);
}
factory BoxInfoResult.error(String message) {
return BoxInfoResult(success: false, errorMessage: message);
}
}
/// 装箱保存结果
class BoxSaveResult {
final bool success;
final bool isDuplicate;
final String? errorMessage;
final String? errorCode;
final int? boxItemId;
final String? paichanNo;
final String? zongpaiNo;
final int? boxNo;
final int? quantity;
BoxSaveResult({
required this.success,
this.isDuplicate = false,
this.errorMessage,
this.errorCode,
this.boxItemId,
this.paichanNo,
this.zongpaiNo,
this.boxNo,
this.quantity,
});
factory BoxSaveResult.ok(Map<String, dynamic> json) {
return BoxSaveResult(
success: true,
boxItemId: json['box_item_id'] as int?,
paichanNo: json['paichan_no'] as String?,
zongpaiNo: json['zongpai_no'] as String?,
boxNo: json['box_no'] as int?,
quantity: json['quantity'] as int?,
);
}
factory BoxSaveResult.duplicate(Map<String, dynamic> json) {
return BoxSaveResult(
success: false,
isDuplicate: true,
errorCode: json['error_code']?.toString(),
errorMessage: json['message']?.toString(),
paichanNo: json['paichan_no'] as String?,
zongpaiNo: json['zongpai_no'] as String?,
boxNo: json['box_no'] as int?,
);
}
factory BoxSaveResult.error(String message) {
return BoxSaveResult(success: false, errorMessage: message);
}
}
class BoxDeleteResult {
final bool success;
final String? errorMessage;
BoxDeleteResult({required this.success, this.errorMessage});
}
class ApiService {
final http.Client _client;
final Duration timeout;
ApiService({http.Client? client, this.timeout = const Duration(seconds: 5)})
: _client = client ?? http.Client();
: _client = client ?? http.Client();
/// Submit a shelf registration (上架登记).
Future<RegistrationResult> registerLocation({
@@ -53,13 +327,32 @@ class ApiService {
switch (response.statusCode) {
case 200:
final body = jsonDecode(response.body) as Map<String, dynamic>;
if (body['previous_location'] != null) {
return RegistrationResult.offShelfSuccess();
}
return RegistrationResult.ok();
case 400:
final body = jsonDecode(response.body) as Map<String, dynamic>;
final msg = body['message']?.toString() ?? '请求参数错误';
return RegistrationResult.error(msg);
case 409:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return RegistrationResult.duplicate(body);
final errorCode = body['error_code']?.toString();
if (errorCode == 'DUPLICATE_LOCATION') {
return RegistrationResult.duplicate(body);
}
if (errorCode == 'ALREADY_OFF_SHELF') {
return RegistrationResult.alreadyOffShelf(body);
}
final msg = body['message']?.toString() ?? '提交失败';
return RegistrationResult.error(msg);
default:
final body = jsonDecode(response.body) as Map<String, dynamic>;
final msg = body['error'] ?? body['message'] ?? 'Unknown error (${response.statusCode})';
final msg =
body['message'] ??
body['error'] ??
'Unknown error (${response.statusCode})';
return RegistrationResult.error(msg.toString());
}
} catch (e) {
@@ -67,6 +360,170 @@ class ApiService {
}
}
Future<PaichaOverviewResult> fetchPaichaOverview({
required String baseUrl,
required String zongpaiNo,
}) async {
final uri = Uri.parse(
'$baseUrl/CargoTrace/location/paicha-overview',
).replace(queryParameters: {'zongpai_no': zongpaiNo});
try {
final response = await _client
.get(uri, headers: {'Content-Type': 'application/json'})
.timeout(timeout);
switch (response.statusCode) {
case 200:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return PaichaOverviewResult.ok(body);
case 400:
return PaichaOverviewResult.error('无效的总排号格式');
case 404:
return PaichaOverviewResult.notFoundResult();
default:
return PaichaOverviewResult.error('加载失败,点击重试');
}
} catch (e) {
return PaichaOverviewResult.error('加载失败,点击重试');
}
}
/// 查询装箱信息 — GET /CargoTrace/box/info
Future<BoxInfoResult> fetchBoxInfo({
required String baseUrl,
required String zongpaiNo,
}) async {
final uri = Uri.parse(
'$baseUrl/CargoTrace/box/info',
).replace(queryParameters: {'zongpai_no': zongpaiNo});
try {
final response = await _client
.get(uri, headers: {'Content-Type': 'application/json'})
.timeout(timeout);
switch (response.statusCode) {
case 200:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxInfoResult.ok(body);
case 400:
return BoxInfoResult.error('无效的总排号格式');
case 404:
return BoxInfoResult.error('未找到该总排号对应的排产号信息');
default:
return BoxInfoResult.error('查询失败 (${response.statusCode})');
}
} catch (e) {
return BoxInfoResult.error('网络异常,请检查网络连接');
}
}
/// 保存装箱记录 — POST /CargoTrace/box
Future<BoxSaveResult> saveBoxRecord({
required String baseUrl,
required String zongpaiNo,
required int boxNo,
required int quantity,
}) async {
final uri = Uri.parse('$baseUrl/CargoTrace/box');
try {
final response = await _client
.post(
uri,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({
'zongpai_no': zongpaiNo,
'box_no': boxNo,
'quantity': quantity,
}),
)
.timeout(timeout);
switch (response.statusCode) {
case 200:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxSaveResult.ok(body);
case 400:
final body = jsonDecode(response.body) as Map<String, dynamic>;
final msg = body['message']?.toString() ?? '请求参数错误';
return BoxSaveResult.error(msg);
case 409:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxSaveResult.duplicate(body);
case 404:
return BoxSaveResult.error('未找到该总排号对应的排产号信息');
default:
return BoxSaveResult.error('提交失败 (${response.statusCode})');
}
} catch (e) {
return BoxSaveResult.error('网络异常,请检查网络连接');
}
}
/// 更新装箱明细 — PATCH /CargoTrace/box/{boxItemId}
Future<BoxSaveResult> updateBoxRecord({
required String baseUrl,
required int boxItemId,
required int boxNo,
required int quantity,
}) async {
final uri = Uri.parse('$baseUrl/CargoTrace/box/$boxItemId');
try {
final response = await _client
.patch(
uri,
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'box_no': boxNo, 'quantity': quantity}),
)
.timeout(timeout);
switch (response.statusCode) {
case 200:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxSaveResult.ok(body);
case 400:
final body = jsonDecode(response.body) as Map<String, dynamic>;
final msg = body['message']?.toString() ?? '请求参数错误';
return BoxSaveResult.error(msg);
case 409:
final body = jsonDecode(response.body) as Map<String, dynamic>;
return BoxSaveResult.duplicate(body);
case 404:
return BoxSaveResult.error('指定装箱明细不存在');
default:
return BoxSaveResult.error('修改失败 (${response.statusCode})');
}
} catch (e) {
return BoxSaveResult.error('网络异常,请检查网络连接');
}
}
/// 删除装箱明细 — DELETE /CargoTrace/box/{boxItemId}
Future<BoxDeleteResult> deleteBoxRecord({
required String baseUrl,
required int boxItemId,
}) async {
final uri = Uri.parse('$baseUrl/CargoTrace/box/$boxItemId');
try {
final response = await _client
.delete(uri, headers: {'Content-Type': 'application/json'})
.timeout(timeout);
switch (response.statusCode) {
case 200:
return BoxDeleteResult(success: true);
case 404:
return BoxDeleteResult(success: false, errorMessage: '指定装箱明细不存在');
default:
return BoxDeleteResult(
success: false,
errorMessage: '删除失败 (${response.statusCode})',
);
}
} catch (e) {
return BoxDeleteResult(success: false, errorMessage: '网络异常,请检查网络连接');
}
}
/// Test connectivity by making a HEAD request to the base URL.
Future<bool> testConnection(String baseUrl) async {
try {

View File

@@ -0,0 +1,53 @@
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:convert';
/// 应用全局配置服务 (替代 SharedPreferences)
/// 配置数据持久化为本地 JSON 文件,覆盖安装应用时数据不丢失。
class AppConfigService {
static const String _kConfigFileName = 'app_config.json';
static final Map<String, dynamic> _defaults = {'api_url': ''};
Future<String> get _filePath async {
final directory = await getApplicationDocumentsDirectory();
return '${directory.path}/$_kConfigFileName';
}
/// 读取完整配置字典
Future<Map<String, dynamic>> loadConfig() async {
try {
final file = File(await _filePath);
if (await file.exists()) {
final jsonString = await file.readAsString();
return jsonDecode(jsonString) as Map<String, dynamic>;
}
} catch (e) {
debugPrint('[AppConfig] 读取配置失败: $e');
}
return Map<String, dynamic>.from(_defaults);
}
/// 读取字符串配置项
Future<String?> getString(String key) async {
final config = await loadConfig();
return config[key] as String?;
}
/// 保存字符串配置项
Future<void> setString(String key, String value) async {
final config = await loadConfig();
config[key.toString()] = value.toString();
await saveConfig(config);
}
/// 完整写入 JSON 文件
Future<void> saveConfig(Map<String, dynamic> config) async {
try {
final file = File(await _filePath);
await file.writeAsString(jsonEncode(config));
} catch (e) {
debugPrint('[AppConfig] 保存配置失败: $e');
}
}
}

View File

@@ -0,0 +1,38 @@
enum PaichanContextChange { firstScan, samePaichan, switchedPaichan }
class PaichanContextDecision {
final PaichanContextChange change;
final int? boxNoToApply;
const PaichanContextDecision({required this.change, this.boxNoToApply});
bool get isSwitched => change == PaichanContextChange.switchedPaichan;
}
PaichanContextDecision decideMultiCodePaichanContext({
required String? lastPaichanNo,
required String? currentPaichanNo,
required String currentBoxNoText,
required int maxBoxNo,
}) {
final recommendedBoxNo = maxBoxNo + 1;
if (currentPaichanNo == null || currentPaichanNo.isEmpty) {
return const PaichanContextDecision(change: PaichanContextChange.firstScan);
}
if (lastPaichanNo == null || lastPaichanNo.isEmpty) {
return PaichanContextDecision(
change: PaichanContextChange.firstScan,
boxNoToApply: currentBoxNoText.trim().isEmpty ? recommendedBoxNo : null,
);
}
if (lastPaichanNo == currentPaichanNo) {
return PaichanContextDecision(
change: PaichanContextChange.samePaichan,
boxNoToApply: currentBoxNoText.trim().isEmpty ? recommendedBoxNo : null,
);
}
return PaichanContextDecision(
change: PaichanContextChange.switchedPaichan,
boxNoToApply: recommendedBoxNo,
);
}

View File

@@ -0,0 +1,88 @@
import 'package:vibration/vibration.dart';
import 'package:pad_scanner/services/sound_service.dart';
/// Unified feedback events used across the app.
enum FeedbackEvent {
scanValid, // Valid barcode scanned → beep + short vibrate
scanInvalid, // Invalid barcode → error sound + short vibrate
submitSuccess, // Submit succeeded → success sound + long vibrate
submitFailure, // Submit failed → failure sound + short vibrate
duplicateError, // Duplicate (shelf) → alert loop + continuous vibrate
networkError, // Network error → failure sound + short vibrate
duplicateBoxNo, // Duplicate box no → failure sound + short vibrate
modeSwitch, // Mode toggle → beep only
paichanSwitch, // Paichan changed → beep + short vibrate
}
/// Centralized feedback dispatcher.
///
/// Each page manages its own bottom status bar state; this service handles
/// the sound, vibration channels only.
class FeedbackService {
final SoundService _soundService;
FeedbackService({SoundService? soundService})
: _soundService = soundService ?? SoundService();
/// Trigger feedback for the given [event].
Future<void> trigger(FeedbackEvent event) async {
switch (event) {
case FeedbackEvent.scanValid:
_soundService.playBeep();
_vibrateShort();
case FeedbackEvent.scanInvalid:
_soundService.playError();
_vibrateShort();
case FeedbackEvent.submitSuccess:
_soundService.playSuccess();
_vibrateLong();
case FeedbackEvent.submitFailure:
_soundService.playFailure();
_vibrateShort();
case FeedbackEvent.duplicateError:
_soundService.playAlertLoop();
_vibratePattern();
case FeedbackEvent.networkError:
_soundService.playFailure();
_vibrateShort();
case FeedbackEvent.duplicateBoxNo:
_soundService.playFailure();
_vibrateShort();
case FeedbackEvent.modeSwitch:
_soundService.playBeep();
case FeedbackEvent.paichanSwitch:
_soundService.playBeep();
_vibrateShort();
}
}
/// Stop any ongoing alert (e.g. when duplicate dialog is closed).
Future<void> stopAlert() async {
_soundService.stopAlert();
}
void _vibrateShort() {
Vibration.vibrate(duration: 100);
}
void _vibrateLong() {
Vibration.vibrate(duration: 200);
}
/// Continuous vibration pattern: 3 bursts to signal critical error.
void _vibratePattern() {
Vibration.vibrate(pattern: [0, 300, 100, 300, 100, 300]);
}
Future<void> dispose() async {
await _soundService.dispose();
}
}

View File

@@ -0,0 +1,128 @@
import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:pad_scanner/services/app_config_service.dart';
class SoundService {
static const _keySuccess = 'sound_success';
static const _keyFailure = 'sound_failure';
static const _keyBeep = 'sound_beep';
static const _keyError = 'sound_error';
static const _keyAlert = 'sound_alert';
final _player = AudioPlayer();
final _alertPlayer = AudioPlayer();
final _configService = AppConfigService();
Timer? _alertTimer;
// --- Path getters ---
Future<String?> getSuccessPath() =>
_configService.getString(_keySuccess);
Future<String?> getFailurePath() =>
_configService.getString(_keyFailure);
Future<String?> getBeepPath() =>
_configService.getString(_keyBeep);
Future<String?> getErrorPath() =>
_configService.getString(_keyError);
Future<String?> getAlertPath() =>
_configService.getString(_keyAlert);
// --- Path setters ---
Future<void> setSuccessPath(String? path) =>
_setConfigPath(_keySuccess, path);
Future<void> setFailurePath(String? path) =>
_setConfigPath(_keyFailure, path);
Future<void> setBeepPath(String? path) =>
_setConfigPath(_keyBeep, path);
Future<void> setErrorPath(String? path) =>
_setConfigPath(_keyError, path);
Future<void> setAlertPath(String? path) =>
_setConfigPath(_keyAlert, path);
Future<void> _setConfigPath(String key, String? path) async {
if (path != null) {
await _configService.setString(key, path);
} else {
final config = await _configService.loadConfig();
config.remove(key);
}
}
// --- Playback methods ---
Future<void> playSuccess() async {
final path = await getSuccessPath();
if (path != null) {
await _player.play(DeviceFileSource(path));
}
}
Future<void> playFailure() async {
final path = await getFailurePath();
if (path != null) {
await _player.play(DeviceFileSource(path));
}
}
Future<void> playBeep() async {
final path = await getBeepPath();
if (path != null) {
await _player.play(DeviceFileSource(path));
}
}
Future<void> playError() async {
final path = await getErrorPath();
if (path != null) {
await _player.play(DeviceFileSource(path));
}
}
/// Play alert sound in a loop until [stopAlert] is called.
/// Loops up to 10 times as a safety guard (~15 seconds max).
Future<void> playAlertLoop() async {
final path = await getAlertPath();
if (path == null) return;
_alertTimer?.cancel();
var count = 0;
_alertTimer = Timer.periodic(const Duration(milliseconds: 1500), (_) async {
if (count >= 10) {
_alertTimer?.cancel();
return;
}
await _alertPlayer.play(DeviceFileSource(path));
count++;
});
// Play immediately first time
await _alertPlayer.play(DeviceFileSource(path));
count++;
}
/// Stop the alert loop.
void stopAlert() {
_alertTimer?.cancel();
_alertTimer = null;
_alertPlayer.stop();
}
Future<void> play(String path) async {
await _player.play(DeviceFileSource(path));
}
Future<void> dispose() async {
_alertTimer?.cancel();
await _player.dispose();
await _alertPlayer.dispose();
}
}

View File

@@ -0,0 +1,60 @@
import 'package:flutter/material.dart';
/// Status bar dot colors matching PRD requirements.
enum StatusDotColor {
blue, // idle / waiting
orange, // submitting
green, // success
red, // error (invalid code / submit failure / duplicate)
yellow, // network error
amber, // warning (duplicate box number)
}
/// Reusable bottom status bar with a colored dot and text.
class StatusBar extends StatelessWidget {
final StatusDotColor dotColor;
final String text;
const StatusBar({super.key, required this.dotColor, required this.text});
Color _resolveDotColor(BuildContext context) {
return switch (dotColor) {
StatusDotColor.blue => Colors.blue,
StatusDotColor.orange => Colors.orange,
StatusDotColor.green => Colors.green,
StatusDotColor.red => Colors.red,
StatusDotColor.yellow => Colors.yellow.shade700,
StatusDotColor.amber => Colors.amber,
};
}
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
color: colorScheme.surfaceContainerHighest,
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: BoxDecoration(
color: _resolveDotColor(context),
shape: BoxShape.circle,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
text,
style: const TextStyle(fontSize: 14),
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}
}

View File

@@ -6,6 +6,10 @@
#include "generated_plugin_registrant.h"
#include <audioplayers_linux/audioplayers_linux_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin");
audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar);
}

View File

@@ -3,9 +3,11 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
audioplayers_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)

View File

@@ -5,8 +5,12 @@
import FlutterMacOS
import Foundation
import shared_preferences_foundation
import audioplayers_darwin
import device_info_plus
import file_picker
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
AudioplayersDarwinPlugin.register(with: registry.registrar(forPlugin: "AudioplayersDarwinPlugin"))
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
FilePickerPlugin.register(with: registry.registrar(forPlugin: "FilePickerPlugin"))
}

View File

@@ -1,14 +1,78 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
args:
dependency: transitive
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
url: "https://pub.dev"
source: hosted
version: "2.7.0"
async:
dependency: transitive
description:
name: async
sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.0"
version: "2.13.1"
audioplayers:
dependency: "direct main"
description:
name: audioplayers
sha256: a72dd459d1a48f61a6fb9c0134dba26597c9236af40639ff0eb70eb4e0baab70
url: "https://pub.dev"
source: hosted
version: "6.6.0"
audioplayers_android:
dependency: transitive
description:
name: audioplayers_android
sha256: "60a6728277228413a85755bd3ffd6fab98f6555608923813ce383b190a360605"
url: "https://pub.dev"
source: hosted
version: "5.2.1"
audioplayers_darwin:
dependency: transitive
description:
name: audioplayers_darwin
sha256: c994b3bb3a921e4904ac40e013fbc94488e824fd7c1de6326f549943b0b44a91
url: "https://pub.dev"
source: hosted
version: "6.4.0"
audioplayers_linux:
dependency: transitive
description:
name: audioplayers_linux
sha256: f75bce1ce864170ef5e6a2c6a61cd3339e1a17ce11e99a25bae4474ea491d001
url: "https://pub.dev"
source: hosted
version: "4.2.1"
audioplayers_platform_interface:
dependency: transitive
description:
name: audioplayers_platform_interface
sha256: "0e2f6a919ab56d0fec272e801abc07b26ae7f31980f912f24af4748763e5a656"
url: "https://pub.dev"
source: hosted
version: "7.1.1"
audioplayers_web:
dependency: transitive
description:
name: audioplayers_web
sha256: faa8fa6587f996a6f604433b53af44c57a1407d4fe8dff5766cf63d6875e8de9
url: "https://pub.dev"
source: hosted
version: "5.2.0"
audioplayers_windows:
dependency: transitive
description:
name: audioplayers_windows
sha256: bafff2b38b6f6d331887558ba6e0a01c9c208d9dbb3ad0005234db065122a734
url: "https://pub.dev"
source: hosted
version: "4.3.0"
boolean_selector:
dependency: transitive
description:
@@ -33,6 +97,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.2"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: "83ccdaa064c980b5596c35dd64a8d3ecc68620174ab9b90b6343b753aa721687"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
collection:
dependency: transitive
description:
@@ -41,14 +113,54 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.19.1"
cross_file:
dependency: transitive
description:
name: cross_file
sha256: "28bb3ae56f117b5aec029d702a90f57d285cd975c3c5c281eaca38dbc47c5937"
url: "https://pub.dev"
source: hosted
version: "0.3.5+2"
crypto:
dependency: transitive
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev"
source: hosted
version: "3.0.7"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
url: "https://pub.dev"
source: hosted
version: "1.0.8"
version: "1.0.9"
dbus:
dependency: transitive
description:
name: dbus
sha256: d0c98dcd4f5169878b6cf8f6e0a52403a9dff371a3e2f019697accbf6f44a270
url: "https://pub.dev"
source: hosted
version: "0.7.12"
device_info_plus:
dependency: transitive
description:
name: device_info_plus
sha256: b4fed1b2835da9d670d7bed7db79ae2a94b0f5ad6312268158a9b5479abbacdd
url: "https://pub.dev"
source: hosted
version: "12.4.0"
device_info_plus_platform_interface:
dependency: transitive
description:
name: device_info_plus_platform_interface
sha256: e1ea89119e34903dca74b883d0dd78eb762814f97fb6c76f35e9ff74d261a18f
url: "https://pub.dev"
source: hosted
version: "7.0.3"
fake_async:
dependency: transitive
description:
@@ -73,6 +185,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
file_picker:
dependency: "direct main"
description:
name: file_picker
sha256: "27c58ff4ec17d8e05b8b27fa66175bf5786b9ff9bd94ca418a571c7f6771b27b"
url: "https://pub.dev"
source: hosted
version: "11.0.0"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flutter:
dependency: "direct main"
description: flutter
@@ -86,6 +214,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.0"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
name: flutter_plugin_android_lifecycle
sha256: "38d1c268de9097ff59cf0e844ac38759fc78f76836d37edad06fa21e182055a0"
url: "https://pub.dev"
source: hosted
version: "2.0.34"
flutter_test:
dependency: "direct dev"
description: flutter
@@ -96,6 +232,22 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
glob:
dependency: transitive
description:
name: glob
sha256: c3f1ee72c96f8f78935e18aa8cecced9ab132419e8625dc187e1c2408efc20de
url: "https://pub.dev"
source: hosted
version: "2.1.3"
hooks:
dependency: transitive
description:
name: hooks
sha256: "025f060e86d2d4c3c47b56e33caf7f93bf9283340f26d23424ebcfccf34f621e"
url: "https://pub.dev"
source: hosted
version: "1.0.3"
http:
dependency: "direct main"
description:
@@ -112,6 +264,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.1.2"
jni:
dependency: transitive
description:
name: jni
sha256: c2230682d5bc2362c1c9e8d3c7f406d9cbba23ab3f2e203a025dd47e0fb2e68f
url: "https://pub.dev"
source: hosted
version: "1.0.0"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "8b59e590786050b1cd866677dddaf76b1ade5e7bc751abe04b86e84d379d3ba6"
url: "https://pub.dev"
source: hosted
version: "1.0.1"
leak_tracker:
dependency: transitive
description:
@@ -144,6 +312,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.1.1"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
@@ -168,6 +344,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.17.0"
native_toolchain_c:
dependency: transitive
description:
name: native_toolchain_c
sha256: "6ba77bb18063eebe9de401f5e6437e95e1438af0a87a3a39084fbd37c90df572"
url: "https://pub.dev"
source: hosted
version: "0.17.6"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: "100a1c87616ab6ed41ec263b083c0ef3261ee6cd1dc3b0f35f8ddfa4f996fe52"
url: "https://pub.dev"
source: hosted
version: "9.3.0"
package_config:
dependency: transitive
description:
name: package_config
sha256: f096c55ebb7deb7e384101542bfba8c52696c1b56fca2eb62827989ef2353bbc
url: "https://pub.dev"
source: hosted
version: "2.2.0"
path:
dependency: transitive
description:
@@ -176,6 +376,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider:
dependency: "direct main"
description:
name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
url: "https://pub.dev"
source: hosted
version: "2.1.5"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"
url: "https://pub.dev"
source: hosted
version: "2.3.1"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
url: "https://pub.dev"
source: hosted
version: "2.6.0"
path_provider_linux:
dependency: transitive
description:
@@ -200,6 +424,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.3.0"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
url: "https://pub.dev"
source: hosted
version: "7.0.2"
platform:
dependency: transitive
description:
@@ -216,62 +448,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
sha256: "6e8bf70b7fef813df4e9a36f658ac46d107db4b4cfe1048b477d4e453a8159f5"
url: "https://pub.dev"
source: hosted
version: "2.5.3"
shared_preferences_android:
pub_semver:
dependency: transitive
description:
name: shared_preferences_android
sha256: bd14436108211b0d4ee5038689a56d4ae3620fd72fd6036e113bf1345bc74d9e
name: pub_semver
sha256: "5bfcf68ca79ef689f8990d1160781b4bad40a3bd5e5218ad4076ddb7f4081585"
url: "https://pub.dev"
source: hosted
version: "2.4.13"
shared_preferences_foundation:
version: "2.2.0"
record_use:
dependency: transitive
description:
name: shared_preferences_foundation
sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03"
name: record_use
sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed"
url: "https://pub.dev"
source: hosted
version: "2.5.4"
shared_preferences_linux:
dependency: transitive
description:
name: shared_preferences_linux
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_platform_interface:
dependency: transitive
description:
name: shared_preferences_platform_interface
sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_web:
dependency: transitive
description:
name: shared_preferences_web
sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
url: "https://pub.dev"
source: hosted
version: "2.4.3"
shared_preferences_windows:
dependency: transitive
description:
name: shared_preferences_windows
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
version: "0.6.0"
sky_engine:
dependency: transitive
description: flutter
@@ -281,10 +473,10 @@ packages:
dependency: transitive
description:
name: source_span
sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.1"
version: "1.10.2"
stack_trace:
dependency: transitive
description:
@@ -309,6 +501,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.1"
synchronized:
dependency: transitive
description:
name: synchronized
sha256: "63896c27e81b28f8cb4e69ead0d3e8f03f1d1e5fc531a3e579cabed6a2c7c9e5"
url: "https://pub.dev"
source: hosted
version: "3.4.0+1"
term_glyph:
dependency: transitive
description:
@@ -333,6 +533,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.4.0"
uuid:
dependency: transitive
description:
name: uuid
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"
url: "https://pub.dev"
source: hosted
version: "4.5.3"
vector_math:
dependency: transitive
description:
@@ -341,14 +549,30 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.2.0"
vibration:
dependency: "direct main"
description:
name: vibration
sha256: "9bb06614c69260f8bd11c80fe01ed7988905cf00e3417d656c2647e41f261d87"
url: "https://pub.dev"
source: hosted
version: "3.1.8"
vibration_platform_interface:
dependency: transitive
description:
name: vibration_platform_interface
sha256: "258c273268f8aa40c88d29741137c536874a738779b92ddb8aa32ed093721ec5"
url: "https://pub.dev"
source: hosted
version: "0.1.2"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: ddfa8d30d89985b96407efce8acbdd124701f96741f2d981ca860662f1c0dc02
sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360"
url: "https://pub.dev"
source: hosted
version: "15.0.0"
version: "15.2.0"
web:
dependency: transitive
description:
@@ -357,6 +581,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.1"
win32:
dependency: transitive
description:
name: win32
sha256: d7cb55e04cd34096cd3a79b3330245f54cb96a370a1c27adb3c84b917de8b08e
url: "https://pub.dev"
source: hosted
version: "5.15.0"
win32_registry:
dependency: transitive
description:
name: win32_registry
sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae"
url: "https://pub.dev"
source: hosted
version: "2.1.0"
xdg_directories:
dependency: transitive
description:
@@ -365,6 +605,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.0"
xml:
dependency: transitive
description:
name: xml
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
url: "https://pub.dev"
source: hosted
version: "6.6.1"
yaml:
dependency: transitive
description:
name: yaml
sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
url: "https://pub.dev"
source: hosted
version: "3.1.3"
sdks:
dart: ">=3.9.0-0 <4.0.0"
flutter: ">=3.29.0"
dart: ">=3.11.0 <4.0.0"
flutter: ">=3.38.4"

View File

@@ -35,7 +35,10 @@ dependencies:
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
http: ^1.2.0
shared_preferences: ^2.2.0
path_provider: ^2.1.1
vibration: ^3.1.8
file_picker: 11.0.0
audioplayers: ^6.6.0
dev_dependencies:
flutter_test:

View File

@@ -0,0 +1,391 @@
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:pad_scanner/services/api_service.dart';
void main() {
group('ApiService.registerLocation', () {
test('returns ok on 200', () async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({
'zongpai_no': '26B1',
'location_code': 'A01-02-03',
'created_at': '2026-05-11T10:00:00',
}),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.registerLocation(
baseUrl: 'http://localhost',
zongpaiNo: '26B1',
locationCode: 'A01-02-03',
);
expect(result.success, isTrue);
expect(result.isDuplicate, isFalse);
expect(result.isOffShelfSuccess, isFalse);
});
test('returns off-shelf success on 200 with previous_location', () async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({
'zongpai_no': '26B1',
'location_code': 'TRANS-01',
'previous_location': 'A01-02-03',
'created_at': '2026-05-13T10:00:00',
}),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.registerLocation(
baseUrl: 'http://localhost',
zongpaiNo: '26B1',
locationCode: 'TRANS-01',
);
expect(result.success, isTrue);
expect(result.isOffShelfSuccess, isTrue);
expect(result.isDuplicate, isFalse);
});
test(
'returns duplicate on 409 with location_code and registered_at',
() async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({
'error_code': 'DUPLICATE_LOCATION',
'message': '该总排号已存在货位记录',
'location_code': 'A01-02-03',
'registered_at': '2026-05-11T10:00:00',
}),
409,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.registerLocation(
baseUrl: 'http://localhost',
zongpaiNo: '26B1',
locationCode: 'A02-01-01',
);
expect(result.success, isFalse);
expect(result.isDuplicate, isTrue);
expect(result.duplicateInfo?['location_code'], 'A01-02-03');
expect(result.duplicateInfo?['registered_at'], '2026-05-11T10:00:00');
},
);
test('returns already off shelf on 409 ALREADY_OFF_SHELF', () async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({
'error_code': 'ALREADY_OFF_SHELF',
'message': '该总排号已下架至转运区域,不可重新上架',
'location_code': 'TRANS-01',
'registered_at': '2026-05-13T10:00:00',
}),
409,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.registerLocation(
baseUrl: 'http://localhost',
zongpaiNo: '26B1',
locationCode: 'A02-01-01',
);
expect(result.success, isFalse);
expect(result.isDuplicate, isFalse);
expect(result.isAlreadyOffShelf, isTrue);
expect(result.errorMessage, '该总排号已下架至转运区域,不可重新上架');
expect(result.conflictInfo?['location_code'], 'TRANS-01');
});
test('returns error on 400 with message', () async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({
'error_code': 'INVALID_ZONGPAI',
'message': 'INVALID_ZONGPAI',
}),
400,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.registerLocation(
baseUrl: 'http://localhost',
zongpaiNo: 'INVALID',
locationCode: 'A01-02-03',
);
expect(result.success, isFalse);
expect(result.isDuplicate, isFalse);
expect(result.errorMessage, 'INVALID_ZONGPAI');
});
test('returns error on network failure', () async {
final mockClient = _MockClient((request) async {
throw Exception('Connection refused');
});
final svc = ApiService(client: mockClient, timeout: Duration(seconds: 1));
final result = await svc.registerLocation(
baseUrl: 'http://localhost',
zongpaiNo: '26B1',
locationCode: 'A01-02-03',
);
expect(result.success, isFalse);
expect(result.errorMessage, '网络异常,请检查网络连接');
});
});
group('ApiService boxing APIs', () {
test('fetchPaichaOverview parses overview items', () async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({
'paicha_no': 'R00001',
'total_count': 2,
'items': [
{
'zongpai_no': '26B1',
'work_order_no': '6-1(7)',
'quantity': 80,
'location_code': 'A01-02-03',
'status': 'on_shelf',
},
{
'zongpai_no': '26B2',
'work_order_no': '6-2(3)',
'quantity': 45,
'location_code': null,
'status': 'not_shelved',
},
],
}),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.fetchPaichaOverview(
baseUrl: 'http://localhost',
zongpaiNo: '26B1',
);
expect(result.success, isTrue);
expect(result.paichaNo, 'R00001');
expect(result.totalCount, 2);
expect(result.items.first.status, 'on_shelf');
expect(result.items.last.locationCode, isNull);
});
test('fetchPaichaOverview maps 404 to not found result', () async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({'error_code': 'PAICHA_NOT_FOUND', 'message': '暂无排产信息'}),
404,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.fetchPaichaOverview(
baseUrl: 'http://localhost',
zongpaiNo: '26B404',
);
expect(result.success, isFalse);
expect(result.notFound, isTrue);
expect(result.errorMessage, '暂无排产信息');
});
test(
'fetchPaichaOverview maps network failure to retryable error',
() async {
final mockClient = _MockClient((request) async {
throw Exception('Connection refused');
});
final svc = ApiService(client: mockClient);
final result = await svc.fetchPaichaOverview(
baseUrl: 'http://localhost',
zongpaiNo: '26B1',
);
expect(result.success, isFalse);
expect(result.notFound, isFalse);
expect(result.errorMessage, '加载失败,点击重试');
},
);
test('fetchBoxInfo parses current boxes and box item ids', () async {
final mockClient = _MockClient((request) async {
return http.Response(
jsonEncode({
'zongpai_no': '26BW0011',
'paichan_no': 'W00009',
'work_order_no': '6-1(7)',
'quantity': 80,
'current_zongpai_boxes': [
{'box_item_id': 101, 'box_no': 3, 'quantity': 30},
],
'existing_boxes': [
{
'box_no': 3,
'items': [
{
'box_item_id': 101,
'zongpai_no': '26BW0011',
'work_order_no': '6-1(7)',
'quantity': 30,
'total_quantity': 80,
},
],
},
],
'max_box_no': 3,
'suggested_box_no': 4,
}),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.fetchBoxInfo(
baseUrl: 'http://localhost',
zongpaiNo: '26BW0011',
);
expect(result.success, isTrue);
expect(result.currentZongpaiBoxes.single.boxItemId, 101);
expect(result.existingBoxes.single.items.single.boxItemId, 101);
expect(result.existingBoxes.single.items.single.totalQuantity, 80);
expect(result.suggestedBoxNo, 4);
});
test('saveBoxRecord sends simplified request body', () async {
late Map<String, dynamic> body;
final mockClient = _MockClient((request) async {
final req = request as http.Request;
body = jsonDecode(req.body) as Map<String, dynamic>;
return http.Response(
jsonEncode({
'box_item_id': 102,
'paichan_no': 'W00009',
'box_no': 4,
'zongpai_no': '26BW0012',
'quantity': 34,
'created_at': '2026-05-13T10:00:00',
}),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.saveBoxRecord(
baseUrl: 'http://localhost',
zongpaiNo: '26BW0012',
boxNo: 4,
quantity: 34,
);
expect(result.success, isTrue);
expect(result.boxItemId, 102);
expect(result.zongpaiNo, '26BW0012');
expect(body, {'zongpai_no': '26BW0012', 'box_no': 4, 'quantity': 34});
expect(body.containsKey('box_mode'), isFalse);
});
test('updateBoxRecord sends simplified request body', () async {
late Map<String, dynamic> body;
final mockClient = _MockClient((request) async {
final req = request as http.Request;
body = jsonDecode(req.body) as Map<String, dynamic>;
return http.Response(
jsonEncode({
'box_item_id': 102,
'paichan_no': 'W00009',
'box_no': 4,
'zongpai_no': '26BW0012',
'quantity': 20,
'updated_at': '2026-05-13T10:00:00',
}),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final result = await svc.updateBoxRecord(
baseUrl: 'http://localhost',
boxItemId: 102,
boxNo: 4,
quantity: 20,
);
expect(result.success, isTrue);
expect(body, {'box_no': 4, 'quantity': 20});
expect(body.containsKey('box_mode'), isFalse);
});
test('deleteBoxRecord handles success and not found', () async {
var calls = 0;
final mockClient = _MockClient((request) async {
calls += 1;
if (calls == 1) {
return http.Response(
jsonEncode({'box_item_id': 102, 'deleted': true}),
200,
headers: {'content-type': 'application/json; charset=utf-8'},
);
}
return http.Response(
jsonEncode({
'error_code': 'BOX_ITEM_NOT_FOUND',
'message': '指定装箱明细不存在',
}),
404,
headers: {'content-type': 'application/json; charset=utf-8'},
);
});
final svc = ApiService(client: mockClient);
final ok = await svc.deleteBoxRecord(
baseUrl: 'http://localhost',
boxItemId: 102,
);
final missing = await svc.deleteBoxRecord(
baseUrl: 'http://localhost',
boxItemId: 999,
);
expect(ok.success, isTrue);
expect(missing.success, isFalse);
expect(missing.errorMessage, '指定装箱明细不存在');
});
});
}
class _MockClient extends http.BaseClient {
final Future<http.Response> Function(http.BaseRequest) _handler;
_MockClient(this._handler);
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final response = await _handler(request);
return http.StreamedResponse(
http.ByteStream.fromBytes(response.bodyBytes),
response.statusCode,
headers: response.headers,
reasonPhrase: response.reasonPhrase,
);
}
}

View File

@@ -0,0 +1,60 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pad_scanner/services/boxing_context.dart';
void main() {
group('decideMultiCodePaichanContext', () {
test('first scan records context and fills recommended box if empty', () {
final decision = decideMultiCodePaichanContext(
lastPaichanNo: null,
currentPaichanNo: 'W00009',
currentBoxNoText: '',
maxBoxNo: 3,
);
expect(decision.change, PaichanContextChange.firstScan);
expect(decision.boxNoToApply, 4);
expect(decision.isSwitched, isFalse);
});
test('same paichan keeps current box number', () {
final decision = decideMultiCodePaichanContext(
lastPaichanNo: 'W00009',
currentPaichanNo: 'W00009',
currentBoxNoText: '8',
maxBoxNo: 3,
);
expect(decision.change, PaichanContextChange.samePaichan);
expect(decision.boxNoToApply, isNull);
expect(decision.isSwitched, isFalse);
});
test('switched paichan resets to new paichan max box plus one', () {
final decision = decideMultiCodePaichanContext(
lastPaichanNo: 'W00009',
currentPaichanNo: 'W00010',
currentBoxNoText: '8',
maxBoxNo: 1,
);
expect(decision.change, PaichanContextChange.switchedPaichan);
expect(decision.boxNoToApply, 2);
expect(decision.isSwitched, isTrue);
});
test(
'same paichan defensively fills recommended box when box is empty',
() {
final decision = decideMultiCodePaichanContext(
lastPaichanNo: 'W00009',
currentPaichanNo: 'W00009',
currentBoxNoText: '',
maxBoxNo: 4,
);
expect(decision.change, PaichanContextChange.samePaichan);
expect(decision.boxNoToApply, 5);
},
);
});
}

View File

@@ -6,6 +6,9 @@
#include "generated_plugin_registrant.h"
#include <audioplayers_windows/audioplayers_windows_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
AudioplayersWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin"));
}

View File

@@ -3,9 +3,11 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
audioplayers_windows
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
set(PLUGIN_BUNDLED_LIBRARIES)