OrderService.php 106 KB

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