OrderService.php 85 KB

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