123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294 |
- <?php
- namespace App\Services\Client;
- use Exception;
- use Carbon\Carbon;
- use App\Models\Order;
- use App\Models\Project;
- use App\Enums\OrderType;
- use App\Enums\UserStatus;
- use App\Models\AgentInfo;
- use App\Models\CoachUser;
- use App\Enums\OrderSource;
- use App\Enums\OrderStatus;
- use App\Models\MemberUser;
- use App\Models\OrderRecord;
- use App\Enums\PaymentMethod;
- use App\Enums\ProjectStatus;
- use App\Models\CoachLocation;
- use App\Models\MemberAddress;
- use App\Enums\TransactionType;
- use App\Enums\TechnicianStatus;
- use App\Models\OrderGrabRecord;
- use App\Enums\OrderRecordStatus;
- use Illuminate\Support\Facades\DB;
- use App\Enums\TechnicianAuthStatus;
- use App\Models\WalletPaymentRecord;
- use Illuminate\Support\Facades\Log;
- use App\Enums\OrderGrabRecordStatus;
- use Illuminate\Support\Facades\Auth;
- use App\Enums\TechnicianLocationType;
- use Illuminate\Support\Facades\Redis;
- use SimpleSoftwareIO\QrCode\Facades\QrCode;
- use Illuminate\Database\Eloquent\Collection;
- use App\Services\Client\Traits\HandlesPayments;
- use App\Services\Client\Traits\HandlesOrderRecords;
- use App\Services\Client\Traits\ValidatesServiceTime;
- use App\Services\Client\Traits\CalculatesOrderAmounts;
- use App\Models\CoachStatistic;
- use App\Models\FinanceRecord;
- use App\Models\OrderRefundRecord;
- use App\Enums\PaymentType;
- use App\Enums\TransactionStatus;
- use App\Enums\TechnicianWorkStatus;
- use App\Models\OrderCommentTag;
- use App\Enums\OrderRecordType;
- use App\Models\CoachOrderComment;
- use function PHPUnit\Framework\isNull;
- readonly class OrderService
- {
- use CalculatesOrderAmounts;
- use HandlesOrderRecords;
- use HandlesPayments;
- use ValidatesServiceTime;
- public function __construct(
- private AgentService $agentService,
- private ProjectService $projectService,
- private CoachService $coachService,
- private WalletService $walletService
- ) {}
- /**
- * 订单初始化
- *
- * @param int $userId 用户ID
- * @param array $data 订单数据
- * @return array 初始化的订单信息
- *
- * @throws \Exception
- *
- * 逻辑描述:
- * 1. 验证初始化参数(project_id、coach_id)
- * 2. 获取用户信息(包含钱包和地址)
- * 3. 获取区域编码(从地址或参数)
- * 4. 验证技师状态并获取可用时间
- * 5. 获取项目详情(含价格)
- * 6. 计算订单金额(含路费)
- * 7. 返回初始化数据(钱包、技师、项目、地址、金额、可用时间)
- */
- public function initialize(int $userId, array $data): array
- {
- // 参数验证
- $this->validateInitializeData($data);
- return DB::transaction(function () use ($userId, $data) {
- // 获取用户信息
- $user = $this->getUserWithWalletAndAddress($userId);
- // 获取区域编码
- $areaCode = $this->getAreaCode($user->address, $data);
- // 获取技师信息
- $coach = $this->validateCoach($data['coach_id']);
- // 计算距离和获取技师位置
- [$distance, $coachLocation] = $this->calculateDistanceAndLocation(
- userId: $userId,
- coachId: $coach->id,
- inputData: $data,
- userAddress: $user->address
- );
- // 设置技师的距离和位置信息
- $coach->distance = $distance;
- if ($coachLocation) {
- $coach->location = $coachLocation;
- }
- // 获取技师可用时间
- $availableTimeSlots = $this->coachService->getSchedule($coach->id);
- // 获取项目信息
- $project = $this->getProjectDetail($data['project_id'], $areaCode);
- // 计算订单金额
- $amounts = $this->calculateOrderAmount(
- userId: $userId,
- addressId: $user->address?->id ?? 0,
- coachId: $data['coach_id'],
- projectId: $data['project_id'],
- agentId: $project->agent_id,
- useBalance: false,
- distance: $distance,
- lat: $data['latitude'] ?? ($user->address?->latitude ?? 0),
- lng: $data['longitude'] ?? ($user->address?->longitude ?? 0)
- );
- return [
- 'wallet' => $user->wallet,
- 'coach' => $coach,
- 'project' => $project,
- 'address' => $user->address,
- 'amounts' => $amounts,
- 'availableTimeSlots' => $availableTimeSlots,
- ];
- });
- }
- /**
- * 计算距离并获取技师位置信息
- *
- * 计算逻辑优先级:
- * 1. 使用前端传入的距离
- * 2. 使用用户默认地址计算
- * 3. 使用前端传入的经纬度计算
- *
- * @param int $userId 用户ID
- * @param int $coachId 技师ID
- * @param array $inputData 输入数据
- * @param ?object $userAddress 用户默认地址
- * @return array{0: float, 1: ?array} [距离, 位置信息]
- */
- private function calculateDistanceAndLocation(
- int $userId,
- int $coachId,
- array $inputData,
- ?object $userAddress
- ): array {
- // 1. 如果前端直接传入距离,直接使用
- if (isset($inputData['distance'])) {
- return [$inputData['distance'], null];
- }
- // 2. 确定用户坐标来源
- $userCoordinates = $this->getUserCoordinates($inputData, $userAddress);
- if (!$userCoordinates) {
- return [0.0, null];
- }
- // 3. 计算距离和获取位置
- return $this->calculateDistanceFromCoordinates(
- userId: $userId,
- coachId: $coachId,
- longitude: $userCoordinates['longitude'],
- latitude: $userCoordinates['latitude']
- );
- }
- /**
- * 获取用户坐标
- *
- * @return array{longitude: float, latitude: float}|null
- */
- private function getUserCoordinates(array $inputData, ?object $userAddress): ?array
- {
- // 优先使用默认地址
- if ($userAddress && $userAddress->latitude && $userAddress->longitude) {
- return [
- 'longitude' => $userAddress->longitude,
- 'latitude' => $userAddress->latitude
- ];
- }
- // 其次使用前端传入的坐标
- if (isset($inputData['latitude']) && isset($inputData['longitude'])) {
- return [
- 'longitude' => $inputData['longitude'],
- 'latitude' => $inputData['latitude']
- ];
- }
- return null;
- }
- /**
- * 根据坐标计算距离和获取技师位置
- *
- * @param int $userId 用户ID
- * @param int $coachId 技师ID
- * @param float $longitude 经度
- * @param float $latitude 纬度
- * @return array{0: float, 1: ?array} [距离, 位置信息]
- */
- private function calculateDistanceFromCoordinates(
- int $userId,
- int $coachId,
- float $longitude,
- float $latitude
- ): array {
- // 临时存储用户位置用于计算
- $userLocationKey = "user_{$userId}_temp_location";
- Redis::geoadd(
- 'coach_locations',
- $longitude,
- $latitude,
- $userLocationKey
- );
- try {
- $distances = [];
- // 计算与技师两个位置点的距离
- foreach ([TechnicianLocationType::COMMON, TechnicianLocationType::CURRENT] as $locationType) {
- $locationKey = "{$coachId}_{$locationType->value}";
- $distance = Redis::geodist('coach_locations', $userLocationKey, $locationKey, 'km');
- if ($distance !== null) {
- $distances[] = [
- 'distance' => (float)$distance,
- 'key' => $locationKey,
- 'type' => $locationType->value
- ];
- }
- }
- // 如果没有有效距离,返回默认值
- if (empty($distances)) {
- return [0.0, null];
- }
- // 获取最小距离的记录
- $minDistance = array_reduce($distances, function ($carry, $item) {
- if (!$carry || $item['distance'] < $carry['distance']) {
- return $item;
- }
- return $carry;
- });
- // 从 Redis 获取原始位置信息
- $originalLocation = Redis::hget(
- "coach_location_original:{$coachId}",
- "type_{$minDistance['type']}"
- );
- if ($originalLocation) {
- $locationData = json_decode($originalLocation, true);
- return [
- $minDistance['distance'],
- [
- 'longitude' => (float)$locationData['longitude'],
- 'latitude' => (float)$locationData['latitude']
- ]
- ];
- }
- // 如果没有原始数据,则从数据库获取
- $location = CoachLocation::where('coach_id', $coachId)
- ->where('type', $minDistance['type'])
- ->latest()
- ->first();
- return [
- $minDistance['distance'],
- $location ? [
- 'longitude' => (float)$location->longitude,
- 'latitude' => (float)$location->latitude
- ] : null
- ];
- } finally {
- // 清理临时数据
- Redis::zrem('coach_locations', $userLocationKey);
- }
- }
- /**
- * 验证初始化数据
- *
- * 逻辑描述:
- * 1. 验证项目ID不能为空
- * 2. 验证技师ID不能为空
- */
- private function validateInitializeData(array $data): void
- {
- abort_if(empty($data['project_id']), 400, '项目ID不能为空');
- abort_if(empty($data['coach_id']), 400, '技师ID不能为空');
- }
- /**
- * 获取用户信息(包含钱包和地址)
- *
- * 逻辑描述:
- * 1. 查询用户信息(关联钱包和地址)
- * 2. 验证用户状态是否正常
- * 3. 返回用户信息
- */
- private function getUserWithWalletAndAddress(int $userId): MemberUser
- {
- $user = MemberUser::with(['wallet', 'address'])
- ->where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->first();
- abort_if(! $user, 400, '用户状态异常');
- return $user;
- }
- /**
- * 获取区域编码
- *
- * 逻辑描述:
- * 1. 优先使用地址中的区域编码
- * 2. 其次使用参数中的区域编码
- * 3. 验证区域编码不能为空
- */
- private function getAreaCode(?object $address, array $data): string
- {
- $areaCode = $address?->area_code ?? ($data['area_code'] ?? null);
- abort_if(empty($areaCode), 400, '区域编码不能为空');
- return $areaCode;
- }
- /**
- * 获取项目详情
- *
- * 逻辑描述:
- * 1. 调用项目服务获取详情
- * 2. 验证项目是否存在
- * 3. 返回项目信息
- */
- private function getProjectDetail(int $projectId, string $areaCode): Project
- {
- $project = $this->projectService->getProjectDetail($projectId, $areaCode);
- abort_if(! $project, 400, '项目不存在');
- return $project;
- }
- /**
- * 记录错误日志
- *
- * 逻辑描述:
- * 1. 记录错误信息
- * 2. 记录上下文数据
- * 3. 记录错误堆栈
- */
- private function logError(string $message, Exception $e, array $context = []): void
- {
- Log::error($message, [
- ...$context,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString(),
- ]);
- }
- /**
- * 创建订单
- *
- * @param array{
- * user_id: int,
- * project_id: int,
- * coach_id: ?int,
- * address_id: int,
- * service_time: string,
- * remark: ?string,
- * use_balance: bool,
- * agent_id: ?int,
- * distance: float,
- * payment_type: int,
- * type: int,
- * } $data 订单数据
- * @return array{
- * order_id: int,
- * order_no: string,
- * total_amount: float,
- * balance_amount: float,
- * pay_amount: float
- * }
- *
- * @throws \Exception
- *
- * 逻辑描述:
- * 1. 验证基础数据(用户状态、项目状态、服务时间、技师状态等)
- * 2. 计算订单金额(项目价格、路费、优惠等)
- * 3. 处理加钟订单特殊逻辑(使用原订单地址和技师)
- * 4. 获取服务地址信息
- * 5. 创建订单数据
- * 6. 创建订单相关记录
- * 7. 处理余额支付(如果是余额支付)
- * 8. 发送订单创建通知
- * 9. 返回订单信息
- */
- public function createOrder(int $userId, array $data): array
- {
- return DB::transaction(function () use ($userId, $data) {
- try {
- // 转换时间格式
- if (!empty($data['service_time'])) {
- $data['service_time'] = Carbon::parse($data['service_time'])->format('Y-m-d H:i:s');
- }
- // 1. 验证基础数据
- $this->validateOrderData($userId, $data);
- // 检测代理
- $agentId = null;
- if (!empty($data['agent_id'])) {
- $agent = $this->agentService->getAgent($data['agent_id']);
- if ($agent) {
- $agentId = $agent->id;
- }
- }
- $data['agent_id'] = $agentId;
- // 2. 计算订单金额
- $amounts = $this->calculateOrderAmount(
- userId: $userId,
- addressId: $data['address_id'] ?? null,
- coachId: $data['coach_id'] ?? null,
- projectId: $data['project_id'],
- agentId: $data['agent_id'] ?? null,
- useBalance: $data['use_balance'] ?? false,
- distance: $data['distance'] ?? 0
- );
- // 加钟订单使用原订单地址和技师ID
- if (! empty($data['order_id'])) {
- $order = Order::findOrFail($data['order_id']);
- // 验证订单状态
- abort_if(
- ! in_array($order->state, [
- OrderStatus::SERVICE_START->value,
- OrderStatus::SERVICING->value,
- OrderStatus::SERVICE_END->value
- ]),
- 422,
- '原订单状态不允许加钟'
- );
- $data['parent_id'] = $order->id;
- $data['address_id'] = $order->address_id;
- $data['coach_id'] = $order->coach_id;
- $data['service_time'] = $order->service_end_time;
- }
- // 3. 获取地址
- $address = MemberUser::find($userId)->addresses()
- ->where('id', $data['address_id'])
- ->first();
- abort_if(! $address, 404, '收货地址不存在');
- // 3. 创建订单
- $order = $this->createOrderData(['user_id' => $userId, ...$data], $amounts, $address);
- // 4. 创建订单相关记录
- $this->createRelatedRecords($order);
- // 5. 检测支付类型,自动进行余额支付
- if ($order->payment_type == PaymentMethod::BALANCE->value) {
- // 处理余额支付
- $this->processBalancePayment($order);
- // 更改订单状态
- $order->state = OrderStatus::PAID->value;
- $order->service_start_time = $data['service_time'];
- $order->service_end_time = Carbon::parse($data['service_time'])
- ->addMinutes($order->project->duration);
- $order->save();
- // 创建订单相关记录
- $this->createRelatedRecords($order);
- } else {
- $order->payment_type = PaymentMethod::WECHAT->value;
- }
- // 6. 发送通知
- $this->notifyOrderCreated($order);
- // 7. 添加订单位置到Redis(仅抢单类型)
- if ($order->type === OrderType::GRAB->value && $address->latitude && $address->longitude) {
- Redis::geoadd(
- 'order_locations',
- $address->longitude,
- $address->latitude,
- 'order_' . $order->id
- );
- // 设置过期时间(24小时)
- Redis::expire('order_locations', 86400);
- }
- $result = [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- ];
- // 8. 如果是微信支付,获取支付参数
- if ($order->payment_type == PaymentMethod::WECHAT->value) {
- $paymentService = app(PaymentService::class);
- $result['wx_payment'] = $paymentService->getPaymentConfig($order->id);
- }
- return $result;
- } catch (Exception $e) {
- $this->logError('创建订单失败', $e, $data);
- throw $e;
- }
- });
- }
- /**
- * 验证订单创建数据
- */
- private function validateOrderData(int $userId, array $data): void
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->first();
- abort_if(! $user, 404, '用户不存在');
- abort_if($user->state != UserStatus::OPEN->value, 403, '用户状态异常');
- // 验证项目状态
- $project = Project::where('id', $data['project_id'])->first();
- abort_if(! $project, 404, '服务项目不存在');
- abort_if($project->state != ProjectStatus::OPEN->value, 403, '服务项目未开放');
- // 验证服务时间和技师状态
- if (! empty($data['service_time']) && ! empty($data['coach_id'])) {
- $this->validateServiceTimeParams($data['coach_id'], $data['service_time']);
- }
- }
- /**
- * 创建订单数据
- */
- private function createOrderData(array $data, array $amounts, object $address): Order
- {
- // 获取项目信息和服务时长
- $project = Project::findOrFail($data['project_id']);
- $serviceDuration = $project->duration;
- return Order::create([
- 'order_no' => $this->generateOrderNo(),
- 'parent_id' => $data['parent_id'] ?? null,
- 'user_id' => $data['user_id'],
- 'project_id' => $data['project_id'],
- 'coach_id' => $data['coach_id'] ?? null,
- 'agent_id' => $data['agent_id'] ?? null,
- 'address_id' => $data['address_id'],
- 'service_time' => $data['service_time'] ?? null,
- 'project_duration' => $serviceDuration, // 添加服务时长记录
- 'remark' => $data['remark'] ?? '',
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- 'traffic_amount' => $amounts['delivery_fee'],
- 'project_amount' => $amounts['project_amount'],
- 'discount_amount' => $amounts['coupon_amount'],
- 'state' => OrderStatus::CREATED->value,
- // 如果余额支付且未使用优惠券且未支付金额,则使用余额支付,否则使用传入的支付方式
- 'payment_type' => $amounts['balance_amount'] > 0 && $amounts['pay_amount'] == 0
- ? PaymentMethod::BALANCE->value
- : PaymentMethod::WECHAT->value,
- 'latitude' => $address->latitude,
- 'longitude' => $address->longitude,
- 'location' => $address->location,
- 'address' => $address->detail,
- 'area_code' => $address->area_code,
- 'type' => $data['order_type'],
- 'distance' => $data['distance'] ?? 0,
- 'dest_phone' => $address->phone,
- ]);
- }
- private function createOrderRecord(Order $order, int $objectId, string $objectType, OrderRecordStatus $status, string $remark): OrderRecord
- {
- return OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $objectId,
- 'object_type' => $objectType,
- 'state' => $status->value,
- 'remark' => $remark,
- ]);
- }
- /**
- * 生成订单号
- */
- private function generateOrderNo(): string
- {
- return 'O' . date('YmdHis') . str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT);
- }
- /**
- * 处理余额支付
- */
- private function processBalancePayment(Order $order): void
- {
- $user = MemberUser::find($order->user_id);
- abort_if(! $user, 404, sprintf('用户[%d]不存在', $order->user_id));
- $wallet = $user->wallet;
- abort_if(
- $wallet->available_balance < $order->balance_amount,
- 400,
- sprintf(
- '用户[%d]可用余额[%.2f]不足,需要[%.2f]',
- $user->id,
- $wallet->available_balance,
- $order->balance_amount
- )
- );
- // 扣除余额
- if ($order->balance_amount > 0) {
- $this->walletService->deduct(
- userId: $user->id,
- amount: $order->balance_amount,
- type: TransactionType::PAYMENT->value,
- objectId: $order->id,
- remark: sprintf('订单[%s]余额支付', $order->order_no)
- );
- }
- }
- /**
- * 创建订单相关记录
- */
- private function createRelatedRecords(Order $order): void
- {
- // 创建订单状态记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => $order->state,
- 'remark' => $order->state === OrderStatus::PAID->value
- ? '余额支付成功'
- : '订单创建成功',
- ]);
- }
- /**
- * 发送订单创建通知
- */
- private function notifyOrderCreated(Order $order): void
- {
- // TODO: 实现订单创建通知
- // 1. 通知用户
- // event(new OrderCreatedEvent($order));
- }
- /**
- * 获取订单地址
- */
- private function getOrderAddress(MemberUser $user, array $data, OrderType $orderType): object
- {
- // 加钟订单使用原订单地址
- if ($orderType === OrderType::OVERTIME) {
- $originalOrder = $this->getOriginalOrder($user, $data['order_id']);
- $data['address_id'] = $originalOrder->address_id;
- }
- abort_if(empty($data['address_id']), 400, '地址ID不能为空');
- return $user->addresses()
- ->where('id', $data['address_id'])
- ->firstOrFail();
- }
- /**
- * 验证支付方式和余额
- */
- private function validatePayment(MemberUser $user, array $data, array $amounts): void
- {
- abort_if($amounts['total_amount'] <= 0, 400, '订单金额异常');
- if ($data['payment_type'] === PaymentMethod::BALANCE->value) {
- $wallet = $user->wallet;
- abort_if($wallet->available_balance < $amounts['balance_amount'], 400, '可用余额不足');
- }
- }
- /**
- * 判断是否需要处理余额支付
- */
- private function shouldHandleBalancePayment(Order $order, OrderType $orderType): bool
- {
- return $order->payment_type === PaymentMethod::BALANCE->value
- && $orderType !== OrderType::GRAB;
- }
- /**
- * 验证技师状态
- */
- private function validateCoach(int $coachId): CoachUser
- {
- $coach = CoachUser::query()
- ->with(['info'])
- ->where('id', $coachId)
- ->where('state', TechnicianStatus::ACTIVE->value)
- ->first();
- abort_if(! $coach, 400, '技师不存在或未激活');
- abort_if(
- ! $coach->info || $coach->info->state !== TechnicianAuthStatus::PASSED->value,
- 400,
- '技师未通过认证'
- );
- return $coach;
- }
- // 提取方法:获取原始订单
- private function getOriginalOrder($user, $orderId): Order
- {
- $originalOrder = $user->orders->where('id', $orderId)
- ->whereIn('state', [OrderStatus::SERVICING->value, OrderStatus::COMPLETED->value])
- ->firstOrFail();
- return $originalOrder;
- }
- // 提取方法:准备加钟订单数据
- private function prepareAddTimeData($originalOrder, $data): array
- {
- if ($originalOrder->state == OrderStatus::SERVICING->value) {
- $startTime = now();
- } else {
- $startTime = now();
- }
- return [
- ...$data,
- 'order_id' => $data['order_id'],
- 'address_id' => $originalOrder->address_id,
- 'service_time' => $startTime,
- 'coach_id' => $originalOrder->coach_id,
- ];
- }
- /**
- * 取消订单
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @param string|null $reason 取消原因
- * @return array{message: string}
- *
- * @throws \Exception
- */
- public function cancelOrder(int $userId, int $orderId, ?string $reason = null): array
- {
- return DB::transaction(function () use ($userId, $orderId, $reason) {
- try {
- // 1. 验证订单状态
- $order = $this->validateOrderForCancel($userId, $orderId);
- // 2. 计算退款金额
- $refundAmounts = $this->calculateCancelAmount($order);
- // 3. 更新订单状态为已取消
- $this->updateOrderCancelStatus($order);
- // 4. 创建取消记录
- $this->createCancelRecords($order, $reason);
- // 5. 处理退款
- $this->processCancelRefund($order, $refundAmounts);
- // 6. 更新订单退款状态
- $this->updateOrderRefundStatus($order);
- // 7. 发送取消通知
- $this->notifyCancel($order);
- return ['message' => '订单取消成功'];
- } catch (Exception $e) {
- $this->logError('取消订单失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'reason' => $reason,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证订单取消条件
- */
- private function validateOrderForCancel(int $userId, int $orderId): Order
- {
- // 获取并锁定订单
- $order = Order::where('id', $orderId)
- ->whereIn('state', [
- OrderStatus::PAID->value, // 已支付
- OrderStatus::ACCEPTED->value, // 已接单
- OrderStatus::DEPARTED->value, // 已出发
- OrderStatus::REJECTED->value, // 技师拒单
- ])
- ->lockForUpdate()
- ->firstOrFail();
- // 验证订单所属用户
- abort_if($order->user_id !== $userId, 403, '无权操作此订单');
- // 验证订单是否已取消
- abort_if($order->state === OrderStatus::CANCELLED->value, 400, '订单已取消');
- return $order;
- }
- /**
- * 计算取消费用
- *
- * @return array{
- * total_refund: float,
- * balance_refund: float,
- * payment_refund: float,
- * penalty_amount: float
- * }
- */
- private function calculateCancelAmount(Order $order): array
- {
- // 计算违约金
- $penaltyAmount = $this->calculatePenaltyAmount($order);
- // 计算退款金额分配
- return $this->calculateRefundDistribution($order, $penaltyAmount);
- }
- /**
- * 计算违约金
- *
- * @return array{
- * total_penalty: float,
- * coach_fee: float,
- * platform_traffic_fee: float,
- * platform_penalty: float
- * }
- */
- private function calculatePenaltyAmount(Order $order): array
- {
- // 根据订单状态计算违约金
- return match ($order->state) {
- // 已出发状态:扣除路费(90%给技师,10%给平台),剩余金额再扣除20%
- OrderStatus::DEPARTED->value => $this->calculateDepartedPenalty($order),
- // 已接单状态:扣除订单总金额的6%作为违约金
- OrderStatus::ACCEPTED->value => [
- 'total_penalty' => bcmul($order->total_amount, '0.06', 2), // 订单总金额的6%
- 'coach_fee' => 0,
- 'platform_traffic_fee' => 0,
- 'platform_penalty' => bcmul($order->total_amount, '0.06', 2) // 平台获得全部违约金
- ],
- // 其他状态(已支付等):不收取违约金
- default => [
- 'total_penalty' => 0,
- 'coach_fee' => 0,
- 'platform_traffic_fee' => 0,
- 'platform_penalty' => 0
- ]
- };
- }
- /**
- * 计算已出发状态的违约金
- * 规则:
- * 1. 路费分配:90%给技师,10%给平台
- * 2. 剩余金额的20%作为平台违约金
- *
- * @return array{
- * total_penalty: float, // 总违约金
- * coach_fee: float, // 技师获得的路费
- * platform_traffic_fee: float, // 平台获得的路费分成
- * platform_penalty: float // 平台获得的违约金
- * }
- */
- private function calculateDepartedPenalty(Order $order): array
- {
- // 获取路费
- $trafficFee = $order->traffic_fee ?? 0;
- // 路费分配:90%给技师,10%给平台
- $coachFee = bcmul($trafficFee, '0.9', 2); // 技师获得的路费
- $platformTrafficFee = bcsub($trafficFee, $coachFee, 2); // 平台获得的路费分成
- // 计算扣除路费后的剩余金额
- $remainingAmount = bcsub($order->total_amount, $trafficFee, 2);
- // 剩余金额的20%作为平台违约金
- $platformPenalty = bcmul($remainingAmount, '0.2', 2);
- // 总违约金 = 路费 + 平台违约金
- $totalPenalty = bcadd($trafficFee, $platformPenalty, 2);
- return [
- 'total_penalty' => $totalPenalty, // 总违约金
- 'coach_fee' => $coachFee, // 技师获得的路费
- 'platform_traffic_fee' => $platformTrafficFee, // 平台获得的路费分成
- 'platform_penalty' => $platformPenalty // 平台获得的违约金
- ];
- }
- /**
- * 计算退款金额分配
- *
- * @return array{
- * total_refund: float,
- * balance_refund: float,
- * payment_refund: float,
- * penalty_amount: float,
- * coach_fee: float,
- * platform_traffic_fee: float,
- * platform_penalty: float
- * }
- */
- private function calculateRefundDistribution(Order $order, array $penaltyInfo): array
- {
- // 计算实际可退金额(总金额减去违约金)
- $totalRefund = bcsub($order->total_amount, $penaltyInfo['total_penalty'], 2);
- // 优先退还用户使用的余额部分
- $balanceRefund = min($order->balance_amount, $totalRefund);
- // 剩余部分退还到支付账户
- $paymentRefund = bcsub($totalRefund, $balanceRefund, 2);
- return [
- 'total_refund' => $totalRefund,
- 'balance_refund' => $balanceRefund,
- 'payment_refund' => $paymentRefund,
- 'penalty_amount' => $penaltyInfo['total_penalty'],
- 'coach_fee' => $penaltyInfo['coach_fee'],
- 'platform_traffic_fee' => $penaltyInfo['platform_traffic_fee'],
- 'platform_penalty' => $penaltyInfo['platform_penalty'],
- ];
- }
- /**
- * 处理取消退款
- */
- private function processCancelRefund(Order $order, array $refundAmounts): void
- {
- try {
- // 1. 处理余额退款
- if ($refundAmounts['balance_refund'] > 0) {
- $this->processBalanceCancelRefund($order, $refundAmounts['balance_refund']);
- }
- // 2. 处理支付退款
- if ($refundAmounts['payment_refund'] > 0) {
- $refundResult = $this->processPaymentCancelRefund($order, $refundAmounts['payment_refund']);
- // 3. 创建退款记录
- $refundRecord = OrderRefundRecord::create([
- 'order_id' => $order->id,
- 'total_refund_amount' => $refundAmounts['total_refund'],
- 'balance_refund_amount' => $refundAmounts['balance_refund'],
- 'payment_refund_amount' => $refundAmounts['payment_refund'],
- 'penalty_amount' => $refundAmounts['penalty_amount'], // 这里使用 penalty_amount 而不是 penalty
- 'coach_fee' => $refundAmounts['coach_fee'],
- 'platform_traffic_fee' => $refundAmounts['platform_traffic_fee'],
- 'platform_penalty' => $refundAmounts['platform_penalty'],
- 'refund_no' => $refundResult['refund_no'],
- 'transaction_id' => $order->transaction_id,
- 'state' => TransactionStatus::SUCCESS->value, // 使用成功状态枚举值
- 'remark' => '订单取消退款'
- ]);
- }
- } catch (\Exception $e) {
- Log::error('处理退款失败', [
- 'order_id' => $order->id,
- 'refund_amounts' => $refundAmounts,
- 'error' => $e->getMessage()
- ]);
- throw $e;
- }
- }
- /**
- * 处理余额退款
- */
- private function processBalanceCancelRefund(Order $order, float $amount): void
- {
- $wallet = $order->user->wallet;
- // 更新钱包余额
- $wallet->increment('total_balance', $amount);
- $wallet->increment('available_balance', $amount);
- // 创建钱包交易记录
- $wallet->transRecords()->create([
- 'amount' => $amount,
- 'trans_type' => TransactionType::REFUND->value, // 使用退款枚举值
- 'owner_type' => Order::class,
- 'owner_id' => $order->id,
- 'remark' => '订单取消退款',
- 'before_balance' => $wallet->total_balance - $amount,
- 'after_balance' => $wallet->total_balance,
- 'state' => TransactionStatus::SUCCESS->value, // 使用成功状态枚举值
- ]);
- // 创建订单记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '余额退款'
- ]);
- }
- /**
- * 处理支付退款
- */
- private function processPaymentCancelRefund(Order $order, float $amount): array
- {
- try {
- // 调用支付服务处理退款
- $paymentService = app(PaymentService::class);
- $result = $paymentService->refund(
- $order->transaction_id,
- $amount,
- $order->pay_amount,
- '订单取消退款'
- );
- if (!$result['success']) {
- throw new \Exception($result['message']);
- }
- // 创建订单记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '微信支付退款'
- ]);
- return $result;
- } catch (\Exception $e) {
- Log::error('订单退款失败', [
- 'order_id' => $order->id,
- 'amount' => $amount,
- 'error' => $e->getMessage()
- ]);
- throw $e;
- }
- }
- /**
- * 更新订单取消状态
- */
- private function updateOrderCancelStatus(Order $order): void
- {
- $order->update([
- 'state' => OrderStatus::CANCELLED->value,
- ]);
- }
- /**
- * 创建取消记录
- */
- private function createCancelRecords(Order $order, ?string $reason): void
- {
- // 创建订单状态记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => Auth::id(),
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::CANCELLED->value,
- 'remark' => "用户取消订单:{$reason}",
- ]);
- }
- /**
- * 发送取消通知
- */
- private function notifyCancel(Order $order): void
- {
- // TODO: 实现取消通知逻辑
- // 1. 知用户
- // event(new OrderCancelledEvent($order));
- // 2. 通知技师
- if ($order->coach_id) {
- // event(new OrderCancelledToCoachEvent($order));
- }
- }
- /**
- * 结束订单
- */
- public function finishOrder(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
- // 1. 验证用户和订单
- $order = $this->validateOrderForFinish($userId, $orderId);
- // 2. 验证技师状
- $coach = $this->validateCoach($order->coach_id);
- // 3. 检测并更新技师状态
- // 如果技师状态为忙碌,则更新为空闲
- if ($coach->work_status === TechnicianWorkStatus::BUSY->value) {
- $coach->update([
- 'work_status' => TechnicianWorkStatus::FREE->value
- ]);
- }
- // 4. 完成订单
- $this->completeOrder($order, $userId);
- // 5. 知技师
- // event(new OrderFinishedEvent($order));
- return ['message' => '订单已完成'];
- } catch (Exception $e) {
- $this->logFinishOrderError($e, $userId, $orderId);
- throw $e;
- }
- });
- }
- /**
- * 验证订单完成条件
- */
- private function validateOrderForFinish(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- // 验证订单状态
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->where('state', OrderStatus::SERVICING->value)
- ->lockForUpdate()
- ->firstOrFail();
- return $order;
- }
- /**
- * 完成订单
- */
- private function completeOrder(Order $order, int $userId): void
- {
- // 1. 创建订单记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::COMPLETED->value,
- 'remark' => '服务完成',
- ]);
- // 2. 更新订单状态
- $order->state = OrderStatus::SERVICE_END->value;
- $order->service_end_time = now();
- $order->save();
- }
- /**
- * 记录订单完成错误日志
- */
- private function logFinishOrderError(Exception $e, int $userId, int $orderId): void
- {
- Log::error('结束订单失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'trace' => $e->getTraceAsString(),
- ]);
- }
- /**
- * 确认技师离开
- */
- public function confirmLeave(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- try {
- // 1. 参数校验
- $order = Order::where('user_id', $userId)
- ->where('id', $orderId)
- ->where('state', OrderStatus::SERVICE_END->value) // 订单状态必须是服务结束
- ->firstOrFail();
- if (! $order) {
- throw new Exception('订单不能撤离');
- }
- // 2. 添加订单撤离记录
- OrderRecord::create([
- 'order_id' => $orderId,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::LEFT->value,
- 'remark' => '技师已离开',
- ]);
- // 3. 修改订单状态为撤离
- $order->state = OrderStatus::LEAVING->value;
- $order->save();
- return ['message' => '已确技师离开'];
- } catch (Exception $e) {
- Log::error('确认技师离开失败:', [
- 'message' => $e->getMessage(),
- 'user_id' => $userId,
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 获取用户订单列表
- *
- * @param int $userId 用户ID
- * @param int $tab 标签页 0:全部 1:待支付 2:进行中 3:已完成 4:已取消
- * @return array
- */
- public function getOrderList(int $userId, int $tab = 0)
- {
- // 1. 验证用户
- $user = $this->validateUserForQuery($userId);
- // 2. 构建基础查询
- $query = $this->buildOrderListQuery($user);
- // 3. 获取状态过滤条件
- $states = $this->getOrderStatesByTab($tab);
- // 4. 加载关联数据并分页
- return $this->paginateOrderList($query, [
- 'states' => $states
- ]);
- }
- /**
- * 分页获取订单列表
- *
- * @param \Illuminate\Database\Eloquent\Builder $query
- * @param array $filters 过滤条件
- */
- private function paginateOrderList($query, array $filters = [])
- {
- // 从请求中获取分页参数
- $perPage = request('per_page', 10);
- $page = request('page', 1);
- // 应用状态过滤
- if (!empty($filters['states'])) {
- $query->whereIn('state', $filters['states']);
- }
- // 按创建时间降序排序并分页
- $paginatedOrders = $query->orderBy('created_at', 'desc')
- ->paginate(
- perPage: $perPage,
- page: $page
- );
- // 格式化订单数据
- $formattedOrders = $paginatedOrders->map(function ($order) {
- return $this->formatOrderListItem($order);
- });
- return [
- 'items' => $formattedOrders,
- 'total' => $paginatedOrders->total(),
- ];
- }
- /**
- * 根据标签页获取订单状态
- */
- private function getOrderStatesByTab(int $tab): array
- {
- return match ($tab) {
- 1 => [OrderStatus::CREATED->value, OrderStatus::PAYMENT_FAILED->value], // 待付款
- 2 => [ // 进行中
- OrderStatus::PAID->value,
- OrderStatus::ASSIGNED->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::DEPARTED->value,
- OrderStatus::ARRIVED->value,
- OrderStatus::SERVICE_START->value,
- OrderStatus::SERVICING->value,
- OrderStatus::SERVICE_END->value,
- OrderStatus::LEAVING->value,
- ],
- 3 => [OrderStatus::COMPLETED->value], // 已完成
- 4 => [OrderStatus::LEFT->value], // 待评价
- 5 => [ // 已取消
- OrderStatus::CANCELLED->value,
- OrderStatus::REFUNDED->value,
- OrderStatus::REJECTED->value,
- OrderStatus::REFUNDING->value,
- OrderStatus::REFUND_FAILED->value,
- ],
- default => [], // 全部订单
- };
- }
- /**
- * 验证用户查询权限
- */
- private function validateUserForQuery(int $userId): MemberUser
- {
- return MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- }
- /**
- * 构建订单列表基础查询
- */
- private function buildOrderListQuery(MemberUser $user)
- {
- return $user->orders()
- ->whereNull('user_deleted_at') // 不显示用户已删除的订单
- ->with([
- 'coach' => function ($query) {
- $query->with(['info' => function ($q) {
- $q->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
- }]);
- },
- 'project:id,title,subtitle,duration,cover',
- 'records' => function ($query) {
- $query->orderBy('created_at', 'desc')
- ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
- },
- // 'evaluation:id,order_id,score,content,created_at',
- ]);
- }
- /**
- * 格式化订单列表项
- */
- private function formatOrderListItem(Order $order): array
- {
- return [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'state' => $order->state,
- 'state_text' => OrderStatus::fromValue($order->state)->label(),
- 'type' => $order->type,
- 'type_text' => OrderType::fromValue($order->type)?->label(),
- 'source' => $order->source,
- 'source_text' => OrderSource::fromValue($order->source)?->label(),
- 'total_amount' => $order->total_amount, // 订单总金额
- 'balance_amount' => $order->balance_amount, // 余额支付金额
- 'pay_amount' => $order->pay_amount, // 实付金额
- 'payment_type' => $order->payment_type, // 支付方式
- 'payment_type_text' => $order->payment_type ? PaymentMethod::fromValue($order->payment_type)->label() : null, // 支付方式文本
- 'discount_amount' => $order->discount_amount, // 优惠金额
- 'traffic_amount' => $order->traffic_amount, // 路费金额
- 'service_time' => $order->service_time,
- 'service_start_time' => $order->service_start_time instanceof \Carbon\Carbon // 服务开始时间
- ? $order->service_start_time->toDateTimeString()
- : $order->service_start_time,
- 'service_end_time' => $order->service_end_time instanceof \Carbon\Carbon // 服务结束时间
- ? $order->service_end_time->toDateTimeString()
- : $order->service_end_time,
- 'created_at' => $order->created_at->toDateTimeString(),
- 'coach' => $order->coach ? [
- 'id' => $order->coach->id,
- 'nickname' => $order->coach->info->nickname,
- 'avatar' => $order->coach->info->avatar,
- ] : null,
- 'project' => $order->project ? [
- 'id' => $order->project->id,
- 'title' => $order->project->title,
- 'subtitle' => $order->project->subtitle,
- 'duration' => $order->project->duration,
- 'cover_image' => $order->project->cover_image,
- ] : null,
- 'address' => $order->address ? [
- 'location' => $order->location,
- 'address' => $order->address,
- ] : null,
- 'latest_record' => $order->records->first() ? [
- 'state' => $order->records->first()->state,
- 'remark' => $order->records->first()->remark,
- 'created_at' => $order->records->first()->created_at->format('Y-m-d H:i:s'),
- ] : null,
- 'evaluation' => $order->evaluation ? [
- 'score' => $order->evaluation->score,
- 'content' => $order->evaluation->content,
- ] : null,
- ];
- }
- /**
- * 获取订单详情
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array 订单详情
- *
- * @throws \Exception
- */
- public function getOrderDetail(int $userId, int $orderId): array
- {
- try {
- // 1. 验证订单权限
- $order = $this->validateOrderAccess($userId, $orderId);
- // 2. 加载订单关联数据
- $order->load([
- 'coach.info' => function ($query) {
- $query->select(['id', 'coach_id', 'nickname', 'avatar', 'gender']);
- },
- 'project:id,title,subtitle,duration,cover',
- 'records' => function ($query) {
- $query->orderBy('created_at', 'desc')
- ->select(['id', 'order_id', 'state', 'remark', 'created_at']);
- },
- // 'evaluation' => function ($query) {
- // $query->select(['id', 'order_id', 'score', 'content', 'images', 'created_at']);
- // },
- ]);
- // 3. 格式化返回数据
- return $this->formatOrderDetail($order);
- } catch (Exception $e) {
- $this->logError('获取订单详情失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- }
- /**
- * 验证订单访问权限
- */
- private function validateOrderAccess(int $userId, int $orderId): Order
- {
- return Order::where('id', $orderId)
- ->where('user_id', $userId)
- ->firstOrFail();
- }
- /**
- * 格式化订单详情数据
- */
- private function formatOrderDetail(Order $order): array
- {
- return [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'state' => $order->state,
- 'state_text' => OrderStatus::fromValue($order->state)->label(),
- 'total_amount' => $order->total_amount,
- 'balance_amount' => $order->balance_amount,
- 'pay_amount' => $order->pay_amount,
- 'delivery_fee' => $order->delivery_fee,
- 'project_amount' => $order->project_amount,
- 'coupon_amount' => $order->coupon_amount,
- 'service_time' => $order->service_time,
- 'service_start_time' => $order->service_start_time instanceof \Carbon\Carbon // 服务开始时间
- ? $order->service_start_time->toDateTimeString()
- : $order->service_start_time,
- 'service_end_time' => $order->service_end_time instanceof \Carbon\Carbon // 服务结束时间
- ? $order->service_end_time->toDateTimeString()
- : $order->service_end_time,
- 'created_at' => $order->created_at->toDateTimeString(),
- 'remark' => $order->remark,
- 'distance' => $order->distance ?? 0,
- 'coach' => $order->coach ? [
- 'id' => $order->coach->id,
- 'nickname' => $order->coach->info->nickname,
- 'avatar' => $order->coach->info->avatar,
- 'gender' => $order->coach->info->gender,
- 'score' => $order->coach->info?->score,
- ] : null,
- 'project' => $order->project ? [
- 'id' => $order->project->id,
- 'title' => $order->project->title,
- 'subtitle' => $order->project->subtitle,
- 'duration' => $order->project->duration,
- 'cover' => $order->project->cover,
- ] : null,
- 'address' => $order->address ? [
- 'id' => $order->address_id,
- 'location' => $order->location,
- 'address' => $order->address,
- 'latitude' => $order->latitude,
- 'longitude' => $order->longitude
- ] : null,
- 'records' => $order->records->map(function ($record) {
- return [
- 'id' => $record->id,
- 'state' => $record->state,
- 'remark' => $record->remark,
- 'created_at' => $record->created_at->format('Y-m-d H:i:s'),
- ];
- })->toArray(),
- // 'evaluation' => $order->evaluation ? [
- // 'score' => $order->evaluation->score,
- // 'content' => $order->evaluation->content,
- // 'images' => $order->evaluation->images,
- // 'created_at' => $order->evaluation->created_at->format('Y-m-d H:i:s'),
- // ] : null,
- ];
- }
- /**
- * 应用订单过滤条件
- */
- private function applyOrderFilters($query, array $filters): void
- {
- // 按状态数组筛选
- if (!empty($filters['states'])) {
- $query->whereIn('state', $filters['states']);
- }
- // 按时间范围筛选
- if (! empty($filters['start_date'])) {
- $query->where('created_at', '>=', $filters['start_date']);
- }
- if (! empty($filters['end_date'])) {
- $query->where('created_at', '<=', $filters['end_date']);
- }
- // 按服务类型筛选
- if (! empty($filters['project_id'])) {
- $query->where('project_id', $filters['project_id']);
- }
- // 按技师筛选
- if (! empty($filters['coach_id'])) {
- $query->where('coach_id', $filters['coach_id']);
- }
- // 按订单号搜索
- if (! empty($filters['order_no'])) {
- $query->where('order_no', 'like', "%{$filters['order_no']}%");
- }
- }
- /**
- * 订单退款
- *
- * @param int $orderId 订单ID
- * @return array{message: string}
- *
- * @throws \Exception
- */
- public function refundOrder(int $orderId): array
- {
- return DB::transaction(function () use ($orderId) {
- try {
- // 1. 验证订单状态
- $order = $this->validateOrderForRefund($orderId);
- // 2. 计算退款金额
- $refundAmounts = $this->calculateRefundAmount($order);
- // 3. 处理退款
- $this->processRefund($order, $refundAmounts);
- // 4. 更新订单状态
- $this->updateOrderRefundStatus($order);
- // 5. 记录退款操作
- $this->createRefundRecords($order, $refundAmounts);
- // 6. 通知相关方
- $this->notifyRefund($order);
- return ['message' => '退款申请成功'];
- } catch (Exception $e) {
- $this->logError('订单退款失败', $e, [
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证订单退款条件
- */
- private function validateOrderForRefund(int $orderId): Order
- {
- // 获取并锁定订单,防止并发操作
- $order = Order::where('id', $orderId)
- ->whereIn('state', [
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::DEPARTED->value,
- ])
- ->lockForUpdate()
- ->firstOrFail();
- // 验证当前用户是否为订单所有者
- $user = Auth::user();
- abort_if($order->user_id !== $user->id, 403, '无权操作此订单');
- // 检查订单是否已经退款
- abort_if($order->state === OrderStatus::REFUNDED->value, 400, '订单已退款');
- return $order;
- }
- /**
- * 计算退款金额
- */
- private function calculateRefundAmount(Order $order): array
- {
- // 计算违约金
- $penaltyAmount = $this->calculatePenaltyAmount($order);
- // 计算退款金额分配
- return $this->calculateRefundDistribution($order, $penaltyAmount);
- }
- /**
- * 处理退款操作
- */
- private function processRefund(Order $order, array $refundAmounts): void
- {
- // 处理余额退款部分
- if ($refundAmounts['balance_refund'] > 0) {
- $this->processBalanceRefund($order, $refundAmounts['balance_refund']);
- }
- // 处理支付退款部分
- if ($refundAmounts['payment_refund'] > 0) {
- $this->processPaymentRefund($order, $refundAmounts['payment_refund']);
- }
- }
- /**
- * 处理余额退款
- */
- private function processBalanceRefund(Order $order, float $amount): void
- {
- $wallet = $order->user->wallet;
- // 增加用户钱包总余额
- $wallet->increment('total_balance', $amount);
- // 增加可用余额
- $wallet->increment('available_balance', $amount);
- // 创建退款交易记录
- $wallet->transRecords()->create([
- 'amount' => $amount,
- 'trans_type' => TransactionType::REFUND->value, // 使用退款枚举值
- 'owner_type' => Order::class,
- 'owner_id' => $order->id,
- 'remark' => '订单退款',
- 'before_balance' => $wallet->total_balance - $amount,
- 'after_balance' => $wallet->total_balance,
- 'state' => TransactionStatus::SUCCESS->value, // 使用成功状态枚举值
- ]);
- }
- /**
- * 处理支付退款
- */
- private function processPaymentRefund(Order $order, float $amount): void
- {
- // TODO: 实现第三方支付退款逻辑
- // $paymentService = app(PaymentService::class);
- // $paymentService->refund($order->payment_no, $amount);
- }
- /**
- * 更新订单退款状态
- *
- * @param Order $order 订单对象
- * @return void
- */
- private function updateOrderRefundStatus(Order $order): void
- {
- // 根据支付方式更新订单状态
- if ($order->payment_type === PaymentMethod::BALANCE->value) {
- // 余额支付直接更新为退款成功
- $order->update([
- 'state' => OrderStatus::REFUNDED->value,
- 'refund_time' => now(),
- ]);
- // 创建退款成功记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDED->value,
- 'remark' => '退款成功'
- ]);
- } else {
- // 微信支付更新为退款中
- $order->update([
- 'state' => OrderStatus::REFUNDING->value
- ]);
- // 创建退款中记录
- $order->records()->create([
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '退款处理中'
- ]);
- }
- }
- /**
- * 创建退款记录
- */
- private function createRefundRecords(Order $order, array $refundAmounts): void
- {
- // 创建退款记录
- $refundRecord = $order->refundRecords()->create([
- 'total_refund_amount' => $refundAmounts['total_refund'],
- 'balance_refund_amount' => $refundAmounts['balance_refund'],
- 'payment_refund_amount' => $refundAmounts['payment_refund'],
- 'deduct_amount' => $refundAmounts['deduct_amount'],
- 'state' => 'success',
- 'remark' => '用户申请退款',
- ]);
- // 创建订单状态记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => Auth::id(),
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::REFUNDING->value,
- 'remark' => '订单退款中',
- ]);
- }
- /**
- * 发送退款通知
- */
- private function notifyRefund(Order $order): void
- {
- // TODO: 实现退款通知逻辑
- // 1. 通知用户
- // event(new OrderRefundedEvent($order));
- // 2. 通知技师
- if ($order->coach_id) {
- // event(new OrderRefundedToCoachEvent($order));
- }
- }
- /**
- * 获取代理商配置
- */
- public function getAgentConfig(int $agentId): array
- {
- $agent = AgentInfo::where('id', $agentId)
- ->where('state', 'enable')
- ->firstOrFail();
- // $config = AgentConfig::where('agent_id', $agentId)->firstOrFail();
- return [
- // 'min_distance' => $config->min_distance,
- // 'min_fee' => $config->min_fee,
- // 'per_km_fee' => $config->per_km_fee
- ];
- }
- /**
- * 获取技师配置
- */
- public function getCoachConfig(int $coachId): array
- {
- $coach = CoachUser::where('id', $coachId)
- ->where('state', 'enable')
- ->where('auth_state', 'passed')
- ->firstOrFail();
- // $config = CoachConfig::where('coach_id', $coachId)->firstOrFail();
- return [
- // 'delivery_fee_type' => $config->delivery_fee_type,
- // 'charge_delivery_fee' => $config->charge_delivery_fee
- ];
- }
- /**
- * 计算路费
- *
- * @param int $coachId 技师ID
- * @param int $projectId 项目ID
- * @param int|null $agentId 代理商ID
- * @param float $distance 距离(公里)
- * @return float 路费金额
- *
- * @throws \Exception
- */
- public function calculateDeliveryFee(
- int $coachId,
- int $projectId,
- ?int $agentId,
- float $distance
- ): float {
- try {
- // 1. 验证基础参数
- $this->validateDeliveryFeeParams($coachId, $projectId, $distance);
- // 2. 获取计费规则
- $feeRules = $this->getDeliveryFeeRules($coachId, $agentId);
- // 3. 算路费
- return $this->calculateFeeByRules($distance, $feeRules, $coachId, $projectId);
- } catch (Exception $e) {
- $this->logError('计算路费失败', $e, [
- 'coach_id' => $coachId,
- 'project_id' => $projectId,
- 'agent_id' => $agentId,
- 'distance' => $distance,
- ]);
- throw $e;
- }
- }
- /**
- * 验证路费计算参数
- */
- private function validateDeliveryFeeParams(int $coachId, int $projectId, float $distance): void
- {
- // 验证技师状态
- $coach = $this->validateCoach($coachId);
- // 验证项目状态
- $project = Project::where('id', $projectId)
- ->where('state', ProjectStatus::OPEN->value)
- ->firstOrFail();
- // 验证距离有效性
- abort_if($distance < 0, 400, '距离计算错误');
- }
- /**
- * 获取路费计算规则
- *
- * @return array{
- * min_distance: float,
- * min_fee: float,
- * per_km_fee: float,
- * max_distance: float,
- * max_fee: float,
- * free_distance: float
- * }
- */
- private function getDeliveryFeeRules(int $coachId, ?int $agentId): array
- {
- // 1. 获取系统默认规则
- $defaultRules = $this->getDefaultDeliveryFeeRules();
- // 2. 获取代理商规则(如果有)
- $agentRules = $agentId ? $this->getAgentDeliveryFeeRules($agentId) : [];
- // 3. 获取技师个性化规则
- // $coachRules = $this->getCoachDeliveryFeeRules($coachId);
- // 4. 合并规则,优先级:技师 > 代理商 > 系统默认
- return array_merge(
- $defaultRules,
- $agentRules,
- // $coachRules
- );
- }
- /**
- * 获取系统默认路费规则
- */
- private function getDefaultDeliveryFeeRules(): array
- {
- // TODO: 从配置表中获取系统默认路费规则
- return [
- 'min_distance' => 3.0, // 最小计费距离(公里)
- 'min_fee' => 10.0, // 最小路费(元)
- 'per_km_fee' => 3.0, // 每公里费用(元)
- 'max_distance' => 120.0, // 最大服务距离(公里)
- 'max_fee' => 50.0, // 最大路费(元)
- 'free_distance' => 1.0, // 免费服务距离(公里)
- ];
- }
- /**
- * 获取代理商路费规则
- */
- private function getAgentDeliveryFeeRules(int $agentId): array
- {
- // $agentConfig = AgentConfig::where('agent_id', $agentId)
- // ->where('state', 'enable')
- // ->first();
- // if (! $agentConfig) {
- // return [];
- // }
- // return [
- // 'min_distance' => $agentConfig->min_distance,
- // 'min_fee' => $agentConfig->min_fee,
- // 'per_km_fee' => $agentConfig->per_km_fee,
- // 'max_distance' => $agentConfig->max_distance,
- // 'max_fee' => $agentConfig->max_fee,
- // 'free_distance' => $agentConfig->free_distance,
- // ];
- return [];
- }
- /**
- * 获取技师路费规则
- */
- private function getCoachDeliveryFeeRules(int $coachId): array
- {
- // TODO: 从配置表中获取技师个性化路费规则
- // $coachConfig = CoachConfig::where('coach_id', $coachId)
- // ->where('state', 'enable')
- // ->first();
- $coachConfig = null;
- if (! $coachConfig) {
- return [];
- }
- // 如果技师设置了不收取路费
- if (! $coachConfig->charge_delivery_fee) {
- return [
- 'min_fee' => 0,
- 'per_km_fee' => 0,
- 'max_fee' => 0,
- ];
- }
- return [
- 'min_distance' => $coachConfig->min_distance,
- 'min_fee' => $coachConfig->min_fee,
- 'per_km_fee' => $coachConfig->per_km_fee,
- 'max_distance' => $coachConfig->max_distance,
- 'max_fee' => $coachConfig->max_fee,
- 'free_distance' => $coachConfig->free_distance,
- ];
- }
- /**
- * 根据规则计算路费
- *
- * @param float $distance 距离(公里)
- * @param array{
- * min_distance: float, // 最小计费距离(公里)
- * min_fee: float, // 小路费(元)
- * per_km_fee: float, // 每公里费用(元)
- * max_distance: float, // 最大服务距离(公里)
- * max_fee: float, // 最大路费(元)
- * free_distance: float // 免费服务距离(公里)
- * } $rules 计费规则
- * @param int $coachId 技师ID
- * @param int $projectId 项目ID
- * @return float 路费金额(元)
- */
- private function calculateFeeByRules(float $distance, array $rules, int $coachId, int $projectId): float
- {
- // 1. 获取技师项目路费设置
- $coachProject = DB::table('coach_project')
- ->where('coach_id', $coachId)
- ->where('project_id', $projectId)
- ->where('state', 1) // 启用状态
- ->first();
- // 2. 如果技师设置了免路费,直接返回技师设置的固定路费
- if ($coachProject && (int)$coachProject->traffic_fee_type === 0) {
- return 0.00;
- }
- // 3. 检查是否超出最大服务距离
- abort_if(
- $distance > $rules['max_distance'],
- 400,
- sprintf('超出最大服务距离 %.1f 公里', $rules['max_distance'])
- );
- // 4. 检查是否在免费距离内
- if ($distance <= $rules['free_distance']) {
- return 0.00;
- }
- // 5. 计算实际计费距离
- $chargeDistance = max(0, $distance - $rules['free_distance']);
- // 6. 检查是否达到最小计费距离
- if ($chargeDistance < $rules['min_distance']) {
- return $rules['min_fee'];
- }
- // 7. 计算基础路费
- $fee = bcmul($chargeDistance, $rules['per_km_fee'], 2);
- // 8. 应用最小路费限制
- $fee = max($fee, $rules['min_fee']);
- // 9. 应用最大路费限制
- $fee = min($fee, $rules['max_fee']);
- // 10. 如果技师设置了固定路费,使用技师设置的路费
- if ($coachProject && $coachProject->traffic_fee > 0) {
- $fee = (float)$coachProject->traffic_fee;
- }
- // 11. 根据路费类型计算(单程/双程)
- if ($coachProject && $coachProject->traffic_fee_type === 2) { // 2表示双程
- $fee = bcmul($fee, '2', 2); // 双程路费翻倍
- }
- return $fee;
- }
- /**
- * 计算两点之间的距离
- *
- * @param float $lat1 起点纬度
- * @param float $lng1 起点经度
- * @param float $lat2 终点纬度
- * @param float $lng2 终点经度
- * @return float 距离(公里)
- */
- private function getDistance(float $lat1, float $lng1, float $lat2, float $lng2): float
- {
- // 将角度转为弧度
- $radLat1 = deg2rad($lat1);
- $radLat2 = deg2rad($lat2);
- $radLng1 = deg2rad($lng1);
- $radLng2 = deg2rad($lng2);
- // 地球半径(公里)
- $earthRadius = 6371;
- // 计算距离
- $distance = acos(
- sin($radLat1) * sin($radLat2) +
- cos($radLat1) * cos($radLat2) * cos($radLng1 - $radLng2)
- ) * $earthRadius;
- // 保留2位小数
- return round($distance, 2);
- }
- /**
- * 计算订单金额
- *
- * @param int $userId 用户ID
- * @param int|null $addressId 地址ID
- * @param int|null $coachId 技师ID
- * @param int $projectId 项目ID
- * @param int|null $agentId 代理商ID
- * @param bool $useBalance 是否使用余额
- * @param float $distance 距离
- * @param float $lat 纬度
- * @param float $lng 经度
- * @return array{
- * total_amount: float,
- * balance_amount: float,
- * pay_amount: float,
- * coupon_amount: float,
- * project_amount: float,
- * delivery_fee: float
- * }
- *
- * @throws \Exception
- */
- public function calculateOrderAmount(
- int $userId,
- ?int $addressId,
- ?int $coachId,
- int $projectId,
- ?int $agentId = null,
- bool $useBalance = false,
- float $distance = 0,
- float $lat = 0,
- float $lng = 0
- ): array {
- try {
- // 1. 验证用户状态和权限
- $user = $this->validateUserForCalculation($userId);
- // 2. 获取项目信息和价格(包含代理价格)
- $project = $this->getProjectWithPrice($projectId, $agentId);
- // 3. 计算路费(如果有技师)
- $deliveryFee = $this->calculateDeliveryFeeForOrder(
- coachId: $coachId,
- projectId: $projectId,
- agentId: $agentId,
- distance: $distance,
- addressId: $addressId,
- lat: $lat,
- lng: $lng
- );
- // 4. 计算优惠金额(优惠券、活动等)
- $discountAmount = $this->calculateDiscountAmount($projectId, $userId);
- // 5. 计算订单总金额(项目价格 + 路费 - 优惠金额)
- $totalAmount = $this->calculateTotalAmount($project->price, $deliveryFee, $discountAmount);
- // 6. 处理余额支付分配(优先使用余额)
- $paymentAmounts = $this->calculatePaymentDistribution(
- user: $user,
- totalAmount: $totalAmount,
- useBalance: $useBalance
- );
- // 7. 返回计算结果
- return [
- 'total_amount' => $totalAmount, // 订单总金额
- 'balance_amount' => $paymentAmounts['balance_amount'], // 余额支付金额
- 'pay_amount' => $paymentAmounts['pay_amount'], // 需要支付金额
- 'coupon_amount' => $discountAmount, // 优惠金额
- 'project_amount' => $project->price, // 项目原价
- 'delivery_fee' => $deliveryFee, // 路费
- ];
- } catch (Exception $e) {
- // 记录错误日志
- $this->logError('计算订单金额失败', $e, [
- 'user_id' => $userId,
- 'project_id' => $projectId,
- 'coach_id' => $coachId,
- 'address_id' => $addressId,
- ]);
- throw $e;
- }
- }
- /**
- * 验证用户状态
- */
- private function validateUserForCalculation(int $userId): MemberUser
- {
- $user = MemberUser::with('wallet')
- ->where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->first();
- abort_if(! $user, 404, '用户不存在或状态异常');
- return $user;
- }
- /**
- * 获取项目信息和价格
- */
- private function getProjectWithPrice(int $projectId, ?int $agentId): Project
- {
- // 获取基础项目信息
- $project = Project::where('id', $projectId)
- ->where('state', ProjectStatus::OPEN->value)
- ->first();
- abort_if(! $project, 404, '项目不存在或状态异常');
- // 如果有代理商,获取代理商价格
- if ($agentId) {
- $agentProject = $this->getAgentProjectPrice($agentId, $projectId);
- if ($agentProject) {
- $project->price = $agentProject->price;
- }
- }
- return $project;
- }
- /**
- * 获取代理商项目价格
- */
- private function getAgentProjectPrice(int $agentId, int $projectId): ?object
- {
- return DB::table('agent_project')
- ->where('agent_id', $agentId)
- ->where('project_id', $projectId)
- ->where('state', 'enable')
- ->first();
- }
- /**
- * 计算订单路费
- */
- private function calculateDeliveryFeeForOrder(
- ?int $coachId,
- int $projectId,
- ?int $agentId,
- float $distance,
- ?int $addressId,
- ?float $lat,
- ?float $lng
- ): float {
- // 如果没有技师,无需计算路费
- if (! $coachId) {
- return 0;
- }
- if (! $addressId && ! $lat && ! $lng) {
- return 0;
- }
- // 如果距离为0,需要重新计算距离
- if ($distance <= 0) {
- $distance = $this->calculateDistance($coachId, $addressId, $lat, $lng);
- }
- return $this->calculateDeliveryFee($coachId, $projectId, $agentId, $distance);
- }
- /**
- * 获取技师位置信息
- */
- private function getCoachLocation(int $coachId): array
- {
- // 从技师服务获取最新位置信息
- $location = $this->coachService->getLocation($coachId);
- // 如果没有位置信息,返回系统默认位置
- if (empty($location)) {
- return [
- 'latitude' => config('business.default_latitude', 0),
- 'longitude' => config('business.default_longitude', 0),
- ];
- }
- // 格式化位置数据
- return [
- 'latitude' => (float) $location->latitude,
- 'longitude' => (float) $location->longitude,
- ];
- }
- /**
- * 计算技师与服务地址的距离
- */
- private function calculateDistance(int $coachId, int $addressId, float $lat, float $lng): float
- {
- try {
- // 如果提供了地址ID,优先使用地址表中的经纬度
- if ($addressId > 0) {
- $address = MemberAddress::find($addressId);
- // 使用地址的经纬度,如果没有则使用传入的经纬度
- $lat = $address?->latitude ?? $lat;
- $lng = $address?->longitude ?? $lng;
- }
- // 从Redis获取技师的两个位置点信息
- // 获取常用地址位置(如家庭地址)
- $homeLocation = Redis::geopos(
- 'coach_locations',
- $coachId . '_' . TechnicianLocationType::COMMON->value
- );
- // 获取当前实时位置
- $workLocation = Redis::geopos(
- 'coach_locations',
- $coachId . '_' . TechnicianLocationType::CURRENT->value
- );
- $distances = [];
- // 计算与常用地址的距离
- if ($homeLocation && $homeLocation[0]) {
- $distances[] = $this->getDistance($homeLocation[0][1], $homeLocation[0][0], $lat, $lng);
- }
- // 计算与当前位置的距离
- if ($workLocation && $workLocation[0]) {
- $distances[] = $this->getDistance($workLocation[0][1], $workLocation[0][0], $lat, $lng);
- }
- // 如果有有效距离,返回最小值;否则返回0
- return ! empty($distances) ? min($distances) : 0.0;
- } catch (\Exception $e) {
- Log::error('计算距离失败', [
- 'error' => $e->getMessage(),
- 'coach_id' => $coachId,
- 'address_id' => $addressId,
- 'lat' => $lat,
- 'lng' => $lng,
- ]);
- return 0.0;
- }
- }
- /**
- * 计算优惠金额
- */
- private function calculateDiscountAmount(int $projectId, int $userId): float
- {
- $discountAmount = 0;
- // TODO: 实现优惠券、活动等优惠计算逻辑
- return $discountAmount;
- }
- /**
- * 计算订单总金额
- */
- private function calculateTotalAmount(float $projectPrice, float $deliveryFee, float $discountAmount): float
- {
- $totalAmount = bcadd($projectPrice, $deliveryFee, 2);
- $totalAmount = bcsub($totalAmount, $discountAmount, 2);
- return max(0, $totalAmount);
- }
- /**
- * 计算支付金额分配
- *
- * @return array{balance_amount: float, pay_amount: float}
- */
- private function calculatePaymentDistribution(MemberUser $user, float $totalAmount, bool $useBalance): array
- {
- if (! $useBalance || $totalAmount <= 0) {
- return [
- 'balance_amount' => 0,
- 'pay_amount' => $totalAmount,
- ];
- }
- $availableBalance = $user->wallet?->available_balance ?? 0;
- if ($availableBalance >= $totalAmount) {
- return [
- 'balance_amount' => $totalAmount,
- 'pay_amount' => 0,
- ];
- }
- return [
- 'balance_amount' => $availableBalance,
- 'pay_amount' => bcsub($totalAmount, $availableBalance, 2),
- ];
- }
- /**
- * 获取订单抢单池列表
- *
- * @param int $orderId 订单ID
- * @return array 抢单池列表
- */
- public function getOrderGrabList(int $orderId): array
- {
- try {
- // 查询订单信息
- $order = Order::where('id', $orderId)
- ->whereIn('state', [OrderStatus::CREATED->value])
- ->firstOrFail();
- // 查询抢单池表
- $grabList = $order->grabRecords()->with(['coach.info'])->get();
- // 格式化返回数据
- $result = [];
- foreach ($grabList as $grab) {
- $coach = $grab->coach;
- // 计算路费
- $trafficAmount = $this->calculateDeliveryFee(
- coachId: $coach->id,
- projectId: $order->project_id,
- agentId: $order->agent_id,
- distance: $grab->distance
- );
- $result[] = [
- 'id' => $grab->id,
- 'coach_id' => $coach->id,
- 'nickname' => $coach->info->nickname,
- 'avatar' => $coach->info->avatar,
- 'distance' => $grab->distance,
- 'traffic_amount' => $trafficAmount,
- 'created_at' => $grab->created_at->format('Y-m-d H:i:s'),
- ];
- }
- return $result;
- } catch (\Exception $e) {
- Log::error('获取订单抢单池列表失败', [
- 'error' => $e->getMessage(),
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- }
- /**
- * 指定技师
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @param int $coachId 技师ID
- * @param int $payment_type 支付类型
- * @return array{
- * order_id: int,
- * order_no: string,
- * total_amount: float,
- * balance_amount: float,
- * pay_amount: float,
- * wx_config?: array
- * }
- * @throws \Exception
- */
- public function assignCoach(int $userId, int $orderId, int $coachId, int $payment_type, ?float $distance = null): array|bool
- {
- return DB::transaction(function () use ($userId, $orderId, $coachId, $payment_type, $distance) {
- try {
- // 1. 验证参数
- $order = $this->validateAssignOrder($userId, $orderId);
- // 2. 验证技师
- $coach = $this->validateCoach($coachId);
- // 3. 检查抢单池状态
- $this->validateGrabPool($order);
- // 4. 更新订单信息
- $this->updateOrderForAssign($order, $coachId);
- // 5. 创建订单记录(指派)
- $this->createAssignRecord($order, $userId, $coachId);
- if (! is_null($payment_type)) {
- $order->payment_type = $payment_type;
- // 2. 计算订单金额
- $amounts = $this->calculateOrderAmount(
- userId: $userId,
- addressId: $order->address_id ?? null,
- coachId: $coachId ?? null,
- projectId: $order->project_id,
- agentId: $order->agent_id ?? null,
- useBalance: $order->payment_type === PaymentMethod::BALANCE->value ? true : false,
- distance: $distance ?? 0
- );
- $order->fill([
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- 'discount_amount' => $amounts['coupon_amount'],
- 'project_amount' => $amounts['project_amount'],
- 'traffic_amount' => $amounts['delivery_fee'],
- ]);
- $order->save();
- }
- $result = [
- 'order_id' => $order->id,
- 'order_no' => $order->order_no,
- 'total_amount' => $order->total_amount,
- 'balance_amount' => $order->balance_amount,
- 'pay_amount' => $order->pay_amount,
- ];
- // 6. 处理支付
- if ((int)$order->payment_type === PaymentMethod::BALANCE->value) {
- $this->handleBalancePaymentForAssign($order, $userId, $coachId);
- // 7. 删除订单位置的Redis记录
- Redis::zrem('order_locations', 'order_' . $order->id);
- } else if ((int)$order->payment_type === PaymentMethod::WECHAT->value) {
- // 获取微信支付配置
- $paymentService = app(PaymentService::class);
- $result['wx_payment'] = $paymentService->getPaymentConfig($order->id);
- }
- // 8. 发送通知
- $this->notifyAssignment($order, $coach);
- return $result;
- } catch (\Exception $e) {
- Log::error('指定技师失败', [
- 'error' => $e->getMessage(),
- 'order_id' => $orderId,
- 'coach_id' => $coachId,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证指定技师的订单条件
- */
- private function validateAssignOrder(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- // 验证订单状态
- $order = $user->orders()
- ->where('id', $orderId)
- ->whereIn('state', [OrderStatus::CREATED->value, OrderStatus::PAID->value])
- ->lockForUpdate()
- ->firstOrFail();
- return $order;
- }
- /**
- * 验证抢单池状态
- */
- private function validateGrabPool(Order $order): void
- {
- // 检查抢单池是否已有抢单成功记录
- $existsGrabSuccess = $order->grabRecords()
- ->where('state', OrderGrabRecordStatus::SUCCEEDED->value)
- ->exists();
- abort_if($existsGrabSuccess, 400, '该订单已抢单完成');
- }
- /**
- * 更新订单信息
- */
- private function updateOrderForAssign(Order $order, int $coachId): void
- {
- // 修改订单技师
- $order->coach_id = $coachId;
- // 待支付订单需要重新计算金额
- if ($order->state === OrderStatus::CREATED->value) {
- $amounts = $this->calculateOrderAmount(
- userId: $order->user_id,
- addressId: $order->address_id,
- coachId: $coachId,
- projectId: $order->project_id,
- agentId: $order->agent_id,
- useBalance: $order->payment_type === PaymentMethod::BALANCE->value
- );
- // 更新订单金额
- $order->fill([
- 'total_amount' => $amounts['total_amount'],
- 'balance_amount' => $amounts['balance_amount'],
- 'pay_amount' => $amounts['pay_amount'],
- 'discount_amount' => $amounts['coupon_amount'],
- 'project_amount' => $amounts['project_amount'],
- 'traffic_amount' => $amounts['delivery_fee'],
- ]);
- }
- $order->save();
- }
- /**
- * 处理指派订单的余额支付
- */
- private function handleBalancePaymentForAssign(Order $order, int $userId, int $coachId): void
- {
- // 验证余额
- $user = MemberUser::find($userId);
- $wallet = $user->wallet;
- abort_if($wallet->available_balance < $order->balance_amount, 400, '可用余额不足');
- // 扣除余额
- DB::transaction(function () use ($wallet, $order, $userId, $coachId) {
- // 更新钱包余额
- $wallet->decrement('total_balance', $order->balance_amount);
- $wallet->decrement('available_balance', $order->balance_amount);
- // 增加总支出
- $wallet->increment('total_expense', $order->balance_amount);
- // 更新订单状态
- $order->update(['state' => OrderStatus::PAID->value]);
- // 创建钱包支付记录
- $this->createWalletPaymentRecord($order, $wallet);
- // 创建支付成功记录
- $this->createPaymentSuccessRecord($order, $userId);
- // 更新抢单记录
- $this->updateGrabRecords($order->id, $coachId);
- // 更新订单状态为已接单
- $order->update(['state' => OrderStatus::ACCEPTED->value]);
- });
- }
- /**
- * 创建钱包支付记录
- */
- private function createWalletPaymentRecord(Order $order, $wallet): void
- {
- WalletPaymentRecord::create([
- 'order_id' => $order->id,
- 'wallet_id' => $wallet->id,
- 'payment_no' => 'B_' . $order->id,
- 'payment_method' => 'balance',
- 'total_amount' => $order->balance_amount,
- 'actual_amount' => 0,
- 'used_wallet_balance' => $order->balance_amount,
- 'used_recharge_balance' => 0,
- 'state' => 1,
- ]);
- }
- /**
- * 创建支付成功记录
- */
- private function createPaymentSuccessRecord(Order $order, int $userId): void
- {
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::PAID->value,
- 'remark' => '余额支付成功',
- ]);
- }
- /**
- * 更新抢单记录
- */
- private function updateGrabRecords(int $orderId, int $coachId): void
- {
- OrderGrabRecord::where('order_id', $orderId)
- ->update([
- 'state' => OrderGrabRecordStatus::SUCCEEDED->value,
- 'coach_id' => $coachId,
- ]);
- }
- /**
- * 发送指派通知
- */
- private function notifyAssignment(Order $order, CoachUser $coach): void
- {
- // TODO: 实现通知逻辑
- // event(new OrderAssignedEvent($order, $coach));
- }
- /**
- * 生成订单核销码
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array{
- * order_id: int,
- * qr_code: string,
- * qr_image: ?string,
- * expired_at: string,
- * state: string
- * } 返回核销码信息
- *
- * @throws \Exception
- */
- public function generateVerificationCode(int $userId, int $orderId): array
- {
- try {
- // 验证订单状态和归属
- $order = $this->validateOrderForVerification($userId, $orderId);
- // 生成核销码数据
- $verificationData = $this->generateVerificationData($order->id);
- // 生成二维码图片
- $qrCodeImage = $this->generateQRCodeImage($verificationData['qr_code']);
- return [
- 'order_id' => $order->id,
- 'qr_code' => $verificationData['qr_code'],
- 'qr_image' => $qrCodeImage,
- 'expired_at' => $verificationData['expired_at'],
- 'state' => $order->state,
- ];
- } catch (Exception $e) {
- $this->logError('生成订单核销码失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- ]);
- throw $e;
- }
- }
- /**
- * 验证订单状态和归属
- */
- private function validateOrderForVerification(int $userId, int $orderId): Order
- {
- // 验证用户状态
- $user = MemberUser::where('id', $userId)
- ->where('state', UserStatus::OPEN->value)
- ->firstOrFail();
- // 验证订单状态和归属
- $order = $user->orders()
- ->where('id', $orderId)
- ->whereIn('state', [
- OrderStatus::PAID->value,
- OrderStatus::ACCEPTED->value,
- OrderStatus::DEPARTED->value,
- OrderStatus::ARRIVED->value,
- ])
- ->firstOrFail();
- return $order;
- }
- /**
- * 生成核销码数据
- *
- * @param int $orderId 订单ID
- * @return array{qr_code: string, expired_at: string}
- */
- private function generateVerificationData(int $orderId): array
- {
- // 生成时间戳
- $timestamp = time();
- // 生成签名
- $sign = md5("order_{$orderId}_{$timestamp}_" . config('app.key'));
- // 组装二维码内容
- $qrCode = "order_{$orderId}_{$timestamp}_{$sign}";
- return [
- 'qr_code' => $qrCode,
- 'expired_at' => date('Y-m-d H:i:s', $timestamp + 300), // 5分钟有效期
- ];
- }
- /**
- * 生成二维码图片
- *
- * @param string $content 二维码内容
- * @return string|null Base64编码的图片数据
- */
- private function generateQRCodeImage(string $content): ?string
- {
- // 生成SVG格式的二维码
- $qrCodeImage = QrCode::format('svg')
- ->size(200) // 设置二维码大小为200px
- ->margin(1) // 设置二维码边距为1
- ->errorCorrection('H') // 设置纠错级别为最高级别H
- ->generate($content);
- // 将SVG转为base64
- return 'data:image/svg+xml;base64,' . base64_encode($qrCodeImage);
- }
- /**
- * 验证技师服务时间是否可用
- */
- public function validateServiceTime(int $coachId, string $serviceTime): bool
- {
- try {
- // 1. 验证基础参数(技师状态、时间格式等)
- $this->validateServiceTimeParams($coachId, $serviceTime);
- // 2. 获取技师工作时间安排
- $workSchedule = $this->getCoachWorkSchedule($coachId);
- // 3. 验证是否在工作时间内
- $this->validateWorkingHours($serviceTime, $workSchedule);
- // 4. 检查是否与其他订单时间冲突
- $this->checkTimeConflicts($coachId, $serviceTime);
- return true;
- } catch (Exception $e) {
- // 记录错误日志
- $this->logError('验证服务时间失败', $e, [
- 'coach_id' => $coachId,
- 'service_time' => $serviceTime,
- ]);
- throw $e;
- }
- }
- /**
- * 检查订单时间冲突
- */
- private function checkTimeConflicts(int $coachId, string $serviceTime): void
- {
- $serviceDateTime = Carbon::parse($serviceTime);
- // 获取服务时长配置(默认2小时)
- $serviceDuration = config('business.default_service_duration', 120);
- // 计算本次服务的结束时间
- $serviceEndTime = $serviceDateTime->copy()->addMinutes($serviceDuration);
- // 检查是否与其他订单时间重叠
- $conflictOrder = Order::where('coach_id', $coachId)
- ->whereIn('state', [
- OrderStatus::PAID->value, // 已支付
- OrderStatus::ACCEPTED->value, // 已接单
- OrderStatus::SERVICING->value, // 服务中
- ])
- ->where(function ($query) use ($serviceDateTime, $serviceEndTime) {
- $query->where(function ($q) use ($serviceDateTime) {
- // 检查服务开始时间是否冲突
- $q->where('service_time', '<=', $serviceDateTime)
- ->where('service_end_time', '>', $serviceDateTime);
- })->orWhere(function ($q) use ($serviceEndTime) {
- // 检查服务结束时间是否冲突
- $q->where('service_time', '<', $serviceEndTime)
- ->where('service_end_time', '>=', $serviceEndTime);
- });
- })
- ->first();
- // 如果存在时间冲突,抛出异常
- abort_if(
- $conflictOrder,
- 400,
- '该时间段技师已有其他订单'
- );
- }
- /**
- * 订单评价
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @param array{
- * score: int,
- * content: string,
- * images: ?array,
- * tags: ?array
- * } $data 评价数据
- * @return array{message: string}
- *
- * @throws \Exception
- */
- public function evaluateOrder(int $userId, int $orderId, array $data): array
- {
- return DB::transaction(function () use ($userId, $orderId, $data) {
- try {
- // 1. 验证订单状态
- $order = $this->validateOrderForEvaluation($userId, $orderId);
- // 2. 创建评价记录
- $evaluation = $this->createEvaluation($order, $data);
- // 3. 更新技师评分
- // TODO: 更新技师评分
- $this->updateCoachScore($order->coach_id);
- // 4. 更新订单状态
- $this->updateOrderEvaluationStatus($order);
- // 5. 创建评价奖励
- // TODO: 创建评价奖励
- // $this->createEvaluationReward($order, $evaluation);
- // 6. 发送评价通知
- // $this->notifyEvaluation($order, $evaluation);
- return ['message' => '评价成功'];
- } catch (Exception $e) {
- $this->logError('订单评价失败', $e, [
- 'user_id' => $userId,
- 'order_id' => $orderId,
- 'data' => $data,
- ]);
- throw $e;
- }
- });
- }
- /**
- * 验证订单评价条件
- */
- private function validateOrderForEvaluation(int $userId, int $orderId): Order
- {
- // 获取订单信息
- $order = Order::where('id', $orderId)
- ->where('user_id', $userId)
- ->where('state', OrderStatus::LEFT->value)
- ->firstOrFail();
- // 检查是否已评价
- abort_if(
- $order->evaluation()->exists(),
- 400,
- '订单已评价'
- );
- // 检查评价时效(7天内可评价)
- $evaluationExpireDays = config('business.evaluation_expire_days', 7);
- abort_if(
- $order->finish_time->addDays($evaluationExpireDays)->isPast(),
- 400,
- '评价已过期'
- );
- return $order;
- }
- /**
- * 更新订单评价状态
- */
- private function updateOrderEvaluationStatus(Order $order): void
- {
- // 创建订单记录
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $order->user_id,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::EVALUATED->value,
- 'remark' => '用户评价完成',
- ]);
- }
- /**
- * 创建评价奖励
- */
- // private function createEvaluationReward(Order $order, OrderEvaluation $evaluation): void
- // {
- // // 获取评价奖励配置
- // $rewardAmount = config('business.evaluation_reward_amount', 0);
- // if ($rewardAmount <= 0) {
- // return;
- // }
- // // 更新用户钱包
- // $wallet = $order->user->wallet;
- // $wallet->increment('total_balance', $rewardAmount);
- // $wallet->increment('available_balance', $rewardAmount);
- // // 创建奖励记录
- // $wallet->transRecords()->create([
- // 'amount' => $rewardAmount,
- // 'trans_type' => 'evaluation_reward',
- // 'owner_type' => OrderEvaluation::class,
- // 'owner_id' => $evaluation->id,
- // 'remark' => '评价奖励',
- // 'before_balance' => $wallet->total_balance - $rewardAmount,
- // 'after_balance' => $wallet->total_balance,
- // 'state' => 'success',
- // ]);
- // }
- /**
- * 发送评价通知
- */
- // private function notifyEvaluation(Order $order, OrderEvaluation $evaluation): void
- // {
- // // TODO: 实现评价通知逻辑
- // // 1. 通知技师
- // // event(new OrderEvaluatedEvent($order, $evaluation));
- // // 2. 更新评价缓存
- // // Cache::tags(['coach_evaluations'])->forget("coach:{$order->coach_id}");
- // }
- private function getNearbyCoaches(float $lat, float $lng, float $radius = 5.0): Collection
- {
- // 获取在线技师列表
- return CoachUser::query()
- ->with(['info'])
- ->where('state', TechnicianStatus::ACTIVE->value)
- ->whereHas('info', fn($q) => $q->where('state', TechnicianAuthStatus::PASSED->value))
- ->get();
- }
- private function validateCoachForGrab(int $coachId): CoachUser
- {
- $coach = CoachUser::query()
- ->with(['info'])
- ->where('id', $coachId)
- ->where('state', TechnicianStatus::ACTIVE->value)
- ->first();
- abort_if(! $coach, 400, '技师不存在或未激活');
- // 验证技师认证状态
- abort_if(
- ! $coach->info || $coach->info->state !== TechnicianAuthStatus::PASSED->value,
- 400,
- '技师未通过认证'
- );
- return $coach;
- }
- public function getOrder(int $orderId): Order
- {
- $order = Order::find($orderId);
- abort_if(! $order, 404, '订单不存在');
- return $order;
- }
- private function findOrder(int $orderId): Order
- {
- $order = Order::find($orderId);
- abort_if(! $order, 404, sprintf('订单[%d]不存在', $orderId));
- return $order;
- }
- private function getOrderForPayment(int $orderId): Order
- {
- $order = Order::where('id', $orderId)
- ->whereIn('state', [OrderStatus::CREATED->value])
- ->first();
- abort_if(! $order, 404, sprintf('订单[%d]不存在', $orderId));
- abort_if(
- $order->state !== OrderStatus::CREATED->value,
- 422,
- sprintf('订单[%d]状态为[%s],不允许支付', $orderId, $order->state)
- );
- return $order;
- }
- /**
- * 评价订单
- *
- * @param int $userId 用户ID
- * @param array $data 评价数据
- */
- public function rateOrder(int $userId, array $data): void
- {
- // 查找订单并加载关联数据
- $order = Order::query()
- ->where('user_id', $userId)
- ->where('id', $data['order_id'])
- ->first();
- // 检查订单是否存在
- abort_if(!$order, 404, sprintf('订单[%d]不存在', $data['order_id']));
- // 检查订单是否属于当前用户
- abort_if((int)$order->user_id !== $userId, 403, '无权评价此订单');
- // 检查订单状态 - 确保类型一致性比较
- abort_if((int)$order->state !== OrderStatus::LEFT->value, 400, sprintf('订单状态为[%s],不允许评价', $order->state));
- // 检查是否已评价
- abort_if($order->comments()->exists(), 400, '订单已评价');
- // 验证评分范围
- foreach (['service_score', 'appearance_score', 'attitude_score', 'professional_score'] as $scoreField) {
- if (isset($data[$scoreField])) {
- $score = (float)$data[$scoreField];
- abort_if($score < 1 || $score > 5, 400, '评分范围必须在1-5之间');
- }
- }
- DB::transaction(function () use ($order, $data, $userId) {
- // 创建评价记录
- $comment = $order->comments()->create([
- 'user_id' => $userId,
- 'coach_id' => $order->coach_id,
- 'service_score' => isset($data['service_score']) ? (float)$data['service_score'] : 5.0,
- 'appearance_score' => isset($data['appearance_score']) ? (float)$data['appearance_score'] : 5.0,
- 'attitude_score' => isset($data['attitude_score']) ? (float)$data['attitude_score'] : 5.0,
- 'professional_score' => isset($data['professional_score']) ? (float)$data['professional_score'] : 5.0,
- 'tags' => $data['tags'] ?? [],
- 'content' => $data['content'] ?? '',
- 'images' => $data['images'] ?? [],
- ]);
- // 更新订单状态为已完成
- $order->update(['state' => OrderStatus::COMPLETED->value]);
- // 更新技师评分
- $this->updateCoachScore($order->coach_id);
- // 记录订单状态变更
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'state' => OrderRecordStatus::EVALUATED->value,
- 'remark' => '用户完成评价',
- ]);
- });
- }
- /**
- * 更新技师评分
- *
- * @param int $coachId 技师ID
- */
- private function updateCoachScore(int $coachId): void
- {
- $coach = CoachUser::find($coachId);
- if (!$coach) {
- return;
- }
- // 计算技师的各维度平均分
- $avgScores = DB::table('order_comments')
- ->where('coach_id', $coachId)
- ->whereExists(function ($query) {
- $query->select(DB::raw(1))
- ->from('order')
- ->whereColumn('order_comments.order_id', 'order.id')
- ->where('order.state', OrderStatus::COMPLETED->value);
- })
- ->select([
- DB::raw('AVG(service_score) as avg_service_score'),
- DB::raw('AVG(appearance_score) as avg_appearance_score'),
- DB::raw('AVG(attitude_score) as avg_attitude_score'),
- DB::raw('AVG(professional_score) as avg_professional_score'),
- DB::raw('COUNT(*) as total_comments')
- ])
- ->first();
- // 获取订单统计
- $orderCounts = DB::table('order')
- ->where('coach_id', $coachId)
- ->select([
- DB::raw('COUNT(*) as total_orders'),
- DB::raw('COUNT(CASE WHEN state = ' . OrderStatus::COMPLETED->value . ' THEN 1 END) as completed_orders')
- ])
- ->first();
- if ($avgScores) {
- // 计算总体平均分
- $overallScore = round(($avgScores->avg_service_score +
- $avgScores->avg_appearance_score +
- $avgScores->avg_attitude_score +
- $avgScores->avg_professional_score) / 4, 1);
- // 更新或创建统计记录
- CoachStatistic::updateOrCreate(
- ['coach_id' => $coachId],
- [
- 'score' => $overallScore,
- 'service_score' => round($avgScores->avg_service_score, 1),
- 'appearance_score' => round($avgScores->avg_appearance_score, 1),
- 'attitude_score' => round($avgScores->avg_attitude_score, 1),
- 'professional_score' => round($avgScores->avg_professional_score, 1),
- 'comment_count' => $avgScores->total_comments,
- 'order_count' => $orderCounts->total_orders,
- 'completed_order_count' => $orderCounts->completed_orders
- ]
- );
- }
- }
- /**
- * 生成退款单号
- * 格式:RF + 年月日时分秒 + 订单ID后4位 + 4位随机数
- * 示例:RF202403151428120001RAND
- *
- * @param Order $order 订单对象
- * @return string 退款单号
- */
- private function generateRefundNo(Order $order): string
- {
- // 获取时间戳
- $timestamp = now()->format('YmdHis');
- // 获取订单ID后4位,不足4位前面补0
- $orderIdSuffix = str_pad(substr($order->id, -4), 4, '0', STR_PAD_LEFT);
- // 生成4位随机数
- $random = str_pad(random_int(0, 9999), 4, '0', STR_PAD_LEFT);
- // 组合退款单号:前缀 + 时间戳 + 订单ID后缀 + 随机数
- return "RF{$timestamp}{$orderIdSuffix}{$random}";
- }
- /**
- * 用户删除订单
- *
- * 业务逻辑:
- * 1. 验证订单是否存在且属于当前用户
- * 2. 验证订单状态是否允许删除(已完成、已取消等)
- * 3. 更新订单的user_deleted_at字段
- * 4. 记录删除操作
- *
- * @param int $userId 用户ID
- * @param int $orderId 订单ID
- * @return array
- * @throws \Exception
- */
- public function deleteOrder(int $userId, int $orderId): array
- {
- return DB::transaction(function () use ($userId, $orderId) {
- // 验证订单是否存在且属于当前用户
- $order = Order::where('id', $orderId)
- ->where('user_id', $userId)
- ->whereNull('user_deleted_at') // 确保订单未被用户删除
- ->first();
- abort_if(!$order, 404, '订单不存在');
- // 验证订单状态是否允许删除
- // 允许删除未支付、已完成、已取消、已退款等状态的订单
- $allowedStates = [
- OrderStatus::CREATED->value, // 未支付
- OrderStatus::COMPLETED->value, // 已完成
- OrderStatus::CANCELLED->value, // 已取消
- OrderStatus::REFUNDED->value, // 已退款
- ];
- abort_if(!in_array($order->state, $allowedStates), 422, '当前订单状态不允许删除');
- // 标记订单为用户已删除
- $order->update([
- 'user_deleted_at' => now()
- ]);
- // 创建订单记录
- $this->createOrderRecord(
- $order,
- $userId,
- 'user',
- OrderRecordStatus::DELETED,
- '用户删除订单'
- );
- return [
- 'message' => '订单删除成功'
- ];
- });
- }
- /**
- * 获取评价标签列表
- *
- * @return array
- */
- public function getCommentTags(): array
- {
- return OrderCommentTag::query()
- ->where('state', 1)
- ->get(['id', 'tag_name'])
- ->toArray();
- }
- /**
- * 创建订单指派记录
- *
- * @param Order $order 订单对象
- * @param int $userId 操作用户ID
- * @return void
- */
- private function createAssignRecord(Order $order, int $userId, int $coachId): void
- {
- OrderRecord::create([
- 'order_id' => $order->id,
- 'object_id' => $userId,
- 'object_type' => MemberUser::class,
- 'new_coach_id' => $coachId,
- 'state' => OrderRecordStatus::ASSIGNED->value,
- 'remark' => '用户指定技师',
- ]);
- }
- }
|