12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233 |
- <?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 App\Models\CoachSchedule;
- 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::find($userId);
- abort_if(!$user, 404, '用户不存在');
- abort_if($user->state !== UserStatus::OPEN->value, 400, '用户状态异常');
- // 验证项目状态
- $project = Project::find($data['project_id']);
- abort_if(!$project, 404, '服务项目不存在');
- abort_if($project->state != ProjectStatus::OPEN->value, 403, '服务项目未开放');
- // 验证服务时间和技师状态
- if (!empty($data['service_time']) && !empty($data['coach_id'])) {
- // 验证技师排班和时间冲突
- $this->validateServiceTime($data['coach_id'], $data['service_time'], $project->duration);
- }
- // 验证地址信息
- if (!empty($data['address_id'])) {
- $address = DB::table('member_address')
- ->where('id', $data['address_id'])
- ->where('user_id', $userId)
- ->first();
- abort_if(!$address, 404, '地址不存在');
- }
- }
- /**
- * 创建订单数据
- */
- 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);
- }
- /**
- * 订单评价
- *
- * @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' => '用户指定技师',
- ]);
- }
- }
|