OrderService.php 104 KB

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