OrderService.php 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679
  1. <?php
  2. namespace App\Services\Client;
  3. use App\Enums\OrderGrabRecordStatus;
  4. use App\Enums\OrderRecordStatus;
  5. use App\Enums\OrderStatus;
  6. use App\Enums\OrderType;
  7. use App\Enums\PaymentMethod;
  8. use App\Enums\ProjectStatus;
  9. use App\Enums\TechnicianAuthStatus;
  10. use App\Enums\TechnicianLocationType;
  11. use App\Enums\TechnicianStatus;
  12. use App\Enums\TransactionType;
  13. use App\Enums\UserStatus;
  14. use App\Models\AgentInfo;
  15. use App\Models\CoachSchedule;
  16. use App\Models\CoachUser;
  17. use App\Models\MemberAddress;
  18. use App\Models\MemberUser;
  19. use App\Models\Order;
  20. use App\Models\OrderGrabRecord;
  21. use App\Models\OrderRecord;
  22. use App\Models\Project;
  23. use App\Models\WalletPaymentRecord;
  24. use App\Services\Client\Traits\CalculatesOrderAmounts;
  25. use App\Services\Client\Traits\HandlesOrderRecords;
  26. use App\Services\Client\Traits\HandlesPayments;
  27. use App\Services\Client\Traits\ValidatesServiceTime;
  28. use Carbon\Carbon;
  29. use Exception;
  30. use Illuminate\Support\Facades\Auth;
  31. use Illuminate\Support\Facades\DB;
  32. use Illuminate\Support\Facades\Log;
  33. use Illuminate\Support\Facades\Redis;
  34. use SimpleSoftwareIO\QrCode\Facades\QrCode;
  35. readonly class OrderService
  36. {
  37. use CalculatesOrderAmounts;
  38. use HandlesOrderRecords;
  39. use HandlesPayments;
  40. use ValidatesServiceTime;
  41. public function __construct(
  42. private AgentService $agentService,
  43. private ProjectService $projectService,
  44. private CoachService $coachService,
  45. private WalletService $walletService
  46. ) {}
  47. /**
  48. * 订单初始化
  49. *
  50. * @param int $userId 用户ID
  51. * @param array $data 订单数据
  52. * @return array 初始化的订单信息
  53. *
  54. * @throws \Exception
  55. *
  56. * 逻辑描述:
  57. * 1. 验证初始化参数(project_id、coach_id)
  58. * 2. 获取用户信息(包含钱包和地址)
  59. * 3. 获取区域编码(从地址或参数)
  60. * 4. 验证技师状态并获取可用时间
  61. * 5. 获取项目详情(含价格)
  62. * 6. 计算订单金额(含路费)
  63. * 7. 返回初始化数据(钱包、技师、项目、地址、金额、可用时间)
  64. */
  65. public function initialize(int $userId, array $data): array
  66. {
  67. try {
  68. // 参数验证
  69. $this->validateInitializeData($data);
  70. return DB::transaction(function () use ($userId, $data) {
  71. // 获取用户信息
  72. $user = $this->getUserWithWalletAndAddress($userId);
  73. // 获取区域编码
  74. $areaCode = $this->getAreaCode($user->address, $data);
  75. // 获取技师信息和可用时间
  76. $coach = $this->validateCoach($data['coach_id']);
  77. $availableTimeSlots = $this->coachService->getSchedule($coach->id);
  78. // 获取项目信息
  79. $project = $this->getProjectDetail($data['project_id'], $areaCode);
  80. // 计算订单金额
  81. $amounts = $this->calculateOrderAmount(
  82. userId: $userId,
  83. addressId: $user->address?->id ?? 0,
  84. coachId: $data['coach_id'],
  85. projectId: $data['project_id'],
  86. agentId: $project->agent_id,
  87. useBalance: false,
  88. distance: $data['distance'] ?? 0,
  89. lat: $data['latitude'] ?? 0,
  90. lng: $data['longitude'] ?? 0
  91. );
  92. return [
  93. 'wallet' => $user->wallet,
  94. 'coach' => $coach,
  95. 'project' => $project,
  96. 'address' => $user->address,
  97. 'amounts' => $amounts,
  98. 'availableTimeSlots' => $availableTimeSlots,
  99. ];
  100. });
  101. } catch (Exception $e) {
  102. $this->logError('订单初始化失败', $e, [
  103. 'userId' => $userId,
  104. 'data' => $data,
  105. ]);
  106. throw $e;
  107. }
  108. }
  109. /**
  110. * 验证初始化数据
  111. *
  112. * 逻辑描述:
  113. * 1. 验证项目ID不能为空
  114. * 2. 验证技师ID不能为空
  115. */
  116. private function validateInitializeData(array $data): void
  117. {
  118. abort_if(empty($data['project_id']), 400, '项目ID不能为空');
  119. abort_if(empty($data['coach_id']), 400, '技师ID不能为空');
  120. }
  121. /**
  122. * 获取用户信息(包含钱包和地址)
  123. *
  124. * 逻辑描述:
  125. * 1. 查询用户信息(关联钱包和地址)
  126. * 2. 验证用户状态是否正常
  127. * 3. 返回用户信息
  128. */
  129. private function getUserWithWalletAndAddress(int $userId): MemberUser
  130. {
  131. $user = MemberUser::with(['wallet', 'address'])
  132. ->where('id', $userId)
  133. ->where('state', UserStatus::OPEN->value)
  134. ->first();
  135. abort_if(! $user, 400, '用户状态异常');
  136. return $user;
  137. }
  138. /**
  139. * 获取区域编码
  140. *
  141. * 逻辑描述:
  142. * 1. 优先使用地址中的区域编码
  143. * 2. 其次使用参数中的区域编码
  144. * 3. 验证区域编码不能为空
  145. */
  146. private function getAreaCode(?object $address, array $data): string
  147. {
  148. $areaCode = $address?->area_code ?? ($data['area_code'] ?? null);
  149. abort_if(empty($areaCode), 400, '区域编码不能为空');
  150. return $areaCode;
  151. }
  152. /**
  153. * 获取项目详情
  154. *
  155. * 逻辑描述:
  156. * 1. 调用项目服务获取详情
  157. * 2. 验证项目是否存在
  158. * 3. 返回项目信息
  159. */
  160. private function getProjectDetail(int $projectId, string $areaCode): Project
  161. {
  162. $project = $this->projectService->getProjectDetail($projectId, $areaCode);
  163. abort_if(! $project, 400, '项目不存在');
  164. return $project;
  165. }
  166. /**
  167. * 记录错误日志
  168. *
  169. * 逻辑描述:
  170. * 1. 记录错误信息
  171. * 2. 记录上下文数据
  172. * 3. 记录错误堆栈
  173. */
  174. private function logError(string $message, Exception $e, array $context = []): void
  175. {
  176. Log::error($message, [
  177. ...$context,
  178. 'error' => $e->getMessage(),
  179. 'trace' => $e->getTraceAsString(),
  180. ]);
  181. }
  182. /**
  183. * 创建订单
  184. *
  185. * @param array{
  186. * user_id: int,
  187. * project_id: int,
  188. * coach_id: ?int,
  189. * address_id: int,
  190. * service_time: string,
  191. * remark: ?string,
  192. * use_balance: bool,
  193. * agent_id: ?int,
  194. * distance: float,
  195. * payment_type: int,
  196. * type: int,
  197. * } $data 订单数据
  198. * @return array{
  199. * order_id: int,
  200. * order_no: string,
  201. * total_amount: float,
  202. * balance_amount: float,
  203. * pay_amount: float
  204. * }
  205. *
  206. * @throws \Exception
  207. *
  208. * 逻辑描述:
  209. * 1. 验证基础数据(用户状态、项目状态、服务时间、技师状态等)
  210. * 2. 计算订单金额(项目价格、路费、优惠等)
  211. * 3. 处理加钟订单特殊逻辑(使用原订单地址和技师)
  212. * 4. 获取服务地址信息
  213. * 5. 创建订单数据
  214. * 6. 创建订单相关记录
  215. * 7. 处理余额支付(如果是余额支付)
  216. * 8. 发送订单创建通知
  217. * 9. 返回订单信息
  218. */
  219. public function createOrder(int $userId, array $data): array
  220. {
  221. return DB::transaction(function () use ($userId, $data) {
  222. try {
  223. // 1. 验证基础数据
  224. $this->validateOrderData($userId, $data);
  225. // 2. 计算订单金额
  226. $amounts = $this->calculateOrderAmount(
  227. userId: $userId,
  228. addressId: $data['address_id'] ?? null,
  229. coachId: $data['coach_id'] ?? null,
  230. projectId: $data['project_id'],
  231. agentId: $data['agent_id'] ?? null,
  232. useBalance: $data['use_balance'] ?? false,
  233. distance: $data['distance'] ?? 0
  234. );
  235. // 加钟订单使用原订单地址和技师ID
  236. if ($data['order_id']) {
  237. $order = Order::find($data['order_id']);
  238. $data['address_id'] = $order->address_id;
  239. $data['coach_id'] = $order->coach_id;
  240. $data['service_time'] = $order->service_end_time;
  241. }
  242. // 3. 获取地址
  243. $address = MemberUser::find($userId)->addresses()
  244. ->where('id', $data['address_id'])
  245. ->firstOrFail();
  246. // 3. 创建订单
  247. $order = $this->createOrderData(['user_id' => $userId, ...$data], $amounts, $address);
  248. // 4. 创建订单相关记录
  249. $this->createRelatedRecords($order);
  250. // 5. 检测支付类型,自动进行余额支付
  251. if ($order->payment_type == PaymentMethod::BALANCE->value) {
  252. // 处理余额支付
  253. if ($amounts['balance_amount'] > 0) {
  254. $this->processBalancePayment($order);
  255. }
  256. // 更改订单状态
  257. $order->state = OrderStatus::PAID->value;
  258. $order->service_start_time = $data['service_time'];
  259. $order->service_end_time = Carbon::parse($data['service_time'])
  260. ->addMinutes($order->project->duration);
  261. $order->save();
  262. // 创建订单相关记录
  263. $this->createRelatedRecords($order);
  264. }
  265. // 6. 发送通知
  266. $this->notifyOrderCreated($order);
  267. return [
  268. 'order_id' => $order->id,
  269. 'order_no' => $order->order_no,
  270. 'total_amount' => $amounts['total_amount'],
  271. 'balance_amount' => $amounts['balance_amount'],
  272. 'pay_amount' => $amounts['pay_amount'],
  273. ];
  274. } catch (Exception $e) {
  275. $this->logError('创建订单失败', $e, $data);
  276. throw $e;
  277. }
  278. });
  279. }
  280. /**
  281. * 验证订单创建数据
  282. */
  283. private function validateOrderData(int $userId, array $data): void
  284. {
  285. // 验证用户状态
  286. $user = MemberUser::where('id', $userId)
  287. ->where('state', UserStatus::OPEN->value)
  288. ->firstOrFail();
  289. // 验证项目状态
  290. $project = Project::where('id', $data['project_id'])
  291. ->where('state', ProjectStatus::OPEN->value)
  292. ->firstOrFail();
  293. // 验证服务时间
  294. if (! empty($data['service_time'])) {
  295. $serviceTime = Carbon::parse($data['service_time']);
  296. abort_if(
  297. $serviceTime->isPast(),
  298. 400,
  299. '服务时间不能早于当前时间'
  300. );
  301. // 如果指定了技师,验证服务时间是否可用
  302. if (! empty($data['coach_id'])) {
  303. $this->validateServiceTime($data['coach_id'], $data['service_time']);
  304. }
  305. }
  306. // 验证技师状态(如果有)
  307. if (! empty($data['coach_id'])) {
  308. $this->validateCoach($data['coach_id']);
  309. }
  310. // TODO: 验证代理商状态(如果有)
  311. // 验证代理商状态(如果有)
  312. // if (! empty($data['agent_id'])) {
  313. // $agent = AgentInfo::where('id', $data['agent_id'])
  314. // ->where('state', AgentStatus::OPEN->value)
  315. // ->firstOrFail();
  316. // }
  317. }
  318. /**
  319. * 创建订单数据
  320. */
  321. private function createOrderData(array $data, array $amounts, object $address): Order
  322. {
  323. return Order::create([
  324. 'order_no' => $this->generateOrderNo(),
  325. 'user_id' => $data['user_id'],
  326. 'project_id' => $data['project_id'],
  327. 'coach_id' => $data['coach_id'] ?? null,
  328. 'agent_id' => $data['agent_id'] ?? null,
  329. 'address_id' => $data['address_id'],
  330. 'service_time' => $data['service_time'] ?? null,
  331. 'remark' => $data['remark'] ?? '',
  332. 'total_amount' => $amounts['total_amount'],
  333. 'balance_amount' => $amounts['balance_amount'],
  334. 'pay_amount' => $amounts['pay_amount'],
  335. 'traffic_amount' => $amounts['delivery_fee'],
  336. 'project_amount' => $amounts['project_amount'],
  337. 'discount_amount' => $amounts['coupon_amount'],
  338. 'state' => OrderStatus::CREATED->value,
  339. // 如果余额支付且未使用优惠券且未支付金额,则使用余额支付,否则使用传入的支付方式
  340. 'payment_type' => $amounts['balance_amount'] > 0 && $amounts['pay_amount'] == 0
  341. ? PaymentMethod::BALANCE->value
  342. : $data['payment_type'],
  343. 'latitude' => $address->latitude,
  344. 'longitude' => $address->longitude,
  345. 'location' => $address->location,
  346. 'address' => $address->detail,
  347. 'area_code' => $address->area_code,
  348. 'type' => $data['order_type'],
  349. ]);
  350. }
  351. private function createOrderRecord(Order $order, int $objectId, string $objectType, OrderRecordStatus $status, string $remark): OrderRecord
  352. {
  353. return OrderRecord::create([
  354. 'order_id' => $order->id,
  355. 'object_id' => $objectId,
  356. 'object_type' => $objectType,
  357. 'state' => $status->value,
  358. 'remark' => $remark,
  359. ]);
  360. }
  361. /**
  362. * 生成订单号
  363. */
  364. private function generateOrderNo(): string
  365. {
  366. return 'O'.date('YmdHis').str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT);
  367. }
  368. /**
  369. * 处理余额支付
  370. */
  371. private function processBalancePayment(Order $order): void
  372. {
  373. $wallet = $order->user->wallet;
  374. // 检查钱包可用余额是否足够
  375. abort_if($wallet->available_balance < $order->balance_amount, 400, '钱包可用余额不足,无法完成支付');
  376. // 扣减钱包余额
  377. $wallet->decrement('total_balance', $order->balance_amount);
  378. $wallet->decrement('available_balance', $order->balance_amount);
  379. // 增加冻结金额
  380. $wallet->increment('frozen_amount', $order->balance_amount);
  381. // 创建钱包交易记录
  382. $wallet->transRecords()->create([
  383. 'amount' => -$order->balance_amount,
  384. 'trans_type' => TransactionType::PAYMENT->value,
  385. 'owner_type' => Order::class,
  386. 'owner_id' => $order->id,
  387. 'remark' => '订单支付',
  388. 'before_balance' => $wallet->total_balance + $order->balance_amount,
  389. 'after_balance' => $wallet->total_balance,
  390. 'state' => 'success',
  391. ]);
  392. }
  393. /**
  394. * 创建订单相关记录
  395. */
  396. private function createRelatedRecords(Order $order): void
  397. {
  398. // 创建订单状态记录
  399. OrderRecord::create([
  400. 'order_id' => $order->id,
  401. 'object_id' => $order->user_id,
  402. 'object_type' => MemberUser::class,
  403. 'state' => $order->state,
  404. 'remark' => $order->state === OrderStatus::PAID->value
  405. ? '余额支付成功'
  406. : '订单创建成功',
  407. ]);
  408. }
  409. /**
  410. * 发送订单创建通知
  411. */
  412. private function notifyOrderCreated(Order $order): void
  413. {
  414. // TODO: 实现订单创建通知逻辑
  415. // 1. 通知用户
  416. // event(new OrderCreatedEvent($order));
  417. // 2. 通知技师(如果有)
  418. if ($order->coach_id) {
  419. // event(new OrderAssignedToCoachEvent($order));
  420. }
  421. }
  422. /**
  423. * 获取订单地址
  424. */
  425. private function getOrderAddress(MemberUser $user, array $data, OrderType $orderType): object
  426. {
  427. // 加钟订单使用原订单地址
  428. if ($orderType === OrderType::OVERTIME) {
  429. $originalOrder = $this->getOriginalOrder($user, $data['order_id']);
  430. $data['address_id'] = $originalOrder->address_id;
  431. }
  432. abort_if(empty($data['address_id']), 400, '地址ID不能为空');
  433. return $user->addresses()
  434. ->where('id', $data['address_id'])
  435. ->firstOrFail();
  436. }
  437. /**
  438. * 验证支付方式和余额
  439. */
  440. private function validatePayment(MemberUser $user, array $data, array $amounts): void
  441. {
  442. abort_if($amounts['total_amount'] <= 0, 400, '订单金额异常');
  443. if ($data['payment_type'] === PaymentMethod::BALANCE->value) {
  444. $wallet = $user->wallet;
  445. abort_if($wallet->available_balance < $amounts['balance_amount'], 400, '可用余额不足');
  446. }
  447. }
  448. /**
  449. * 判断是否需要处理余额支付
  450. */
  451. private function shouldHandleBalancePayment(Order $order, OrderType $orderType): bool
  452. {
  453. return $order->payment_type === PaymentMethod::BALANCE->value
  454. && $orderType !== OrderType::GRAB;
  455. }
  456. // 提取方法:验证技师
  457. public function validateCoach(int $coachId): CoachUser
  458. {
  459. return CoachUser::where('id', $coachId)
  460. ->where('state', TechnicianStatus::ACTIVE->value)
  461. ->whereHas('info', fn ($q) => $q->where('state', TechnicianAuthStatus::PASSED->value))
  462. ->whereHas('qual', fn ($q) => $q->where('state', TechnicianAuthStatus::PASSED->value))
  463. ->whereHas('real', fn ($q) => $q->where('state', TechnicianAuthStatus::PASSED->value))
  464. ->firstOrFail();
  465. }
  466. // 提取方法:获取原始订单
  467. private function getOriginalOrder($user, $orderId): Order
  468. {
  469. $originalOrder = $user->orders->where('id', $orderId)
  470. ->whereIn('state', [OrderStatus::SERVING->value, OrderStatus::FINISHED->value])
  471. ->firstOrFail();
  472. return $originalOrder;
  473. }
  474. // 提取方法:准备加钟订单数据
  475. private function prepareAddTimeData($originalOrder, $data): array
  476. {
  477. if ($originalOrder->state == OrderStatus::SERVING->value) {
  478. $startTime = now();
  479. } else {
  480. $startTime = now();
  481. }
  482. return [
  483. ...$data,
  484. 'order_id' => $data['order_id'],
  485. 'address_id' => $originalOrder->address_id,
  486. 'service_time' => $startTime,
  487. 'coach_id' => $originalOrder->coach_id,
  488. ];
  489. }
  490. /**
  491. * 取消订单
  492. *
  493. * @param int $userId 用户ID
  494. * @param int $orderId 订单ID
  495. * @param string|null $reason 取消原因
  496. * @return array{message: string}
  497. *
  498. * @throws \Exception
  499. */
  500. public function cancelOrder(int $userId, int $orderId, ?string $reason = null): array
  501. {
  502. return DB::transaction(function () use ($userId, $orderId, $reason) {
  503. try {
  504. // 1. 验证订单状态
  505. $order = $this->validateOrderForCancel($userId, $orderId);
  506. // 2. 计算取消���用
  507. $cancelAmounts = $this->calculateCancelAmount($order);
  508. // 3. 处理退款
  509. $this->processCancelRefund($order, $cancelAmounts);
  510. // 4. 更新订单状态
  511. $this->updateOrderCancelStatus($order);
  512. // 5. 创建取消记录
  513. $this->createCancelRecords($order, $cancelAmounts, $reason);
  514. // 6. 发送取消通知
  515. $this->notifyCancel($order);
  516. return ['message' => '订单取消成功'];
  517. } catch (Exception $e) {
  518. $this->logError('取消订单失败', $e, [
  519. 'user_id' => $userId,
  520. 'order_id' => $orderId,
  521. 'reason' => $reason,
  522. ]);
  523. throw $e;
  524. }
  525. });
  526. }
  527. /**
  528. * 验证订单取消条件
  529. */
  530. private function validateOrderForCancel(int $userId, int $orderId): Order
  531. {
  532. // 获取并锁定订单
  533. $order = Order::where('id', $orderId)
  534. ->whereIn('state', [
  535. OrderStatus::CREATED->value,
  536. OrderStatus::PAID->value,
  537. OrderStatus::ACCEPTED->value,
  538. ])
  539. ->lockForUpdate()
  540. ->firstOrFail();
  541. // 验证订单所属用户
  542. abort_if($order->user_id !== $userId, 403, '无权操作此订单');
  543. // 验证订单是否已取消
  544. abort_if($order->state === OrderStatus::CANCELLED->value, 400, '订单已取消');
  545. return $order;
  546. }
  547. /**
  548. * 计算取消费用
  549. *
  550. * @return array{
  551. * total_refund: float,
  552. * balance_refund: float,
  553. * payment_refund: float,
  554. * penalty_amount: float
  555. * }
  556. */
  557. private function calculateCancelAmount(Order $order): array
  558. {
  559. $penaltyAmount = 0;
  560. // 计算违约金(根据订单状态和时间)
  561. if ($order->state === OrderStatus::ACCEPTED->value) {
  562. // 已接单取消,收取10%违约金
  563. $penaltyAmount = bcmul($order->total_amount, '0.1', 2);
  564. }
  565. // 计算实际退款金额
  566. $totalRefund = bcsub($order->total_amount, $penaltyAmount, 2);
  567. // 分配退款金额(优先退还支付金额)
  568. $balanceRefund = min($order->balance_amount, $totalRefund);
  569. $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
  570. return [
  571. 'total_refund' => $totalRefund,
  572. 'balance_refund' => $balanceRefund,
  573. 'payment_refund' => $paymentRefund,
  574. 'penalty_amount' => $penaltyAmount,
  575. ];
  576. }
  577. /**
  578. * 处理取消退款
  579. */
  580. private function processCancelRefund(Order $order, array $cancelAmounts): void
  581. {
  582. // 处理余额退款
  583. if ($cancelAmounts['balance_refund'] > 0) {
  584. $this->processBalanceCancelRefund($order, $cancelAmounts['balance_refund']);
  585. }
  586. // 处理支付退款
  587. if ($cancelAmounts['payment_refund'] > 0) {
  588. $this->processPaymentCancelRefund($order, $cancelAmounts['payment_refund']);
  589. }
  590. }
  591. /**
  592. * 处理余额退款
  593. */
  594. private function processBalanceCancelRefund(Order $order, float $amount): void
  595. {
  596. $wallet = $order->user->wallet;
  597. // 更新钱包余额
  598. $wallet->increment('total_balance', $amount);
  599. $wallet->increment('available_balance', $amount);
  600. // 创建钱包交易记录
  601. $wallet->transRecords()->create([
  602. 'amount' => $amount,
  603. 'trans_type' => 'cancel_refund',
  604. 'owner_type' => Order::class,
  605. 'owner_id' => $order->id,
  606. 'remark' => '订单取消退款',
  607. 'before_balance' => $wallet->total_balance - $amount,
  608. 'after_balance' => $wallet->total_balance,
  609. 'state' => 'success',
  610. ]);
  611. }
  612. /**
  613. * 处理支付退款
  614. */
  615. private function processPaymentCancelRefund(Order $order, float $amount): void
  616. {
  617. // TODO: 实现第三方支付退款逻辑
  618. // $paymentService = app(PaymentService::class);
  619. // $paymentService->refund($order->payment_no, $amount);
  620. }
  621. /**
  622. * 更新订单取消状态
  623. */
  624. private function updateOrderCancelStatus(Order $order): void
  625. {
  626. $order->update([
  627. 'state' => OrderStatus::CANCELLED->value,
  628. ]);
  629. }
  630. /**
  631. * 创建取消记录
  632. */
  633. private function createCancelRecords(Order $order, array $cancelAmounts, ?string $reason): void
  634. {
  635. // TODO: 创建取消记录
  636. // 创建取消记录
  637. // $order->cancelRecords()->create([
  638. // 'total_refund_amount' => $cancelAmounts['total_refund'],
  639. // 'balance_refund_amount' => $cancelAmounts['balance_refund'],
  640. // 'payment_refund_amount' => $cancelAmounts['payment_refund'],
  641. // 'penalty_amount' => $cancelAmounts['penalty_amount'],
  642. // 'remark' => $reason ?? '',
  643. // 'state' => 'success',
  644. // ]);
  645. // 创建订单状态记录
  646. OrderRecord::create([
  647. 'order_id' => $order->id,
  648. 'object_id' => Auth::id(),
  649. 'object_type' => MemberUser::class,
  650. 'state' => OrderRecordStatus::CANCELLED->value,
  651. 'remark' => "用户取消订单:{$reason}",
  652. ]);
  653. }
  654. /**
  655. * 发送取消通知
  656. */
  657. private function notifyCancel(Order $order): void
  658. {
  659. // TODO: 实现取消通知逻辑
  660. // 1. ��知用户
  661. // event(new OrderCancelledEvent($order));
  662. // 2. 通知技师
  663. if ($order->coach_id) {
  664. // event(new OrderCancelledToCoachEvent($order));
  665. }
  666. }
  667. /**
  668. * 结束订单
  669. */
  670. public function finishOrder(int $userId, int $orderId): array
  671. {
  672. return DB::transaction(function () use ($userId, $orderId) {
  673. try {
  674. // 1. 验证用户和订单
  675. $order = $this->validateOrderForFinish($userId, $orderId);
  676. // 2. 验证技师状态
  677. $coach = $this->validateCoach($order->coach_id);
  678. // 4. 完成订单
  679. $this->completeOrder($order, $userId);
  680. // 5. ���知技师
  681. // event(new OrderFinishedEvent($order));
  682. return ['message' => '订单已完成'];
  683. } catch (Exception $e) {
  684. $this->logFinishOrderError($e, $userId, $orderId);
  685. throw $e;
  686. }
  687. });
  688. }
  689. /**
  690. * 验证订单完成条件
  691. */
  692. private function validateOrderForFinish(int $userId, int $orderId): Order
  693. {
  694. // 验证用户状态
  695. $user = MemberUser::where('id', $userId)
  696. ->where('state', UserStatus::OPEN->value)
  697. ->firstOrFail();
  698. // 验证订单状态
  699. $order = Order::where('user_id', $userId)
  700. ->where('id', $orderId)
  701. ->where('state', OrderStatus::SERVING->value)
  702. ->lockForUpdate()
  703. ->firstOrFail();
  704. return $order;
  705. }
  706. /**
  707. * 完成订单
  708. */
  709. private function completeOrder(Order $order, int $userId): void
  710. {
  711. // 1. 创建订单记录
  712. OrderRecord::create([
  713. 'order_id' => $order->id,
  714. 'object_id' => $userId,
  715. 'object_type' => MemberUser::class,
  716. 'state' => OrderRecordStatus::COMPLETED->value,
  717. 'remark' => '服务完成',
  718. ]);
  719. // 2. 更新订单状态
  720. $order->state = OrderStatus::FINISHED->value;
  721. $order->save();
  722. }
  723. /**
  724. * 记录订单完成错误日志
  725. */
  726. private function logFinishOrderError(Exception $e, int $userId, int $orderId): void
  727. {
  728. Log::error('结束订单失败:', [
  729. 'message' => $e->getMessage(),
  730. 'user_id' => $userId,
  731. 'order_id' => $orderId,
  732. 'trace' => $e->getTraceAsString(),
  733. ]);
  734. }
  735. /**
  736. * 确认技师离开
  737. */
  738. public function confirmLeave(int $userId, int $orderId): array
  739. {
  740. return DB::transaction(function () use ($userId, $orderId) {
  741. try {
  742. // 1. 参数校验
  743. $order = Order::where('user_id', $userId)
  744. ->where('id', $orderId)
  745. ->where('state', OrderStatus::FINISHED->value) // 订单状态必须是服务结束
  746. ->firstOrFail();
  747. if (! $order) {
  748. throw new Exception('订单不能撤离');
  749. }
  750. // 2. 添加订单撤离记录
  751. OrderRecord::create([
  752. 'order_id' => $orderId,
  753. 'object_id' => $userId,
  754. 'object_type' => MemberUser::class,
  755. 'state' => OrderRecordStatus::LEFT->value,
  756. 'remark' => '技师已离开',
  757. ]);
  758. // 3. 修改订单状态为撤离
  759. $order->state = OrderStatus::LEFT->value;
  760. $order->save();
  761. return ['message' => '已确技师离开'];
  762. } catch (Exception $e) {
  763. Log::error('确认技师离开失败:', [
  764. 'message' => $e->getMessage(),
  765. 'user_id' => $userId,
  766. 'order_id' => $orderId,
  767. ]);
  768. throw $e;
  769. }
  770. });
  771. }
  772. /**
  773. * 获取订单列表
  774. *
  775. * @param int $userId 用户ID
  776. * @param array{
  777. * state: ?string,
  778. * start_date: ?string,
  779. * end_date: ?string,
  780. * project_id: ?int,
  781. * coach_id: ?int,
  782. * order_no: ?string,
  783. * per_page: ?int,
  784. * page: ?int
  785. * } $filters 过滤条件
  786. *
  787. * @throws \Exception
  788. */
  789. public function getOrderList(int $userId, array $filters = [])
  790. {
  791. try {
  792. // 1. 验证用户
  793. $user = $this->validateUserForQuery($userId);
  794. // 2. 构建基础查询
  795. $query = $this->buildOrderListQuery($user);
  796. // 3. 应用过滤条件
  797. $this->applyOrderFilters($query, $filters);
  798. // 4. 加载关联数据并分页
  799. return $this->paginateOrderList($query, $filters);
  800. } catch (Exception $e) {
  801. $this->logError('获取订单列表失败', $e, [
  802. 'user_id' => $userId,
  803. 'filters' => $filters,
  804. ]);
  805. throw $e;
  806. }
  807. }
  808. /**
  809. * 验证用户查询权限
  810. */
  811. private function validateUserForQuery(int $userId): MemberUser
  812. {
  813. return MemberUser::where('id', $userId)
  814. ->where('state', UserStatus::OPEN->value)
  815. ->firstOrFail();
  816. }
  817. /**
  818. * 构建订单列表基础查询
  819. */
  820. private function buildOrderListQuery(MemberUser $user)
  821. {
  822. return $user->orders()
  823. ->with([
  824. 'coach' => function ($query) {
  825. $query->with(['info' => function ($q) {
  826. $q->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
  827. }]);
  828. },
  829. 'project:id,title,subtitle,duration,cover',
  830. 'records' => function ($query) {
  831. $query->orderBy('created_at', 'desc')
  832. ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
  833. },
  834. // 'evaluation:id,order_id,score,content,created_at',
  835. ]);
  836. }
  837. /**
  838. * 分页获取订单列表
  839. */
  840. private function paginateOrderList($query, array $filters)
  841. {
  842. $paginatedOrders = $query->orderBy('created_at', 'desc')
  843. ->paginate(
  844. perPage: $filters['per_page'] ?? 10,
  845. page: $filters['page'] ?? 1
  846. );
  847. $formattedOrders = $paginatedOrders->map(function ($order) {
  848. return $this->formatOrderListItem($order);
  849. });
  850. return [
  851. 'items' => $formattedOrders,
  852. 'total' => $paginatedOrders->total(),
  853. ];
  854. }
  855. /**
  856. * 格式化订单列表项
  857. */
  858. private function formatOrderListItem(Order $order): array
  859. {
  860. return [
  861. 'order_id' => $order->id,
  862. 'order_no' => $order->order_no,
  863. 'state' => $order->state,
  864. 'state_description' => $this->getOrderStateDescription($order->state),
  865. 'total_amount' => $order->total_amount,
  866. 'service_time' => $order->service_time,
  867. 'created_at' => $order->created_at->toDateTimeString(),
  868. 'coach' => $order->coach ? [
  869. 'id' => $order->coach->id,
  870. 'nickname' => $order->coach->info->nickname,
  871. 'avatar' => $order->coach->info->avatar,
  872. ] : null,
  873. 'project' => $order->project ? [
  874. 'id' => $order->project->id,
  875. 'title' => $order->project->title,
  876. 'subtitle' => $order->project->subtitle,
  877. 'duration' => $order->project->duration,
  878. 'cover_image' => $order->project->cover_image,
  879. ] : null,
  880. 'address' => $order->address ? [
  881. 'location' => $order->location,
  882. 'address' => $order->address,
  883. ] : null,
  884. 'latest_record' => $order->records->first() ? [
  885. 'state' => $order->records->first()->state,
  886. 'remark' => $order->records->first()->remark,
  887. 'created_at' => $order->records->first()->created_at->format('Y-m-d H:i:s'),
  888. ] : null,
  889. 'evaluation' => $order->evaluation ? [
  890. 'score' => $order->evaluation->score,
  891. 'content' => $order->evaluation->content,
  892. ] : null,
  893. ];
  894. }
  895. /**
  896. * 获取订单详情
  897. *
  898. * @param int $userId 用户ID
  899. * @param int $orderId 订单ID
  900. * @return array 订单详情
  901. *
  902. * @throws \Exception
  903. */
  904. public function getOrderDetail(int $userId, int $orderId): array
  905. {
  906. try {
  907. // 1. 验证订单权限
  908. $order = $this->validateOrderAccess($userId, $orderId);
  909. // 2. 加载订单关联数据
  910. $order->load([
  911. 'coach.info' => function ($query) {
  912. $query->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
  913. },
  914. 'project:id,title,subtitle,duration,cover',
  915. 'records' => function ($query) {
  916. $query->orderBy('created_at', 'desc')
  917. ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
  918. },
  919. // 'evaluation' => function ($query) {
  920. // $query->select(['id', 'order_id', 'score', 'content', 'images', 'created_at']);
  921. // },
  922. ]);
  923. // 3. 格式化返回数据
  924. return $this->formatOrderDetail($order);
  925. } catch (Exception $e) {
  926. $this->logError('获取订单详情失败', $e, [
  927. 'user_id' => $userId,
  928. 'order_id' => $orderId,
  929. ]);
  930. throw $e;
  931. }
  932. }
  933. /**
  934. * 验证订单访问权限
  935. */
  936. private function validateOrderAccess(int $userId, int $orderId): Order
  937. {
  938. return Order::where('id', $orderId)
  939. ->where('user_id', $userId)
  940. ->firstOrFail();
  941. }
  942. /**
  943. * 格式化订单详情数据
  944. */
  945. private function formatOrderDetail(Order $order): array
  946. {
  947. return [
  948. 'order_id' => $order->id,
  949. 'order_no' => $order->order_no,
  950. 'state' => $order->state,
  951. 'state_description' => $this->getOrderStateDescription($order->state),
  952. 'total_amount' => $order->total_amount,
  953. 'balance_amount' => $order->balance_amount,
  954. 'pay_amount' => $order->pay_amount,
  955. 'delivery_fee' => $order->delivery_fee,
  956. 'project_amount' => $order->project_amount,
  957. 'coupon_amount' => $order->coupon_amount,
  958. 'service_time' => $order->service_time,
  959. 'created_at' => $order->created_at->toDateTimeString(),
  960. 'remark' => $order->remark,
  961. 'coach' => $order->coach ? [
  962. 'id' => $order->coach->id,
  963. 'nickname' => $order->coach->info->nickname,
  964. 'avatar' => $order->coach->info->avatar,
  965. 'gender' => $order->coach->info->gender,
  966. 'score' => $order->coach->info?->score,
  967. ] : null,
  968. 'project' => $order->project ? [
  969. 'id' => $order->project->id,
  970. 'title' => $order->project->title,
  971. 'subtitle' => $order->project->subtitle,
  972. 'duration' => $order->project->duration,
  973. 'cover' => $order->project->cover,
  974. ] : null,
  975. 'address' => $order->address ? [
  976. 'id' => $order->address_id,
  977. 'location' => $order->location,
  978. 'address' => $order->address,
  979. ] : null,
  980. 'records' => $order->records->map(function ($record) {
  981. return [
  982. 'id' => $record->id,
  983. 'state' => $record->state,
  984. 'remark' => $record->remark,
  985. 'created_at' => $record->created_at->format('Y-m-d H:i:s'),
  986. ];
  987. })->toArray(),
  988. // 'evaluation' => $order->evaluation ? [
  989. // 'score' => $order->evaluation->score,
  990. // 'content' => $order->evaluation->content,
  991. // 'images' => $order->evaluation->images,
  992. // 'created_at' => $order->evaluation->created_at->format('Y-m-d H:i:s'),
  993. // ] : null,
  994. ];
  995. }
  996. /**
  997. * 应用订单过滤条件
  998. */
  999. private function applyOrderFilters($query, array $filters): void
  1000. {
  1001. // 按状态筛选
  1002. if (! empty($filters['state'])) {
  1003. $query->where('state', $filters['state']);
  1004. }
  1005. // 按时间范围筛选
  1006. if (! empty($filters['start_date'])) {
  1007. $query->where('created_at', '>=', $filters['start_date']);
  1008. }
  1009. if (! empty($filters['end_date'])) {
  1010. $query->where('created_at', '<=', $filters['end_date']);
  1011. }
  1012. // 按服务类型筛选
  1013. if (! empty($filters['project_id'])) {
  1014. $query->where('project_id', $filters['project_id']);
  1015. }
  1016. // 按技师筛选
  1017. if (! empty($filters['coach_id'])) {
  1018. $query->where('coach_id', $filters['coach_id']);
  1019. }
  1020. // 按订单号搜索
  1021. if (! empty($filters['order_no'])) {
  1022. $query->where('order_no', 'like', "%{$filters['order_no']}%");
  1023. }
  1024. }
  1025. /**
  1026. * 获取订单状态描述
  1027. */
  1028. private function getOrderStateDescription(string $state): string
  1029. {
  1030. return match ($state) {
  1031. OrderStatus::CREATED->value => '待支付',
  1032. OrderStatus::PAID->value => '待接单',
  1033. OrderStatus::ACCEPTED->value => '已接单',
  1034. OrderStatus::DEPARTED->value => '已出发',
  1035. OrderStatus::ARRIVED->value => '已到达',
  1036. OrderStatus::SERVING->value => '服务中',
  1037. OrderStatus::FINISHED->value => '已完成',
  1038. OrderStatus::CANCELLED->value => '已取消',
  1039. OrderStatus::REFUNDED->value => '已退款',
  1040. default => '未知状态',
  1041. };
  1042. }
  1043. /**
  1044. * 订单退款
  1045. *
  1046. * @param int $orderId 订单ID
  1047. * @return array{message: string}
  1048. *
  1049. * @throws \Exception
  1050. */
  1051. public function refundOrder(int $orderId): array
  1052. {
  1053. return DB::transaction(function () use ($orderId) {
  1054. try {
  1055. // 1. 验证订单状态
  1056. $order = $this->validateOrderForRefund($orderId);
  1057. // 2. 计算退款金额
  1058. $refundAmounts = $this->calculateRefundAmount($order);
  1059. // 3. 处理退款
  1060. $this->processRefund($order, $refundAmounts);
  1061. // 4. 更新订单状态
  1062. $this->updateOrderRefundStatus($order);
  1063. // 5. 记录退款操作
  1064. $this->createRefundRecords($order, $refundAmounts);
  1065. // 6. 通知相关方
  1066. $this->notifyRefund($order);
  1067. return ['message' => '退款成功'];
  1068. } catch (Exception $e) {
  1069. $this->logError('订单退款失败', $e, [
  1070. 'order_id' => $orderId,
  1071. ]);
  1072. throw $e;
  1073. }
  1074. });
  1075. }
  1076. /**
  1077. * 验证订单退款条件
  1078. */
  1079. private function validateOrderForRefund(int $orderId): Order
  1080. {
  1081. // 获取并锁定订单,防止并发操作
  1082. $order = Order::where('id', $orderId)
  1083. ->whereIn('state', [
  1084. OrderStatus::PAID->value,
  1085. OrderStatus::ACCEPTED->value,
  1086. OrderStatus::DEPARTED->value,
  1087. ])
  1088. ->lockForUpdate()
  1089. ->firstOrFail();
  1090. // 验证当前用户是否为订单所有者
  1091. $user = Auth::user();
  1092. abort_if($order->user_id !== $user->id, 403, '无权操作此订单');
  1093. // 检查订单是否已经退款
  1094. abort_if($order->state === OrderStatus::REFUNDED->value, 400, '订单已退款');
  1095. return $order;
  1096. }
  1097. /**
  1098. * 计算退款金额
  1099. */
  1100. private function calculateRefundAmount(Order $order): array
  1101. {
  1102. // 初始化扣除金额
  1103. $deductAmount = 0;
  1104. // 根据订单状态计算违约金
  1105. switch ($order->state) {
  1106. case OrderStatus::ACCEPTED->value:
  1107. // 已接单状态扣除订单金额的20%作为违约金
  1108. $deductAmount = bcmul($order->total_amount, '0.2', 2);
  1109. break;
  1110. case OrderStatus::DEPARTED->value:
  1111. // 已出发状态扣除订单金额的50%作为违约金
  1112. $deductAmount = bcmul($order->total_amount, '0.5', 2);
  1113. break;
  1114. }
  1115. // 计算实际可退金额(总金额减去违约金)
  1116. $totalRefund = bcsub($order->total_amount, $deductAmount, 2);
  1117. // 优先退还用户使用的余额部分
  1118. $balanceRefund = min($order->balance_amount, $totalRefund);
  1119. // 剩余部分退还到支付账户
  1120. $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
  1121. return [
  1122. 'total_refund' => $totalRefund, // 总退款金额
  1123. 'balance_amount' => $balanceRefund, // 退还到余额的金额
  1124. 'payment_refund' => $paymentRefund, // 退还到支付账户的金额
  1125. 'deduct_amount' => $deductAmount, // 扣除的违约金
  1126. ];
  1127. }
  1128. /**
  1129. * 处理退款操作
  1130. */
  1131. private function processRefund(Order $order, array $refundAmounts): void
  1132. {
  1133. // 处理余额退款部分
  1134. if ($refundAmounts['balance_refund'] > 0) {
  1135. $this->processBalanceRefund($order, $refundAmounts['balance_refund']);
  1136. }
  1137. // 处理支付退款部分
  1138. if ($refundAmounts['payment_refund'] > 0) {
  1139. $this->processPaymentRefund($order, $refundAmounts['payment_refund']);
  1140. }
  1141. }
  1142. /**
  1143. * 处理余额退款
  1144. */
  1145. private function processBalanceRefund(Order $order, float $amount): void
  1146. {
  1147. $wallet = $order->user->wallet;
  1148. // 增加用户钱包总余额
  1149. $wallet->increment('total_balance', $amount);
  1150. // 增加可用余额
  1151. $wallet->increment('available_balance', $amount);
  1152. // 创建退款交易记录
  1153. $wallet->transRecords()->create([
  1154. 'amount' => $amount,
  1155. 'trans_type' => 'refund',
  1156. 'owner_type' => Order::class,
  1157. 'owner_id' => $order->id,
  1158. 'remark' => '订单退款',
  1159. 'before_balance' => $wallet->total_balance - $amount,
  1160. 'after_balance' => $wallet->total_balance,
  1161. 'state' => 'success',
  1162. ]);
  1163. }
  1164. /**
  1165. * 处理支付退款
  1166. */
  1167. private function processPaymentRefund(Order $order, float $amount): void
  1168. {
  1169. // TODO: 实现第三方支付退款逻辑
  1170. // $paymentService = app(PaymentService::class);
  1171. // $paymentService->refund($order->payment_no, $amount);
  1172. }
  1173. /**
  1174. * 更新订单退款状态
  1175. */
  1176. private function updateOrderRefundStatus(Order $order): void
  1177. {
  1178. $order->update([
  1179. 'state' => OrderStatus::REFUNDED->value,
  1180. 'refund_time' => now(),
  1181. ]);
  1182. }
  1183. /**
  1184. * 创建退款记录
  1185. */
  1186. private function createRefundRecords(Order $order, array $refundAmounts): void
  1187. {
  1188. // 创建退款记录
  1189. $refundRecord = $order->refundRecords()->create([
  1190. 'total_refund_amount' => $refundAmounts['total_refund'],
  1191. 'balance_refund_amount' => $refundAmounts['balance_refund'],
  1192. 'payment_refund_amount' => $refundAmounts['payment_refund'],
  1193. 'deduct_amount' => $refundAmounts['deduct_amount'],
  1194. 'state' => 'success',
  1195. 'remark' => '用户申请退款',
  1196. ]);
  1197. // 创建订单状态记录
  1198. OrderRecord::create([
  1199. 'order_id' => $order->id,
  1200. 'object_id' => Auth::id(),
  1201. 'object_type' => MemberUser::class,
  1202. 'state' => OrderRecordStatus::REFUNDING->value,
  1203. 'remark' => '订单退款中',
  1204. ]);
  1205. }
  1206. /**
  1207. * 发送退款通知
  1208. */
  1209. private function notifyRefund(Order $order): void
  1210. {
  1211. // TODO: 实现退款通知逻辑
  1212. // 1. 通知用户
  1213. // event(new OrderRefundedEvent($order));
  1214. // 2. 通知技师
  1215. if ($order->coach_id) {
  1216. // event(new OrderRefundedToCoachEvent($order));
  1217. }
  1218. }
  1219. /**
  1220. * 获取代理商配置
  1221. */
  1222. public function getAgentConfig(int $agentId): array
  1223. {
  1224. $agent = AgentInfo::where('id', $agentId)
  1225. ->where('state', 'enable')
  1226. ->firstOrFail();
  1227. // $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();
  1228. return [
  1229. // 'min_distance' => $config->min_distance,
  1230. // 'min_fee' => $config->min_fee,
  1231. // 'per_km_fee' => $config->per_km_fee
  1232. ];
  1233. }
  1234. /**
  1235. * 获取技师配置
  1236. */
  1237. public function getCoachConfig(int $coachId): array
  1238. {
  1239. $coach = CoachUser::where('id', $coachId)
  1240. ->where('state', 'enable')
  1241. ->where('auth_state', 'passed')
  1242. ->firstOrFail();
  1243. // $config = CoachConfig::where('coach_id', $coachId)->firstOrFail();
  1244. return [
  1245. // 'delivery_fee_type' => $config->delivery_fee_type,
  1246. // 'charge_delivery_fee' => $config->charge_delivery_fee
  1247. ];
  1248. }
  1249. /**
  1250. * 计算路费
  1251. *
  1252. * @param int $coachId 技师ID
  1253. * @param int $projectId 项目ID
  1254. * @param int|null $agentId 代理商ID
  1255. * @param float $distance 距离(公里)
  1256. * @return float 路费金额
  1257. *
  1258. * @throws \Exception
  1259. */
  1260. public function calculateDeliveryFee(
  1261. int $coachId,
  1262. int $projectId,
  1263. ?int $agentId,
  1264. float $distance
  1265. ): float {
  1266. try {
  1267. // 1. 验证基础参数
  1268. $this->validateDeliveryFeeParams($coachId, $projectId, $distance);
  1269. // 2. 获取计费规则
  1270. $feeRules = $this->getDeliveryFeeRules($coachId, $agentId);
  1271. // 3. 计算路费
  1272. return $this->calculateFeeByRules($distance, $feeRules);
  1273. } catch (Exception $e) {
  1274. $this->logError('计算路费失败', $e, [
  1275. 'coach_id' => $coachId,
  1276. 'project_id' => $projectId,
  1277. 'agent_id' => $agentId,
  1278. 'distance' => $distance,
  1279. ]);
  1280. throw $e;
  1281. }
  1282. }
  1283. /**
  1284. * 验证路费计算参数
  1285. */
  1286. private function validateDeliveryFeeParams(int $coachId, int $projectId, float $distance): void
  1287. {
  1288. // 验证技师状态
  1289. $coach = $this->validateCoach($coachId);
  1290. // 验证项目状态
  1291. $project = Project::where('id', $projectId)
  1292. ->where('state', ProjectStatus::OPEN->value)
  1293. ->firstOrFail();
  1294. // 验证距离有效性
  1295. abort_if($distance < 0, 400, '距离计算错误');
  1296. }
  1297. /**
  1298. * 获取路费计算规则
  1299. *
  1300. * @return array{
  1301. * min_distance: float,
  1302. * min_fee: float,
  1303. * per_km_fee: float,
  1304. * max_distance: float,
  1305. * max_fee: float,
  1306. * free_distance: float
  1307. * }
  1308. */
  1309. private function getDeliveryFeeRules(int $coachId, ?int $agentId): array
  1310. {
  1311. // 1. 获取系统默认规则
  1312. $defaultRules = $this->getDefaultDeliveryFeeRules();
  1313. // 2. 获取代理商规则(如果有)
  1314. $agentRules = $agentId ? $this->getAgentDeliveryFeeRules($agentId) : [];
  1315. // 3. 获取技师个性化规则
  1316. $coachRules = $this->getCoachDeliveryFeeRules($coachId);
  1317. // 4. 合并规则,优先级:技师 > 代理商 > 系统默认
  1318. return array_merge(
  1319. $defaultRules,
  1320. $agentRules,
  1321. $coachRules
  1322. );
  1323. }
  1324. /**
  1325. * 获取系统默认路费规则
  1326. */
  1327. private function getDefaultDeliveryFeeRules(): array
  1328. {
  1329. // TODO: 从配置表中获取系统默认路费规则
  1330. return [
  1331. 'min_distance' => 3.0, // 最小计费距离(公里)
  1332. 'min_fee' => 10.0, // 最小路费(元)
  1333. 'per_km_fee' => 3.0, // 每公里费用(元)
  1334. 'max_distance' => 120.0, // 最大服务距离(公里)
  1335. 'max_fee' => 50.0, // 最大路费(元)
  1336. 'free_distance' => 1.0, // 免费服务距离(公里)
  1337. ];
  1338. }
  1339. /**
  1340. * 获取代理商路费规则
  1341. */
  1342. private function getAgentDeliveryFeeRules(int $agentId): array
  1343. {
  1344. // $agentConfig = AgentConfig::where('agent_id', $agentId)
  1345. // ->where('state', 'enable')
  1346. // ->first();
  1347. // if (! $agentConfig) {
  1348. // return [];
  1349. // }
  1350. // return [
  1351. // 'min_distance' => $agentConfig->min_distance,
  1352. // 'min_fee' => $agentConfig->min_fee,
  1353. // 'per_km_fee' => $agentConfig->per_km_fee,
  1354. // 'max_distance' => $agentConfig->max_distance,
  1355. // 'max_fee' => $agentConfig->max_fee,
  1356. // 'free_distance' => $agentConfig->free_distance,
  1357. // ];
  1358. return [];
  1359. }
  1360. /**
  1361. * 获取技师路费规则
  1362. */
  1363. private function getCoachDeliveryFeeRules(int $coachId): array
  1364. {
  1365. // TODO: 从配置表中获取技师个性化路费规则
  1366. // $coachConfig = CoachConfig::where('coach_id', $coachId)
  1367. // ->where('state', 'enable')
  1368. // ->first();
  1369. $coachConfig = null;
  1370. if (! $coachConfig) {
  1371. return [];
  1372. }
  1373. // 如果技师设置了不收取路费
  1374. if (! $coachConfig->charge_delivery_fee) {
  1375. return [
  1376. 'min_fee' => 0,
  1377. 'per_km_fee' => 0,
  1378. 'max_fee' => 0,
  1379. ];
  1380. }
  1381. return [
  1382. 'min_distance' => $coachConfig->min_distance,
  1383. 'min_fee' => $coachConfig->min_fee,
  1384. 'per_km_fee' => $coachConfig->per_km_fee,
  1385. 'max_distance' => $coachConfig->max_distance,
  1386. 'max_fee' => $coachConfig->max_fee,
  1387. 'free_distance' => $coachConfig->free_distance,
  1388. ];
  1389. }
  1390. /**
  1391. * 根据规则计算路费
  1392. *
  1393. * @param float $distance 距离(公里)
  1394. * @param array{
  1395. * min_distance: float, // 最小计费距离(公里)
  1396. * min_fee: float, // 最小路费(元)
  1397. * per_km_fee: float, // 每公里费用(元)
  1398. * max_distance: float, // 最大服务距离(公里)
  1399. * max_fee: float, // 最大路费(元)
  1400. * free_distance: float // 免费服务距离(公里)
  1401. * } $rules 计费规则
  1402. * @return float 路费金额(元)
  1403. */
  1404. private function calculateFeeByRules(float $distance, array $rules): float
  1405. {
  1406. // 1. 检查是否超出最大服务距离
  1407. abort_if(
  1408. $distance > $rules['max_distance'],
  1409. 400,
  1410. sprintf('超出最大服务距离 %.1f 公里', $rules['max_distance'])
  1411. );
  1412. // 2. 检查是否在免费距离内
  1413. if ($distance <= $rules['free_distance']) {
  1414. return 0;
  1415. }
  1416. // 3. 计算实际计费距离
  1417. $chargeDistance = max(0, $distance - $rules['free_distance']);
  1418. // 4. 检查是否达到最小计费距离
  1419. if ($chargeDistance < $rules['min_distance']) {
  1420. return $rules['min_fee'];
  1421. }
  1422. // 5. 计算基础路费
  1423. $fee = bcmul($chargeDistance, $rules['per_km_fee'], 2);
  1424. // 6. 应用最小路费限制
  1425. $fee = max($fee, $rules['min_fee']);
  1426. // 7. 应用最大路费限制
  1427. $fee = min($fee, $rules['max_fee']);
  1428. return $fee;
  1429. }
  1430. /**
  1431. * 计算两点之间的距离
  1432. *
  1433. * @param float $lat1 起点纬度
  1434. * @param float $lng1 起点经度
  1435. * @param float $lat2 终点纬度
  1436. * @param float $lng2 终点经度
  1437. * @return float 距离(公里)
  1438. */
  1439. private function getDistance(float $lat1, float $lng1, float $lat2, float $lng2): float
  1440. {
  1441. // 将角度转为弧度
  1442. $radLat1 = deg2rad($lat1);
  1443. $radLat2 = deg2rad($lat2);
  1444. $radLng1 = deg2rad($lng1);
  1445. $radLng2 = deg2rad($lng2);
  1446. // 地球半径(公里)
  1447. $earthRadius = 6371;
  1448. // 计算距离
  1449. $distance = acos(
  1450. sin($radLat1) * sin($radLat2) +
  1451. cos($radLat1) * cos($radLat2) * cos($radLng1 - $radLng2)
  1452. ) * $earthRadius;
  1453. // 保留2位小数
  1454. return round($distance, 2);
  1455. }
  1456. /**
  1457. * 计算订单金额
  1458. *
  1459. * @param int $userId 用户ID
  1460. * @param int|null $addressId 地址ID
  1461. * @param int|null $coachId 技师ID
  1462. * @param int $projectId 项目ID
  1463. * @param int|null $agentId 代理商ID
  1464. * @param bool $useBalance 是否使用余额
  1465. * @param float $distance 距离
  1466. * @param float $lat 纬度
  1467. * @param float $lng 经度
  1468. * @return array{
  1469. * total_amount: float,
  1470. * balance_amount: float,
  1471. * pay_amount: float,
  1472. * coupon_amount: float,
  1473. * project_amount: float,
  1474. * delivery_fee: float
  1475. * }
  1476. *
  1477. * @throws \Exception
  1478. */
  1479. public function calculateOrderAmount(
  1480. int $userId,
  1481. ?int $addressId,
  1482. ?int $coachId,
  1483. int $projectId,
  1484. ?int $agentId = null,
  1485. bool $useBalance = false,
  1486. float $distance = 0,
  1487. float $lat = 0,
  1488. float $lng = 0
  1489. ): array {
  1490. try {
  1491. // 1. 验证用户状态和权限
  1492. $user = $this->validateUserForCalculation($userId);
  1493. // 2. 获取项目信息和价格(包含代理���价格)
  1494. $project = $this->getProjectWithPrice($projectId, $agentId);
  1495. // 3. 计算路费(如果有技师)
  1496. $deliveryFee = $this->calculateDeliveryFeeForOrder(
  1497. coachId: $coachId,
  1498. projectId: $projectId,
  1499. agentId: $agentId,
  1500. distance: $distance,
  1501. addressId: $addressId,
  1502. lat: $lat,
  1503. lng: $lng
  1504. );
  1505. // 4. 计算优惠金额(优惠券、活动等)
  1506. $discountAmount = $this->calculateDiscountAmount($projectId, $userId);
  1507. // 5. 计算订单总金额(项目价格 + 路费 - 优惠金额)
  1508. $totalAmount = $this->calculateTotalAmount($project->price, $deliveryFee, $discountAmount);
  1509. // 6. 处理余额支付分配(优先使用余额)
  1510. $paymentAmounts = $this->calculatePaymentDistribution(
  1511. user: $user,
  1512. totalAmount: $totalAmount,
  1513. useBalance: $useBalance
  1514. );
  1515. // 7. 返回计算结果
  1516. return [
  1517. 'total_amount' => $totalAmount, // 订单总金额
  1518. 'balance_amount' => $paymentAmounts['balance_amount'], // 余额支付金额
  1519. 'pay_amount' => $paymentAmounts['pay_amount'], // 需要支付金额
  1520. 'coupon_amount' => $discountAmount, // 优惠金额
  1521. 'project_amount' => $project->price, // 项目原价
  1522. 'delivery_fee' => $deliveryFee, // 路费
  1523. ];
  1524. } catch (Exception $e) {
  1525. // 记录错误日志
  1526. $this->logError('计算订单金额失败', $e, [
  1527. 'user_id' => $userId,
  1528. 'project_id' => $projectId,
  1529. 'coach_id' => $coachId,
  1530. 'address_id' => $addressId,
  1531. ]);
  1532. throw $e;
  1533. }
  1534. }
  1535. /**
  1536. * 验证用户状态
  1537. */
  1538. private function validateUserForCalculation(int $userId): MemberUser
  1539. {
  1540. $user = MemberUser::with('wallet')
  1541. ->where('id', $userId)
  1542. ->where('state', UserStatus::OPEN->value)
  1543. ->first();
  1544. abort_if(! $user, 404, '用户不存在或状态异常');
  1545. return $user;
  1546. }
  1547. /**
  1548. * 获取项目信息和价格
  1549. */
  1550. private function getProjectWithPrice(int $projectId, ?int $agentId): Project
  1551. {
  1552. // 获取基础项目信息
  1553. $project = Project::where('id', $projectId)
  1554. ->where('state', ProjectStatus::OPEN->value)
  1555. ->first();
  1556. abort_if(! $project, 404, '项目不存在或状态异常');
  1557. // 如果有代理商,获取代理商价格
  1558. if ($agentId) {
  1559. $agentProject = $this->getAgentProjectPrice($agentId, $projectId);
  1560. if ($agentProject) {
  1561. $project->price = $agentProject->price;
  1562. }
  1563. }
  1564. return $project;
  1565. }
  1566. /**
  1567. * 获取代理商项目价格
  1568. */
  1569. private function getAgentProjectPrice(int $agentId, int $projectId): ?object
  1570. {
  1571. return DB::table('agent_projects')
  1572. ->where('agent_id', $agentId)
  1573. ->where('project_id', $projectId)
  1574. ->where('state', 'enable')
  1575. ->first();
  1576. }
  1577. /**
  1578. * 计算订单路费
  1579. */
  1580. private function calculateDeliveryFeeForOrder(
  1581. ?int $coachId,
  1582. int $projectId,
  1583. ?int $agentId,
  1584. float $distance,
  1585. ?int $addressId,
  1586. ?float $lat,
  1587. ?float $lng
  1588. ): float {
  1589. // 如果没有技师,无需计算路费
  1590. if (! $coachId) {
  1591. return 0;
  1592. }
  1593. if (! $addressId && ! $lat && ! $lng) {
  1594. return 0;
  1595. }
  1596. // 如果距离为0,需要重新计算距离
  1597. if ($distance <= 0) {
  1598. $distance = $this->calculateDistance($coachId, $addressId, $lat, $lng);
  1599. }
  1600. return $this->calculateDeliveryFee($coachId, $projectId, $agentId, $distance);
  1601. }
  1602. /**
  1603. * 获取技师位置信息
  1604. */
  1605. private function getCoachLocation(int $coachId): array
  1606. {
  1607. // 从技师服务获取最新位置信息
  1608. $location = $this->coachService->getLocation($coachId);
  1609. // 如果没有位置信息,返回系统默认位置
  1610. if (empty($location)) {
  1611. return [
  1612. 'latitude' => config('business.default_latitude', 0),
  1613. 'longitude' => config('business.default_longitude', 0),
  1614. ];
  1615. }
  1616. // 格式化位置数据
  1617. return [
  1618. 'latitude' => (float) $location->latitude,
  1619. 'longitude' => (float) $location->longitude,
  1620. ];
  1621. }
  1622. /**
  1623. * 计算技师与服务地址的距离
  1624. */
  1625. private function calculateDistance(int $coachId, int $addressId, float $lat, float $lng): float
  1626. {
  1627. // 如果提供了地址ID,优先使用地址表中的经纬度
  1628. if ($addressId > 0) {
  1629. // 查询地址信息
  1630. $address = MemberAddress::find($addressId);
  1631. // 使用地址的经纬度,如果没有则使用传入的经纬度
  1632. $lat = $address?->latitude ?? $lat;
  1633. $lng = $address?->longitude ?? $lng;
  1634. }
  1635. // 从Redis获取技师的两个位置点信息
  1636. // 获取常用地址位置(如家庭地址)
  1637. $homeLocation = Redis::geopos(
  1638. 'coach_locations',
  1639. $coachId.'_'.TechnicianLocationType::COMMON->value
  1640. );
  1641. // 获取当前实时位置
  1642. $workLocation = Redis::geopos(
  1643. 'coach_locations',
  1644. $coachId.'_'.TechnicianLocationType::CURRENT->value
  1645. );
  1646. // 初始化最近距离变量
  1647. $nearestDistance = null;
  1648. // 分别计算与两个位置点的距离
  1649. // 计算与常用地址的距离
  1650. $homeDistance = $homeLocation && $homeLocation[0] ?
  1651. $this->getDistance($homeLocation[0][1], $homeLocation[0][0], $lat, $lng) :
  1652. null;
  1653. // 计算与当前位置的距离
  1654. $workDistance = $workLocation && $workLocation[0] ?
  1655. $this->getDistance($workLocation[0][1], $workLocation[0][0], $lat, $lng) :
  1656. null;
  1657. // 选择最近的距离作为服务距离
  1658. if ($homeDistance < $workDistance) {
  1659. $nearestDistance = $homeDistance;
  1660. } else {
  1661. $nearestDistance = $workDistance;
  1662. }
  1663. return $nearestDistance;
  1664. }
  1665. /**
  1666. * 计算优惠金额
  1667. */
  1668. private function calculateDiscountAmount(int $projectId, int $userId): float
  1669. {
  1670. $discountAmount = 0;
  1671. // TODO: 实现优惠券、活动等优惠计算逻辑
  1672. return $discountAmount;
  1673. }
  1674. /**
  1675. * 计算订单总金额
  1676. */
  1677. private function calculateTotalAmount(float $projectPrice, float $deliveryFee, float $discountAmount): float
  1678. {
  1679. $totalAmount = bcadd($projectPrice, $deliveryFee, 2);
  1680. $totalAmount = bcsub($totalAmount, $discountAmount, 2);
  1681. return max(0, $totalAmount);
  1682. }
  1683. /**
  1684. * 计算支付金额分配
  1685. *
  1686. * @return array{balance_amount: float, pay_amount: float}
  1687. */
  1688. private function calculatePaymentDistribution(MemberUser $user, float $totalAmount, bool $useBalance): array
  1689. {
  1690. if (! $useBalance || $totalAmount <= 0) {
  1691. return [
  1692. 'balance_amount' => 0,
  1693. 'pay_amount' => $totalAmount,
  1694. ];
  1695. }
  1696. $availableBalance = $user->wallet?->available_balance ?? 0;
  1697. if ($availableBalance >= $totalAmount) {
  1698. return [
  1699. 'balance_amount' => $totalAmount,
  1700. 'pay_amount' => 0,
  1701. ];
  1702. }
  1703. return [
  1704. 'balance_amount' => $availableBalance,
  1705. 'pay_amount' => bcsub($totalAmount, $availableBalance, 2),
  1706. ];
  1707. }
  1708. /**
  1709. * 获取订单抢单池列表
  1710. *
  1711. * @param int $orderId 订单ID
  1712. * @return array 抢单池列表
  1713. */
  1714. public function getOrderGrabList(int $orderId): array
  1715. {
  1716. try {
  1717. // 查询订单信息
  1718. $order = Order::where('id', $orderId)
  1719. ->whereIn('state', [OrderStatus::CREATED->value])
  1720. ->firstOrFail();
  1721. // 查询抢单池列表
  1722. $grabList = $order->grabRecords()->with(['coach.info'])->get();
  1723. // 格式化返回数据
  1724. $result = [];
  1725. foreach ($grabList as $grab) {
  1726. $coach = $grab->coach;
  1727. $result[] = [
  1728. 'id' => $grab->id,
  1729. 'coach_id' => $coach->id,
  1730. 'nickname' => $coach->info->nickname,
  1731. 'avatar' => $coach->info->avatar,
  1732. 'distance' => $grab->distance,
  1733. 'created_at' => $grab->created_at->format('Y-m-d H:i:s'),
  1734. ];
  1735. }
  1736. return $result;
  1737. } catch (\Exception $e) {
  1738. Log::error('获取订单抢单池列表失败', [
  1739. 'error' => $e->getMessage(),
  1740. 'order_id' => $orderId,
  1741. ]);
  1742. throw $e;
  1743. }
  1744. }
  1745. /**
  1746. * 指定技师
  1747. *
  1748. * @param int $userId 用户ID
  1749. * @param int $orderId 订单ID
  1750. * @param int $coachId 技师ID
  1751. *
  1752. * @throws \Exception
  1753. */
  1754. public function assignCoach(int $userId, int $orderId, int $coachId): bool
  1755. {
  1756. return DB::transaction(function () use ($userId, $orderId, $coachId) {
  1757. try {
  1758. // 1. 验证参数
  1759. $order = $this->validateAssignOrder($userId, $orderId);
  1760. // 2. 验证技师
  1761. $coach = $this->validateCoach($coachId);
  1762. // 3. 检查抢单池状态
  1763. $this->validateGrabPool($order);
  1764. // 4. 更新订单信息
  1765. $this->updateOrderForAssign($order, $coachId);
  1766. // 5. 创建订单记录(指派)
  1767. $this->createAssignRecord($order, $userId);
  1768. // 6. 处理支付
  1769. if ($order->payment_type === PaymentMethod::BALANCE->value) {
  1770. $this->handleBalancePaymentForAssign($order, $userId, $coachId);
  1771. }
  1772. // 7. 发送通知
  1773. $this->notifyAssignment($order, $coach);
  1774. return true;
  1775. } catch (Exception $e) {
  1776. $this->logError('指定技师失败', $e, [
  1777. 'user_id' => $userId,
  1778. 'order_id' => $orderId,
  1779. 'coach_id' => $coachId,
  1780. ]);
  1781. throw $e;
  1782. }
  1783. });
  1784. }
  1785. /**
  1786. * 验证指定技师的订单条件
  1787. */
  1788. private function validateAssignOrder(int $userId, int $orderId): Order
  1789. {
  1790. // 验证用户状态
  1791. $user = MemberUser::where('id', $userId)
  1792. ->where('state', UserStatus::OPEN->value)
  1793. ->firstOrFail();
  1794. // 验证订单状态
  1795. $order = $user->orders()
  1796. ->where('id', $orderId)
  1797. ->whereIn('state', [OrderStatus::CREATED->value, OrderStatus::PAID->value])
  1798. ->lockForUpdate()
  1799. ->firstOrFail();
  1800. return $order;
  1801. }
  1802. /**
  1803. * 验证抢单池状态
  1804. */
  1805. private function validateGrabPool(Order $order): void
  1806. {
  1807. // 检查抢单池是否已有抢单成功记录
  1808. $existsGrabSuccess = $order->grabRecords()
  1809. ->where('state', OrderGrabRecordStatus::SUCCEEDED->value)
  1810. ->exists();
  1811. abort_if($existsGrabSuccess, 400, '该订单已抢单完成');
  1812. }
  1813. /**
  1814. * 更新订单信息
  1815. */
  1816. private function updateOrderForAssign(Order $order, int $coachId): void
  1817. {
  1818. // 修改订单技师
  1819. $order->coach_id = $coachId;
  1820. // 待支付订单需要重新计算金额
  1821. if ($order->state === OrderStatus::CREATED->value) {
  1822. $amounts = $this->calculateOrderAmount(
  1823. userId: $order->user_id,
  1824. addressId: $order->address_id,
  1825. coachId: $coachId,
  1826. projectId: $order->project_id,
  1827. agentId: $order->agent_id,
  1828. useBalance: $order->payment_type === PaymentMethod::BALANCE->value
  1829. );
  1830. // 更新订单金额
  1831. $order->fill([
  1832. 'total_amount' => $amounts['total_amount'],
  1833. 'balance_amount' => $amounts['balance_amount'],
  1834. 'pay_amount' => $amounts['pay_amount'],
  1835. 'discount_amount' => $amounts['coupon_amount'],
  1836. 'project_amount' => $amounts['project_amount'],
  1837. 'traffic_amount' => $amounts['delivery_fee'],
  1838. ]);
  1839. }
  1840. $order->save();
  1841. }
  1842. /**
  1843. * 处理指派订单的余额支付
  1844. */
  1845. private function handleBalancePaymentForAssign(Order $order, int $userId, int $coachId): void
  1846. {
  1847. // 验证余额
  1848. $user = MemberUser::find($userId);
  1849. $wallet = $user->wallet;
  1850. abort_if($wallet->available_balance < $order->balance_amount, 400, '可���余额不足');
  1851. // 扣除余额
  1852. DB::transaction(function () use ($wallet, $order, $userId, $coachId) {
  1853. // 更新钱包余额
  1854. $wallet->decrement('total_balance', $order->balance_amount);
  1855. $wallet->decrement('available_balance', $order->balance_amount);
  1856. // 更新订单状态
  1857. $order->update(['state' => OrderStatus::PAID->value]);
  1858. // 创建钱包支付记录
  1859. $this->createWalletPaymentRecord($order, $wallet);
  1860. // 创建支付成功记录
  1861. $this->createPaymentSuccessRecord($order, $userId);
  1862. // 更新抢单记录
  1863. $this->updateGrabRecords($order->id, $coachId);
  1864. });
  1865. }
  1866. /**
  1867. * 创建钱包支付记录
  1868. */
  1869. private function createWalletPaymentRecord(Order $order, $wallet): void
  1870. {
  1871. WalletPaymentRecord::create([
  1872. 'order_id' => $order->id,
  1873. 'wallet_id' => $wallet->id,
  1874. 'payment_no' => 'B_'.$order->id,
  1875. 'payment_method' => 'balance',
  1876. 'total_amount' => $order->balance_amount,
  1877. 'actual_amount' => 0,
  1878. 'used_wallet_balance' => $order->balance_amount,
  1879. 'used_recharge_balance' => 0,
  1880. 'state' => 'success',
  1881. ]);
  1882. }
  1883. /**
  1884. * 创建支付成功记录
  1885. */
  1886. private function createPaymentSuccessRecord(Order $order, int $userId): void
  1887. {
  1888. OrderRecord::create([
  1889. 'order_id' => $order->id,
  1890. 'object_id' => $userId,
  1891. 'object_type' => MemberUser::class,
  1892. 'state' => OrderRecordStatus::PAID->value,
  1893. 'remark' => '余额支付成功',
  1894. ]);
  1895. }
  1896. /**
  1897. * 更新抢单记录
  1898. */
  1899. private function updateGrabRecords(int $orderId, int $coachId): void
  1900. {
  1901. OrderGrabRecord::where('order_id', $orderId)
  1902. ->update([
  1903. 'state' => OrderGrabRecordStatus::SUCCEEDED->value,
  1904. 'coach_id' => $coachId,
  1905. ]);
  1906. }
  1907. /**
  1908. * 发送指派通知
  1909. */
  1910. private function notifyAssignment(Order $order, CoachUser $coach): void
  1911. {
  1912. // TODO: 实现通知逻辑
  1913. // event(new OrderAssignedEvent($order, $coach));
  1914. }
  1915. /**
  1916. * 生成订单核销码
  1917. *
  1918. * @param int $userId 用户ID
  1919. * @param int $orderId 订单ID
  1920. * @return array{
  1921. * order_id: int,
  1922. * qr_code: string,
  1923. * qr_image: ?string,
  1924. * expired_at: string,
  1925. * state: string
  1926. * } 返回核销码信息
  1927. *
  1928. * @throws \Exception
  1929. */
  1930. public function generateVerificationCode(int $userId, int $orderId): array
  1931. {
  1932. try {
  1933. // 验证订单状态和归属
  1934. $order = $this->validateOrderForVerification($userId, $orderId);
  1935. // 生成核销码数据
  1936. $verificationData = $this->generateVerificationData($order->id);
  1937. // 生成二维码图片
  1938. $qrCodeImage = $this->generateQRCodeImage($verificationData['qr_code']);
  1939. return [
  1940. 'order_id' => $order->id,
  1941. 'qr_code' => $verificationData['qr_code'],
  1942. 'qr_image' => $qrCodeImage,
  1943. 'expired_at' => $verificationData['expired_at'],
  1944. 'state' => $order->state,
  1945. ];
  1946. } catch (Exception $e) {
  1947. $this->logError('生成订单核销码失败', $e, [
  1948. 'user_id' => $userId,
  1949. 'order_id' => $orderId,
  1950. ]);
  1951. throw $e;
  1952. }
  1953. }
  1954. /**
  1955. * 验证订单状态和归属
  1956. */
  1957. private function validateOrderForVerification(int $userId, int $orderId): Order
  1958. {
  1959. // 验证用户状态
  1960. $user = MemberUser::where('id', $userId)
  1961. ->where('state', UserStatus::OPEN->value)
  1962. ->firstOrFail();
  1963. // 验证订单状态和归属
  1964. $order = $user->orders()
  1965. ->where('id', $orderId)
  1966. ->whereIn('state', [
  1967. OrderStatus::PAID->value,
  1968. OrderStatus::ACCEPTED->value,
  1969. OrderStatus::DEPARTED->value,
  1970. OrderStatus::ARRIVED->value,
  1971. ])
  1972. ->firstOrFail();
  1973. return $order;
  1974. }
  1975. /**
  1976. * 生成核销码数据
  1977. *
  1978. * @param int $orderId 订单ID
  1979. * @return array{qr_code: string, expired_at: string}
  1980. */
  1981. private function generateVerificationData(int $orderId): array
  1982. {
  1983. // 生成时间戳
  1984. $timestamp = time();
  1985. // 生成签名
  1986. $sign = md5("order_{$orderId}_{$timestamp}_".config('app.key'));
  1987. // 组装二维码内容
  1988. $qrCode = "order_{$orderId}_{$timestamp}_{$sign}";
  1989. return [
  1990. 'qr_code' => $qrCode,
  1991. 'expired_at' => date('Y-m-d H:i:s', $timestamp + 300), // 5分钟有效期
  1992. ];
  1993. }
  1994. /**
  1995. * 生成二维码图片
  1996. *
  1997. * @param string $content 二维码内容
  1998. * @return string|null Base64编码的图片数据
  1999. */
  2000. private function generateQRCodeImage(string $content): ?string
  2001. {
  2002. try {
  2003. // 生成PNG格式的二维码
  2004. $qrCodeImage = QrCode::format('png')
  2005. ->size(200) // 设置二维码大小为200px
  2006. ->margin(1) // 设置二维码边距为1
  2007. ->errorCorrection('H') // 设置纠错级别为最高级别H
  2008. ->generate($content);
  2009. // 将PNG转为base64
  2010. return 'data:image/png;base64,'.base64_encode($qrCodeImage);
  2011. } catch (Exception $e) {
  2012. Log::error('生成二维码图片失败:', [
  2013. 'content' => $content,
  2014. 'error' => $e->getMessage(),
  2015. ]);
  2016. return null;
  2017. }
  2018. }
  2019. /**
  2020. * 验证技师服务时间是否可用
  2021. */
  2022. public function validateServiceTime(int $coachId, string $serviceTime): bool
  2023. {
  2024. try {
  2025. // 1. 验证基础参数(技师状态、时间格式等)
  2026. $this->validateServiceTimeParams($coachId, $serviceTime);
  2027. // 2. 获取技师工作时间安排
  2028. $workSchedule = $this->getCoachWorkSchedule($coachId);
  2029. // 3. 验证是否在工作时间内
  2030. $this->validateWorkingHours($serviceTime, $workSchedule);
  2031. // 4. 检查是否与其他订单时间冲突
  2032. $this->checkTimeConflicts($coachId, $serviceTime);
  2033. return true;
  2034. } catch (Exception $e) {
  2035. // 记录错误日志
  2036. $this->logError('验证服务时间失败', $e, [
  2037. 'coach_id' => $coachId,
  2038. 'service_time' => $serviceTime,
  2039. ]);
  2040. throw $e;
  2041. }
  2042. }
  2043. /**
  2044. * 验证服务时间参数
  2045. */
  2046. private function validateServiceTimeParams(int $coachId, string $serviceTime): void
  2047. {
  2048. // 验证技师状态是否正常
  2049. $coach = CoachUser::where('id', $coachId)
  2050. ->where('state', TechnicianStatus::ACTIVE->value)
  2051. ->where('auth_state', TechnicianAuthStatus::PASSED->value)
  2052. ->firstOrFail();
  2053. // 验证时间格式并检查是否早于当前时间
  2054. $serviceDateTime = Carbon::parse($serviceTime);
  2055. abort_if(
  2056. $serviceDateTime->isPast(),
  2057. 400,
  2058. '服务时间不能早于当前时间'
  2059. );
  2060. // 验证预约提前时间(至少提前指定小时)
  2061. $minAdvanceHours = config('business.min_advance_hours', 2);
  2062. abort_if(
  2063. $serviceDateTime->diffInHours(now()) < $minAdvanceHours,
  2064. 400,
  2065. "需要至少提前{$minAdvanceHours}小时预约"
  2066. );
  2067. // 验证预约时间范围(最多提前指定天数)
  2068. $maxAdvanceDays = config('business.max_advance_days', 7);
  2069. abort_if(
  2070. $serviceDateTime->diffInDays(now()) > $maxAdvanceDays,
  2071. 400,
  2072. "最多只能提前{$maxAdvanceDays}天预约"
  2073. );
  2074. }
  2075. /**
  2076. * 验证是否在工作时间内
  2077. */
  2078. private function validateWorkingHours(string $serviceTime, array $workSchedule): void
  2079. {
  2080. $serviceDateTime = Carbon::parse($serviceTime);
  2081. // 检查是否为工作日
  2082. $dayOfWeek = $serviceDateTime->dayOfWeek;
  2083. abort_if(
  2084. ! in_array($dayOfWeek, $workSchedule['work_days']),
  2085. 400,
  2086. '该时间不在技师工作日内'
  2087. );
  2088. // 检查是否为特殊休息日
  2089. $dateStr = $serviceDateTime->format('Y-m-d');
  2090. abort_if(
  2091. in_array($dateStr, $workSchedule['rest_dates']),
  2092. 400,
  2093. '技师该日期休息'
  2094. );
  2095. // 检查是否在工作时间范围内
  2096. $timeStr = $serviceDateTime->format('H:i');
  2097. $startTime = Carbon::parse($workSchedule['work_hours']['start']);
  2098. $endTime = Carbon::parse($workSchedule['work_hours']['end']);
  2099. abort_if(
  2100. $timeStr < $startTime->format('H:i') || $timeStr > $endTime->format('H:i'),
  2101. 400,
  2102. sprintf(
  2103. '服务时间需在%s-%s之间',
  2104. $startTime->format('H:i'),
  2105. $endTime->format('H:i')
  2106. )
  2107. );
  2108. }
  2109. /**
  2110. * 检查订单时间冲突
  2111. */
  2112. private function checkTimeConflicts(int $coachId, string $serviceTime): void
  2113. {
  2114. $serviceDateTime = Carbon::parse($serviceTime);
  2115. // 获取服务时长配置(默认2小时)
  2116. $serviceDuration = config('business.default_service_duration', 120);
  2117. // 计算本次服务的结束时间
  2118. $serviceEndTime = $serviceDateTime->copy()->addMinutes($serviceDuration);
  2119. // 检查是否与其他订单时间重叠
  2120. $conflictOrder = Order::where('coach_id', $coachId)
  2121. ->whereIn('state', [
  2122. OrderStatus::PAID->value, // 已支付
  2123. OrderStatus::ACCEPTED->value, // 已接单
  2124. OrderStatus::SERVING->value, // 服务中
  2125. ])
  2126. ->where(function ($query) use ($serviceDateTime, $serviceEndTime) {
  2127. $query->where(function ($q) use ($serviceDateTime) {
  2128. // 检查服务开始时间是否冲突
  2129. $q->where('service_time', '<=', $serviceDateTime)
  2130. ->where('service_end_time', '>', $serviceDateTime);
  2131. })->orWhere(function ($q) use ($serviceEndTime) {
  2132. // 检查服务结束时间是否冲突
  2133. $q->where('service_time', '<', $serviceEndTime)
  2134. ->where('service_end_time', '>=', $serviceEndTime);
  2135. });
  2136. })
  2137. ->first();
  2138. // 如果存在时间冲突,抛出异常
  2139. abort_if(
  2140. $conflictOrder,
  2141. 400,
  2142. '该时间段技师已有其他订单'
  2143. );
  2144. }
  2145. /**
  2146. * 订单评价
  2147. *
  2148. * @param int $userId 用户ID
  2149. * @param int $orderId 订单ID
  2150. * @param array{
  2151. * score: int,
  2152. * content: string,
  2153. * images: ?array,
  2154. * tags: ?array
  2155. * } $data 评价数据
  2156. * @return array{message: string}
  2157. *
  2158. * @throws \Exception
  2159. */
  2160. public function evaluateOrder(int $userId, int $orderId, array $data): array
  2161. {
  2162. return DB::transaction(function () use ($userId, $orderId, $data) {
  2163. try {
  2164. // 1. 验证订单状态
  2165. $order = $this->validateOrderForEvaluation($userId, $orderId);
  2166. // 2. 创建评价记录
  2167. $evaluation = $this->createEvaluation($order, $data);
  2168. // 3. 更新技师评分
  2169. // TODO: 更新技师评分
  2170. // $this->updateCoachScore($order->coach_id);
  2171. // 4. 更新订单状态
  2172. $this->updateOrderEvaluationStatus($order);
  2173. // 5. 创建评价奖励
  2174. // TODO: 创建评价奖励
  2175. // $this->createEvaluationReward($order, $evaluation);
  2176. // 6. 发送评价通知
  2177. // $this->notifyEvaluation($order, $evaluation);
  2178. return ['message' => '评价成功'];
  2179. } catch (Exception $e) {
  2180. $this->logError('订单评价失败', $e, [
  2181. 'user_id' => $userId,
  2182. 'order_id' => $orderId,
  2183. 'data' => $data,
  2184. ]);
  2185. throw $e;
  2186. }
  2187. });
  2188. }
  2189. /**
  2190. * 验证订单评价条件
  2191. */
  2192. private function validateOrderForEvaluation(int $userId, int $orderId): Order
  2193. {
  2194. // 获取订单信息
  2195. $order = Order::where('id', $orderId)
  2196. ->where('user_id', $userId)
  2197. ->where('state', OrderStatus::FINISHED->value)
  2198. ->firstOrFail();
  2199. // 检查是否已评价
  2200. abort_if(
  2201. $order->evaluation()->exists(),
  2202. 400,
  2203. '订单已评价'
  2204. );
  2205. // 检查评价时效(7天内可评价)
  2206. $evaluationExpireDays = config('business.evaluation_expire_days', 7);
  2207. abort_if(
  2208. $order->finish_time->addDays($evaluationExpireDays)->isPast(),
  2209. 400,
  2210. '评价已过期'
  2211. );
  2212. return $order;
  2213. }
  2214. /**
  2215. * 创建评价记录
  2216. */
  2217. // private function createEvaluation(Order $order, array $data): OrderEvaluation
  2218. // {
  2219. // // 创建评价记录
  2220. // $evaluation = $order->evaluation()->create([
  2221. // 'user_id' => $order->user_id,
  2222. // 'coach_id' => $order->coach_id,
  2223. // 'project_id' => $order->project_id,
  2224. // 'score' => $data['score'],
  2225. // 'content' => $data['content'],
  2226. // 'images' => $data['images'] ?? [],
  2227. // 'state' => 'normal',
  2228. // ]);
  2229. // // 创建评价标签
  2230. // if (! empty($data['tags'])) {
  2231. // // TODO: 创建评价标签
  2232. // $this->createEvaluationTags($evaluation, $data['tags']);
  2233. // }
  2234. // return $evaluation;
  2235. // }
  2236. /**
  2237. * 创建评价标签
  2238. */
  2239. // private function createEvaluationTags(OrderEvaluation $evaluation, array $tags): void
  2240. // {
  2241. // $tagIds = EvaluationTag::whereIn('id', $tags)
  2242. // ->where('state', 'enable')
  2243. // ->pluck('id');
  2244. // $evaluation->tags()->attach($tagIds);
  2245. // }
  2246. /**
  2247. * 更新技师评分
  2248. */
  2249. // private function updateCoachScore(int $coachId): void
  2250. // {
  2251. // $coach = CoachUser::findOrFail($coachId);
  2252. // // 计算平均分
  2253. // $avgScore = OrderEvaluation::where('coach_id', $coachId)
  2254. // ->where('state', 'normal')
  2255. // ->avg('score');
  2256. // // 更新技师评分
  2257. // $coach->info()->update([
  2258. // 'score' => round($avgScore, 1),
  2259. // 'evaluation_count' => OrderEvaluation::where('coach_id', $coachId)
  2260. // ->where('state', 'normal')
  2261. // ->count(),
  2262. // ]);
  2263. // }
  2264. /**
  2265. * 更新订单评价状态
  2266. */
  2267. private function updateOrderEvaluationStatus(Order $order): void
  2268. {
  2269. // 创建订单记录
  2270. OrderRecord::create([
  2271. 'order_id' => $order->id,
  2272. 'object_id' => $order->user_id,
  2273. 'object_type' => MemberUser::class,
  2274. 'state' => OrderRecordStatus::EVALUATED->value,
  2275. 'remark' => '用户评价完成',
  2276. ]);
  2277. }
  2278. /**
  2279. * 创建评价奖励
  2280. */
  2281. // private function createEvaluationReward(Order $order, OrderEvaluation $evaluation): void
  2282. // {
  2283. // // 获取评价奖励配置
  2284. // $rewardAmount = config('business.evaluation_reward_amount', 0);
  2285. // if ($rewardAmount <= 0) {
  2286. // return;
  2287. // }
  2288. // // 更新用户钱包
  2289. // $wallet = $order->user->wallet;
  2290. // $wallet->increment('total_balance', $rewardAmount);
  2291. // $wallet->increment('available_balance', $rewardAmount);
  2292. // // 创建奖励记录
  2293. // $wallet->transRecords()->create([
  2294. // 'amount' => $rewardAmount,
  2295. // 'trans_type' => 'evaluation_reward',
  2296. // 'owner_type' => OrderEvaluation::class,
  2297. // 'owner_id' => $evaluation->id,
  2298. // 'remark' => '评价奖励',
  2299. // 'before_balance' => $wallet->total_balance - $rewardAmount,
  2300. // 'after_balance' => $wallet->total_balance,
  2301. // 'state' => 'success',
  2302. // ]);
  2303. // }
  2304. /**
  2305. * 发送评价通知
  2306. */
  2307. // private function notifyEvaluation(Order $order, OrderEvaluation $evaluation): void
  2308. // {
  2309. // // TODO: 实现评价通知逻辑
  2310. // // 1. 通知技师
  2311. // // event(new OrderEvaluatedEvent($order, $evaluation));
  2312. // // 2. 更新评价缓存
  2313. // // Cache::tags(['coach_evaluations'])->forget("coach:{$order->coach_id}");
  2314. // }
  2315. /**
  2316. * 获取技师工作时间安排
  2317. */
  2318. private function getCoachWorkSchedule(int $coachId): array
  2319. {
  2320. // 查询技师排班信息
  2321. $schedule = CoachSchedule::where('coach_id', $coachId)
  2322. ->where('state', 1)
  2323. ->first();
  2324. // 如果没有排班信息,返回默认工作时间
  2325. if (! $schedule) {
  2326. return [
  2327. 'work_days' => range(1, 7), // 默认每天工作
  2328. 'work_hours' => [
  2329. 'start' => '09:00', // 默认早9点开始
  2330. 'end' => '21:00', // 默认晚9点结束
  2331. ],
  2332. 'rest_dates' => [], // 默认无休息日
  2333. ];
  2334. }
  2335. // 返回技师的实际排班信息
  2336. return [
  2337. 'work_days' => json_decode($schedule->work_days, true),
  2338. 'work_hours' => [
  2339. 'start' => $schedule->work_start_time,
  2340. 'end' => $schedule->work_end_time,
  2341. ],
  2342. 'rest_dates' => json_decode($schedule->rest_dates, true) ?? [],
  2343. ];
  2344. }
  2345. }