OrderService.php 103 KB

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