OrderService.php 109 KB

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