commit c8d1a0cfbc499f1a95111943aab013659f6506f7 Author: Mrhongxing <154480715+Mrhongxing@users.noreply.github.com> Date: Fri Oct 2 21:48:08 2026 +0800 yiyibuming diff --git a/README.md b/README.md new file mode 100644 index 0000000..a5c01ce --- /dev/null +++ b/README.md @@ -0,0 +1,353 @@ +预设代码使用方式 +本题针对 Python / Go / Java / C++ / TypeScript 在 work/baseline/ 目录下提供了预设基线代码。建议在 baseline 代码基础上修复和补全功能;也可以从 0 开始编码,但通常会花费更多时间。请选择作答语言,并按该语言的判题入口要求,把对应预设目录下的内容复制到当前 work/ 根目录。 + +语言 预设目录 +Python work/baseline/python/ +Go work/baseline/go/ +TypeScript work/baseline/ts/ +Java / Spring Boot work/baseline/java/ +C++ work/baseline/cpp/ +复制命令示例(在 work/ 目录下执行): + +# Python +cp -R baseline/python/. . + +# Go +cp -R baseline/go/. . + +# TypeScript +cp -R baseline/ts/. . + +# Java / Spring Boot +cp -R baseline/java/. . + +# C++ +cp -R baseline/cpp/. . +不要复制其他语言目录,也不要提交运行过程中生成的数据库、构建目录或缓存文件。 + +题目描述 +实现一个快递/物流配送履约后端服务。系统覆盖包裹从揽收、分拣、干线运输、派送到签收的全链路,并处理收件人拒收逆向退回、包裹破损理赔、在途改址重路由、货到付款(COD,此处款项指收件人向寄件人支付的货款)代收与结算、以及网点爆仓时的调度。 + +系统要求 +管理包裹(Parcel)的全生命周期:揽收、分拣、推进、派单、派送、签收、拒收、改址、报损。 +管理运单(Waybill):记录路由段序列、当前所在网点、时效承诺,支持路由追加、重算、冻结与结算。 +管理网点(Station):揽收点 / 分拣中心 / 中转站 / 派送网点,含容量与在仓量,支持入站、出站、停用、启用。 +管理快递员(Courier):归属网点,含当日派件配额与在途件数,支持审核、派件占额、释放、异常审查、重分配。 +管理客户(Customer):寄件人与收件人双角色,含信用等级与代收余额,支持寄件、信用调整、收取回款。 +管理理赔单(Claim):破损/丢件赔付凭证,支持定损、赔付、驳回、结案。 +管理代收货款(COD):签收时收款、对账、回款给寄件人,拒收时关闭。 +提供逻辑时钟与事件流,驱动并广播超时、窗口与关键履约节点。 +业务流程 +快递履约围绕三条主线推进,彼此通过包裹与运单状态相互牵动: + +正向履约线:寄件人下单创建包裹,揽收网点揽收,分拣中心按品类分拣,沿路由段逐站推进运输,到达派送网点后派单给快递员,快递员派送,收件人签收。 +异常处理线:派送失败、收件人拒收、运输破损、在途改址、网点停用等异常,会触发包裹的退回、改派、重路由或理赔,并牵动相关的运单、网点与快递员。 +财务结算线:代收货款在签收时收款、对账后回款给寄件人;理赔定损后向相关方赔付。 +各实体状态随这三条线推进而变化;包裹与运单是各线交汇的核心,其状态变动可能反过来影响关联的网点在仓量、快递员负载与客户账务。 + +业务规则 +> 以下为业务语义描述。状态枚举为精确字符串,需原样使用。 + +状态枚举(精确字符串) +包裹 Parcel:待揽收 / 已揽收 / 分拣中 / 运输中 / 待派送 / 派送中 / 已签收 / 已拒收 / 退回中 / 已退回 / 已理赔关闭 +运单 Waybill:已创建 / 运输中 / 派送阶段 / 已完成 / 逆向退回 / 理赔冻结 / 已作废 / 已结算 +网点 Station:正常 / 繁忙 / 爆仓 / 质量预警 / 停用 +快递员 Courier:待审核 / 空闲 / 派送中 / 已满载 / 异常审查 / 待重分配 +理赔单 Claim:已受理 / 定损中 / 已赔付 / 已驳回 / 已结案 +代收货款 COD:待收款 / 已收款 / 对账中 / 已回款 / 已关闭 +客户 Customer:正常 / 信用观察 / 受限 / 冻结 +品类:易碎 / 冷链 / 普通 +优先级:加急 / 普通 +信用等级:金 / 银 / 铜 +实体字段 +> 字段名与一句话业务含义。其余实现细节自行决定。 + +包裹 Parcel + +字段 含义 +id 包裹标识 +sender 寄件人客户标识 +receiver 收件人客户标识 +category 品类(易碎/冷链/普通) +declared_value 申报价值(整数分) +priority 优先级(加急/普通) +is_cod 是否货到付款 +cod_amount 代收金额(整数分) +address 收件地址(必填) +status 包裹状态 +current_station 当前所在网点 +zone 分拣后所入专区(分拣前可空) +courier_id 派单后绑定的快递员标识(未派单为 NULL) +运单 Waybill + +字段 含义 +id 运单标识 +parcel_id 关联包裹 +route_legs 路由段序列(网点节点的有序列表,从揽收点起、至目标派送网点止) +current_station 当前所在网点 +deliv_target 目标派送网点 +promised_at 时效承诺时间(逻辑时钟) +status 运单状态 +网点 Station + +字段 含义 +id 网点标识 +name 网点名称 +capacity 容量上限 +in_stock 当前在仓量 +fault_count 责任记账数 +status 网点状态 +快递员 Courier + +字段 含义 +id 快递员标识 +station_id 归属网点 +daily_quota 当日派件配额 +active_count 当前在途件数 +status 快递员状态 +客户 Customer + +字段 含义 +id 客户标识 +credit_level 信用等级(金/银/铜) +cod_balance 代收回款余额(整数分) +status 客户状态 +理赔单 Claim + +字段 含义 +id 理赔单标识 +parcel_id 关联包裹 +amount 赔付金额(整数分) +degree 破损程度(轻微破损/严重破损/全损) +status 理赔单状态 +代收货款 COD + +字段 含义 +id COD 账目标识 +parcel_id 关联包裹 +amount 代收金额(整数分) +status COD 状态 +业务约束 +包裹按揽收 → 分拣 → 运输 → 派送 → 签收的物流流程推进;推进、签收、拒收、改址等操作仅在业务上合理的阶段才被允许,否则应拒绝且不改变任何状态。 +分拣需按品类把包裹分到对应专区处理,不匹配的专区不接收。 +包裹按运单规划的路由段逐站推进。 +派单时从包裹所在派送网点的可用快递员中分配,分配后占用快递员的在途件额;快递员在途件达到配额即不可再分配。 +收件人拒收的包裹需退回寄件人;货到付款的包裹只有成功签收才收款,款项随后结算给寄件人,拒收则不收款。 +包裹破损时受理理赔并按破损程度分档赔付;理赔进行中的运单应停止流转。 +在途改址会引起后续路由重算,可能改变目标派送网点。改址仅允许在「运输中」或「待派送」阶段执行;包裹进入「派送中」及之后阶段,改址请求应被拒绝且不改变任何状态。 +网点停用后,其在仓与在途包裹需妥善改路由处置。 +已到终态的包裹(已签收 / 已退回 / 已理赔关闭)拒绝一切写操作;重复签收应幂等。 +揽收对输入做合理的归一化容错(地址:首尾去空格、内部连续空格折叠为单个空格),对外输出保持精确;同一运单重复揽收应拒绝。 +金额一律以整数分表示并精确处理。 +业务提示(业务场景暗示,非穷举) +同一派送网点可能有多名快递员,请合理派单,避免某位快递员长期过载;加急件应享有更快的处理。 +包裹多次派送失败,或在某网点长时间滞留时,系统需妥善退回或改派。 +收件人拒收的包裹需原路退回寄件人;货到付款的包裹只有成功签收才收款,款项随后结算给寄件人。 +包裹破损时按破损程度分档赔付,赔付对象是寄件人;理赔进行中运单应停止流转。 +不同品类(易碎 / 冷链 / 普通)需分区处理;网点爆仓时新到包裹需绕行。 +派送异常频繁的快递员需暂停接单;理赔定损应及时。 +高信用寄件人在派送匹配中享有合理的优先权。 +逻辑时钟 +系统使用逻辑时钟而非真实时间。初始逻辑时间 t=0,1 step 表示 1 个逻辑小时。通过 POST /system/clock/tick(请求体形如 {"steps": N})推进逻辑时钟。GET /system/clock 返回当前逻辑时间,字段名为 now(整数,如 {"now": 0})。所有与时间相关的判定(滞留、窗口、时效等)均基于逻辑时钟,禁止使用真实墙钟时间。 + +后端接口 +> 下表给出方法 + 路径 + 一句话功能 + 调用者。请求/响应结构请按业务语义自行设计。 + +方法 路径 功能 调用者 +GET / 服务健康探活 系统 +POST /system/clock/tick 推进逻辑时钟 N 步 测试驱动 +GET /system/clock 查询当前逻辑时间 测试/运营 +POST /system/reset 重置:清空全部业务数据并恢复初始预置数据、逻辑时钟归零 测试驱动 +POST /parcels 创建包裹 寄件人/运营 +GET /parcels 查询包裹列表 运营 +GET /parcels/{id} 查询包裹详情 运营/客户 +POST /parcels/{id}/pickup 揽收包裹 快递员 +POST /parcels/{id}/sort 分拣包裹 分拣中心 +POST /parcels/{id}/advance 推进包裹一站 运营/系统 +POST /parcels/{id}/assign-courier 为包裹派单 派送网点 +POST /parcels/{id}/deliver 开始派送 快递员 +POST /parcels/{id}/deliver-fail 登记派送失败 快递员 +POST /parcels/{id}/sign 签收包裹 收件人 +POST /parcels/{id}/reject 拒收包裹 收件人 +POST /parcels/{id}/redirect 改址 寄件人/收件人 +POST /parcels/{id}/report-damage 上报破损 运营/客户 +GET /waybills 查询运单列表 运营 +GET /waybills/{id} 查询运单详情 运营 +GET /waybills/{id}/route 查询运单路由(返回含 route_legs 数组与 current_station 的对象) 运营 +POST /waybills/{id}/append-leg 追加路由段 运营/系统 +POST /waybills/{id}/recalc-route 重算路由 运营/系统 +POST /waybills/{id}/freeze 理赔冻结运单 系统 +POST /waybills/{id}/settle 运单结算 运营 +POST /stations 创建网点 运营 +GET /stations 查询网点列表 运营 +GET /stations/{id} 查询网点详情 运营 +POST /stations/{id}/disable 停用网点 运营 +POST /stations/{id}/enable 启用网点 运营 +POST /stations/{id}/clear-warning 解除网点质量预警 运营 +GET /stations/{id}/parcels 查询该网点在仓包裹 运营 +POST /couriers 创建快递员 运营 +GET /couriers 查询快递员列表 运营 +GET /couriers/{id} 查询快递员详情 运营 +POST /couriers/{id}/approve 审核通过快递员 运营 +POST /couriers/{id}/suspend 异常审查快递员 运营/系统 +POST /couriers/{id}/reassign 重分配快递员 运营/系统 +GET /claims 查询理赔单列表 运营/客户 +GET /claims/{id} 查询理赔单详情 运营/客户 +POST /claims/{id}/assess 定损 运营 +POST /claims/{id}/pay 赔付 运营/系统 +POST /claims/{id}/reject 驳回理赔 运营 +GET /cod 查询代收货款列表 运营 +GET /cod/{id} 查询代收货款详情 运营 +POST /cod/{id}/reconcile 对账 运营/系统 +POST /cod/{id}/settle 回款给寄件人 运营/系统 +POST /customers 创建客户 运营 +GET /customers 查询客户列表 运营 +GET /customers/{id} 查询客户详情 运营/客户 +POST /customers/{id}/adjust-credit 调整客户信用 运营/系统 +GET /events 履约关键节点事件流(SSE) 客户端/运营 +> 请求/响应结构请按业务语义自行设计;下面仅固定若干字段名约定(判分按此名读写),其余自定。 + +> 列表类 GET 接口(如 /parcels、/waybills、/stations、/couriers、/claims、/cod、/customers、/stations/{id}/parcels)直接返回资源对象的 JSON 数组(不加 {items:[...]} 之类外层包装)。 + +请求字段约定(硬契约:仅约定字段名,业务取值/触发逻辑自行判断) +创建实体(POST /parcels、/stations、/couriers、/customers)允许在请求体携带 id 指定该资源标识;未携带时由服务生成。 +创建包裹(POST /parcels)请求体含 sender / receiver / category / declared_value / priority / is_cod / cod_amount,以及目标派送网点 deliv_target(网点标识);address(收件地址)为必填字段。 +揽收(POST /parcels/{id}/pickup)可携带运单号 waybill_no。 +分拣(POST /parcels/{id}/sort)可携带分拣专区 zone;专区取值为 A / B / C 三者之一,对应品类如下硬约定:易碎 → A 区 / 冷链 → B 区 / 普通 → C 区。错区分拣(如易碎件传 zone="C")应被拒绝。包裹分拣后其 zone 字段记录所入专区。 +改址(POST /parcels/{id}/redirect)请求体含目标派送网点 deliv_target。 +报损(POST /parcels/{id}/report-damage)请求体含破损程度 degree,取值为 轻微破损 / 严重破损 / 全损 三者之一;其余值视为非法。 +创建快递员(POST /couriers)请求体含归属网点 station_id;创建客户(POST /customers)与调整信用(adjust-credit)请求体含信用等级 credit_level(金 / 银 / 铜)。 +业务参数(硬约定,必须按此实现) +判分系统会严格按以下数值验证;上文「分档赔付」「累计退回」「滞留超时」「滑动窗口异常审查」等业务规则提到的触发阈值与具体数值,统一在此约定。题目仅约定数值,触发条件下的级联效果与状态流转请按业务直觉自行推导。 + +参数 含义 数值 +daily_quota(快递员日配额) 单个快递员每日派件上限;达到上限后状态变为「已满载」 5 单 +派送失败累计退回 同一包裹累计派送失败次数达到阈值 → 包裹自动进入退回流程 3 次 +网点滞留自动推进 包裹在某网点滞留时长达到阈值 → 系统自动推进到下一站 24 小时 +派送失败滑动窗口 单个快递员在滑动窗口内累计失败次数达到阈值 → 进入「异常审查」 6 小时窗口 / 4 次 +理赔受理超时 理赔单受理后未定损时长达到阈值 → 自动按全损金额定损 48 小时 +网点责任质量预警 单个网点 fault_count 累计达到阈值 → 状态变为「质量预警」 3 次 +破损赔付分档比例 「轻微破损」/「严重破损」/「全损」按 declared_value 乘比例赔付 30% / 60% / 100% +路由段时效承诺 运单 promised_at 基础计算公式 = 当前时间 + 路由剩余段数 × 单段耗时 6 小时/段 +网点停用的业务处置 +网点停用意味着该网点不再接收新的业务,但已经在系统里的责任不能凭空消失。处置时需兼顾两类责任: + +未派送的包裹:尚未交到快递员手上的在仓件,需要转移到同级正常网点继续处理,包裹与在仓量随之同步迁移(不允许账面凭空消失)。 +快递员的契约责任:已经接单的快递员手头还有未完成的派送任务,理应继续完成;只有当前没有承担任务的快递员才转入「待重分配」等待重新安排。 +具体级联到哪些字段、状态如何流转,请按业务直觉自行推导。 + +理赔进行中的包裹处置 +包裹进入理赔流程(已受理 / 定损中)后,物理上需原地等待定损与赔付决定,运单状态为「理赔冻结」。期间包裹不可继续推进、改址或派单,相关写操作应被拒绝。理赔结案(赔付完成或被驳回)后,包裹才能恢复正常流转或进入终态。理赔赔付后包裹进入终态「已理赔关闭」,受损原件(残件)的物理处置不在本系统建模范围。 + +破损理赔赔付结案时,本次破损的网点责任记入包裹当前所在网点(current_station)的 fault_count(累计 +1)。 + +拒收的状态语义 +收件人拒收(POST /parcels/{id}/reject)是触发逆向退回流程的入口动作。执行后包裹状态直接进入「退回中」开始沿逆向路由退回,不持久化「已拒收」状态——「已拒收」仅作为状态枚举里的历史事件标签保留,实际业务流程不会停在该状态。退回路由沿原正向已走段倒序构建,通过 advance 逐站推进,到达揽收点时进入终态「已退回」。「已退回」表示包裹已回到起点揽收点并通知寄件人取回;揽收点至寄件人的线下交付不在本系统建模范围。 + +快递员异常审查的触发处置 +当快递员在短时间内累计多次派送失败、达到异常审查阈值时,系统立即将其转入「异常审查」并停止给其分配新单;其手头在途单即时收回、状态置回「待派送」,交还常规派单流程重新处理。运营通过 POST /couriers/{id}/suspend 手动停用快递员时,同样按此即时处置。 + +网点质量预警的解除 +网点处于「质量预警」状态时,可由运营手动评估并解除预警。接口为 POST /stations/{id}/clear-warning,调用后 fault_count 清零,状态恢复「正常」。 + +信用等级的语义 +credit_level(金 / 银 / 铜)仅作客户分级记录,本题不要求在派单、赔付、回款等环节按等级做差异化处理。status(受限 / 冻结)的账户状态优先于信用等级判定(受限 / 冻结的客户禁止寄件)。 + +初始数据 +服务启动时应预置以下基础数据: + +网点 5 个:ST_HUB(分拣中心,capacity 100)、ST_PICK(揽收网点)、ST_TRANS(中转站)、ST_DELIV_A、ST_DELIV_B(派送网点,capacity 20);分拣中心设有易碎 / 冷链 / 普通三个分拣专区。 +快递员 3 个:CR_1、CR_2(归属 ST_DELIV_A)、CR_3(归属 ST_DELIV_B),初始 空闲,daily_quota 按上表硬约定 5。 +客户 3 个:CUS_GOLD(金)、CUS_SILVER(银)、CUS_BRONZE(铜),初始 正常。 +持久化要求 +服务需将数据持久化,进程被强制终止(SIGKILL)后重新启动时,已完成的写操作不得丢失,数据保持一致。 + +服务启动要求 +监听 8000 端口(硬编码,不要读环境变量),绑定 0.0.0.0 +入口放在 workspace 根目录: +脚本/单文件型:main.py / main.ts / main.cpp +项目型:Java 用 pom.xml +判分只针对后端服务,TUI 用于自测与演示 +本题仅支持 Python / Go / Java / C++ / TypeScript 作答,其他编程语言不参与判分。 +语言 入口 启动命令 +Python main.py python3 main.py(若 import 了 fastapi,自动改用 uvicorn main:app --host 0.0.0.0 --port 8000) +Go main.go + go.mod go build . && ./ +TypeScript main.ts + tsconfig.json tsx main.ts +Java pom.xml mvn package -DskipTests && java -jar target/*.jar +C++ main.cpp / CMakeLists.txt / Makefile 见下方「开发环境说明 → C++」章节的自动识别表 +开发环境说明 +可用作答语言:Python 3.11 / Go 1.22 / Java 21 / C++(g++ 12,C++17)/ TypeScript(Node.js 22 + tsx) + +> 下表列出镜像里已经预装、开箱即用的依赖与版本,免去你下载的时间。你也可以按各语言常规方式自行引入其他依赖(mvn / npm install / pip install)。 + +--- + +Java(JDK 21 + Maven) +判题入口:pom.xml,启动 mvn package -DskipTests && java -jar target/*.jar。 + +已预装依赖 版本 +org.springframework.boot:spring-boot-starter-parent 3.3.4 +org.springframework.boot:spring-boot-starter-web 3.3.4(Spring Boot BOM 管理) +org.springframework.boot:spring-boot-starter-websocket 3.3.4(Spring Boot BOM 管理) +org.springframework.boot:spring-boot-starter-jdbc 3.3.4(Spring Boot BOM 管理) +org.xerial:sqlite-jdbc 3.46.1.0 +--- + +Go(Go 1.22) +判题入口:main.go + go.mod,启动 go build . && ./。 + +已预装依赖 版本 +modernc.org/sqlite v1.34.1 +--- + +TypeScript(Node 22 LTS) +判题入口:main.ts + tsconfig.json,启动 tsx main.ts。 + +已预装依赖 版本 +express 4.21.2 +ws 8.18.0 +better-sqlite3 11.3.0 +tsx(TS 直跑) 4.19.2 +--- + +C++(g++-12,C++17) +判题入口:main.cpp(C 题 main.c)。判题侧自动识别项目结构: + +你提交的文件 判题侧执行的构建 +CMakeLists.txt(推荐) cmake -S . -B build -DCMAKE_BUILD_TYPE=Release && cmake --build build -j,产物名固定 app +Makefile / makefile make -j,默认目标产物名固定 main +仅 main.cpp g++ -std=c++17 -O2 -pthread -o main.cpp(只接纯标准库;要链 -lsqlite3 等系统库请改用 CMakeLists.txt) +预装头/库(全部走系统标准路径,直接 #include 即可): + +apt 包 头/库 版本 +libsqlite3-dev + -lsqlite3 3.37.2 +libwebsocketpp-dev (header-only) 0.8.2 +libasio-dev (standalone,需 #define ASIO_STANDALONE) 1.18.1 +nlohmann-json3-dev (header-only) 3.10.5 +> 使用 websocketpp 时必须加这 3 行宏。镜像未安装 boost,默认走 boost::asio 会在编译期直接报头文件缺失: + +> + +> #define ASIO_STANDALONE +> #define _WEBSOCKETPP_CPP11_STL_ +> #define _WEBSOCKETPP_CPP11_THREAD_ +> +--- + +Python(Python 3.11) +判题入口:main.py。 + +> FastAPI 应用 app 实例必须命名为 app,judge 会用 uvicorn main:app 启动。 + +已预装依赖 用途 +fastapi / uvicorn HTTP / ASGI +flask HTTP(同步) +websockets / websocket-client WS +httpx / requests HTTP 客户端 +pydantic 数据校验 +sqlalchemy / redis / pymysql DB +pandas / numpy 数据 +orjson / aiofiles / rich / textual 工具 +pillow 图像 +pytest 测试 +> 内置 sqlite3 模块自带,无需额外安装。 \ No newline at end of file diff --git a/context.md b/context.md new file mode 100644 index 0000000..c4e2d5f --- /dev/null +++ b/context.md @@ -0,0 +1,39 @@ +BASE=http://localhost:8000 + +curl -X POST $BASE/system/reset + +# 1 建包裹(COD,金客户寄出,目标派送网点 A) +curl -X POST $BASE/parcels -H 'Content-Type: application/json' -d '{ + "id":"P1","sender":"CUS_GOLD","receiver":"CUS_SILVER", + "category":"易碎","declared_value":10000,"priority":"加急", + "is_cod":true,"cod_amount":5000,"deliv_target":"ST_DELIV_A", + "address":" 北京市 朝阳区 " +}' + +# 2 揽收 +curl -X POST $BASE/parcels/P1/pickup -d '{}' -H 'Content-Type: application/json' +curl $BASE/waybills # 取运单 id(假设 W_P1) + +# 3 分拣(易碎必须 A 区) +curl -X POST $BASE/parcels/P1/sort -d '{"zone":"A"}' -H 'Content-Type: application/json' + +# 4 推进两站:ST_HUB→ST_TRANS→ST_DELIV_A +curl -X POST $BASE/parcels/P1/advance +curl -X POST $BASE/parcels/P1/advance + +# 5 派单 +curl -X POST $BASE/parcels/P1/assign-courier + +# 6 派送 +curl -X POST $BASE/parcels/P1/deliver + +# 7 签收(COD 收款) +curl -X POST $BASE/parcels/P1/sign + +# 8 COD 对账 + 回款 +curl -X POST $BASE/cod/COD_P1/reconcile +curl -X POST $BASE/cod/COD_P1/settle + +# 9 核对:包裹已签收 / 运单已完成 / 寄件人余额 = 5000(只应一次) +curl $BASE/parcels/P1 +curl $BASE/customers/CUS_GOLD \ No newline at end of file diff --git a/logistics.db b/logistics.db new file mode 100644 index 0000000..fd19ba7 Binary files /dev/null and b/logistics.db differ diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..65765f0 --- /dev/null +++ b/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.3.4 + + + + com.nowcoder + logistics-preset-java + 1.0.0 + logistics-preset-java + + + 17 + + + + + org.springframework.boot + spring-boot-starter-web + + + org.xerial + sqlite-jdbc + 3.46.1.0 + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/src/main/java/com/nowcoder/logistics/LogisticsPresetApplication.java b/src/main/java/com/nowcoder/logistics/LogisticsPresetApplication.java new file mode 100644 index 0000000..63293ec --- /dev/null +++ b/src/main/java/com/nowcoder/logistics/LogisticsPresetApplication.java @@ -0,0 +1,733 @@ +package com.nowcoder.logistics; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.sql.*; +import java.util.*; + +@SpringBootApplication +@RestController +public class LogisticsPresetApplication { + private static final String DB_PATH = "logistics.db"; + private static final ObjectMapper JSON = new ObjectMapper(); + private static final Map CATEGORY_MAP = Map.of("易碎", "A", "冷链", "B", "普通", "C"); + private static final Map DAMAGE_DEGREE_MAP = Map.of("轻微破损", 0.3, "严重破损", 0.6, "全损", 1.0); + private static final int ROUTE_TIME_PER_LEG = 6; + private static final int CLAIM_AUTO_ASSESS_HOURS = 48; + private static final int FAIL_RETURN_THRESHOLD = 3; + private static final int SUSPEND_WINDOW_HOURS = 6; + private static final int SUSPEND_FAIL_COUNT = 4; + private static final Random RAND = new Random(1); + + public static void main(String[] args) throws Exception { + String port = System.getenv().getOrDefault("PORT", "8000"); + System.setProperty("server.port", port); + initDb(); + seedData(); + SpringApplication.run(LogisticsPresetApplication.class, args); + } + + private static Connection conn() throws SQLException { + Connection c = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH); + try (Statement st = c.createStatement()) { + st.execute("PRAGMA journal_mode=WAL"); + } + return c; + } + + private static void initDb() throws SQLException { + try (Connection c = conn(); Statement st = c.createStatement()) { + st.execute("CREATE TABLE IF NOT EXISTS system_config (key TEXT PRIMARY KEY, value TEXT)"); + st.execute(""" + CREATE TABLE IF NOT EXISTS parcels ( + id TEXT PRIMARY KEY, sender TEXT, receiver TEXT, category TEXT, + declared_value INTEGER DEFAULT 0, priority TEXT DEFAULT '普通', + is_cod INTEGER DEFAULT 0, cod_amount INTEGER DEFAULT 0, + address TEXT, + status TEXT DEFAULT '待揽收', current_station TEXT, zone TEXT, + courier_id TEXT, waybill_id TEXT, created_at INTEGER DEFAULT 0, + fail_count INTEGER DEFAULT 0, last_station_time INTEGER DEFAULT 0, + damage_reported INTEGER DEFAULT 0, deliv_target TEXT + ) + """); + st.execute(""" + CREATE TABLE IF NOT EXISTS waybills ( + id TEXT PRIMARY KEY, parcel_id TEXT, route_legs TEXT, + current_station TEXT, deliv_target TEXT, promised_at INTEGER, + status TEXT DEFAULT '已创建' + ) + """); + st.execute("CREATE TABLE IF NOT EXISTS stations (id TEXT PRIMARY KEY, name TEXT, capacity INTEGER, in_stock INTEGER DEFAULT 0, fault_count INTEGER DEFAULT 0, status TEXT DEFAULT '正常')"); + st.execute("CREATE TABLE IF NOT EXISTS couriers (id TEXT PRIMARY KEY, station_id TEXT, daily_quota INTEGER DEFAULT 5, active_count INTEGER DEFAULT 0, status TEXT DEFAULT '待审核', fail_history TEXT DEFAULT '[]')"); + st.execute("CREATE TABLE IF NOT EXISTS customers (id TEXT PRIMARY KEY, credit_level TEXT DEFAULT '铜', cod_balance INTEGER DEFAULT 0, status TEXT DEFAULT '正常')"); + st.execute("CREATE TABLE IF NOT EXISTS claims (id TEXT PRIMARY KEY, parcel_id TEXT, amount INTEGER DEFAULT 0, status TEXT DEFAULT '已受理', created_at INTEGER DEFAULT 0)"); + st.execute("CREATE TABLE IF NOT EXISTS cod_records (id TEXT PRIMARY KEY, parcel_id TEXT, amount INTEGER DEFAULT 0, status TEXT DEFAULT '待收款')"); + st.execute("CREATE TABLE IF NOT EXISTS events (id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, data TEXT, timestamp INTEGER)"); + try { st.execute("ALTER TABLE parcels ADD COLUMN address TEXT"); } catch (SQLException ignore) { } + } + } + + private static void seedData() throws Exception { + try (Connection c = conn()) { + Map count = one(c, "SELECT count(*) AS n FROM stations"); + if (count != null && asInt(count.get("n")) > 0) return; + exec(c, "INSERT OR REPLACE INTO system_config (key,value) VALUES ('clock','0')"); + Object[][] stations = { + {"ST_HUB", "分拣中心", 100, 0, 0, "正常"}, + {"ST_PICK", "揽收网点", 50, 0, 0, "正常"}, + {"ST_TRANS", "中转站", 80, 0, 0, "正常"}, + {"ST_DELIV_A", "派送网点A", 20, 0, 0, "正常"}, + {"ST_DELIV_B", "派送网点B", 20, 0, 0, "正常"} + }; + for (Object[] r : stations) exec(c, "INSERT INTO stations (id,name,capacity,in_stock,fault_count,status) VALUES (?,?,?,?,?,?)", r); + Object[][] couriers = { + {"CR_1", "ST_DELIV_A", 5, 0, "空闲", "[]"}, + {"CR_2", "ST_DELIV_A", 5, 0, "空闲", "[]"}, + {"CR_3", "ST_DELIV_B", 5, 0, "空闲", "[]"} + }; + for (Object[] r : couriers) exec(c, "INSERT INTO couriers (id,station_id,daily_quota,active_count,status,fail_history) VALUES (?,?,?,?,?,?)", r); + Object[][] customers = { + {"CUS_GOLD", "金", 0, "正常"}, + {"CUS_SILVER", "银", 0, "正常"}, + {"CUS_BRONZE", "铜", 0, "正常"} + }; + for (Object[] r : customers) exec(c, "INSERT INTO customers (id,credit_level,cod_balance,status) VALUES (?,?,?,?)", r); + } + } + + private static void exec(Connection c, String sql, Object... args) throws SQLException { + try (PreparedStatement ps = c.prepareStatement(sql)) { + for (int i = 0; i < args.length; i++) ps.setObject(i + 1, args[i]); + ps.executeUpdate(); + } + } + + private static List> all(Connection c, String sql, Object... args) throws SQLException { + try (PreparedStatement ps = c.prepareStatement(sql)) { + for (int i = 0; i < args.length; i++) ps.setObject(i + 1, args[i]); + try (ResultSet rs = ps.executeQuery()) { + List> out = new ArrayList<>(); + ResultSetMetaData md = rs.getMetaData(); + while (rs.next()) { + Map row = new LinkedHashMap<>(); + for (int i = 1; i <= md.getColumnCount(); i++) row.put(md.getColumnName(i), rs.getObject(i)); + out.add(row); + } + return out; + } + } + } + + private static Map one(Connection c, String sql, Object... args) throws SQLException { + List> rows = all(c, sql, args); + return rows.isEmpty() ? null : rows.get(0); + } + + private static int getClock(Connection c) throws SQLException { + Map row = one(c, "SELECT value FROM system_config WHERE key='clock'"); + return row == null ? 0 : Integer.parseInt(String.valueOf(row.get("value"))); + } + + private static void setClock(Connection c, int t) throws SQLException { + exec(c, "INSERT OR REPLACE INTO system_config (key,value) VALUES ('clock',?)", String.valueOf(t)); + } + + private static void addEvent(Connection c, String type, Map data) throws Exception { + exec(c, "INSERT INTO events (type,data,timestamp) VALUES (?,?,?)", type, JSON.writeValueAsString(data), getClock(c)); + } + + private static Map parcel(Connection c, String pid) throws SQLException { + return one(c, "SELECT * FROM parcels WHERE id=?", pid); + } + + private static String hex(int n) { + char[] chars = "0123456789abcdef".toCharArray(); + StringBuilder s = new StringBuilder(); + for (int i = 0; i < n; i++) s.append(chars[RAND.nextInt(chars.length)]); + return s.toString(); + } + + private static int asInt(Object v) { + if (v == null) return 0; + if (v instanceof Number n) return n.intValue(); + return Integer.parseInt(String.valueOf(v)); + } + + private static String asStr(Object v) { + return v == null ? "" : String.valueOf(v); + } + + private static boolean asBool(Object v) { + if (v instanceof Boolean b) return b; + if (v instanceof Number n) return n.intValue() != 0; + return Boolean.parseBoolean(asStr(v)); + } + + private static String bodyStr(Map b, String key, String def) { + Object v = b == null ? null : b.get(key); + return v == null ? def : String.valueOf(v); + } + + private static int bodyInt(Map b, String key, int def) { + Object v = b == null ? null : b.get(key); + return v == null ? def : asInt(v); + } + + private static boolean has(Map b, String key) { + return b != null && b.containsKey(key); + } + + private static boolean in(String s, String... values) { + for (String v : values) if (Objects.equals(s, v)) return true; + return false; + } + + private static String normalizeSpace(String s) { + return s == null ? "" : s.trim().replaceAll("\\s+", " "); + } + + private static ResponseEntity> err(int status, String detail) { + return ResponseEntity.status(status).body(Map.of("detail", detail)); + } + + private static ResponseEntity ok(T value) { + return ResponseEntity.ok(value); + } + + private static List readLegs(Object raw) throws Exception { + return JSON.readValue(asStr(raw), new TypeReference>() {}); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> anyError(Exception e) { + return err(500, e.getMessage() == null ? e.toString() : e.getMessage()); + } + + @PostMapping("/system/reset") + public Map reset() throws Exception { + try (Connection c = conn(); Statement st = c.createStatement()) { + for (String t : List.of("parcels", "waybills", "stations", "couriers", "customers", "claims", "cod_records", "events", "system_config")) { + st.execute("DROP TABLE IF EXISTS " + t); + } + } + initDb(); + seedData(); + return Map.of("status", "reset"); + } + + @GetMapping("/system/clock") + public Map clock() throws Exception { + try (Connection c = conn()) { + return Map.of("now", getClock(c)); + } + } + + @GetMapping("/") + public Map health() { + return Map.of("status", "ok"); + } + + @PostMapping("/system/clock/tick") + public Map tick(@RequestBody(required = false) Map b) throws Exception { + try (Connection c = conn()) { + int newNow = getClock(c) + bodyInt(b, "steps", 1); + setClock(c, newNow); + for (Map p : all(c, "SELECT id,current_station,last_station_time FROM parcels WHERE status IN ('已揽收','分拣中','运输中','待派送')")) { + if (newNow - asInt(p.get("last_station_time")) >= 24) { + Map wb = one(c, "SELECT * FROM waybills WHERE parcel_id=?", p.get("id")); + if (wb != null) { + List legs = readLegs(wb.get("route_legs")); + int idx = legs.indexOf(asStr(wb.get("current_station"))); + if (idx != -1 && idx < legs.size() - 1) { + String next = legs.get(idx + 1); + exec(c, "UPDATE parcels SET current_station=?,last_station_time=? WHERE id=?", next, newNow, p.get("id")); + exec(c, "UPDATE waybills SET current_station=? WHERE id=?", next, wb.get("id")); + exec(c, "UPDATE stations SET in_stock=in_stock-1 WHERE id=?", p.get("current_station")); + exec(c, "UPDATE stations SET in_stock=in_stock+1 WHERE id=?", next); + addEvent(c, "auto_advance", Map.of("parcel_id", p.get("id"), "from", p.get("current_station"), "to", next)); + } + } + } + } + for (Map cl : all(c, "SELECT id,parcel_id FROM claims WHERE status='已受理' AND created_at <= ?", newNow - CLAIM_AUTO_ASSESS_HOURS)) { + Map pv = one(c, "SELECT declared_value FROM parcels WHERE id=?", cl.get("parcel_id")); + if (pv != null) { + exec(c, "UPDATE claims SET status='定损中',amount=? WHERE id=?", asInt(pv.get("declared_value")), cl.get("id")); + addEvent(c, "claim_auto_assess", Map.of("claim_id", cl.get("id"))); + } + } + return Map.of("now", newNow); + } + } + + @PostMapping("/parcels") + public ResponseEntity createParcel(@RequestBody Map b) throws Exception { + try (Connection c = conn()) { + if (!has(b, "sender") || !has(b, "receiver")) return err(422, "missing required field"); + String pid = bodyStr(b, "id", ""); + if (pid.isEmpty()) pid = "P_" + hex(8); + Map sender = one(c, "SELECT status FROM customers WHERE id=?", bodyStr(b, "sender", "")); + if (sender == null) return err(404, "Sender not found"); + if (in(asStr(sender.get("status")), "受限", "冻结")) return err(403, "Sender account restricted"); + if (bodyStr(b, "receiver", "").isEmpty()) return err(400, "receiver 缺失"); + if (!has(b, "address") || bodyStr(b, "address", "").trim().isEmpty()) return err(400, "address 必填"); + String address = normalizeSpace(bodyStr(b, "address", "")); + String target = bodyStr(b, "deliv_target", "ST_DELIV_A"); + if (one(c, "SELECT id FROM stations WHERE id=?", target) == null) return err(404, "Target station not found"); + int now = getClock(c); + exec(c, """ + INSERT INTO parcels (id,sender,receiver,category,declared_value,priority,is_cod,cod_amount,address,status,current_station,created_at,last_station_time,deliv_target) + VALUES (?,?,?,?,?,?,?,?,?,'待揽收',NULL,?,?,?) + """, pid, bodyStr(b, "sender", ""), bodyStr(b, "receiver", ""), bodyStr(b, "category", "普通"), + bodyInt(b, "declared_value", 0), bodyStr(b, "priority", "普通"), asBool(b.get("is_cod")) ? 1 : 0, + bodyInt(b, "cod_amount", 0), address, now, now, target); + return ok(parcel(c, pid)); + } + } + + @GetMapping("/parcels") + public List> parcels() throws Exception { try (Connection c = conn()) { return all(c, "SELECT * FROM parcels"); } } + + @GetMapping("/parcels/{pid}") + public ResponseEntity getParcel(@PathVariable String pid) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + return p == null ? err(404, "Parcel not found") : ok(p); + } + } + + @PostMapping("/parcels/{pid}/pickup") + public ResponseEntity pickup(@PathVariable String pid, @RequestBody(required = false) Map b) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!"待揽收".equals(asStr(p.get("status")))) return err(400, "Invalid status for pickup"); + String start = "ST_PICK"; + String target = asStr(p.get("deliv_target")).isEmpty() ? "ST_DELIV_A" : asStr(p.get("deliv_target")); + int now = getClock(c); + String wid = bodyStr(b, "waybill_no", ""); + if (wid.isEmpty()) wid = "W_" + hex(8); + List route = new ArrayList<>(List.of("ST_PICK", "ST_HUB", "ST_TRANS")); + int ti = route.indexOf(target); + if (ti >= 0) route = new ArrayList<>(route.subList(0, ti + 1)); + else route.add(target); + int promised = now + (route.size() - 1) * ROUTE_TIME_PER_LEG; + exec(c, "INSERT INTO waybills (id,parcel_id,route_legs,current_station,deliv_target,promised_at,status) VALUES (?,?,?,?,?,?,'已创建')", + wid, pid, JSON.writeValueAsString(route), start, target, promised); + exec(c, "UPDATE parcels SET status='已揽收',current_station=?,waybill_id=?,last_station_time=? WHERE id=?", start, wid, now, pid); + exec(c, "UPDATE stations SET in_stock=in_stock+1 WHERE id=?", start); + if (asInt(p.get("is_cod")) == 1) exec(c, "INSERT INTO cod_records (id,parcel_id,amount,status) VALUES (?,?,?,'待收款')", "COD_" + hex(8), pid, asInt(p.get("cod_amount"))); + addEvent(c, "pickup", Map.of("parcel_id", pid, "waybill_id", wid)); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/sort") + public ResponseEntity sort(@PathVariable String pid, @RequestBody(required = false) Map b) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!"已揽收".equals(asStr(p.get("status")))) return err(400, "Invalid status for sort"); + String expected = CATEGORY_MAP.getOrDefault(asStr(p.get("category")), "C"); + String reqZone = bodyStr(b, "zone", expected); + if (!reqZone.equals(expected)) return err(400, "Zone mismatch. Expected " + expected + ", got " + reqZone); + int now = getClock(c); + String old = asStr(p.get("current_station")); + exec(c, "UPDATE parcels SET status='分拣中',current_station=?,zone=?,last_station_time=? WHERE id=?", "ST_HUB", reqZone, now, pid); + exec(c, "UPDATE waybills SET current_station=? WHERE parcel_id=?", "ST_HUB", pid); + exec(c, "UPDATE stations SET in_stock=in_stock-1 WHERE id=?", old); + exec(c, "UPDATE stations SET in_stock=in_stock+1 WHERE id=?", "ST_HUB"); + addEvent(c, "sort", Map.of("parcel_id", pid, "zone", reqZone)); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/advance") + public ResponseEntity advance(@PathVariable String pid) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (in(asStr(p.get("status")), "已签收", "已退回", "已理赔关闭")) return err(400, "Parcel is in final state"); + if (in(asStr(p.get("status")), "已受理", "定损中")) return err(400, "Parcel frozen due to claim"); + Map wb = one(c, "SELECT * FROM waybills WHERE parcel_id=?", pid); + if (wb == null) return err(400, "No waybill"); + List legs = readLegs(wb.get("route_legs")); + int idx = legs.indexOf(asStr(wb.get("current_station"))); + if (idx == -1 || idx >= legs.size() - 1) return err(400, "Already at destination or invalid route"); + String next = legs.get(idx + 1); + String old = asStr(wb.get("current_station")); + int now = getClock(c); + String ns = asStr(p.get("status")); + if (next.equals(asStr(wb.get("deliv_target")))) ns = "待派送"; + else if ("分拣中".equals(asStr(p.get("status")))) ns = "运输中"; + exec(c, "UPDATE parcels SET status=?,current_station=?,last_station_time=? WHERE id=?", ns, next, now, pid); + exec(c, "UPDATE waybills SET current_station=? WHERE id=?", next, wb.get("id")); + exec(c, "UPDATE stations SET in_stock=in_stock-1 WHERE id=?", old); + exec(c, "UPDATE stations SET in_stock=in_stock+1 WHERE id=?", next); + addEvent(c, "advance", Map.of("parcel_id", pid, "to", next)); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/assign-courier") + public ResponseEntity assignCourier(@PathVariable String pid) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!"待派送".equals(asStr(p.get("status")))) return err(400, "Not ready for delivery"); + Map courier = one(c, "SELECT * FROM couriers WHERE station_id=? AND status IN ('空闲','派送中') AND active_count < daily_quota ORDER BY active_count ASC LIMIT 1", p.get("current_station")); + if (courier == null) return err(400, "No available courier"); + int active = asInt(courier.get("active_count")) + 1; + String status = active >= asInt(courier.get("daily_quota")) ? "已满载" : "派送中"; + exec(c, "UPDATE couriers SET active_count=?,status=? WHERE id=?", active, status, courier.get("id")); + exec(c, "UPDATE parcels SET status='派送中',courier_id=? WHERE id=?", courier.get("id"), pid); + addEvent(c, "assign", Map.of("parcel_id", pid, "courier_id", courier.get("id"))); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/deliver") + public ResponseEntity deliver(@PathVariable String pid) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!in(asStr(p.get("status")), "待派送", "派送中")) return err(400, "Invalid status"); + exec(c, "UPDATE parcels SET status='派送中' WHERE id=?", pid); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/deliver-fail") + public ResponseEntity deliverFail(@PathVariable String pid) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!"派送中".equals(asStr(p.get("status")))) return err(400, "Not in delivery"); + int now = getClock(c); + int fail = asInt(p.get("fail_count")) + 1; + exec(c, "UPDATE parcels SET fail_count=? WHERE id=?", fail, pid); + String courierId = asStr(p.get("courier_id")); + if (!courierId.isEmpty()) { + Map cr = one(c, "SELECT * FROM couriers WHERE id=?", courierId); + if (cr != null) { + int active = Math.max(0, asInt(cr.get("active_count")) - 1); + String status = active >= asInt(cr.get("daily_quota")) ? "已满载" : "空闲"; + List fh = JSON.readValue(asStr(cr.get("fail_history")), new TypeReference>() {}); + fh.add(now); + List kept = new ArrayList<>(); + for (int t : fh) if (t > now - SUSPEND_WINDOW_HOURS) kept.add(t); + if (kept.size() >= SUSPEND_FAIL_COUNT && active == 0) status = "异常审查"; + exec(c, "UPDATE couriers SET active_count=?,status=?,fail_history=? WHERE id=?", active, status, JSON.writeValueAsString(kept), cr.get("id")); + } + } + if (fail >= FAIL_RETURN_THRESHOLD) { + exec(c, "UPDATE parcels SET status='退回中' WHERE id=?", pid); + addEvent(c, "return_start", Map.of("parcel_id", pid)); + } else { + exec(c, "UPDATE parcels SET status='待派送',courier_id=NULL WHERE id=?", pid); + } + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/sign") + public ResponseEntity sign(@PathVariable String pid) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!"派送中".equals(asStr(p.get("status")))) { + if ("已签收".equals(asStr(p.get("status")))) return ok(p); + return err(400, "Not in delivery"); + } + exec(c, "UPDATE parcels SET status='已签收' WHERE id=?", pid); + String courierId = asStr(p.get("courier_id")); + if (!courierId.isEmpty()) { + Map cr = one(c, "SELECT * FROM couriers WHERE id=?", courierId); + if (cr != null) { + int active = Math.max(0, asInt(cr.get("active_count")) - 1); + String status = active >= asInt(cr.get("daily_quota")) ? "已满载" : "空闲"; + exec(c, "UPDATE couriers SET active_count=?,status=? WHERE id=?", active, status, cr.get("id")); + } + } + if (asInt(p.get("is_cod")) == 1) { + Map cod = one(c, "SELECT * FROM cod_records WHERE parcel_id=?", pid); + if (cod != null && "待收款".equals(asStr(cod.get("status")))) { + exec(c, "UPDATE cod_records SET status='已收款' WHERE id=?", cod.get("id")); + } + } + exec(c, "UPDATE waybills SET status='已完成' WHERE parcel_id=?", pid); + addEvent(c, "sign", Map.of("parcel_id", pid)); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/reject") + public ResponseEntity reject(@PathVariable String pid) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!"派送中".equals(asStr(p.get("status")))) return err(400, "Not in delivery"); + exec(c, "UPDATE parcels SET status='退回中' WHERE id=?", pid); + String courierId = asStr(p.get("courier_id")); + if (!courierId.isEmpty()) { + Map cr = one(c, "SELECT * FROM couriers WHERE id=?", courierId); + if (cr != null) { + int active = Math.max(0, asInt(cr.get("active_count")) - 1); + String status = active >= asInt(cr.get("daily_quota")) ? "已满载" : "空闲"; + exec(c, "UPDATE couriers SET active_count=?,status=? WHERE id=?", active, status, cr.get("id")); + } + } + if (asInt(p.get("is_cod")) == 1) exec(c, "UPDATE cod_records SET status='已关闭' WHERE parcel_id=?", pid); + exec(c, "UPDATE waybills SET status='逆向退回' WHERE parcel_id=?", pid); + addEvent(c, "reject", Map.of("parcel_id", pid)); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/redirect") + public ResponseEntity redirect(@PathVariable String pid, @RequestBody Map b) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (in(asStr(p.get("status")), "已签收", "已退回", "已理赔关闭")) return err(400, "Final state"); + if (in(asStr(p.get("status")), "已受理", "定损中")) return err(400, "Frozen by claim"); + Map wb = one(c, "SELECT * FROM waybills WHERE parcel_id=?", pid); + if (wb != null) { + String target = bodyStr(b, "deliv_target", ""); + exec(c, "UPDATE waybills SET route_legs=?,deliv_target=? WHERE id=?", JSON.writeValueAsString(List.of("ST_HUB", "ST_TRANS", target)), target, wb.get("id")); + } + addEvent(c, "redirect", Map.of("parcel_id", pid, "new_target", bodyStr(b, "deliv_target", ""))); + return ok(parcel(c, pid)); + } + } + + @PostMapping("/parcels/{pid}/report-damage") + public ResponseEntity reportDamage(@PathVariable String pid, @RequestBody Map b) throws Exception { + try (Connection c = conn()) { + Map p = parcel(c, pid); + if (p == null) return err(404, "Parcel not found"); + if (!DAMAGE_DEGREE_MAP.containsKey(bodyStr(b, "degree", ""))) return err(400, "Invalid damage degree"); + String cid = "CL_" + hex(8); + exec(c, "INSERT INTO claims (id,parcel_id,status,created_at) VALUES (?,?,'已受理',?)", cid, pid, getClock(c)); + exec(c, "UPDATE waybills SET status='理赔冻结' WHERE parcel_id=?", pid); + addEvent(c, "damage_report", Map.of("parcel_id", pid, "claim_id", cid)); + return ok(one(c, "SELECT * FROM claims WHERE id=?", cid)); + } + } + + @GetMapping("/waybills") + public List> waybills() throws Exception { + try (Connection c = conn()) { + List> rows = all(c, "SELECT * FROM waybills"); + for (Map wb : rows) wb.put("route_legs", readLegs(wb.get("route_legs"))); + return rows; + } + } + + @GetMapping("/waybills/{wid}") + public ResponseEntity getWaybill(@PathVariable String wid) throws Exception { + try (Connection c = conn()) { + Map wb = one(c, "SELECT * FROM waybills WHERE id=?", wid); + if (wb == null) return err(404, "Waybill not found"); + wb.put("route_legs", readLegs(wb.get("route_legs"))); + return ok(wb); + } + } + + @GetMapping("/waybills/{wid}/route") + public ResponseEntity getRoute(@PathVariable String wid) throws Exception { + try (Connection c = conn()) { + Map wb = one(c, "SELECT * FROM waybills WHERE id=?", wid); + if (wb == null) return err(404, "Waybill not found"); + wb.put("route_legs", readLegs(wb.get("route_legs"))); + return ok(wb); + } + } + + @PostMapping("/waybills/{wid}/append-leg") + public Map appendLeg(@PathVariable String wid) { return Map.of("status", "ok"); } + + @PostMapping("/waybills/{wid}/recalc-route") + public Map recalcRoute(@PathVariable String wid) { return Map.of("status", "ok"); } + + @PostMapping("/waybills/{wid}/freeze") + public Map freeze(@PathVariable String wid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE waybills SET status='理赔冻结' WHERE id=?", wid); return Map.of("status", "frozen"); } } + + @PostMapping("/waybills/{wid}/settle") + public Map settleWaybill(@PathVariable String wid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE waybills SET status='已结算' WHERE id=?", wid); return Map.of("status", "settled"); } } + + @PostMapping("/stations") + public Map createStation(@RequestBody Map b) throws Exception { + try (Connection c = conn()) { + String sid = bodyStr(b, "id", ""); + if (sid.isEmpty()) sid = "ST_" + hex(6); + exec(c, "INSERT INTO stations (id,name,capacity,in_stock,fault_count,status) VALUES (?,?,?,0,0,'正常')", sid, bodyStr(b, "name", ""), bodyInt(b, "capacity", 0)); + return one(c, "SELECT * FROM stations WHERE id=?", sid); + } + } + + @GetMapping("/stations") + public List> stations() throws Exception { try (Connection c = conn()) { return all(c, "SELECT * FROM stations"); } } + + @GetMapping("/stations/{sid}") + public ResponseEntity getStation(@PathVariable String sid) throws Exception { + try (Connection c = conn()) { + Map s = one(c, "SELECT * FROM stations WHERE id=?", sid); + return s == null ? err(404, "Station not found") : ok(s); + } + } + + @PostMapping("/stations/{sid}/disable") + public Map disable(@PathVariable String sid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE stations SET status='停用' WHERE id=?", sid); return Map.of("status", "disabled"); } } + + @PostMapping("/stations/{sid}/enable") + public Map enable(@PathVariable String sid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE stations SET status='正常' WHERE id=?", sid); return Map.of("status", "enabled"); } } + + @PostMapping("/stations/{sid}/clear-warning") + public Map clearWarning(@PathVariable String sid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE stations SET fault_count=0,status='正常' WHERE id=?", sid); return Map.of("status", "warning cleared"); } } + + @GetMapping("/stations/{sid}/parcels") + public List> stationParcels(@PathVariable String sid) throws Exception { try (Connection c = conn()) { return all(c, "SELECT * FROM parcels WHERE current_station=?", sid); } } + + @PostMapping("/couriers") + public Map createCourier(@RequestBody Map b) throws Exception { + try (Connection c = conn()) { + String cid = bodyStr(b, "id", ""); + if (cid.isEmpty()) cid = "CR_" + hex(6); + exec(c, "INSERT INTO couriers (id,station_id,daily_quota,active_count,status,fail_history) VALUES (?,?,?,0,'待审核','[]')", cid, bodyStr(b, "station_id", ""), bodyInt(b, "daily_quota", 5)); + return one(c, "SELECT * FROM couriers WHERE id=?", cid); + } + } + + @GetMapping("/couriers") + public List> couriers() throws Exception { try (Connection c = conn()) { return all(c, "SELECT * FROM couriers"); } } + + @GetMapping("/couriers/{cid}") + public ResponseEntity getCourier(@PathVariable String cid) throws Exception { + try (Connection c = conn()) { + Map cr = one(c, "SELECT * FROM couriers WHERE id=?", cid); + return cr == null ? err(404, "Courier not found") : ok(cr); + } + } + + @PostMapping("/couriers/{cid}/approve") + public Map approve(@PathVariable String cid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE couriers SET status='空闲' WHERE id=?", cid); return Map.of("status", "approved"); } } + + @PostMapping("/couriers/{cid}/suspend") + public Map suspend(@PathVariable String cid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE couriers SET status='异常审查' WHERE id=?", cid); return Map.of("status", "suspended"); } } + + @PostMapping("/couriers/{cid}/reassign") + public Map reassign(@PathVariable String cid) { return Map.of("status", "ok"); } + + @GetMapping("/claims") + public List> claims() throws Exception { try (Connection c = conn()) { return all(c, "SELECT * FROM claims"); } } + + @GetMapping("/claims/{cid}") + public ResponseEntity getClaim(@PathVariable String cid) throws Exception { + try (Connection c = conn()) { + Map cl = one(c, "SELECT * FROM claims WHERE id=?", cid); + return cl == null ? err(404, "Claim not found") : ok(cl); + } + } + + @PostMapping("/claims/{cid}/assess") + public ResponseEntity assess(@PathVariable String cid) throws Exception { + try (Connection c = conn()) { + Map cl = one(c, "SELECT * FROM claims WHERE id=?", cid); + if (cl == null) return err(404, "Claim not found"); + Map p = one(c, "SELECT * FROM parcels WHERE id=?", cl.get("parcel_id")); + exec(c, "UPDATE claims SET status='定损中',amount=? WHERE id=?", p == null ? 0 : asInt(p.get("declared_value")), cid); + return ok(one(c, "SELECT * FROM claims WHERE id=?", cid)); + } + } + + @PostMapping("/claims/{cid}/pay") + public Map pay(@PathVariable String cid) throws Exception { + try (Connection c = conn()) { + exec(c, "UPDATE claims SET status='已赔付' WHERE id=?", cid); + Map cl = one(c, "SELECT * FROM claims WHERE id=?", cid); + if (cl != null && !asStr(cl.get("parcel_id")).isEmpty()) exec(c, "UPDATE parcels SET status='已理赔关闭' WHERE id=?", cl.get("parcel_id")); + return Map.of("status", "paid"); + } + } + + @PostMapping("/claims/{cid}/reject") + public Map rejectClaim(@PathVariable String cid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE claims SET status='已驳回' WHERE id=?", cid); return Map.of("status", "rejected"); } } + + @GetMapping("/cod") + public List> cods() throws Exception { try (Connection c = conn()) { return all(c, "SELECT * FROM cod_records"); } } + + @GetMapping("/cod/{cid}") + public ResponseEntity getCod(@PathVariable String cid) throws Exception { + try (Connection c = conn()) { + Map cd = one(c, "SELECT * FROM cod_records WHERE id=?", cid); + return cd == null ? err(404, "COD record not found") : ok(cd); + } + } + + @PostMapping("/cod/{cid}/reconcile") + public Map reconcile(@PathVariable String cid) throws Exception { try (Connection c = conn()) { exec(c, "UPDATE cod_records SET status='对账中' WHERE id=?", cid); return Map.of("status", "reconciling"); } } + + @PostMapping("/cod/{cid}/settle") + public Map settleCod(@PathVariable String cid) throws Exception { + try (Connection c = conn()) { + Map cd = one(c, "SELECT * FROM cod_records WHERE id=?", cid); + if (cd != null) { + exec(c, "UPDATE cod_records SET status='已回款' WHERE id=?", cid); + Map p = one(c, "SELECT * FROM parcels WHERE id=?", cd.get("parcel_id")); + if (p != null) exec(c, "UPDATE customers SET cod_balance=cod_balance+? WHERE id=?", asInt(cd.get("amount")), p.get("sender")); + } + return Map.of("status", "settled"); + } + } + + @PostMapping("/customers") + public Map createCustomer(@RequestBody Map b) throws Exception { + try (Connection c = conn()) { + String cid = bodyStr(b, "id", ""); + if (cid.isEmpty()) cid = "CUS_" + hex(6); + exec(c, "INSERT INTO customers (id,credit_level,cod_balance,status) VALUES (?,?,0,'正常')", cid, bodyStr(b, "credit_level", "铜")); + return one(c, "SELECT * FROM customers WHERE id=?", cid); + } + } + + @GetMapping("/customers") + public List> customers() throws Exception { try (Connection c = conn()) { return all(c, "SELECT * FROM customers"); } } + + @GetMapping("/customers/{cid}") + public ResponseEntity getCustomer(@PathVariable String cid) throws Exception { + try (Connection c = conn()) { + Map cu = one(c, "SELECT * FROM customers WHERE id=?", cid); + return cu == null ? err(404, "Customer not found") : ok(cu); + } + } + + @PostMapping("/customers/{cid}/adjust-credit") + public ResponseEntity adjustCredit(@PathVariable String cid, @RequestBody(required = false) Map b) throws Exception { + try (Connection c = conn()) { + if (one(c, "SELECT id FROM customers WHERE id=?", cid) == null) return err(404, "Customer not found"); + if (b != null && b.containsKey("credit_level") && b.get("credit_level") != null) { + String cl = asStr(b.get("credit_level")); + if (!in(cl, "金", "银", "铜")) return err(400, "credit_level 非法"); + exec(c, "UPDATE customers SET credit_level=? WHERE id=?", cl, cid); + } + if (b != null && b.containsKey("status") && b.get("status") != null) { + String st = asStr(b.get("status")); + if (!in(st, "正常", "信用观察", "受限", "冻结")) return err(400, "status 非法"); + exec(c, "UPDATE customers SET status=? WHERE id=?", st, cid); + } + return ok(Map.of("status", "updated")); + } + } + + @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) + public String events() { + return "\n"; + } +} diff --git a/src/main/java/com/nowcoder/logistics/aaa.java b/src/main/java/com/nowcoder/logistics/aaa.java new file mode 100644 index 0000000..0eb5097 --- /dev/null +++ b/src/main/java/com/nowcoder/logistics/aaa.java @@ -0,0 +1,7 @@ +package com.nowcoder.logistics; + +public class aaa { + public static void main(String[] args) { + System.out.println("Hello, Logistics!"); + } +} \ No newline at end of file diff --git a/target/classes/com/nowcoder/logistics/LogisticsPresetApplication$1.class b/target/classes/com/nowcoder/logistics/LogisticsPresetApplication$1.class new file mode 100644 index 0000000..e3c0762 Binary files /dev/null and b/target/classes/com/nowcoder/logistics/LogisticsPresetApplication$1.class differ diff --git a/target/classes/com/nowcoder/logistics/LogisticsPresetApplication$2.class b/target/classes/com/nowcoder/logistics/LogisticsPresetApplication$2.class new file mode 100644 index 0000000..019c138 Binary files /dev/null and b/target/classes/com/nowcoder/logistics/LogisticsPresetApplication$2.class differ diff --git a/target/classes/com/nowcoder/logistics/LogisticsPresetApplication.class b/target/classes/com/nowcoder/logistics/LogisticsPresetApplication.class new file mode 100644 index 0000000..384506c Binary files /dev/null and b/target/classes/com/nowcoder/logistics/LogisticsPresetApplication.class differ diff --git a/target/classes/com/nowcoder/logistics/aaa.class b/target/classes/com/nowcoder/logistics/aaa.class new file mode 100644 index 0000000..7217505 Binary files /dev/null and b/target/classes/com/nowcoder/logistics/aaa.class differ diff --git a/target/logistics-preset-java-1.0.0.jar b/target/logistics-preset-java-1.0.0.jar new file mode 100644 index 0000000..6128dc8 Binary files /dev/null and b/target/logistics-preset-java-1.0.0.jar differ diff --git a/target/logistics-preset-java-1.0.0.jar.original b/target/logistics-preset-java-1.0.0.jar.original new file mode 100644 index 0000000..7c6f32e Binary files /dev/null and b/target/logistics-preset-java-1.0.0.jar.original differ diff --git a/target/maven-archiver/pom.properties b/target/maven-archiver/pom.properties new file mode 100644 index 0000000..a776f5d --- /dev/null +++ b/target/maven-archiver/pom.properties @@ -0,0 +1,3 @@ +artifactId=logistics-preset-java +groupId=com.nowcoder +version=1.0.0 diff --git a/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 0000000..5f07dab --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1,3 @@ +com/nowcoder/logistics/LogisticsPresetApplication$1.class +com/nowcoder/logistics/LogisticsPresetApplication.class +com/nowcoder/logistics/LogisticsPresetApplication$2.class diff --git a/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 0000000..eff9bb6 --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1,2 @@ +/Users/mac/Documents/GitHub/testForNiuKe/src/main/java/com/nowcoder/logistics/aaa.java +/Users/mac/Documents/GitHub/testForNiuKe/src/main/java/com/nowcoder/logistics/LogisticsPresetApplication.java diff --git a/test.py b/test.py new file mode 100644 index 0000000..2de46fa --- /dev/null +++ b/test.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""快递物流配送履约系统 — 样例测试用例 (sample) + +╔═══════════════════════════════════════════════════════════════════════════╗ +║ 重要原则: sample 只测「连通性」, 不暴露隐形规则, 也不演示任何 create body ║ +║ - 只测: 种子实体读取 / 网点·客户创建 / 默认值 / 时钟 / 404 ║ +║ - 不测: 逆向退回 / 理赔分档 / COD 链 / 阈值 / 级联 / 调度算法 ║ +║ - 不测建包裹/揽收/运单: 刻意不演示 parcel create 的必填字段(如 address), ║ +║ 避免给考生作答 body 模板; 包裹只做 404 读连通 ║ +║ - 用例数: ≤ 15 条 ║ +║ - 通过全部 sample ≠ 通过最终判分 ║ +╚═══════════════════════════════════════════════════════════════════════════╝ + +运行: 先启动服务监听 PORT, 再执行 + python3 sample_testcases/run_sample_testcases.py +""" + +import os +import sys +import requests + +BASE_URL = "http://localhost:" + os.environ.get("PORT", "8000") +S = requests.Session() +S.trust_env = False +TIMEOUT = 5 + + +def GET(path): + return S.get(f"{BASE_URL}{path}", timeout=TIMEOUT) + +def POST(path, data=None): + return S.post(f"{BASE_URL}{path}", json=data or {}, timeout=TIMEOUT) + + +def _need(obj, fields): + miss = [f for f in fields if f not in obj] + return f"缺少字段 {miss}" if miss else "" + + +def _to_list(r): + data = r.json() + if isinstance(data, list): + return data + if isinstance(data, dict): + for v in data.values(): + if isinstance(v, list): + return v + return data + + +def _reset(): + POST("/system/reset") + + +# (1) 网点列表 — 初始 seed 5 个 +def test_stations_seeded(): + _reset() + r = GET("/stations") + if r.status_code != 200: + return False, f"网点列表失败: {r.status_code}" + lst = _to_list(r) + if not isinstance(lst, list) or len(lst) < 5: + return False, f"初始网点应≥5, 得到 {len(lst) if isinstance(lst, list) else 'non-list'}" + return True, "" + + +# (2) 网点详情字段 +def test_station_detail(): + r = GET("/stations/ST_HUB") + if r.status_code != 200: + return False, f"网点详情失败: {r.status_code}" + return (lambda m: (not m, m))(_need(r.json(), ["id", "capacity", "in_stock", "status"])) + + +# (3) 客户列表 — 初始 seed 3 个 +def test_customers_seeded(): + r = GET("/customers") + if r.status_code != 200: + return False, f"客户列表失败: {r.status_code}" + lst = _to_list(r) + if len(lst) < 3: + return False, f"初始客户应≥3, 得到 {len(lst)}" + return True, "" + + +# (4) 快递员列表 — 初始 seed 3 个 +def test_couriers_seeded(): + r = GET("/couriers") + if r.status_code != 200: + return False, f"快递员列表失败: {r.status_code}" + lst = _to_list(r) + if len(lst) < 3: + return False, f"初始快递员应≥3, 得到 {len(lst)}" + d = lst[0] + return (lambda m: (not m, m))(_need(d, ["id", "station_id", "active_count", "status"])) + + +# (5) 包裹不存在 → 404 +def test_parcel_404(): + r = GET("/parcels/NO_SUCH_ID") + if r.status_code != 404: + return False, f"应 404, 得到 {r.status_code}" + return True, "" + + +# (6) 创建网点 +def test_station_create(): + r = POST("/stations", {"id": "ST_X1", "name": "测试网点", "capacity": 30}) + if r.status_code not in (200, 201): + return False, f"创建网点失败: {r.status_code}" + return (GET("/stations/ST_X1").status_code == 200, "") + + +# (7) 创建客户 + 信用等级 +def test_customer_create(): + r = POST("/customers", {"id": "CUS_T1", "credit_level": "银"}) + if r.status_code not in (200, 201): + return False, f"创建客户失败: {r.status_code}" + d = GET("/customers/CUS_T1").json() + if d.get("credit_level") != "银": + return False, "credit_level 未写入" + return True, "" + + +# (8) 逻辑时钟推进 +def test_clock_tick(): + t0 = GET("/system/clock").json().get("now") + POST("/system/clock/tick", {"steps": 3}) + t1 = GET("/system/clock").json().get("now") + if t1 != t0 + 3: + return False, f"时钟推进异常: {t0} → {t1}" + return True, "" + + +# (9) claims / cod 列表连通 +def test_claims_cod_list(): + if GET("/claims").status_code != 200: + return False, "claims 列表失败" + if GET("/cod").status_code != 200: + return False, "cod 列表失败" + return True, "" + + +def get_sample_cases(): + return [ + ("网点初始数据", test_stations_seeded), + ("网点详情字段", test_station_detail), + ("客户初始数据", test_customers_seeded), + ("快递员初始数据", test_couriers_seeded), + ("包裹 404", test_parcel_404), + ("网点创建", test_station_create), + ("客户创建", test_customer_create), + ("逻辑时钟推进", test_clock_tick), + ("理赔/COD 列表", test_claims_cod_list), + ] + + +def main(): + cases = get_sample_cases() + passed = failed = 0 + print(f"测试服务: {BASE_URL}\n") + for name, fn in cases: + try: + ok, msg = fn() + if ok: + print(f" PASS {name}") + passed += 1 + else: + print(f" FAIL {name}: {msg}") + failed += 1 + except Exception as e: + print(f" ERROR {name}: {e}") + failed += 1 + print(f"\n结果: {passed} 通过, {failed} 失败, 共 {passed + failed} 条") + print("\n注意: 这些只是基础连通性验证, 通过全部样例不代表最终得分。") + sys.exit(0 if failed == 0 else 1) + + +if __name__ == "__main__": + main()