StoreOrder.php 224 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756
  1. <<<<<<< HEAD
  2. <?php
  3. /**
  4. *
  5. * @author: xaboy<365615158@qq.com>
  6. * @day: 2017/12/20
  7. */
  8. namespace app\models\store;
  9. use app\admin\model\system\ShippingTemplatesFree;
  10. use app\admin\model\system\ShippingTemplatesRegion;
  11. use app\admin\model\system\SystemAdmin;
  12. use app\admin\model\system\SystemStorePoint;
  13. use crmeb\basic\BaseModel;
  14. use think\db\exception\DataNotFoundException;
  15. use think\db\exception\DbException;
  16. use think\db\exception\ModelNotFoundException;
  17. use think\facade\Cache;
  18. use crmeb\traits\ModelTrait;
  19. use think\facade\Log;
  20. use app\models\system\SystemStore;
  21. use app\models\routine\RoutineTemplate;
  22. use think\Model;
  23. use app\models\user\{User, UserAddress, UserBill, UserSpread, WechatUser};
  24. use crmeb\services\{MiniProgramService,
  25. OtherSMSService,
  26. SystemConfigService,
  27. WechatTemplateService,
  28. workerman\ChannelService
  29. };
  30. use crmeb\repositories\{
  31. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  32. };
  33. use app\admin\model\system\ShippingTemplates;
  34. /**
  35. * TODO 订单Model
  36. * Class StoreOrder
  37. * @package app\models\store
  38. */
  39. class StoreOrder extends BaseModel
  40. {
  41. /**
  42. * 数据表主键
  43. * @var string
  44. */
  45. protected $pk = 'id';
  46. /**
  47. * 模型名称
  48. * @var string
  49. */
  50. protected $name = 'store_order';
  51. use ModelTrait;
  52. protected $insert = ['add_time'];
  53. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付'];
  54. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  55. protected function setAddTimeAttr()
  56. {
  57. return time();
  58. }
  59. protected function setCartIdAttr($value)
  60. {
  61. return is_array($value) ? json_encode($value) : $value;
  62. }
  63. protected function getCartIdAttr($value)
  64. {
  65. return json_decode($value, true);
  66. }
  67. /**获取订单组信息
  68. * @param $cartInfo
  69. * @return array
  70. */
  71. public static function getOrderPriceGroup($cartInfo, $addr, $store_id = 0)
  72. {
  73. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  74. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  75. $totalIntegral = self::getOrderSumPrice($cartInfo, 'integral');//获取订单总金额
  76. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  77. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  78. $totalDeposit = self::getOrderSumPrice($cartInfo, 'deposit');//获取订单会员优惠金额
  79. //如果满额包邮等于0
  80. if (!$storeFreePostage) {
  81. $storePostage = 0;
  82. } else {
  83. if ($addr) {
  84. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  85. $temp_num = [];
  86. foreach ($cartInfo as $cart) {
  87. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  88. if (!$temp) $temp = ShippingTemplates::get(1);
  89. if ($temp->getData('type') == 1) {
  90. $num = $cart['cart_num'];
  91. } elseif ($temp->getData('type') == 2) {
  92. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  93. } else {
  94. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  95. }
  96. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  97. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  98. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  99. if (!$region) {
  100. return self::setErrorInfo('运费模板不存在');
  101. }
  102. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  103. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  104. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  105. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  106. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  107. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  108. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  109. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  110. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  111. } else {
  112. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  113. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  114. }
  115. }
  116. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  117. $type = $storePostage = 0;
  118. foreach ($temp_num as $k => $v) {
  119. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  120. unset($temp_num[$k]);
  121. }
  122. }
  123. foreach ($temp_num as $v) {
  124. if ($type == 0) {
  125. if ($v['number'] <= $v['first']) {
  126. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  127. } else {
  128. if ($v['continue'] <= 0) {
  129. $storePostage = $storePostage;
  130. } else {
  131. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  132. }
  133. }
  134. $type = 1;
  135. } else {
  136. if ($v['continue'] <= 0) {
  137. $storePostage = $storePostage;
  138. } else {
  139. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  140. }
  141. }
  142. }
  143. } else {
  144. $storePostage = 0;
  145. }
  146. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  147. }
  148. if (!$store_id || !$addr) {
  149. $storePostageSh = 0;
  150. } else {
  151. $store = SystemStore::verificWhere()->find($store_id);
  152. $distance = getDistance($addr['latitude'], $addr['longitude'], $store['latitude'], $store['longitude']);
  153. //如果满额包邮等于0
  154. if (!$distance) {
  155. $storePostageSh = 0;
  156. } else {
  157. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  158. $storePostageSh = $store['sh_start_money'];
  159. if ($distance > $store['sh_start_distance']) {
  160. if ($store['sh_step'] > 0) {
  161. $steps = ceil(($distance - $store['sh_start_distance']) / $store['sh_step']);
  162. $storePostageSh = bcadd($storePostageSh, bcmul($steps, $store['sh_step_money'], 2), 2);
  163. }
  164. }
  165. }
  166. }
  167. return compact('storePostageSh', 'totalDeposit', 'storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral');
  168. }
  169. /**获取某个字段总金额
  170. * @param $cartInfo
  171. * @param $key 键名
  172. * @return int|string
  173. */
  174. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  175. {
  176. $SumPrice = 0;
  177. foreach ($cartInfo as $cart) {
  178. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  179. }
  180. return $SumPrice;
  181. }
  182. /**
  183. * 拼团
  184. * @param $cartInfo
  185. * @return array
  186. */
  187. public static function getCombinationOrderPriceGroup($cartInfo)
  188. {
  189. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  190. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  191. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  192. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  193. if (!$storeFreePostage) {
  194. $storePostage = 0;
  195. } else {
  196. foreach ($cartInfo as $cart) {
  197. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  198. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  199. }
  200. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  201. }
  202. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  203. }
  204. /**
  205. * 拼团价格
  206. * @param $cartInfo
  207. * @return float
  208. */
  209. public static function getCombinationOrderTotalPrice($cartInfo)
  210. {
  211. $totalPrice = 0;
  212. foreach ($cartInfo as $cart) {
  213. if ($cart['combination_id']) {
  214. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  215. }
  216. }
  217. return (float)$totalPrice;
  218. }
  219. /**
  220. * 缓存订单信息
  221. * @param $uid
  222. * @param $cartInfo
  223. * @param $priceGroup
  224. * @param array $other
  225. * @param int $cacheTime
  226. * @return string
  227. * @throws \Psr\SimpleCache\InvalidArgumentException
  228. */
  229. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  230. {
  231. do {
  232. $key = md5(time() . rand(100000, 999999));
  233. } while (Cache::has('user_order_' . $uid . $key));
  234. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  235. return $key;
  236. }
  237. /**
  238. * 获取订单缓存信息
  239. * @param $uid
  240. * @param $key
  241. * @return mixed|null
  242. * @throws \Psr\SimpleCache\InvalidArgumentException
  243. */
  244. public static function getCacheOrderInfo($uid, $key)
  245. {
  246. $cacheName = 'user_order_' . $uid . $key;
  247. if (!Cache::has($cacheName)) return null;
  248. return Cache::get($cacheName);
  249. }
  250. /**
  251. * 删除订单缓存
  252. * @param $uid
  253. * @param $key
  254. */
  255. public static function clearCacheOrderInfo($uid, $key)
  256. {
  257. Cache::delete('user_order_' . $uid . $key);
  258. }
  259. /**
  260. * 生成订单
  261. * @param $uid
  262. * @param $key
  263. * @param $addressId
  264. * @param $payType
  265. * @param bool $useIntegral
  266. * @param int $couponId
  267. * @param string $mark
  268. * @param int $combinationId
  269. * @param int $pinkId
  270. * @param int $seckill_id
  271. * @param int $bargain_id
  272. * @param bool $test
  273. * @param int $isChannel
  274. * @param int $shipping_type
  275. * @param string $real_name
  276. * @param string $phone
  277. * @return StoreOrder|bool|\think\Model
  278. * @throws \think\Exception
  279. * @throws DataNotFoundException
  280. * @throws ModelNotFoundException
  281. * @throws \think\exception\DbException
  282. */
  283. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $integral_id = 0, $exchange_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0, $pointId = 0, $store_order = 0, $free_check = 0, $time_area = '')
  284. {
  285. self::beginTrans();
  286. try {
  287. $shipping_type = (int)$shipping_type;
  288. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  289. if ($offlinePayStatus == 2 && !$store_order) unset(self::$payType['offline']);
  290. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  291. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  292. $userInfo = User::getUserInfo($uid);
  293. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  294. $cartGroup = self::getCacheOrderInfo($uid, $key);
  295. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  296. $cartInfo = $cartGroup['cartInfo'];
  297. $priceGroup = $cartGroup['priceGroup'];
  298. $other = $cartGroup['other'];
  299. $distance = 0;
  300. if ($other['store_id'] != $storeId && !$store_order && !$free_check && !$test) {
  301. self::clearCacheOrderInfo($uid, $key);
  302. return self::setErrorInfo('所选门店改变,请刷新当前页面!', true);
  303. }
  304. $payPrice = (float)$priceGroup['totalPrice'];
  305. $usedIntegral = (float)$priceGroup['totalIntegral'];
  306. $deposit = (float)$priceGroup['totalDeposit'];
  307. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  308. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  309. $payPostage = 0;
  310. $payPostageSh = 0;
  311. } else {
  312. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  313. $payPostageSh = self::getOrderPriceGroup($cartInfo, $addr, $storeId)['storePostageSh'];
  314. }
  315. if (!$userInfo['admin_id']) {
  316. if ($other['only_store_user'] ?? 0)
  317. return self::setErrorInfo('不支持采购!', true);
  318. } else {
  319. $ADMIN = SystemAdmin::where('id', $userInfo['admin_id'])->find();
  320. if (!$ADMIN || !$ADMIN['store_id']) {
  321. return self::setErrorInfo('不支持采购!', true);
  322. } else {
  323. if (!SystemStore::where('id', $ADMIN['store_id'])->value('pay')) {
  324. $payPrice = 0;
  325. }
  326. }
  327. }
  328. $cartIds = [];
  329. $totalNum = 0;
  330. $gainIntegral = 0;
  331. $giveCoupons = [];
  332. foreach ($cartInfo as $cart) {
  333. $cartIds[] = $cart['id'];
  334. $totalNum += $cart['cart_num'];
  335. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  336. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  337. if (!$combinationId) $combinationId = $cart['combination_id'];
  338. if (!$integral_id) $integral_id = $cart['integral_id'];
  339. if (!$exchange_id) $exchange_id = $cart['exchange_id'];
  340. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  341. $cartInfoGainCoupons = [];
  342. for ($i = 0; $i < $cart['cart_num']; $i++) {
  343. if (isset($cart['productInfo']['give_coupon']) && $cart['productInfo']['give_coupon'] > 0)
  344. $cartInfoGainCoupons[] = $cart['productInfo']['give_coupon'];
  345. }
  346. $giveCoupons = array_merge($giveCoupons, $cartInfoGainCoupons);
  347. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  348. }
  349. $deduction = $seckill_id || $bargain_id || $combinationId || $integral_id || $exchange_id;
  350. if ($deduction) {
  351. $couponId = 0;
  352. $useIntegral = false;
  353. if (!$test) {
  354. unset(self::$payType['offline']);
  355. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  356. }
  357. }
  358. if ($shipping_type === 1) {
  359. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  360. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  361. return self::setErrorInfo('地址选择有误!', true);
  362. if (!$storeId && !$test && !$free_check && !$store_order) {
  363. return self::setErrorInfo('请选择配送门店!', true);
  364. }
  365. $store = SystemStore::verificWhere()->where('id', $storeId)->find();
  366. if (!$store && !$free_check && !$store_order && !$test) {
  367. return self::setErrorInfo('门店错误!', true);
  368. }
  369. $distance = getDistance($addr['latitude'], $addr['longitude'], $store['latitude'], $store['longitude']);
  370. if (!$test && !$free_check && !$store_order && $distance > $store['radius']) return self::setErrorInfo('地址在派送范围外!', true);
  371. } else {
  372. if ((!$real_name || !$phone) && !$test && !$exchange_id) return self::setErrorInfo('请填写姓名和电话', true);
  373. $addressInfo['real_name'] = $real_name ?? '';
  374. $addressInfo['phone'] = $phone ?? '';
  375. $addressInfo['province'] = '';
  376. $addressInfo['city'] = '';
  377. $addressInfo['district'] = '';
  378. $addressInfo['detail'] = '';
  379. }
  380. if (!$storeId && !$test && !$free_check && !$exchange_id) return self::setErrorInfo('请选择下单门店!', true);
  381. if (!SystemStore::verificWhere()->find($storeId) && !$test && !$free_check && !$exchange_id) return self::setErrorInfo('请选择正确的下单门店!', true);
  382. //使用优惠劵
  383. $res1 = true;
  384. if ($couponId) {
  385. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  386. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  387. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  388. $flag = false;
  389. foreach ($coupons as $coupon) {
  390. if ($coupon['id'] == $couponId) {
  391. $flag = true;
  392. continue;
  393. }
  394. }
  395. if (!$flag)
  396. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  397. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  398. $res1 = StoreCouponUser::useCoupon($couponId);
  399. $couponPrice = $couponInfo['coupon_price'];
  400. } else {
  401. $couponId = 0;
  402. $couponPrice = 0;
  403. }
  404. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  405. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  406. $store_self_mention = sys_config('store_self_mention') ?? 0;
  407. if (!$store_self_mention) $shipping_type = 1;
  408. if ($shipping_type === 1) {
  409. //是否包邮
  410. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  411. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  412. $payPrice = bcadd($payPrice, $payPostageSh, 2);
  413. } else if ($shipping_type === 2) {
  414. //门店自提没有邮费支付
  415. $priceGroup['storePostage'] = 0;
  416. $payPostage = 0;
  417. $payPostageSh = 0;
  418. if (!$pointId && !$test && !$store_order && !$free_check) {
  419. return self::setErrorInfo('请选择自提点', true);
  420. }
  421. }
  422. $res2 = true;
  423. //积分商品
  424. $SurplusIntegral = $userInfo['integral'];
  425. if ($usedIntegral > 0) {
  426. if ($usedIntegral > $userInfo['integral']) {
  427. return self::setErrorInfo('积分不足', true);
  428. } else {
  429. $SurplusIntegral -= $usedIntegral;
  430. $res2 = $res2 && User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  431. $res2 = $res2 && false != UserBill::expend('积分商品兑换', $uid, 'integral', 'exchange', $usedIntegral, $key, bcsub($userInfo['integral'], $usedIntegral), '购买积分商品使用' . floatval($usedIntegral) . '积分');
  432. }
  433. }
  434. //积分抵扣
  435. if ($useIntegral && bcsub($userInfo['integral'], $usedIntegral) > 0) {
  436. $deductionPrice = (float)bcmul(bcsub($userInfo['integral'], $usedIntegral), $other['integralRatio'], 2);
  437. if ($deductionPrice < $payPrice) {
  438. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  439. $usedIntegral2 = bcsub($userInfo['integral'], $usedIntegral);
  440. $usedIntegral = $userInfo['integral'];
  441. $SurplusIntegral = 0;
  442. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  443. } else {
  444. $deductionPrice = $payPrice;
  445. $usedIntegral2 = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  446. $usedIntegral += (float)bcdiv($payPrice, $other['integralRatio'], 2);
  447. $SurplusIntegral = bcsub($SurplusIntegral, $usedIntegral, 2);
  448. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral2, 'uid');
  449. $payPrice = 0;
  450. }
  451. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral2, $key, $SurplusIntegral, '购买商品使用' . floatval($usedIntegral2) . '积分抵扣' . floatval($deductionPrice) . '元');
  452. } else {
  453. $deductionPrice = 0;
  454. $usedIntegral += 0;
  455. }
  456. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  457. if ($payPrice <= 0) $payPrice = 0;
  458. if ($test) {
  459. self::rollbackTrans();
  460. return [
  461. 'total_price' => $priceGroup['totalPrice'],
  462. 'pay_price' => $payPrice,
  463. 'pay_postage' => $payPostage,
  464. 'coupon_price' => $couponPrice,
  465. 'deduction_price' => $deductionPrice,
  466. 'SurplusIntegral' => $SurplusIntegral,
  467. 'pay_postage_sh' => $payPostageSh,
  468. 'store' => SystemStore::verificWhere()->find($storeId),
  469. 'deposit' => $deposit,
  470. 'distance' => $distance,
  471. 'store_user' => $other['only_store_user'] ?? 0,
  472. ];
  473. }
  474. $orderInfo = [
  475. 'uid' => $uid,
  476. 'order_id' => $test ? 0 : self::getNewOrderId(),
  477. 'real_name' => $addressInfo['real_name'],
  478. 'user_phone' => $addressInfo['phone'],
  479. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  480. 'cart_id' => $cartIds,
  481. 'total_num' => $totalNum,
  482. 'total_price' => $priceGroup['totalPrice'],
  483. 'total_postage' => $priceGroup['storePostage'],
  484. 'coupon_id' => $couponId,
  485. 'coupon_price' => $couponPrice,
  486. 'pay_price' => ($store_order && $payType == 'weixin') ? 0 : $payPrice,
  487. 'pay_postage' => ($store_order && $payType == 'weixin') ? 0 : $payPostage,
  488. 'pay_postage_sh' => ($store_order && $payType == 'weixin') ? 0 : $payPostageSh,
  489. 'distance' => $distance,
  490. 'deduction_price' => $deductionPrice,
  491. 'paid' => 0,
  492. 'pay_type' => $payType,
  493. 'use_integral' => $usedIntegral,
  494. 'gain_integral' => $gainIntegral,
  495. 'give_coupons' => implode(',', $giveCoupons),
  496. 'mark' => htmlspecialchars($mark),
  497. 'combination_id' => $combinationId,
  498. 'pink_id' => $pinkId,
  499. 'seckill_id' => $seckill_id,
  500. 'bargain_id' => $bargain_id,
  501. 'integral_id' => $integral_id,
  502. 'exchange_id' => $exchange_id,
  503. 'cost' => $priceGroup['costPrice'],
  504. 'is_channel' => $isChannel,
  505. 'add_time' => time(),
  506. 'unique' => $key,
  507. 'shipping_type' => $shipping_type,
  508. 'deposit' => $deposit,
  509. 'deposit_back' => 0,
  510. 'deposit_status' => 0,
  511. 'store_order' => $store_order,
  512. 'province' => $addressInfo['province'],
  513. 'city' => $addressInfo['city'],
  514. 'district' => $addressInfo['district'],
  515. 'time_area' => $time_area,
  516. 'store_user' => $other['only_store_user'] ?? 0,
  517. ];
  518. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  519. if (!$orderInfo['store_id'] && !$free_check) return self::setErrorInfo('暂无门店无法选择门店!', true);
  520. else if ($free_check) $orderInfo['store_id'] = 0;
  521. if (($other['only_store_user'] ?? 0) && !$orderInfo['store_id']) {
  522. return self::setErrorInfo('请选择采购门店!', true);
  523. }
  524. if ($orderInfo['store_id']) {
  525. $store = SystemStore::get($orderInfo['store_id']);
  526. if (!$store['store_user'] && ($other['only_store_user'] ?? 0)) {
  527. return self::setErrorInfo('门店不支持采购!', true);
  528. }
  529. $orderInfo['province'] = explode(',', $store['address'])[0] ?? '';
  530. $orderInfo['city'] = explode(',', $store['address'])[1] ?? '';
  531. $orderInfo['district'] = explode(',', $store['address'])[2] ?? '';
  532. }
  533. if ($shipping_type === 2) {
  534. $orderInfo['verify_code'] = self::getStoreCode();
  535. if (!$store_order && !$free_check) {
  536. $orderInfo['point_id'] = SystemStorePoint::verificWhere()->where('store_id', $orderInfo['store_id'])->where('id', $pointId)->value('id');
  537. if (!$orderInfo['point_id']) return self::setErrorInfo('找不到对应自提点!', true);
  538. }
  539. }
  540. $order = self::create($orderInfo);
  541. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  542. $res5 = true;
  543. foreach ($cartInfo as $cart) {
  544. //减库存加销量
  545. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  546. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  547. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  548. else if ($integral_id) $res5 = $res5 && StoreIntegral::decIntegralStock($cart['cart_num'], $integral_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  549. else if ($exchange_id) $res5 = $res5 && StoreExchange::decIntegralStock($cart['cart_num'], $exchange_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  550. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  551. }
  552. //保存购物车商品信息
  553. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  554. //门店库存
  555. $res4 = $res4 && SystemStore::decStock($order);
  556. if (!$res4) return self::setErrorInfo(SystemStore::getErrorInfo(), true);
  557. //购物车状态修改
  558. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  559. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  560. //自动设置默认地址
  561. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  562. self::clearCacheOrderInfo($uid, $key);
  563. self::commitTrans();
  564. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  565. return $order;
  566. } catch
  567. (\PDOException $e) {
  568. self::rollbackTrans();
  569. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  570. } catch (\Exception $e) {
  571. self::rollbackTrans();
  572. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  573. }
  574. }
  575. /**
  576. * 回退积分
  577. * @param $order 订单信息
  578. * @return bool
  579. */
  580. public static function RegressionIntegral($order)
  581. {
  582. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  583. if ($order['use_integral'] <= 0) return true;
  584. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  585. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  586. if (!$res) return self::setErrorInfo('回退积分增加失败');
  587. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  588. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  589. }
  590. /**
  591. * 回退库存和销量
  592. * @param $order 订单信息
  593. * @return bool
  594. * @throws DataNotFoundException
  595. * @throws ModelNotFoundException
  596. * @throws \think\exception\DbException
  597. */
  598. public static function RegressionStock($order)
  599. {
  600. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  601. $combinationId = $order['combination_id'];
  602. $seckill_id = $order['seckill_id'];
  603. $bargain_id = $order['bargain_id'];
  604. $integral_id = $order['integral_id'];
  605. $exchange_id = $order['exchange_id'];
  606. $res5 = true;
  607. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  608. foreach ($cartInfo as $cart) {
  609. //增库存减销量
  610. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
  611. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
  612. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
  613. else if ($integral_id) $res5 = $res5 && StoreIntegral::incSeckillStock($cart['cart_info']['cart_num'], $integral_id);
  614. else if ($exchange_id) $res5 = $res5 && StoreExchange::incSeckillStock($cart['cart_info']['cart_num'], $exchange_id);
  615. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  616. }
  617. return $res5;
  618. }
  619. /**
  620. * 回退优惠卷
  621. * @param $order 订单信息
  622. * @return bool
  623. */
  624. public static function RegressionCoupon($order)
  625. {
  626. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  627. $res = true;
  628. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  629. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  630. }
  631. return $res;
  632. }
  633. /**
  634. * 取消订单
  635. * @param string order_id 订单id
  636. * @param $uid
  637. * @return bool
  638. * @throws DataNotFoundException
  639. * @throws ModelNotFoundException
  640. * @throws \think\exception\DbException
  641. */
  642. public static function cancelOrder($order_id, $uid)
  643. {
  644. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  645. if (!$order) return self::setErrorInfo('没有查到此订单');
  646. self::beginTrans();
  647. try {
  648. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  649. $order->is_del = 1;
  650. if ($res && $order->save()) {
  651. self::commitTrans();
  652. return true;
  653. } else
  654. return false;
  655. } catch (\Exception $e) {
  656. self::rollbackTrans();
  657. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  658. }
  659. }
  660. /**
  661. * 生成订单唯一id
  662. * @param $uid 用户uid
  663. * @return string
  664. */
  665. public static function getNewOrderId()
  666. {
  667. do {
  668. list($msec, $sec) = explode(' ', microtime());
  669. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  670. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  671. } while (self::be(['order_id' => $orderId]));// $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  672. return $orderId;
  673. }
  674. /**
  675. * 修改订单号
  676. * @param $orderId
  677. * @return string
  678. */
  679. public static function changeOrderId($orderId)
  680. {
  681. $ymd = substr($orderId, 2, 8);
  682. $key = substr($orderId, 16);
  683. return 'wx' . $ymd . date('His') . $key;
  684. }
  685. /**
  686. * 查找购物车里的所有产品标题
  687. * @param $cartId 购物车id
  688. * @return bool|string
  689. */
  690. public static function getProductTitle($cartId)
  691. {
  692. $title = '';
  693. try {
  694. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  695. foreach ($orderCart as $item) {
  696. if (isset($item['cart_info']['productInfo']['store_name'])) {
  697. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  698. }
  699. }
  700. unset($item);
  701. if (!$title) {
  702. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  703. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  704. foreach ($productlist as $item) {
  705. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  706. }
  707. }
  708. if ($title) $title = substr($title, 0, strlen($title) - 1);
  709. unset($item);
  710. } catch (\Exception $e) {
  711. }
  712. return $title;
  713. }
  714. /**
  715. * 获取门店自提唯一核销码
  716. * @return bool|string
  717. */
  718. public static function getStoreCode()
  719. {
  720. list($msec, $sec) = explode(' ', microtime());
  721. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  722. if (strlen($num) < 12)
  723. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  724. else
  725. $num = substr($num, 0, 12);
  726. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  727. return $num;
  728. }
  729. /**
  730. * 余额支付
  731. * @param $order_id
  732. * @param $uid
  733. * @param string $formId
  734. * @return bool
  735. * @throws \think\Exception
  736. * @throws DataNotFoundException
  737. * @throws ModelNotFoundException
  738. * @throws \think\exception\DbException
  739. */
  740. public static function yuePay($order_id, $uid, $formId = '')
  741. {
  742. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  743. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  744. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  745. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  746. $userInfo = User::getUserInfo($uid);
  747. if ($userInfo['now_money'] < bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2))
  748. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval(bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2))]);
  749. self::beginTrans();
  750. $res1 = false !== User::bcDec($uid, 'now_money', bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2), 'uid');
  751. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2), $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval(bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2)) . '元购买商品' . ($orderInfo['deposit'] ? "(含押金{$orderInfo['deposit']})" : ''));
  752. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  753. try {
  754. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  755. } catch (\Exception $e) {
  756. self::rollbackTrans();
  757. return self::setErrorInfo($e->getMessage());
  758. }
  759. $res = $res1 && $res2 && $res3;
  760. self::checkTrans($res);
  761. return $res;
  762. }
  763. /**
  764. * 微信支付 为 0元时
  765. * @param $order_id
  766. * @param $uid
  767. * @param string $formId
  768. * @return bool
  769. * @throws \think\Exception
  770. * @throws DataNotFoundException
  771. * @throws ModelNotFoundException
  772. * @throws \think\exception\DbException
  773. */
  774. public static function jsPayPrice($order_id, $uid, $formId = '')
  775. {
  776. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  777. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  778. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  779. $userInfo = User::getUserInfo($uid);
  780. self::beginTrans();
  781. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  782. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  783. $res = $res1 && $res2;
  784. self::checkTrans($res);
  785. return $res;
  786. }
  787. /**
  788. * 用户申请退款
  789. * @param $uni
  790. * @param $uid
  791. * @param string $refundReasonWap
  792. * @return bool
  793. */
  794. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  795. {
  796. $order = self::getUserOrderDetail($uid, $uni);
  797. if (!$order) return self::setErrorInfo('支付订单不存在!');
  798. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  799. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  800. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  801. self::beginTrans();
  802. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  803. $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
  804. $res = $res1 && $res2;
  805. self::checkTrans($res);
  806. if (!$res)
  807. return self::setErrorInfo('申请退款失败!');
  808. else {
  809. try {
  810. if (in_array($order['is_channel'], [0, 2])) {
  811. //公众号发送模板消息通知客服
  812. WechatTemplateService::sendAdminNoticeTemplate([
  813. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  814. 'keyword1' => '退款申请',
  815. 'keyword2' => '已支付',
  816. 'keyword3' => date('Y/m/d H:i', time()),
  817. 'remark' => '请及时处理'
  818. ]);
  819. }
  820. if (in_array($order['is_channel'], [1, 2])) {
  821. //小程序 发送模板消息
  822. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  823. }
  824. //通知后台消息提醒
  825. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  826. } catch (\Exception $e) {
  827. }
  828. //发送短信
  829. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  830. return true;
  831. }
  832. }
  833. /**
  834. * //TODO 支付成功后
  835. * @param $orderId
  836. * @param string $paytype
  837. * @param string $formId
  838. * @return bool
  839. * @throws DataNotFoundException
  840. * @throws DbException
  841. * @throws ModelNotFoundException
  842. */
  843. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  844. {
  845. $order = self::where('order_id', $orderId)->find();
  846. $resPink = true;
  847. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'is_del' => 0, 'is_system_del' => 0, 'pay_type' => $paytype, 'pay_time' => time()]);//订单改为支付
  848. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  849. if ($order->exchange_id && $res1 && !$order->refund_status) $resExhcnage = StoreExchange::createOrder($order);//创建兑换券
  850. $oid = self::where('order_id', $orderId)->value('id');
  851. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  852. $now_money = User::where('uid', $order['uid'])->value('now_money');
  853. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', bcadd($order['pay_price'], $order['deposit'], 2), $order['id'], $now_money, '支付' . floatval(bcadd($order['pay_price'], $order['deposit'], 2)) . '元购买商品' . ($order['deposit'] ? "(含押金{$order['deposit']})" : ''));
  854. //支付成功后
  855. event('OrderPaySuccess', [$order, $formId]);
  856. $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
  857. $user = User::getUserInfo($order['uid']);
  858. if (!$order['store_order']) {
  859. if ($user['phone'])
  860. OtherSMSService::send($user['phone'], '成功支付' . floatval(bcadd($order['pay_price'], $order['deposit'], 2)) . '元购买商品' . ($order['deposit'] ? "(含押金{$order['deposit']})" : ''));
  861. if ($openid = WechatUser::where('uid', $order['uid'])->value('routine_openid')) {
  862. MiniProgramService::sendSubscribeTemlate($openid, 'utyQMQe5vfiJt1CA3-Q3JnGd2_dQ3mdyY0K44Gpaut4',
  863. [
  864. 'thing2' => self::getSubstrUTf8(self::getProductTitle($order['cart_id']), 8),
  865. 'amount3' => $order['total_price'],
  866. 'number4' => $order['total_num'],
  867. 'thing6' => $order['pay_price'],
  868. ]);
  869. }
  870. }
  871. return false !== $res;
  872. }
  873. /*
  874. * 线下支付消息通知
  875. * 待完善
  876. *
  877. * */
  878. public static function createOrderTemplate($order)
  879. {
  880. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  881. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  882. // 'first'=>'亲,您购买的商品已支付成功',
  883. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  884. // 'keyword2'=>implode(',',$goodsName),
  885. // 'keyword3'=>$order['order_id'],
  886. // 'remark'=>'点击查看订单详情'
  887. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  888. // RoutineTemplateService::sendAdminNoticeTemplate([
  889. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  890. // 'keyword1'=>'新订单',
  891. // 'keyword2'=>'线下支付',
  892. // 'keyword3'=>date('Y/m/d H:i',time()),
  893. // 'remark'=>'请及时处理'
  894. // ]);
  895. }
  896. public function point()
  897. {
  898. return $this->hasOne(SystemStorePoint::class, 'id', 'point_id')->field('*');
  899. }
  900. public function store()
  901. {
  902. return $this->hasOne(SystemStore::class, 'id', 'store_id')->field('*');
  903. }
  904. /**
  905. * 获取订单详情
  906. * @param $uid
  907. * @param $key
  908. * @return array|\think\Model|null
  909. * @throws DataNotFoundException
  910. * @throws ModelNotFoundException
  911. * @throws \think\exception\DbException
  912. */
  913. public static function getUserOrderDetail($uid, $key)
  914. {
  915. return self::with(['store', 'point'])->where('order_id|unique', $key)->where('uid|gift_uid', $uid)->where('is_del', 0)->find();
  916. }
  917. /**
  918. * TODO 订单发货
  919. * @param array $postageData 发货信息
  920. * @param string $oid orderID
  921. */
  922. public static function orderPostageAfter($postageData, $oid)
  923. {
  924. $order = self::where('id', $oid)->find();
  925. if ($postageData['delivery_type'] == 'send') {//送货
  926. RoutineTemplate::sendOrderPostage($order);
  927. } else if ($postageData['delivery_type'] == 'express') {//发货
  928. RoutineTemplate::sendOrderPostage($order, 1);
  929. }
  930. }
  931. /** 收货后发送模版消息
  932. * @param $order
  933. */
  934. public static function orderTakeAfter($order)
  935. {
  936. $title = self::getProductTitle($order['cart_id']);
  937. if ($order['is_channel'] == 1) {//小程序
  938. RoutineTemplate::sendOrderTakeOver($order, $title);
  939. } else {
  940. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  941. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  942. 'first' => '亲,您的订单已收货',
  943. 'keyword1' => $order['order_id'],
  944. 'keyword2' => '已收货',
  945. 'keyword3' => date('Y-m-d H:i:s', time()),
  946. 'keyword4' => $title,
  947. 'remark' => '感谢您的光临!'
  948. ]);
  949. }
  950. }
  951. /**
  952. * 删除订单
  953. * @param $uni
  954. * @param $uid
  955. * @return bool
  956. */
  957. public static function removeOrder($uni, $uid)
  958. {
  959. $order = self::getUserOrderDetail($uid, $uni);
  960. if (!$order) return self::setErrorInfo('订单不存在!');
  961. $order = self::tidyOrder($order);
  962. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  963. return self::setErrorInfo('该订单无法删除!');
  964. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  965. //未支付和已退款的状态下才可以退积分退库存退优惠券
  966. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  967. event('StoreOrderRegressionAllAfter', [$order]);
  968. }
  969. event('UserOrderRemoved', $uni);
  970. return true;
  971. } else
  972. return self::setErrorInfo('订单删除失败!');
  973. }
  974. /**
  975. * //TODO 用户确认收货
  976. * @param $uni
  977. * @param $uid
  978. */
  979. public static function takeOrder($uni, $uid)
  980. {
  981. $order = self::getUserOrderDetail($uid, $uni);
  982. if (!$order) return self::setErrorInfo('订单不存在!');
  983. $order = self::tidyOrder($order);
  984. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  985. self::beginTrans();
  986. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  987. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  988. try {
  989. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  990. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  991. } catch (\Exception $e) {
  992. self::rollbackTrans();
  993. return self::setErrorInfo($e->getMessage());
  994. }
  995. self::commitTrans();
  996. event('UserLevelAfter', [User::get($uni)]);
  997. event('UserOrderTake', $uni);
  998. //短信通知
  999. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  1000. return true;
  1001. } else {
  1002. self::rollbackTrans();
  1003. return false;
  1004. }
  1005. }
  1006. /**
  1007. * 获取订单状态购物车等信息
  1008. * @param $order
  1009. * @param bool $detail 是否获取订单购物车详情
  1010. * @param bool $isPic 是否获取订单状态图片
  1011. * @return mixed
  1012. * @throws DataNotFoundException
  1013. * @throws ModelNotFoundException
  1014. * @throws \think\exception\DbException
  1015. */
  1016. public static function tidyOrder($order, $detail = false, $isPic = false)
  1017. {
  1018. if ($detail == true && isset($order['id'])) {
  1019. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  1020. $info = [];
  1021. foreach ($cartInfo as $k => $cart) {
  1022. $cart = json_decode($cart, true);
  1023. $cart['unique'] = $k;
  1024. //新增是否评价字段
  1025. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  1026. array_push($info, $cart);
  1027. unset($cart);
  1028. }
  1029. $order['cartInfo'] = $info;
  1030. }
  1031. $status = [];
  1032. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  1033. $status['_type'] = 9;
  1034. $status['_title'] = '线下付款';
  1035. $status['_msg'] = '商家处理中,请耐心等待';
  1036. $status['_class'] = 'nobuy';
  1037. } else if (!$order['paid']) {
  1038. $status['_type'] = 0;
  1039. $status['_title'] = '未支付';
  1040. //系统预设取消订单时间段
  1041. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1042. //获取配置
  1043. $systemValue = SystemConfigService::more($keyValue);
  1044. //格式化数据
  1045. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1046. if ($order['pink_id'] || $order['combination_id']) {
  1047. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1048. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  1049. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1050. } else if ($order['seckill_id']) {
  1051. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1052. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  1053. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1054. } else if ($order['bargain_id']) {
  1055. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1056. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  1057. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1058. } else {
  1059. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1060. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  1061. }
  1062. $status['_class'] = 'nobuy';
  1063. } else if ($order['refund_status'] == 1) {
  1064. $status['_type'] = -1;
  1065. $status['_title'] = '申请退款中';
  1066. $status['_msg'] = '商家审核中,请耐心等待';
  1067. $status['_class'] = 'state-sqtk';
  1068. } else if ($order['refund_status'] == 2) {
  1069. $status['_type'] = -2;
  1070. $status['_title'] = '已退款';
  1071. $status['_msg'] = '已为您退款,感谢您的支持';
  1072. $status['_class'] = 'state-sqtk';
  1073. } else if (!$order['status']) {
  1074. if ($order['pink_id']) {
  1075. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  1076. $status['_type'] = 1;
  1077. $status['_title'] = '拼团中';
  1078. $status['_msg'] = '等待其他人参加拼团';
  1079. $status['_class'] = 'state-nfh';
  1080. } else {
  1081. $status['_type'] = 1;
  1082. $status['_title'] = '未发货';
  1083. $status['_msg'] = '商家未发货,请耐心等待';
  1084. $status['_class'] = 'state-nfh';
  1085. }
  1086. } else {
  1087. if ($order['shipping_type'] === 1) {
  1088. $status['_type'] = 1;
  1089. $status['_title'] = '未发货';
  1090. $status['_msg'] = '商家未发货,请耐心等待';
  1091. $status['_class'] = 'state-nfh';
  1092. } else {
  1093. $status['_type'] = 1;
  1094. $status['_title'] = '待核销';
  1095. $status['_msg'] = '待核销,请到核销点进行核销';
  1096. $status['_class'] = 'state-nfh';
  1097. }
  1098. }
  1099. } else if ($order['status'] == 1) {
  1100. if ($order['delivery_type'] == 'send') {//TODO 送货
  1101. $status['_type'] = 2;
  1102. $status['_title'] = '待收货';
  1103. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  1104. $status['_class'] = 'state-ysh';
  1105. } else {//TODO 发货
  1106. $status['_type'] = 2;
  1107. $status['_title'] = '待收货';
  1108. if ($order['delivery_type'] == 'fictitious')
  1109. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  1110. else
  1111. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  1112. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  1113. $status['_class'] = 'state-ysh';
  1114. }
  1115. } else if ($order['status'] == 2) {
  1116. $status['_type'] = 3;
  1117. $status['_title'] = '待评价';
  1118. $status['_msg'] = '已收货,快去评价一下吧';
  1119. $status['_class'] = 'state-ypj';
  1120. } else if ($order['status'] == 3) {
  1121. $status['_type'] = 4;
  1122. $status['_title'] = '交易完成';
  1123. $status['_msg'] = '交易完成,感谢您的支持';
  1124. $status['_class'] = 'state-ytk';
  1125. }
  1126. if (isset($order['pay_type']))
  1127. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  1128. if (isset($order['delivery_type']))
  1129. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  1130. $order['_status'] = $status;
  1131. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
  1132. $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  1133. $order['_arrive_time'] = isset($order['arrive_time']) ? (strstr($order['arrive_time'], '-') === false ? date('Y-m-d H:i:s', $order['arrive_time']) : $order['arrive_time']) : '';
  1134. $order['status_pic'] = '';
  1135. $order['gift_user'] = User::get($order['gift_uid']);
  1136. $order['user'] = User::get($order['uid']);
  1137. $order['store'] = SystemStore::get($order['store_id']);
  1138. $order['point'] = SystemStorePoint::get($order['point_id']);
  1139. //获取产品状态图片
  1140. if ($isPic) {
  1141. $order_details_images = sys_data('order_details_images') ?: [];
  1142. foreach ($order_details_images as $image) {
  1143. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  1144. $order['status_pic'] = $image['pic'];
  1145. break;
  1146. }
  1147. }
  1148. }
  1149. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1150. return $order;
  1151. }
  1152. /**
  1153. * 设置订单查询状态
  1154. * @param $status
  1155. * @param int $uid
  1156. * @param null $model
  1157. * @return StoreOrder|null
  1158. */
  1159. public static function statusByWhere($status, $uid = 0, $model = null)
  1160. {
  1161. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  1162. if ($model == null) $model = new self;
  1163. if ('' === $status)
  1164. return $model;
  1165. else if ($status == 0)//未支付
  1166. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  1167. else if ($status == 1)//待发货
  1168. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  1169. else if ($status == 2)//待收货
  1170. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  1171. else if ($status == 3)//待评价
  1172. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  1173. else if ($status == 4)//已完成
  1174. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  1175. else if ($status == -1)//退款中
  1176. return $model->where('paid', 1)->where('refund_status', 1);
  1177. else if ($status == -2)//已退款
  1178. return $model->where('paid', 1)->where('refund_status', 2);
  1179. else if ($status == -3)//退款
  1180. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  1181. else if ($status == 10086)//退款
  1182. return $model->where('paid', 1)->where('refund_status', 0)->where('store_id', 0)->where('shipping_type', 2);
  1183. // else if($status == 11){
  1184. // return $model->where('order_id','IN',implode(',',$orderId));
  1185. // }
  1186. else
  1187. return $model;
  1188. }
  1189. /**
  1190. * 获取订单并分页
  1191. * @param $uid
  1192. * @param string $status
  1193. * @param int $page
  1194. * @param int $limit
  1195. * @return mixed
  1196. * @throws DataNotFoundException
  1197. * @throws ModelNotFoundException
  1198. * @throws \think\exception\DbException
  1199. */
  1200. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  1201. {
  1202. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)
  1203. // ->field('pay_postage_sh,uid,add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type,gift_uid,store_id')
  1204. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1205. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)
  1206. // ->field('pay_postage_sh,uid,add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type,gift_uid,store_id')
  1207. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  1208. foreach ($list as $k => $order) {
  1209. $list[$k] = self::tidyOrder($order, true);
  1210. }
  1211. return $list;
  1212. }
  1213. /**
  1214. * 获取推广人地下用户的订单金额
  1215. * @param string $uid
  1216. * @param string $status
  1217. * @return array
  1218. */
  1219. public static function getUserOrderCount($uid = '', $status = '')
  1220. {
  1221. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  1222. return $res;
  1223. }
  1224. /**
  1225. * 搜索某个订单详细信息
  1226. * @param $uid
  1227. * @param $order_id
  1228. * @return bool|mixed
  1229. * @throws DataNotFoundException
  1230. * @throws ModelNotFoundException
  1231. * @throws \think\exception\DbException
  1232. */
  1233. public static function searchUserOrder($uid, $order_id)
  1234. {
  1235. $order = self::where('uid|gift_uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('*')
  1236. ->order('add_time DESC')->find();
  1237. if (!$order)
  1238. return false;
  1239. else
  1240. return self::tidyOrder($order->toArray(), true);
  1241. }
  1242. /**
  1243. * 订单评价信息记录
  1244. * @param $oid
  1245. * @return StoreOrderStatus|\think\Model
  1246. * @throws \Exception
  1247. */
  1248. public static function orderOver($oid)
  1249. {
  1250. $res = self::edit(['status' => '3'], $oid, 'id');
  1251. if (!$res) exception('评价后置操作失败!');
  1252. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  1253. }
  1254. /**
  1255. * 设置订单产品评价完毕事件
  1256. * @param $oid
  1257. * @return StoreOrderStatus|\think\Model
  1258. * @throws \Exception
  1259. */
  1260. public static function checkOrderOver($oid)
  1261. {
  1262. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  1263. //订单产品全部评价完成
  1264. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  1265. event('StoreProductOrderOver', [$oid]);
  1266. return self::orderOver($oid);
  1267. }
  1268. }
  1269. public static function getOrderStatusNum($uid)
  1270. {
  1271. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  1272. $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1273. $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1274. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  1275. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  1276. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  1277. $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  1278. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  1279. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  1280. }
  1281. /**
  1282. * 购买商品赠送积分
  1283. * @param $order
  1284. * @return bool
  1285. * @throws \think\Exception
  1286. * @throws DataNotFoundException
  1287. * @throws ModelNotFoundException
  1288. * @throws \think\exception\DbException
  1289. */
  1290. public static function gainUserIntegral($order)
  1291. {
  1292. if ($order['gain_integral'] > 0) {
  1293. $userInfo = User::getUserInfo($order['uid']);
  1294. BaseModel::beginTrans();
  1295. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  1296. $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  1297. $res = $res1 && $res2;
  1298. BaseModel::checkTrans($res);
  1299. return $res;
  1300. }
  1301. return true;
  1302. }
  1303. /**
  1304. * 获取当前订单中有没有拼团存在
  1305. * @param $pid
  1306. * @return int|string
  1307. */
  1308. public static function getIsOrderPink($pid = 0, $uid = 0)
  1309. {
  1310. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  1311. }
  1312. /**
  1313. * 获取order_id
  1314. * @param $pid
  1315. * @return mixed
  1316. */
  1317. public static function getStoreIdPink($pid = 0, $uid = 0)
  1318. {
  1319. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  1320. }
  1321. /**
  1322. * 删除当前用户拼团未支付的订单
  1323. */
  1324. public static function delCombination()
  1325. {
  1326. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  1327. }
  1328. public static function getUserPrice($uid = 0)
  1329. {
  1330. if (!$uid) return 0;
  1331. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  1332. $count = 0;
  1333. if ($price) {
  1334. foreach ($price as $v) {
  1335. $count = bcadd($count, $v, 2);
  1336. }
  1337. }
  1338. return $count;
  1339. }
  1340. /**
  1341. * 个人中心获取个人订单列表和订单搜索
  1342. * @param int $uid 用户uid
  1343. * @param int | string 查找订单类型
  1344. * @param int $first 分页
  1345. * @param int 每页显示多少条
  1346. * @param string $search 订单号
  1347. * @return array
  1348. * */
  1349. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  1350. {
  1351. if ($search) {
  1352. $order = self::searchUserOrder($uid, $search) ?: [];
  1353. $list = $order == false ? [] : [$order];
  1354. } else {
  1355. $list = self::getUserOrderList($uid, $type, $page, $limit);
  1356. }
  1357. foreach ($list as $k => $order) {
  1358. $list[$k] = self::tidyOrder($order, true);
  1359. if ($list[$k]['_status']['_type'] == 3) {
  1360. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1361. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1362. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  1363. }
  1364. }
  1365. }
  1366. return $list;
  1367. }
  1368. /**
  1369. * 获取用户下级的订单
  1370. * @param int $xuid 下级用户用户uid
  1371. * @param int $uid 用户uid
  1372. * @param int $type 订单类型
  1373. * @param int $first 截取行数
  1374. * @param int $limit 展示条数
  1375. * @return array
  1376. * */
  1377. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  1378. {
  1379. $list = [];
  1380. if (!$xUid) {
  1381. $arr = User::getOneSpreadUid($uid);
  1382. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  1383. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  1384. foreach ($list as $k => $order) {
  1385. $list[$k] = self::tidyOrder($order, true);
  1386. if ($list[$k]['_status']['_type'] == 3) {
  1387. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  1388. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  1389. }
  1390. }
  1391. }
  1392. return $list;
  1393. }
  1394. /**
  1395. * 获取 今日 昨日 本月 订单金额
  1396. * @param array $where
  1397. * @return mixed
  1398. */
  1399. public static function getOrderTimeData($where = [])
  1400. {
  1401. $to_day = strtotime(date('Y-m-d'));//今日
  1402. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  1403. $now_month = strtotime(date('Y-m'));//本月
  1404. //今日成交额
  1405. // $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1406. $data['todayPrice'] = number_format(self::where('is_del', 0)->where($where)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1407. //今日订单数
  1408. $data['todayCount'] = self::where('is_del', 0)->where($where)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  1409. //昨日成交额
  1410. $data['proPrice'] = number_format(self::where('is_del', 0)->where($where)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1411. //昨日订单数
  1412. $data['proCount'] = self::where('is_del', 0)->where($where)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  1413. //本月成交额
  1414. $data['monthPrice'] = number_format(self::where('is_del', 0)->where($where)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  1415. //本月订单数
  1416. $data['monthCount'] = self::where('is_del', 0)->where($where)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  1417. return $data;
  1418. }
  1419. /**
  1420. * 获取某个用户的订单统计数据
  1421. * @param $uid
  1422. * @return mixed
  1423. */
  1424. public static function getOrderData($uid)
  1425. {
  1426. //订单支付没有退款 数量
  1427. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid|gift_uid', $uid)->where('refund_status', 0)->count();
  1428. //订单支付没有退款 支付总金额
  1429. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid|gift_uid', $uid)->where('refund_status', 0)->sum('pay_price');
  1430. //订单待支付 数量
  1431. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  1432. //订单待发货 数量
  1433. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  1434. //订单待收货 数量
  1435. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  1436. //订单待评价 数量
  1437. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  1438. //订单已完成 数量
  1439. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  1440. //订单退款
  1441. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  1442. $data['exchange_ticket_count'] = StoreExchangeOrder::where('uid|gift_uid', $uid)->where('refund_status', 0)->where('status', 0)->count();
  1443. return $data;
  1444. }
  1445. /**
  1446. * 获取订单统计数据
  1447. * @param $uid
  1448. * @return mixed
  1449. */
  1450. public static function getOrderDataAdmin($where = [])
  1451. {
  1452. //订单支付没有退款 数量
  1453. $data['order_count'] = self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->count();
  1454. //订单支付没有退款 支付总金额
  1455. $data['sum_price'] = self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  1456. //订单待支付 数量
  1457. $data['unpaid_count'] = self::statusByWhere(0, 0)->where($where)->where('is_del', 0)->count();
  1458. //订单待发货 数量
  1459. $data['unshipped_count'] = self::statusByWhere(1, 0)->where($where)->where('is_del', 0)->count();
  1460. //订单待收货 数量
  1461. $data['received_count'] = self::statusByWhere(2, 0)->where($where)->where('is_del', 0)->count();
  1462. //订单待评价 数量
  1463. $data['evaluated_count'] = self::statusByWhere(3, 0)->where($where)->where('is_del', 0)->count();
  1464. //订单已完成 数量
  1465. $data['complete_count'] = self::statusByWhere(4, 0)->where($where)->where('is_del', 0)->count();
  1466. //订单退款 数量
  1467. $data['refund_count'] = self::statusByWhere(-3, 0)->where($where)->where('is_del', 0)->count();
  1468. return $data;
  1469. }
  1470. /**
  1471. * 累计消费
  1472. * @param $uid
  1473. * @return float
  1474. */
  1475. public static function getOrderStatusSum($uid)
  1476. {
  1477. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
  1478. }
  1479. public static function getPinkOrderId($id)
  1480. {
  1481. return self::where('id', $id)->value('order_id');
  1482. }
  1483. /**
  1484. * 未支付订单自动取消
  1485. * @param int $limit 分页截取条数
  1486. * @param string $prefid 缓存名称
  1487. * @param int $expire 缓存时间
  1488. * @return string|null
  1489. * @throws \Psr\SimpleCache\InvalidArgumentException
  1490. */
  1491. public static function orderUnpaidCancel()
  1492. {
  1493. //系统预设取消订单时间段
  1494. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1495. //获取配置
  1496. $systemValue = SystemConfigService::more($keyValue);
  1497. //格式化数据
  1498. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1499. //检查是否有未支付的订单 未支付查询条件
  1500. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  1501. if (!$unPidCount) return null;
  1502. try {
  1503. $res = true;
  1504. // 未支付查询条件
  1505. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
  1506. foreach ($orderList as $order) {
  1507. if ($order['seckill_id']) {
  1508. //优先使用单独配置的过期时间
  1509. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1510. $res = $res && self::RegressionAll($order_seckill_time, $order);
  1511. unset($order_seckill_time);
  1512. } else if ($order['bargain_id']) {
  1513. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1514. $res = $res && self::RegressionAll($order_bargain_time, $order);
  1515. unset($order_bargain_time);
  1516. } else if ($order['pink_id'] || $order['combination_id']) {
  1517. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1518. $res = $res && self::RegressionAll($order_pink_time, $order);
  1519. unset($order_pink_time);
  1520. } else {
  1521. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  1522. }
  1523. }
  1524. if (!$res) throw new \Exception('更新错误');
  1525. unset($orderList, $res, $pages);
  1526. return null;
  1527. } catch (PDOException $e) {
  1528. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  1529. throw new \Exception($e->getMessage());
  1530. } catch (\think\Exception $e) {
  1531. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  1532. throw new \Exception($e->getMessage());
  1533. }
  1534. }
  1535. /**
  1536. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  1537. * @param $time 预设时间
  1538. * @param $order 订单详情
  1539. * @return bool
  1540. * @throws DataNotFoundException
  1541. * @throws ModelNotFoundException
  1542. * @throws \think\exception\DbException
  1543. */
  1544. protected static function RegressionAll($time, $order)
  1545. {
  1546. if ($time == 0) return true;
  1547. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  1548. $res1 = self::RegressionStock($order);
  1549. $res2 = self::RegressionIntegral($order);
  1550. $res3 = self::RegressionCoupon($order);
  1551. $res = $res1 && $res2 && $res3;
  1552. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  1553. unset($res1, $res2, $res3);
  1554. return $res;
  1555. } else
  1556. return true;
  1557. }
  1558. /**
  1559. * 格式化数据
  1560. * @param array $array 原本数据键
  1561. * @param $value 需要格式化的数据
  1562. * @param int $default 默认值
  1563. * @return mixed
  1564. */
  1565. protected static function setValeTime(array $array, $value, $default = 0)
  1566. {
  1567. foreach ($array as $item) {
  1568. if (!isset($value[$item]))
  1569. $value[$item] = $default;
  1570. else if (is_string($value[$item]))
  1571. $value[$item] = (float)$value[$item];
  1572. }
  1573. return $value;
  1574. }
  1575. public static function getOrderTotalPrice($cartInfo)
  1576. {
  1577. $totalPrice = 0;
  1578. foreach ($cartInfo as $cart) {
  1579. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  1580. }
  1581. return $totalPrice;
  1582. }
  1583. public static function getOrderCostPrice($cartInfo)
  1584. {
  1585. $costPrice = 0;
  1586. foreach ($cartInfo as $cart) {
  1587. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  1588. }
  1589. return $costPrice;
  1590. }
  1591. public static function getCombinationOrderCostPrice($cartInfo)
  1592. {
  1593. $costPrice = 0;
  1594. foreach ($cartInfo as $cart) {
  1595. if ($cart['combination_id']) {
  1596. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  1597. }
  1598. }
  1599. return (float)$costPrice;
  1600. }
  1601. public static function yueRefundAfter($order)
  1602. {
  1603. }
  1604. /**
  1605. * 获取余额支付的金额
  1606. * @param $uid
  1607. * @return float|int
  1608. */
  1609. public static function getOrderStatusYueSum($uid)
  1610. {
  1611. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  1612. }
  1613. /**
  1614. * 砍价支付成功订单数量
  1615. * @param $bargain
  1616. * @return int
  1617. */
  1618. public static function getBargainPayCount($bargain)
  1619. {
  1620. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  1621. }
  1622. /**
  1623. * 7天自动收货
  1624. * @return bool
  1625. */
  1626. public static function startTakeOrder()
  1627. {
  1628. //7天前时间戳
  1629. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  1630. //0为取消自动收货功能
  1631. if ($systemDeliveryTime == 0) return true;
  1632. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  1633. $model = new self;
  1634. $model = $model->alias('o');
  1635. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  1636. $model = $model->where('o.paid', 1);
  1637. $model = $model->where('s.change_type', 'in', ['delivery_goods', 'delivery', 'delivery_fictitious']);
  1638. $model = $model->where('s.change_time', '<', $sevenDay);
  1639. $model = $model->where('o.status', 1);
  1640. $model = $model->where('o.refund_status', 0);
  1641. $model = $model->where('o.is_del', 0);
  1642. $orderInfo = $model->column('id', 'id');
  1643. if (!count($orderInfo)) return true;
  1644. $res = true;
  1645. foreach ($orderInfo as $key => &$item) {
  1646. $order = self::get($item);
  1647. if ($order['status'] == 2) continue;
  1648. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  1649. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  1650. else continue;
  1651. if (!self::edit($data, $item, 'id')) continue;
  1652. try {
  1653. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  1654. $res = $res && true;
  1655. } catch (\Exception $e) {
  1656. Log::error($item . ':' . $e->getFile() . $e->getLine() . $e->getMessage() . json_encode($e->getTrace()));
  1657. $res = $res && false;
  1658. }
  1659. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  1660. }
  1661. if (!$res) {
  1662. throw new \Exception('');
  1663. }
  1664. }
  1665. /**
  1666. * 获取订单信息
  1667. * @param $id
  1668. * @param string $field
  1669. * @return array|null|\think\Model
  1670. * @throws DataNotFoundException
  1671. * @throws ModelNotFoundException
  1672. * @throws \think\exception\DbException
  1673. */
  1674. public static function getOrderInfo($id, $field = 'order_id')
  1675. {
  1676. return self::where('id', $id)->field($field)->find();
  1677. }
  1678. /**
  1679. * 订单每月统计数据
  1680. * @param $page
  1681. * @param $limit
  1682. * @return array
  1683. */
  1684. public static function getOrderDataPriceCount($page, $limit, $start, $stop, $where = [])
  1685. {
  1686. if (!$limit) return [];
  1687. $model = self::where($where);
  1688. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  1689. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  1690. $model = $model->where('is_del', 0);
  1691. $model = $model->where('paid', 1);
  1692. $model = $model->where('refund_status', 0);
  1693. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  1694. $model = $model->order('pay_time DESC');
  1695. if ($page) $model = $model->page($page, $limit);
  1696. return $model->select();
  1697. }
  1698. /**
  1699. * 前台订单管理订单列表获取
  1700. * @param $where
  1701. * @return mixed
  1702. */
  1703. public static function orderList($where)
  1704. {
  1705. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.*');
  1706. if ($where['order'] != '') {
  1707. $model = $model->order(self::setOrder($where['order']));
  1708. } else {
  1709. $model = $model->order('a.id desc');
  1710. }
  1711. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  1712. return self::tidyAdminOrder($data);
  1713. }
  1714. /**
  1715. * 前台订单管理 订单信息设置
  1716. * @param $data
  1717. * @param bool $status
  1718. * @return mixed
  1719. * @throws DataNotFoundException
  1720. * @throws ModelNotFoundException
  1721. * @throws \think\exception\DbException
  1722. */
  1723. public static function tidyAdminOrder($data, $status = false)
  1724. {
  1725. foreach ($data as &$item) {
  1726. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  1727. foreach ($_info as $k => $v) {
  1728. if (!is_array($v['cart_info']))
  1729. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  1730. }
  1731. foreach ($_info as $k => $v) {
  1732. unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
  1733. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  1734. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  1735. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  1736. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  1737. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  1738. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  1739. }
  1740. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  1741. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  1742. }
  1743. }
  1744. $item['_info'] = $_info;
  1745. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  1746. // if($item['pink_id'] || $item['combination_id']){
  1747. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  1748. // switch ($pinkStatus){
  1749. // case 1:
  1750. // $item['pink_name'] = '[拼团订单]正在进行中';
  1751. // $item['color'] = '#f00';
  1752. // break;
  1753. // case 2:
  1754. // $item['pink_name'] = '[拼团订单]已完成';
  1755. // $item['color'] = '#00f';
  1756. // break;
  1757. // case 3:
  1758. // $item['pink_name'] = '[拼团订单]未完成';
  1759. // $item['color'] = '#f0f';
  1760. // break;
  1761. // default:
  1762. // $item['pink_name'] = '[拼团订单]历史订单';
  1763. // $item['color'] = '#457856';
  1764. // break;
  1765. // }
  1766. // }elseif ($item['seckill_id']){
  1767. // $item['pink_name'] = '[秒杀订单]';
  1768. // $item['color'] = '#32c5e9';
  1769. // }elseif ($item['bargain_id']){
  1770. // $item['pink_name'] = '[砍价订单]';
  1771. // $item['color'] = '#12c5e9';
  1772. // }else{
  1773. // $item['pink_name'] = '[普通订单]';
  1774. // $item['color'] = '#895612';
  1775. // }
  1776. // if($item['paid']==1){
  1777. // switch ($item['pay_type']){
  1778. // case 'weixin':
  1779. // $item['pay_type_name']='微信支付';
  1780. // break;
  1781. // case 'yue':
  1782. // $item['pay_type_name']='余额支付';
  1783. // break;
  1784. // case 'offline':
  1785. // $item['pay_type_name']='线下支付';
  1786. // break;
  1787. // default:
  1788. // $item['pay_type_name']='其他支付';
  1789. // break;
  1790. // }
  1791. // }else{
  1792. // switch ($item['pay_type']){
  1793. // default:
  1794. // $item['pay_type_name']='未支付';
  1795. // break;
  1796. // case 'offline':
  1797. // $item['pay_type_name']='线下支付';
  1798. // $item['pay_type_info']=1;
  1799. // break;
  1800. // }
  1801. // }
  1802. if ($status) {
  1803. $status = [];
  1804. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  1805. $status['_type'] = 9;
  1806. $status['_title'] = '线下付款';
  1807. $status['_msg'] = '商家处理中,请耐心等待';
  1808. $status['_class'] = 'nobuy';
  1809. } else if (!$item['paid']) {
  1810. $status['_type'] = 0;
  1811. $status['_title'] = '未支付';
  1812. //系统预设取消订单时间段
  1813. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  1814. //获取配置
  1815. $systemValue = SystemConfigService::more($keyValue);
  1816. //格式化数据
  1817. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  1818. if ($item['pink_id'] || $item['combination_id']) {
  1819. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  1820. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  1821. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1822. } else if ($item['seckill_id']) {
  1823. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  1824. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  1825. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1826. } else if ($item['bargain_id']) {
  1827. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  1828. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  1829. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1830. } else {
  1831. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  1832. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  1833. }
  1834. $status['_class'] = 'nobuy';
  1835. } else if ($item['refund_status'] == 1) {
  1836. $status['_type'] = -1;
  1837. $status['_title'] = '申请退款中';
  1838. $status['_msg'] = '商家审核中,请耐心等待';
  1839. $status['_class'] = 'state-sqtk';
  1840. } else if ($item['refund_status'] == 2) {
  1841. $status['_type'] = -2;
  1842. $status['_title'] = '已退款';
  1843. $status['_msg'] = '已为您退款,感谢您的支持';
  1844. $status['_class'] = 'state-sqtk';
  1845. } else if (!$item['status']) {
  1846. if ($item['pink_id']) {
  1847. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  1848. $status['_type'] = 11;
  1849. $status['_title'] = '拼团中';
  1850. $status['_msg'] = '等待其他人参加拼团';
  1851. $status['_class'] = 'state-nfh';
  1852. } else {
  1853. $status['_type'] = 1;
  1854. $status['_title'] = '未发货';
  1855. $status['_msg'] = '商家未发货,请耐心等待';
  1856. $status['_class'] = 'state-nfh';
  1857. }
  1858. } else {
  1859. $status['_type'] = 1;
  1860. $status['_title'] = '未发货';
  1861. $status['_msg'] = '商家未发货,请耐心等待';
  1862. $status['_class'] = 'state-nfh';
  1863. }
  1864. } else if ($item['status'] == 1) {
  1865. if ($item['delivery_type'] == 'send') {//TODO 送货
  1866. $status['_type'] = 2;
  1867. $status['_title'] = '待收货';
  1868. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  1869. $status['_class'] = 'state-ysh';
  1870. } else {//TODO 发货
  1871. $status['_type'] = 2;
  1872. $status['_title'] = '待收货';
  1873. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  1874. $status['_class'] = 'state-ysh';
  1875. }
  1876. } else if ($item['status'] == 2) {
  1877. $status['_type'] = 3;
  1878. $status['_title'] = '待评价';
  1879. $status['_msg'] = '已收货,快去评价一下吧';
  1880. $status['_class'] = 'state-ypj';
  1881. } else if ($item['status'] == 3) {
  1882. $status['_type'] = 4;
  1883. $status['_title'] = '交易完成';
  1884. $status['_msg'] = '交易完成,感谢您的支持';
  1885. $status['_class'] = 'state-ytk';
  1886. }
  1887. if (isset($item['pay_type']))
  1888. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  1889. if (isset($item['delivery_type']))
  1890. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  1891. $item['_status'] = $status;
  1892. } else {
  1893. if ($item['paid'] == 0 && $item['status'] == 0) {
  1894. $item['status_name'] = '未支付';
  1895. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  1896. $item['status_name'] = '未发货';
  1897. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  1898. $item['status_name'] = '待收货';
  1899. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  1900. $item['status_name'] = '待评价';
  1901. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  1902. $item['status_name'] = '已完成';
  1903. }
  1904. }
  1905. $item['store'] = SystemStore::get($item['store_id']);
  1906. $item['point'] = SystemStorePoint::get($item['point_id']);
  1907. // unset($item['refund_status']);
  1908. // else if($item['paid']==1 && $item['refund_status']==1){
  1909. // $item['status_name']=<<<HTML
  1910. //<b style="color:#f124c7">申请退款</b><br/>
  1911. //<span>退款原因:{$item['refund_reason_wap']}</span>
  1912. //HTML;
  1913. // }else if($item['paid']==1 && $item['refund_status']==2){
  1914. // $item['status_name']='已退款';
  1915. // }
  1916. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  1917. // $item['_status']=1;
  1918. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  1919. // $item['_status']=2;
  1920. // }else if($item['paid']==1 && $item['refund_status']==1){
  1921. // $item['_status']=3;
  1922. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  1923. // $item['_status']=4;
  1924. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  1925. // $item['_status']=5;
  1926. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  1927. // $item['_status']=6;
  1928. // }else if($item['paid']==1 && $item['refund_status']==2){
  1929. // $item['_status']=7;
  1930. // }
  1931. }
  1932. return $data;
  1933. }
  1934. /**
  1935. * 处理where条件
  1936. * @param $where
  1937. * @param $model
  1938. * @param string $aler
  1939. * @param string $join
  1940. * @return StoreOrder|null
  1941. */
  1942. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  1943. {
  1944. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  1945. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  1946. if (isset($where['store_id']) && $where['store_id'] != '' && $where['store_id'] != -1) $model = $model->where($aler . 'store_id', $where['store_id']);
  1947. if (isset($where['combination_id'])) {
  1948. if ($where['combination_id'] == '普通订单') {
  1949. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1950. }
  1951. if ($where['combination_id'] == '拼团订单') {
  1952. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  1953. }
  1954. if ($where['combination_id'] == '秒杀订单') {
  1955. $model = $model->where($aler . 'seckill_id', ">", 0);
  1956. }
  1957. if ($where['combination_id'] == '砍价订单') {
  1958. $model = $model->where($aler . 'bargain_id', ">", 0);
  1959. }
  1960. }
  1961. if (isset($where['type'])) {
  1962. switch ($where['type']) {
  1963. case 1:
  1964. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  1965. break;
  1966. case 2:
  1967. $model = $model->where($aler . 'combination_id', ">", 0);
  1968. break;
  1969. case 3:
  1970. $model = $model->where($aler . 'seckill_id', ">", 0);
  1971. break;
  1972. case 4:
  1973. $model = $model->where($aler . 'bargain_id', ">", 0);
  1974. break;
  1975. }
  1976. }
  1977. if (isset($where['user_phone']) && $where['user_phone'] != '')
  1978. $model = $model->where($aler . 'user_phone', 'LIKE', "%$where[user_phone]%");
  1979. if (isset($where['real_name']) && $where['real_name'] != '')
  1980. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  1981. if (isset($where['data']) && $where['data'] !== '')
  1982. $model = self::getModelTime($where, $model, $aler . 'add_time');
  1983. return $model;
  1984. }
  1985. /**
  1986. * 设置where条件
  1987. * @param $status
  1988. * @param null $model
  1989. * @param string $alert
  1990. * @return StoreOrder|null
  1991. */
  1992. public static function statusWhere($status, $model = null, $alert = '')
  1993. {
  1994. if ($model == null) $model = new self;
  1995. if ('' === $status)
  1996. return $model;
  1997. else if ($status == 0)//未支付
  1998. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  1999. else if ($status == 1)//已支付 未发货
  2000. return $model->where($alert . 'paid', 1)->where('shipping_type', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2001. else if ($status == 5)//待核销
  2002. return $model->where($alert . 'paid', 1)->where('shipping_type', 2)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  2003. else if ($status == 2)//已支付 待收货
  2004. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  2005. else if ($status == 3)// 已支付 已收货 待评价
  2006. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  2007. else if ($status == 4)// 交易完成
  2008. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  2009. else if ($status == -1)//退款中
  2010. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  2011. else if ($status == -2)//已退款
  2012. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  2013. else if ($status == -3)//退款
  2014. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  2015. else
  2016. return $model;
  2017. }
  2018. /**
  2019. * 订单详情 管理员
  2020. * @param $orderId
  2021. * @param string $field
  2022. * @return array|null|\think\Model
  2023. * @throws DataNotFoundException
  2024. * @throws ModelNotFoundException
  2025. * @throws \think\exception\DbException
  2026. */
  2027. public static function getAdminOrderDetail($orderId, $field = '*', $other_where = [])
  2028. {
  2029. return self::where('order_id', $orderId)->where($other_where)->field($field)->find();
  2030. }
  2031. /**
  2032. * 获取指定时间区间的支付金额 管理员
  2033. * @param $start
  2034. * @param $stop
  2035. * @return float
  2036. */
  2037. public static function getOrderTimeBusinessVolumePrice($start, $stop, $where = [])
  2038. {
  2039. return self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  2040. }
  2041. /**
  2042. * 获取指定时间区间的支付订单数量 管理员
  2043. * @param $start
  2044. * @param $stop
  2045. * @return float
  2046. */
  2047. public static function getOrderTimeBusinessVolumeNumber($start, $stop, $where = [])
  2048. {
  2049. return self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  2050. }
  2051. /**
  2052. * 获取当前时间到指定时间的支付金额 管理员
  2053. * @param $start 开始时间
  2054. * @param $stop 结束时间
  2055. * @return mixed
  2056. */
  2057. public static function chartTimePrice($start, $stop, $where = [])
  2058. {
  2059. $model = self::where($where);
  2060. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2061. $model = $model->where('is_del', 0);
  2062. $model = $model->where('paid', 1);
  2063. $model = $model->where('refund_status', 0);
  2064. $model = $model->where('add_time', '>=', $start);
  2065. $model = $model->where('add_time', '<', $stop);
  2066. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2067. $model = $model->order('add_time ASC');
  2068. return $model->select();
  2069. }
  2070. /**
  2071. * 获取当前时间到指定时间的支付订单数 管理员
  2072. * @param $start 开始时间
  2073. * @param $stop 结束时间
  2074. * @return mixed
  2075. */
  2076. public static function chartTimeNumber($start, $stop, $where = [])
  2077. {
  2078. $model = self::where($where);
  2079. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  2080. $model = $model->where('is_del', 0);
  2081. $model = $model->where('paid', 1);
  2082. $model = $model->where('refund_status', 0);
  2083. $model = $model->where('add_time', '>=', $start);
  2084. $model = $model->where('add_time', '<', $stop);
  2085. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  2086. $model = $model->order('add_time ASC');
  2087. return $model->select();
  2088. }
  2089. /**
  2090. * 修改支付方式为线下支付
  2091. * @param $orderId
  2092. * @return bool
  2093. */
  2094. public static function setOrderTypePayOffline($orderId)
  2095. {
  2096. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  2097. }
  2098. /**
  2099. * 线下付款
  2100. * @param $id
  2101. * @return $this
  2102. */
  2103. public static function updateOffline($id)
  2104. {
  2105. $count = self::where('id', $id)->count();
  2106. if (!$count) return self::setErrorInfo('订单不存在');
  2107. $count = self::where('id', $id)->where('paid', 0)->count();
  2108. if (!$count) return self::setErrorInfo('订单已支付');
  2109. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  2110. return $res;
  2111. }
  2112. /**
  2113. * 向创建订单10分钟未付款的用户发送短信
  2114. */
  2115. public static function sendTen()
  2116. {
  2117. $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
  2118. foreach ($list as $phone) {
  2119. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  2120. }
  2121. }
  2122. public function productInfo()
  2123. {
  2124. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  2125. }
  2126. public static function setOrderProductReplyWhere($where)
  2127. {
  2128. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  2129. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  2130. })->with('productInfo', function ($query) use ($where) {
  2131. $alias = '';
  2132. if (isset($where['title']) && $where['title'] != '')
  2133. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  2134. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  2135. if ($where['is_reply'] >= 0) {
  2136. $query->where("{$alias}is_reply", $where['is_reply']);
  2137. } else {
  2138. $query->where("{$alias}is_reply", '>', 0);
  2139. }
  2140. }
  2141. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  2142. $query->where($alias . 'product_id', $where['producr_id']);
  2143. $query->where("{$alias}is_del", 0);
  2144. });
  2145. return $model;
  2146. }
  2147. public static function getOrderProductReplyList($where)
  2148. {
  2149. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  2150. $list = count($list) ? $list->toArray() : [];
  2151. foreach ($list as $key => $item) {
  2152. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  2153. foreach ($item['productInfo'] as $k => $v) {
  2154. if (!$v['nickname'] && $v['uid']) {
  2155. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  2156. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  2157. }
  2158. $v['image'] = '';
  2159. $v['store_name'] = '';
  2160. if ($v['product_id']) {
  2161. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  2162. if ($product) {
  2163. $v['image'] = $product['image'];
  2164. $v['store_name'] = $product['store_name'];
  2165. }
  2166. }
  2167. $list[$key]['productInfo'][$k] = $v;
  2168. }
  2169. }
  2170. }
  2171. $count = self::setOrderProductReplyWhere($where)->count();
  2172. return compact('list', 'count');
  2173. }
  2174. /**
  2175. * 处理奖励
  2176. */
  2177. public static function treatmentAward($order_id)
  2178. {
  2179. $order = StoreOrder::get($order_id);
  2180. if (!$order) return self::setErrorInfo('找不到订单');
  2181. if (!$order['transaction_id']) return true;
  2182. $store = SystemStore::get($order['store_id']);
  2183. if (!$store) {
  2184. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  2185. return true;
  2186. }
  2187. $store_leader = SystemAdmin::where('roles', sys_config('default_store_admin', 7))
  2188. ->where('store_id', $store['id'])->where('is_del', 0)->where('status', 1)
  2189. ->find();
  2190. if (!$store_leader) {
  2191. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  2192. return true;
  2193. }
  2194. $user = User::where('admin_id', $store_leader['id'])->find();
  2195. if (!$user) {
  2196. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  2197. return true;
  2198. }
  2199. $p_user_info = WechatUser::get($user['uid']);
  2200. // 选择发起人的订单作为分账的账单
  2201. $transaction_id = $order['transaction_id']; // 微信订单号
  2202. $out_order_no = $order['order_id'];
  2203. // 计算发起人和参与者的分账金额
  2204. $price = $order['pay_price'] - $order['pay_postage_sh'] - $order['pay_postage'];
  2205. $p_amount = bcmul($price, bcdiv($store['sharing'], 100, 4), 2); //bcmul:2个任意精度数字乘法计算
  2206. $p_separate_account_amount = floor($p_amount * 100); // 发起人分账金额,以分为单位
  2207. if ($p_separate_account_amount <= 0) {
  2208. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  2209. return true;
  2210. }
  2211. $receivers[] = array(
  2212. 'type' => 'PERSONAL_OPENID',
  2213. 'account' => $p_user_info['routine_openid'],
  2214. 'amount' => $p_separate_account_amount,
  2215. 'description' => '门店订单'
  2216. );
  2217. // 记录发起人分账开始的信息
  2218. $p_separate_account_record = new StoreSeparateAccountRecord();
  2219. $p_separate_account_record['money'] = $p_amount;
  2220. $p_separate_account_record['order_id'] = $order_id; // OK
  2221. $p_separate_account_record['uid'] = $user['uid'];
  2222. $p_separate_account_record['state'] = 0; // 默认为失败
  2223. $p_separate_account_record['notice'] = "分账失败";
  2224. $p_separate_account_record['store_id'] = $order['store_id'];
  2225. $p_separate_account_record['start_time'] = time();
  2226. $p_separate_account_record['end_time'] = 0;
  2227. $p_separate_account_record->save();
  2228. // 添加发起人为分账接受方
  2229. MiniProgramService::addReceiver($p_user_info['routine_openid']); // 添加发起人为分账接受方
  2230. if ($transaction_id) {
  2231. $res = MiniProgramService::multi_profit_sharing($transaction_id, $out_order_no, $receivers);
  2232. $res = json_decode($res, true);
  2233. // var_dump($res);
  2234. $separateAccount = StoreSeparateAccountRecord::where('order_id', $order_id)->select();
  2235. if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
  2236. foreach ($separateAccount as $key => $value) {
  2237. $value['state'] = 1;
  2238. $value['notice'] = "分账成功";
  2239. $value['end_time'] = time();
  2240. $value->save();
  2241. }
  2242. }
  2243. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  2244. }
  2245. return true;
  2246. }
  2247. =======
  2248. <?php
  2249. /**
  2250. *
  2251. * @author: xaboy<365615158@qq.com>
  2252. * @day: 2017/12/20
  2253. */
  2254. namespace app\models\store;
  2255. use app\admin\model\system\ShippingTemplatesFree;
  2256. use app\admin\model\system\ShippingTemplatesRegion;
  2257. use app\admin\model\system\SystemAdmin;
  2258. use app\admin\model\system\SystemStorePoint;
  2259. use crmeb\basic\BaseModel;
  2260. use think\db\exception\DataNotFoundException;
  2261. use think\db\exception\DbException;
  2262. use think\db\exception\ModelNotFoundException;
  2263. use think\facade\Cache;
  2264. use crmeb\traits\ModelTrait;
  2265. use think\facade\Log;
  2266. use app\models\system\SystemStore;
  2267. use app\models\routine\RoutineTemplate;
  2268. use think\Model;
  2269. use app\models\user\{User, UserAddress, UserBill, UserSpread, WechatUser};
  2270. use crmeb\services\{MiniProgramService,
  2271. OtherSMSService,
  2272. SystemConfigService,
  2273. WechatTemplateService,
  2274. workerman\ChannelService
  2275. };
  2276. use crmeb\repositories\{
  2277. GoodsRepository, PaymentRepositories, OrderRepository, ShortLetterRepositories, UserRepository
  2278. };
  2279. use app\admin\model\system\ShippingTemplates;
  2280. /**
  2281. * TODO 订单Model
  2282. * Class StoreOrder
  2283. * @package app\models\store
  2284. */
  2285. class StoreOrder extends BaseModel
  2286. {
  2287. /**
  2288. * 数据表主键
  2289. * @var string
  2290. */
  2291. protected $pk = 'id';
  2292. /**
  2293. * 模型名称
  2294. * @var string
  2295. */
  2296. protected $name = 'store_order';
  2297. use ModelTrait;
  2298. protected $insert = ['add_time'];
  2299. protected static $payType = ['weixin' => '微信支付', 'yue' => '余额支付', 'offline' => '线下支付'];
  2300. protected static $deliveryType = ['send' => '商家配送', 'express' => '快递配送'];
  2301. protected function setAddTimeAttr()
  2302. {
  2303. return time();
  2304. }
  2305. protected function setCartIdAttr($value)
  2306. {
  2307. return is_array($value) ? json_encode($value) : $value;
  2308. }
  2309. protected function getCartIdAttr($value)
  2310. {
  2311. return json_decode($value, true);
  2312. }
  2313. /**获取订单组信息
  2314. * @param $cartInfo
  2315. * @return array
  2316. */
  2317. public static function getOrderPriceGroup($cartInfo, $addr, $store_id = 0)
  2318. {
  2319. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮
  2320. $totalPrice = self::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
  2321. $totalIntegral = self::getOrderSumPrice($cartInfo, 'integral');//获取订单总金额
  2322. $costPrice = self::getOrderSumPrice($cartInfo, 'costPrice');//获取订单成本价
  2323. $vipPrice = self::getOrderSumPrice($cartInfo, 'vip_truePrice');//获取订单会员优惠金额
  2324. $totalDeposit = self::getOrderSumPrice($cartInfo, 'deposit');//获取订单会员优惠金额
  2325. //如果满额包邮等于0
  2326. if (!$storeFreePostage) {
  2327. $storePostage = 0;
  2328. } else {
  2329. if ($addr) {
  2330. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  2331. $temp_num = [];
  2332. foreach ($cartInfo as $cart) {
  2333. $temp = ShippingTemplates::get($cart['productInfo']['temp_id']);
  2334. if (!$temp) $temp = ShippingTemplates::get(1);
  2335. if ($temp->getData('type') == 1) {
  2336. $num = $cart['cart_num'];
  2337. } elseif ($temp->getData('type') == 2) {
  2338. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['weight'];
  2339. } else {
  2340. $num = $cart['cart_num'] * $cart['productInfo']['attrInfo']['volume'];
  2341. }
  2342. $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', $addr['city_id'])->find();
  2343. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', $cart['productInfo']['temp_id'])->where('city_id', 0)->find();
  2344. if (!$region) $region = ShippingTemplatesRegion::where('temp_id', 1)->where('city_id', 0)->find();
  2345. if (!$region) {
  2346. return self::setErrorInfo('运费模板不存在');
  2347. }
  2348. if (!isset($temp_num[$cart['productInfo']['temp_id']])) {
  2349. $temp_num[$cart['productInfo']['temp_id']]['number'] = $num;
  2350. $temp_num[$cart['productInfo']['temp_id']]['price'] = bcmul($cart['cart_num'], $cart['truePrice'], 2);
  2351. $temp_num[$cart['productInfo']['temp_id']]['first'] = $region['first'];
  2352. $temp_num[$cart['productInfo']['temp_id']]['first_price'] = $region['first_price'];
  2353. $temp_num[$cart['productInfo']['temp_id']]['continue'] = $region['continue'];
  2354. $temp_num[$cart['productInfo']['temp_id']]['continue_price'] = $region['continue_price'];
  2355. $temp_num[$cart['productInfo']['temp_id']]['temp_id'] = $cart['productInfo']['temp_id'];
  2356. $temp_num[$cart['productInfo']['temp_id']]['city_id'] = $addr['city_id'];
  2357. } else {
  2358. $temp_num[$cart['productInfo']['temp_id']]['number'] += $num;
  2359. $temp_num[$cart['productInfo']['temp_id']]['price'] += bcmul($cart['cart_num'], $cart['truePrice'], 2);
  2360. }
  2361. }
  2362. array_multisort(array_column($temp_num, 'first_price'), SORT_DESC, $temp_num);
  2363. $type = $storePostage = 0;
  2364. foreach ($temp_num as $k => $v) {
  2365. if (ShippingTemplatesFree::where('temp_id', $v['temp_id'])->where('city_id', $v['city_id'])->where('number', '<=', $v['number'])->where('price', '<=', $v['price'])->find()) {
  2366. unset($temp_num[$k]);
  2367. }
  2368. }
  2369. foreach ($temp_num as $v) {
  2370. if ($type == 0) {
  2371. if ($v['number'] <= $v['first']) {
  2372. $storePostage = bcadd($storePostage, $v['first_price'], 2);
  2373. } else {
  2374. if ($v['continue'] <= 0) {
  2375. $storePostage = $storePostage;
  2376. } else {
  2377. $storePostage = bcadd(bcadd($storePostage, $v['first_price'], 2), bcmul(ceil(bcdiv(bcsub($v['number'], $v['first']), $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  2378. }
  2379. }
  2380. $type = 1;
  2381. } else {
  2382. if ($v['continue'] <= 0) {
  2383. $storePostage = $storePostage;
  2384. } else {
  2385. $storePostage = bcadd($storePostage, bcmul(ceil(bcdiv($v['number'], $v['continue'] ?? 0, 2)), $v['continue_price']), 2);
  2386. }
  2387. }
  2388. }
  2389. } else {
  2390. $storePostage = 0;
  2391. }
  2392. if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
  2393. }
  2394. if (!$store_id || !$addr) {
  2395. $storePostageSh = 0;
  2396. } else {
  2397. $store = SystemStore::verificWhere()->find($store_id);
  2398. $distance = getDistance($addr['latitude'], $addr['longitude'], $store['latitude'], $store['longitude']);
  2399. //如果满额包邮等于0
  2400. if (!$distance) {
  2401. $storePostageSh = 0;
  2402. } else {
  2403. //按照运费模板计算每个运费模板下商品的件数/重量/体积以及总金额 按照首重倒序排列
  2404. $storePostageSh = $store['sh_start_money'];
  2405. if ($distance > $store['sh_start_distance']) {
  2406. if ($store['sh_step'] > 0) {
  2407. $steps = ceil(($distance - $store['sh_start_distance']) / $store['sh_step']);
  2408. $storePostageSh = bcadd($storePostageSh, bcmul($steps, $store['sh_step_money'], 2), 2);
  2409. }
  2410. }
  2411. }
  2412. }
  2413. return compact('storePostageSh', 'totalDeposit', 'storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral');
  2414. }
  2415. /**获取某个字段总金额
  2416. * @param $cartInfo
  2417. * @param $key 键名
  2418. * @return int|string
  2419. */
  2420. public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
  2421. {
  2422. $SumPrice = 0;
  2423. foreach ($cartInfo as $cart) {
  2424. $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
  2425. }
  2426. return $SumPrice;
  2427. }
  2428. /**
  2429. * 拼团
  2430. * @param $cartInfo
  2431. * @return array
  2432. */
  2433. public static function getCombinationOrderPriceGroup($cartInfo)
  2434. {
  2435. $storePostage = floatval(sys_config('store_postage')) ?: 0;
  2436. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;
  2437. $totalPrice = self::getCombinationOrderTotalPrice($cartInfo);
  2438. $costPrice = self::getCombinationOrderTotalPrice($cartInfo);
  2439. if (!$storeFreePostage) {
  2440. $storePostage = 0;
  2441. } else {
  2442. foreach ($cartInfo as $cart) {
  2443. if (!StoreCombination::where('id', $cart['combination_id'])->value('is_postage'))
  2444. $storePostage = bcadd($storePostage, StoreCombination::where('id', $cart['combination_id'])->value('postage'), 2);
  2445. }
  2446. if ($storeFreePostage <= $totalPrice) $storePostage = 0;
  2447. }
  2448. return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice');
  2449. }
  2450. /**
  2451. * 拼团价格
  2452. * @param $cartInfo
  2453. * @return float
  2454. */
  2455. public static function getCombinationOrderTotalPrice($cartInfo)
  2456. {
  2457. $totalPrice = 0;
  2458. foreach ($cartInfo as $cart) {
  2459. if ($cart['combination_id']) {
  2460. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  2461. }
  2462. }
  2463. return (float)$totalPrice;
  2464. }
  2465. /**
  2466. * 缓存订单信息
  2467. * @param $uid
  2468. * @param $cartInfo
  2469. * @param $priceGroup
  2470. * @param array $other
  2471. * @param int $cacheTime
  2472. * @return string
  2473. * @throws \Psr\SimpleCache\InvalidArgumentException
  2474. */
  2475. public static function cacheOrderInfo($uid, $cartInfo, $priceGroup, $other = [], $cacheTime = 600)
  2476. {
  2477. do {
  2478. $key = md5(time() . rand(100000, 999999));
  2479. } while (Cache::has('user_order_' . $uid . $key));
  2480. Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other'), $cacheTime);
  2481. return $key;
  2482. }
  2483. /**
  2484. * 获取订单缓存信息
  2485. * @param $uid
  2486. * @param $key
  2487. * @return mixed|null
  2488. * @throws \Psr\SimpleCache\InvalidArgumentException
  2489. */
  2490. public static function getCacheOrderInfo($uid, $key)
  2491. {
  2492. $cacheName = 'user_order_' . $uid . $key;
  2493. if (!Cache::has($cacheName)) return null;
  2494. return Cache::get($cacheName);
  2495. }
  2496. /**
  2497. * 删除订单缓存
  2498. * @param $uid
  2499. * @param $key
  2500. */
  2501. public static function clearCacheOrderInfo($uid, $key)
  2502. {
  2503. Cache::delete('user_order_' . $uid . $key);
  2504. }
  2505. /**
  2506. * 生成订单
  2507. * @param $uid
  2508. * @param $key
  2509. * @param $addressId
  2510. * @param $payType
  2511. * @param bool $useIntegral
  2512. * @param int $couponId
  2513. * @param string $mark
  2514. * @param int $combinationId
  2515. * @param int $pinkId
  2516. * @param int $seckill_id
  2517. * @param int $bargain_id
  2518. * @param bool $test
  2519. * @param int $isChannel
  2520. * @param int $shipping_type
  2521. * @param string $real_name
  2522. * @param string $phone
  2523. * @return StoreOrder|bool|\think\Model
  2524. * @throws \think\Exception
  2525. * @throws DataNotFoundException
  2526. * @throws ModelNotFoundException
  2527. * @throws \think\exception\DbException
  2528. */
  2529. public static function cacheKeyCreateOrder($uid, $key, $addressId, $payType, $useIntegral = false, $couponId = 0, $mark = '', $combinationId = 0, $pinkId = 0, $seckill_id = 0, $bargain_id = 0, $integral_id = 0, $exchange_id = 0, $test = false, $isChannel = 0, $shipping_type = 1, $real_name = '', $phone = '', $storeId = 0, $pointId = 0, $store_order = 0, $free_check = 0, $time_area = '')
  2530. {
  2531. self::beginTrans();
  2532. try {
  2533. $shipping_type = (int)$shipping_type;
  2534. $offlinePayStatus = (int)sys_config('offline_pay_status') ?? (int)2;
  2535. if ($offlinePayStatus == 2 && !$store_order) unset(self::$payType['offline']);
  2536. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('选择支付方式有误!', true);
  2537. if (self::be(['unique' => $key, 'uid' => $uid])) return self::setErrorInfo('请勿重复提交订单', true);
  2538. $userInfo = User::getUserInfo($uid);
  2539. if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
  2540. $cartGroup = self::getCacheOrderInfo($uid, $key);
  2541. if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
  2542. $cartInfo = $cartGroup['cartInfo'];
  2543. $priceGroup = $cartGroup['priceGroup'];
  2544. $other = $cartGroup['other'];
  2545. $distance = 0;
  2546. if ($other['store_id'] != $storeId && !$store_order && !$free_check && !$test) {
  2547. self::clearCacheOrderInfo($uid, $key);
  2548. return self::setErrorInfo('所选门店改变,请刷新当前页面!', true);
  2549. }
  2550. $payPrice = (float)$priceGroup['totalPrice'];
  2551. $usedIntegral = (float)$priceGroup['totalIntegral'];
  2552. $deposit = (float)$priceGroup['totalDeposit'];
  2553. $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
  2554. if ($payType == 'offline' && sys_config('offline_postage') == 1) {
  2555. $payPostage = 0;
  2556. $payPostageSh = 0;
  2557. } else {
  2558. $payPostage = self::getOrderPriceGroup($cartInfo, $addr)['storePostage'];
  2559. $payPostageSh = self::getOrderPriceGroup($cartInfo, $addr, $storeId)['storePostageSh'];
  2560. }
  2561. if (!$userInfo['admin_id']) {
  2562. if ($other['only_store_user'] ?? 0)
  2563. return self::setErrorInfo('不支持采购!', true);
  2564. } else {
  2565. $ADMIN = SystemAdmin::where('id', $userInfo['admin_id'])->find();
  2566. if (!$ADMIN || !$ADMIN['store_id']) {
  2567. return self::setErrorInfo('不支持采购!', true);
  2568. } else {
  2569. if (!SystemStore::where('id', $ADMIN['store_id'])->value('pay')) {
  2570. $payPrice = 0;
  2571. }
  2572. }
  2573. }
  2574. $cartIds = [];
  2575. $totalNum = 0;
  2576. $gainIntegral = 0;
  2577. $giveCoupons = [];
  2578. foreach ($cartInfo as $cart) {
  2579. $cartIds[] = $cart['id'];
  2580. $totalNum += $cart['cart_num'];
  2581. if (!$seckill_id) $seckill_id = $cart['seckill_id'];
  2582. if (!$bargain_id) $bargain_id = $cart['bargain_id'];
  2583. if (!$combinationId) $combinationId = $cart['combination_id'];
  2584. if (!$integral_id) $integral_id = $cart['integral_id'];
  2585. if (!$exchange_id) $exchange_id = $cart['exchange_id'];
  2586. $cartInfoGainIntegral = isset($cart['productInfo']['give_integral']) ? bcmul($cart['cart_num'], $cart['productInfo']['give_integral'], 2) : 0;
  2587. $cartInfoGainCoupons = [];
  2588. for ($i = 0; $i < $cart['cart_num']; $i++) {
  2589. if (isset($cart['productInfo']['give_coupon']) && $cart['productInfo']['give_coupon'] > 0)
  2590. $cartInfoGainCoupons[] = $cart['productInfo']['give_coupon'];
  2591. }
  2592. $giveCoupons = array_merge($giveCoupons, $cartInfoGainCoupons);
  2593. $gainIntegral = bcadd($gainIntegral, $cartInfoGainIntegral, 2);
  2594. }
  2595. $deduction = $seckill_id || $bargain_id || $combinationId || $integral_id || $exchange_id;
  2596. if ($deduction) {
  2597. $couponId = 0;
  2598. $useIntegral = false;
  2599. if (!$test) {
  2600. unset(self::$payType['offline']);
  2601. if (!array_key_exists($payType, self::$payType)) return self::setErrorInfo('营销产品不能使用线下支付!', true);
  2602. }
  2603. }
  2604. if ($shipping_type === 1) {
  2605. if (!$test && !$addressId) return self::setErrorInfo('请选择收货地址!', true);
  2606. if (!$test && (!UserAddress::be(['uid' => $uid, 'id' => $addressId, 'is_del' => 0]) || !($addressInfo = UserAddress::find($addressId))))
  2607. return self::setErrorInfo('地址选择有误!', true);
  2608. if (!$storeId && !$test && !$free_check && !$store_order) {
  2609. return self::setErrorInfo('请选择配送门店!', true);
  2610. }
  2611. $store = SystemStore::verificWhere()->where('id', $storeId)->find();
  2612. if (!$store && !$free_check && !$store_order && !$test) {
  2613. return self::setErrorInfo('门店错误!', true);
  2614. }
  2615. $distance = getDistance($addr['latitude'], $addr['longitude'], $store['latitude'], $store['longitude']);
  2616. if (!$test && !$free_check && !$store_order && $distance > $store['radius']) return self::setErrorInfo('地址在派送范围外!', true);
  2617. } else {
  2618. if ((!$real_name || !$phone) && !$test && !$exchange_id) return self::setErrorInfo('请填写姓名和电话', true);
  2619. $addressInfo['real_name'] = $real_name ?? '';
  2620. $addressInfo['phone'] = $phone ?? '';
  2621. $addressInfo['province'] = '';
  2622. $addressInfo['city'] = '';
  2623. $addressInfo['district'] = '';
  2624. $addressInfo['detail'] = '';
  2625. }
  2626. if (!$storeId && !$test && !$free_check && !$exchange_id) return self::setErrorInfo('请选择下单门店!', true);
  2627. if (!SystemStore::verificWhere()->find($storeId) && !$test && !$free_check && !$exchange_id) return self::setErrorInfo('请选择正确的下单门店!', true);
  2628. //使用优惠劵
  2629. $res1 = true;
  2630. if ($couponId) {
  2631. $couponInfo = StoreCouponUser::validAddressWhere()->where('id', $couponId)->where('uid', $uid)->find();
  2632. if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
  2633. $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
  2634. $flag = false;
  2635. foreach ($coupons as $coupon) {
  2636. if ($coupon['id'] == $couponId) {
  2637. $flag = true;
  2638. continue;
  2639. }
  2640. }
  2641. if (!$flag)
  2642. return self::setErrorInfo('不满足优惠劵的使用条件!', true);
  2643. $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
  2644. $res1 = StoreCouponUser::useCoupon($couponId);
  2645. $couponPrice = $couponInfo['coupon_price'];
  2646. } else {
  2647. $couponId = 0;
  2648. $couponPrice = 0;
  2649. }
  2650. if (!$res1) return self::setErrorInfo('使用优惠劵失败!', true);
  2651. //$shipping_type = 1 快递发货 $shipping_type = 2 门店自提
  2652. $store_self_mention = sys_config('store_self_mention') ?? 0;
  2653. if (!$store_self_mention) $shipping_type = 1;
  2654. if ($shipping_type === 1) {
  2655. //是否包邮
  2656. if ((isset($other['offlinePostage']) && $other['offlinePostage'] && $payType == 'offline')) $payPostage = 0;
  2657. $payPrice = (float)bcadd($payPrice, $payPostage, 2);
  2658. $payPrice = bcadd($payPrice, $payPostageSh, 2);
  2659. } else if ($shipping_type === 2) {
  2660. //门店自提没有邮费支付
  2661. $priceGroup['storePostage'] = 0;
  2662. $payPostage = 0;
  2663. $payPostageSh = 0;
  2664. if (!$pointId && !$test && !$store_order && !$free_check) {
  2665. return self::setErrorInfo('请选择自提点', true);
  2666. }
  2667. }
  2668. $res2 = true;
  2669. //积分商品
  2670. $SurplusIntegral = $userInfo['integral'];
  2671. if ($usedIntegral > 0) {
  2672. if ($usedIntegral > $userInfo['integral']) {
  2673. return self::setErrorInfo('积分不足', true);
  2674. } else {
  2675. $SurplusIntegral -= $usedIntegral;
  2676. $res2 = $res2 && User::bcDec($userInfo['uid'], 'integral', $usedIntegral, 'uid');
  2677. $res2 = $res2 && false != UserBill::expend('积分商品兑换', $uid, 'integral', 'exchange', $usedIntegral, $key, bcsub($userInfo['integral'], $usedIntegral), '购买积分商品使用' . floatval($usedIntegral) . '积分');
  2678. }
  2679. }
  2680. //积分抵扣
  2681. if ($useIntegral && bcsub($userInfo['integral'], $usedIntegral) > 0) {
  2682. $deductionPrice = (float)bcmul(bcsub($userInfo['integral'], $usedIntegral), $other['integralRatio'], 2);
  2683. if ($deductionPrice < $payPrice) {
  2684. $payPrice = bcsub($payPrice, $deductionPrice, 2);
  2685. $usedIntegral2 = bcsub($userInfo['integral'], $usedIntegral);
  2686. $usedIntegral = $userInfo['integral'];
  2687. $SurplusIntegral = 0;
  2688. $res2 = false !== User::edit(['integral' => 0], $userInfo['uid'], 'uid');
  2689. } else {
  2690. $deductionPrice = $payPrice;
  2691. $usedIntegral2 = (float)bcdiv($payPrice, $other['integralRatio'], 2);
  2692. $usedIntegral += (float)bcdiv($payPrice, $other['integralRatio'], 2);
  2693. $SurplusIntegral = bcsub($SurplusIntegral, $usedIntegral, 2);
  2694. $res2 = false !== User::bcDec($userInfo['uid'], 'integral', $usedIntegral2, 'uid');
  2695. $payPrice = 0;
  2696. }
  2697. $res2 = $res2 && false != UserBill::expend('积分抵扣', $uid, 'integral', 'deduction', $usedIntegral2, $key, $SurplusIntegral, '购买商品使用' . floatval($usedIntegral2) . '积分抵扣' . floatval($deductionPrice) . '元');
  2698. } else {
  2699. $deductionPrice = 0;
  2700. $usedIntegral += 0;
  2701. }
  2702. if (!$res2) return self::setErrorInfo('使用积分抵扣失败!', true);
  2703. if ($payPrice <= 0) $payPrice = 0;
  2704. if ($test) {
  2705. self::rollbackTrans();
  2706. return [
  2707. 'total_price' => $priceGroup['totalPrice'],
  2708. 'pay_price' => $payPrice,
  2709. 'pay_postage' => $payPostage,
  2710. 'coupon_price' => $couponPrice,
  2711. 'deduction_price' => $deductionPrice,
  2712. 'SurplusIntegral' => $SurplusIntegral,
  2713. 'pay_postage_sh' => $payPostageSh,
  2714. 'store' => SystemStore::verificWhere()->find($storeId),
  2715. 'deposit' => $deposit,
  2716. 'distance' => $distance,
  2717. 'store_user' => $other['only_store_user'] ?? 0,
  2718. ];
  2719. }
  2720. $orderInfo = [
  2721. 'uid' => $uid,
  2722. 'order_id' => $test ? 0 : self::getNewOrderId(),
  2723. 'real_name' => $addressInfo['real_name'],
  2724. 'user_phone' => $addressInfo['phone'],
  2725. 'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
  2726. 'cart_id' => $cartIds,
  2727. 'total_num' => $totalNum,
  2728. 'total_price' => $priceGroup['totalPrice'],
  2729. 'total_postage' => $priceGroup['storePostage'],
  2730. 'coupon_id' => $couponId,
  2731. 'coupon_price' => $couponPrice,
  2732. 'pay_price' => ($store_order && $payType == 'weixin') ? 0 : $payPrice,
  2733. 'pay_postage' => ($store_order && $payType == 'weixin') ? 0 : $payPostage,
  2734. 'pay_postage_sh' => ($store_order && $payType == 'weixin') ? 0 : $payPostageSh,
  2735. 'distance' => $distance,
  2736. 'deduction_price' => $deductionPrice,
  2737. 'paid' => 0,
  2738. 'pay_type' => $payType,
  2739. 'use_integral' => $usedIntegral,
  2740. 'gain_integral' => $gainIntegral,
  2741. 'give_coupons' => implode(',', $giveCoupons),
  2742. 'mark' => htmlspecialchars($mark),
  2743. 'combination_id' => $combinationId,
  2744. 'pink_id' => $pinkId,
  2745. 'seckill_id' => $seckill_id,
  2746. 'bargain_id' => $bargain_id,
  2747. 'integral_id' => $integral_id,
  2748. 'exchange_id' => $exchange_id,
  2749. 'cost' => $priceGroup['costPrice'],
  2750. 'is_channel' => $isChannel,
  2751. 'add_time' => time(),
  2752. 'unique' => $key,
  2753. 'shipping_type' => $shipping_type,
  2754. 'deposit' => $deposit,
  2755. 'deposit_back' => 0,
  2756. 'deposit_status' => 0,
  2757. 'store_order' => $store_order,
  2758. 'province' => $addressInfo['province'],
  2759. 'city' => $addressInfo['city'],
  2760. 'district' => $addressInfo['district'],
  2761. 'time_area' => $time_area,
  2762. 'store_user' => $other['only_store_user'] ?? 0,
  2763. ];
  2764. $orderInfo['store_id'] = SystemStore::getStoreDispose($storeId, 'id');
  2765. if (!$orderInfo['store_id'] && !$free_check) return self::setErrorInfo('暂无门店无法选择门店!', true);
  2766. else if ($free_check) $orderInfo['store_id'] = 0;
  2767. if (($other['only_store_user'] ?? 0) && !$orderInfo['store_id']) {
  2768. return self::setErrorInfo('请选择采购门店!', true);
  2769. }
  2770. if ($orderInfo['store_id']) {
  2771. $store = SystemStore::get($orderInfo['store_id']);
  2772. if (!$store['store_user'] && ($other['only_store_user'] ?? 0)) {
  2773. return self::setErrorInfo('门店不支持采购!', true);
  2774. }
  2775. $orderInfo['province'] = explode(',', $store['address'])[0] ?? '';
  2776. $orderInfo['city'] = explode(',', $store['address'])[1] ?? '';
  2777. $orderInfo['district'] = explode(',', $store['address'])[2] ?? '';
  2778. }
  2779. if ($shipping_type === 2) {
  2780. $orderInfo['verify_code'] = self::getStoreCode();
  2781. if (!$store_order && !$free_check) {
  2782. $orderInfo['point_id'] = SystemStorePoint::verificWhere()->where('store_id', $orderInfo['store_id'])->where('id', $pointId)->value('id');
  2783. if (!$orderInfo['point_id']) return self::setErrorInfo('找不到对应自提点!', true);
  2784. }
  2785. }
  2786. $order = self::create($orderInfo);
  2787. if (!$order) return self::setErrorInfo('订单生成失败!', true);
  2788. $res5 = true;
  2789. foreach ($cartInfo as $cart) {
  2790. //减库存加销量
  2791. if ($combinationId) $res5 = $res5 && StoreCombination::decCombinationStock($cart['cart_num'], $combinationId, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2792. else if ($seckill_id) $res5 = $res5 && StoreSeckill::decSeckillStock($cart['cart_num'], $seckill_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2793. else if ($bargain_id) $res5 = $res5 && StoreBargain::decBargainStock($cart['cart_num'], $bargain_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2794. else if ($integral_id) $res5 = $res5 && StoreIntegral::decIntegralStock($cart['cart_num'], $integral_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2795. else if ($exchange_id) $res5 = $res5 && StoreExchange::decIntegralStock($cart['cart_num'], $exchange_id, isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2796. else $res5 = $res5 && StoreProduct::decProductStock($cart['cart_num'], $cart['productInfo']['id'], isset($cart['productInfo']['attrInfo']) ? $cart['productInfo']['attrInfo']['unique'] : '');
  2797. }
  2798. //保存购物车商品信息
  2799. $res4 = false !== StoreOrderCartInfo::setCartInfo($order['id'], $cartInfo);
  2800. //门店库存
  2801. $res4 = $res4 && SystemStore::decStock($order);
  2802. if (!$res4) return self::setErrorInfo(SystemStore::getErrorInfo(), true);
  2803. //购物车状态修改
  2804. $res6 = false !== StoreCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]);
  2805. if (!$res4 || !$res5 || !$res6) return self::setErrorInfo('订单生成失败!', true);
  2806. //自动设置默认地址
  2807. UserRepository::storeProductOrderCreateEbApi($order, compact('cartInfo', 'addressId'));
  2808. self::clearCacheOrderInfo($uid, $key);
  2809. self::commitTrans();
  2810. StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
  2811. return $order;
  2812. } catch
  2813. (\PDOException $e) {
  2814. self::rollbackTrans();
  2815. return self::setErrorInfo('生成订单时SQL执行错误错误原因:' . $e->getMessage());
  2816. } catch (\Exception $e) {
  2817. self::rollbackTrans();
  2818. return self::setErrorInfo('生成订单时系统错误错误原因:' . $e->getMessage());
  2819. }
  2820. }
  2821. /**
  2822. * 回退积分
  2823. * @param $order 订单信息
  2824. * @return bool
  2825. */
  2826. public static function RegressionIntegral($order)
  2827. {
  2828. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  2829. if ($order['use_integral'] <= 0) return true;
  2830. if ((int)$order['status'] != -2 && (int)$order['refund_status'] != 2 && $order['back_integral'] >= $order['use_integral']) return true;
  2831. $res = User::bcInc($order['uid'], 'integral', $order['use_integral']);
  2832. if (!$res) return self::setErrorInfo('回退积分增加失败');
  2833. UserBill::income('积分回退', $order['uid'], 'integral', 'deduction', $order['use_integral'], $order['unique'], User::where('uid', $order['uid'])->value('integral'), '购买商品失败,回退积分' . floatval($order['use_integral']));
  2834. return false !== self::where('order_id', $order['order_id'])->update(['back_integral' => $order['use_integral']]);
  2835. }
  2836. /**
  2837. * 回退库存和销量
  2838. * @param $order 订单信息
  2839. * @return bool
  2840. * @throws DataNotFoundException
  2841. * @throws ModelNotFoundException
  2842. * @throws \think\exception\DbException
  2843. */
  2844. public static function RegressionStock($order)
  2845. {
  2846. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  2847. $combinationId = $order['combination_id'];
  2848. $seckill_id = $order['seckill_id'];
  2849. $bargain_id = $order['bargain_id'];
  2850. $integral_id = $order['integral_id'];
  2851. $exchange_id = $order['exchange_id'];
  2852. $res5 = true;
  2853. $cartInfo = StoreOrderCartInfo::where('cart_id', 'in', $order['cart_id'])->select();
  2854. foreach ($cartInfo as $cart) {
  2855. //增库存减销量
  2856. if ($combinationId) $res5 = $res5 && StoreCombination::incCombinationStock($cart['cart_info']['cart_num'], $combinationId);
  2857. else if ($seckill_id) $res5 = $res5 && StoreSeckill::incSeckillStock($cart['cart_info']['cart_num'], $seckill_id);
  2858. else if ($bargain_id) $res5 = $res5 && StoreBargain::incBargainStock($cart['cart_info']['cart_num'], $bargain_id);
  2859. else if ($integral_id) $res5 = $res5 && StoreIntegral::incSeckillStock($cart['cart_info']['cart_num'], $integral_id);
  2860. else if ($exchange_id) $res5 = $res5 && StoreExchange::incSeckillStock($cart['cart_info']['cart_num'], $exchange_id);
  2861. else $res5 = $res5 && StoreProduct::incProductStock($cart['cart_info']['cart_num'], $cart['cart_info']['productInfo']['id'], isset($cart['cart_info']['productInfo']['attrInfo']) ? $cart['cart_info']['productInfo']['attrInfo']['unique'] : '');
  2862. }
  2863. return $res5;
  2864. }
  2865. /**
  2866. * 回退优惠卷
  2867. * @param $order 订单信息
  2868. * @return bool
  2869. */
  2870. public static function RegressionCoupon($order)
  2871. {
  2872. if ($order['paid'] || $order['status'] == -2 || $order['is_del']) return true;
  2873. $res = true;
  2874. if ($order['coupon_id'] && StoreCouponUser::be(['id' => $order['coupon_id'], 'uid' => $order['uid'], 'status' => 1])) {
  2875. $res = $res && false !== StoreCouponUser::where('id', $order['coupon_id'])->where('uid', $order['uid'])->update(['status' => 0, 'use_time' => 0]);
  2876. }
  2877. return $res;
  2878. }
  2879. /**
  2880. * 取消订单
  2881. * @param string order_id 订单id
  2882. * @param $uid
  2883. * @return bool
  2884. * @throws DataNotFoundException
  2885. * @throws ModelNotFoundException
  2886. * @throws \think\exception\DbException
  2887. */
  2888. public static function cancelOrder($order_id, $uid)
  2889. {
  2890. $order = self::where('order_id', $order_id)->where('uid', $uid)->find();
  2891. if (!$order) return self::setErrorInfo('没有查到此订单');
  2892. self::beginTrans();
  2893. try {
  2894. $res = self::RegressionIntegral($order) && self::RegressionStock($order) && self::RegressionCoupon($order);
  2895. $order->is_del = 1;
  2896. if ($res && $order->save()) {
  2897. self::commitTrans();
  2898. return true;
  2899. } else
  2900. return false;
  2901. } catch (\Exception $e) {
  2902. self::rollbackTrans();
  2903. return self::setErrorInfo(['line' => $e->getLine(), 'message' => $e->getMessage()]);
  2904. }
  2905. }
  2906. /**
  2907. * 生成订单唯一id
  2908. * @param $uid 用户uid
  2909. * @return string
  2910. */
  2911. public static function getNewOrderId()
  2912. {
  2913. do {
  2914. list($msec, $sec) = explode(' ', microtime());
  2915. $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
  2916. $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  2917. } while (self::be(['order_id' => $orderId]));// $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
  2918. return $orderId;
  2919. }
  2920. /**
  2921. * 修改订单号
  2922. * @param $orderId
  2923. * @return string
  2924. */
  2925. public static function changeOrderId($orderId)
  2926. {
  2927. $ymd = substr($orderId, 2, 8);
  2928. $key = substr($orderId, 16);
  2929. return 'wx' . $ymd . date('His') . $key;
  2930. }
  2931. /**
  2932. * 查找购物车里的所有产品标题
  2933. * @param $cartId 购物车id
  2934. * @return bool|string
  2935. */
  2936. public static function getProductTitle($cartId)
  2937. {
  2938. $title = '';
  2939. try {
  2940. $orderCart = StoreOrderCartInfo::where('cart_id', 'in', $cartId)->field('cart_info')->select();
  2941. foreach ($orderCart as $item) {
  2942. if (isset($item['cart_info']['productInfo']['store_name'])) {
  2943. $title .= $item['cart_info']['productInfo']['store_name'] . '|';
  2944. }
  2945. }
  2946. unset($item);
  2947. if (!$title) {
  2948. $productIds = StoreCart::where('id', 'in', $cartId)->column('product_id');
  2949. $productlist = ($productlist = StoreProduct::getProductField($productIds, 'store_name')) ? $productlist->toArray() : [];
  2950. foreach ($productlist as $item) {
  2951. if (isset($item['store_name'])) $title .= $item['store_name'] . '|';
  2952. }
  2953. }
  2954. if ($title) $title = substr($title, 0, strlen($title) - 1);
  2955. unset($item);
  2956. } catch (\Exception $e) {
  2957. }
  2958. return $title;
  2959. }
  2960. /**
  2961. * 获取门店自提唯一核销码
  2962. * @return bool|string
  2963. */
  2964. public static function getStoreCode()
  2965. {
  2966. list($msec, $sec) = explode(' ', microtime());
  2967. $num = bcadd(time(), mt_rand(10, 999999), 0) . '' . substr($msec, 2, 3);//生成随机数
  2968. if (strlen($num) < 12)
  2969. $num = str_pad((string)$num, 12, 0, STR_PAD_RIGHT);
  2970. else
  2971. $num = substr($num, 0, 12);
  2972. if (self::be(['verify_code' => $num])) return self::getStoreCode();
  2973. return $num;
  2974. }
  2975. /**
  2976. * 余额支付
  2977. * @param $order_id
  2978. * @param $uid
  2979. * @param string $formId
  2980. * @return bool
  2981. * @throws \think\Exception
  2982. * @throws DataNotFoundException
  2983. * @throws ModelNotFoundException
  2984. * @throws \think\exception\DbException
  2985. */
  2986. public static function yuePay($order_id, $uid, $formId = '')
  2987. {
  2988. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  2989. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  2990. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  2991. // if($orderInfo['pay_type'] != 'yue') return self::setErrorInfo('该订单不能使用余额支付!');
  2992. $userInfo = User::getUserInfo($uid);
  2993. if ($userInfo['now_money'] < bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2))
  2994. return self::setErrorInfo(['status' => 'pay_deficiency', 'msg' => '余额不足' . floatval(bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2))]);
  2995. self::beginTrans();
  2996. $res1 = false !== User::bcDec($uid, 'now_money', bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2), 'uid');
  2997. $res2 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2), $orderInfo['id'], $userInfo['now_money'], '余额支付' . floatval(bcadd($orderInfo['pay_price'], $orderInfo['deposit'], 2)) . '元购买商品' . ($orderInfo['deposit'] ? "(含押金{$orderInfo['deposit']})" : ''));
  2998. $res3 = self::paySuccess($order_id, 'yue', $formId);//余额支付成功
  2999. try {
  3000. PaymentRepositories::yuePayProduct($userInfo, $orderInfo);
  3001. } catch (\Exception $e) {
  3002. self::rollbackTrans();
  3003. return self::setErrorInfo($e->getMessage());
  3004. }
  3005. $res = $res1 && $res2 && $res3;
  3006. self::checkTrans($res);
  3007. return $res;
  3008. }
  3009. /**
  3010. * 微信支付 为 0元时
  3011. * @param $order_id
  3012. * @param $uid
  3013. * @param string $formId
  3014. * @return bool
  3015. * @throws \think\Exception
  3016. * @throws DataNotFoundException
  3017. * @throws ModelNotFoundException
  3018. * @throws \think\exception\DbException
  3019. */
  3020. public static function jsPayPrice($order_id, $uid, $formId = '')
  3021. {
  3022. $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
  3023. if (!$orderInfo) return self::setErrorInfo('订单不存在!');
  3024. if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
  3025. $userInfo = User::getUserInfo($uid);
  3026. self::beginTrans();
  3027. $res1 = UserBill::expend('购买商品', $uid, 'now_money', 'pay_product', $orderInfo['pay_price'], $orderInfo['id'], $userInfo['now_money'], '微信支付' . floatval($orderInfo['pay_price']) . '元购买商品');
  3028. $res2 = self::paySuccess($order_id, 'weixin', $formId);//微信支付为0时
  3029. $res = $res1 && $res2;
  3030. self::checkTrans($res);
  3031. return $res;
  3032. }
  3033. /**
  3034. * 用户申请退款
  3035. * @param $uni
  3036. * @param $uid
  3037. * @param string $refundReasonWap
  3038. * @return bool
  3039. */
  3040. public static function orderApplyRefund($uni, $uid, $refundReasonWap = '', $refundReasonWapExplain = '', $refundReasonWapImg = [])
  3041. {
  3042. $order = self::getUserOrderDetail($uid, $uni);
  3043. if (!$order) return self::setErrorInfo('支付订单不存在!');
  3044. if ($order['refund_status'] == 2) return self::setErrorInfo('订单已退款!');
  3045. if ($order['refund_status'] == 1) return self::setErrorInfo('正在申请退款中!');
  3046. if ($order['status'] == 1) return self::setErrorInfo('订单当前无法退款!');
  3047. self::beginTrans();
  3048. $res1 = false !== StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款,原因:' . $refundReasonWap);
  3049. $res2 = false !== self::edit(['refund_status' => 1, 'refund_reason_time' => time(), 'refund_reason_wap' => $refundReasonWap, 'refund_reason_wap_explain' => $refundReasonWapExplain, 'refund_reason_wap_img' => json_encode($refundReasonWapImg)], $order['id'], 'id');
  3050. $res = $res1 && $res2;
  3051. self::checkTrans($res);
  3052. if (!$res)
  3053. return self::setErrorInfo('申请退款失败!');
  3054. else {
  3055. try {
  3056. if (in_array($order['is_channel'], [0, 2])) {
  3057. //公众号发送模板消息通知客服
  3058. WechatTemplateService::sendAdminNoticeTemplate([
  3059. 'first' => "亲,有个订单申请退款 \n订单号:{$order['order_id']}",
  3060. 'keyword1' => '退款申请',
  3061. 'keyword2' => '已支付',
  3062. 'keyword3' => date('Y/m/d H:i', time()),
  3063. 'remark' => '请及时处理'
  3064. ]);
  3065. }
  3066. if (in_array($order['is_channel'], [1, 2])) {
  3067. //小程序 发送模板消息
  3068. RoutineTemplate::sendOrderRefundStatus($order, $refundReasonWap);
  3069. }
  3070. //通知后台消息提醒
  3071. ChannelService::instance()->send('NEW_REFUND_ORDER', ['order_id' => $order['order_id']]);
  3072. } catch (\Exception $e) {
  3073. }
  3074. //发送短信
  3075. event('ShortMssageSend', [$order['order_id'], 'AdminRefund']);
  3076. return true;
  3077. }
  3078. }
  3079. /**
  3080. * //TODO 支付成功后
  3081. * @param $orderId
  3082. * @param string $paytype
  3083. * @param string $formId
  3084. * @return bool
  3085. * @throws DataNotFoundException
  3086. * @throws DbException
  3087. * @throws ModelNotFoundException
  3088. */
  3089. public static function paySuccess($orderId, $paytype = 'weixin', $formId = '')
  3090. {
  3091. $order = self::where('order_id', $orderId)->find();
  3092. $resPink = true;
  3093. $res1 = self::where('order_id', $orderId)->update(['paid' => 1, 'is_del' => 0, 'is_system_del' => 0, 'pay_type' => $paytype, 'pay_time' => time()]);//订单改为支付
  3094. if ($order->combination_id && $res1 && !$order->refund_status) $resPink = StorePink::createPink($order);//创建拼团
  3095. if ($order->exchange_id && $res1 && !$order->refund_status) $resExhcnage = StoreExchange::createOrder($order);//创建兑换券
  3096. $oid = self::where('order_id', $orderId)->value('id');
  3097. StoreOrderStatus::status($oid, 'pay_success', '用户付款成功');
  3098. $now_money = User::where('uid', $order['uid'])->value('now_money');
  3099. UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', bcadd($order['pay_price'], $order['deposit'], 2), $order['id'], $now_money, '支付' . floatval(bcadd($order['pay_price'], $order['deposit'], 2)) . '元购买商品' . ($order['deposit'] ? "(含押金{$order['deposit']})" : ''));
  3100. //支付成功后
  3101. event('OrderPaySuccess', [$order, $formId]);
  3102. $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
  3103. $user = User::getUserInfo($order['uid']);
  3104. if (!$order['store_order']) {
  3105. if ($user['phone'])
  3106. OtherSMSService::send($user['phone'], '成功支付' . floatval(bcadd($order['pay_price'], $order['deposit'], 2)) . '元购买商品' . ($order['deposit'] ? "(含押金{$order['deposit']})" : ''));
  3107. if ($openid = WechatUser::where('uid', $order['uid'])->value('routine_openid')) {
  3108. MiniProgramService::sendSubscribeTemlate($openid, 'utyQMQe5vfiJt1CA3-Q3JnGd2_dQ3mdyY0K44Gpaut4',
  3109. [
  3110. 'thing2' => self::getSubstrUTf8(self::getProductTitle($order['cart_id']), 8),
  3111. 'amount3' => $order['total_price'],
  3112. 'number4' => $order['total_num'],
  3113. 'thing6' => $order['pay_price'],
  3114. ]);
  3115. }
  3116. }
  3117. return false !== $res;
  3118. }
  3119. /*
  3120. * 线下支付消息通知
  3121. * 待完善
  3122. *
  3123. * */
  3124. public static function createOrderTemplate($order)
  3125. {
  3126. //$goodsName = StoreOrderCartInfo::getProductNameList($order['id']);
  3127. // RoutineTemplateService::sendTemplate(WechatUser::getOpenId($order['uid']),RoutineTemplateService::ORDER_CREATE, [
  3128. // 'first'=>'亲,您购买的商品已支付成功',
  3129. // 'keyword1'=>date('Y/m/d H:i',$order['add_time']),
  3130. // 'keyword2'=>implode(',',$goodsName),
  3131. // 'keyword3'=>$order['order_id'],
  3132. // 'remark'=>'点击查看订单详情'
  3133. // ],Url::build('/wap/My/order',['uni'=>$order['order_id']],true,true));
  3134. // RoutineTemplateService::sendAdminNoticeTemplate([
  3135. // 'first'=>"亲,您有一个新订单 \n订单号:{$order['order_id']}",
  3136. // 'keyword1'=>'新订单',
  3137. // 'keyword2'=>'线下支付',
  3138. // 'keyword3'=>date('Y/m/d H:i',time()),
  3139. // 'remark'=>'请及时处理'
  3140. // ]);
  3141. }
  3142. public function point()
  3143. {
  3144. return $this->hasOne(SystemStorePoint::class, 'id', 'point_id')->field('*');
  3145. }
  3146. public function store()
  3147. {
  3148. return $this->hasOne(SystemStore::class, 'id', 'store_id')->field('*');
  3149. }
  3150. /**
  3151. * 获取订单详情
  3152. * @param $uid
  3153. * @param $key
  3154. * @return array|\think\Model|null
  3155. * @throws DataNotFoundException
  3156. * @throws ModelNotFoundException
  3157. * @throws \think\exception\DbException
  3158. */
  3159. public static function getUserOrderDetail($uid, $key)
  3160. {
  3161. return self::with(['store', 'point'])->where('order_id|unique', $key)->where('uid|gift_uid', $uid)->where('is_del', 0)->find();
  3162. }
  3163. /**
  3164. * TODO 订单发货
  3165. * @param array $postageData 发货信息
  3166. * @param string $oid orderID
  3167. */
  3168. public static function orderPostageAfter($postageData, $oid)
  3169. {
  3170. $order = self::where('id', $oid)->find();
  3171. if ($postageData['delivery_type'] == 'send') {//送货
  3172. RoutineTemplate::sendOrderPostage($order);
  3173. } else if ($postageData['delivery_type'] == 'express') {//发货
  3174. RoutineTemplate::sendOrderPostage($order, 1);
  3175. }
  3176. }
  3177. /** 收货后发送模版消息
  3178. * @param $order
  3179. */
  3180. public static function orderTakeAfter($order)
  3181. {
  3182. $title = self::getProductTitle($order['cart_id']);
  3183. if ($order['is_channel'] == 1) {//小程序
  3184. RoutineTemplate::sendOrderTakeOver($order, $title);
  3185. } else {
  3186. $openid = WechatUser::where('uid', $order['uid'])->value('openid');
  3187. \crmeb\services\WechatTemplateService::sendTemplate($openid, \crmeb\services\WechatTemplateService::ORDER_TAKE_SUCCESS, [
  3188. 'first' => '亲,您的订单已收货',
  3189. 'keyword1' => $order['order_id'],
  3190. 'keyword2' => '已收货',
  3191. 'keyword3' => date('Y-m-d H:i:s', time()),
  3192. 'keyword4' => $title,
  3193. 'remark' => '感谢您的光临!'
  3194. ]);
  3195. }
  3196. }
  3197. /**
  3198. * 删除订单
  3199. * @param $uni
  3200. * @param $uid
  3201. * @return bool
  3202. */
  3203. public static function removeOrder($uni, $uid)
  3204. {
  3205. $order = self::getUserOrderDetail($uid, $uni);
  3206. if (!$order) return self::setErrorInfo('订单不存在!');
  3207. $order = self::tidyOrder($order);
  3208. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  3209. return self::setErrorInfo('该订单无法删除!');
  3210. if (false !== self::edit(['is_del' => 1], $order['id'], 'id') && false !== StoreOrderStatus::status($order['id'], 'remove_order', '删除订单')) {
  3211. //未支付和已退款的状态下才可以退积分退库存退优惠券
  3212. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  3213. event('StoreOrderRegressionAllAfter', [$order]);
  3214. }
  3215. event('UserOrderRemoved', $uni);
  3216. return true;
  3217. } else
  3218. return self::setErrorInfo('订单删除失败!');
  3219. }
  3220. /**
  3221. * //TODO 用户确认收货
  3222. * @param $uni
  3223. * @param $uid
  3224. */
  3225. public static function takeOrder($uni, $uid)
  3226. {
  3227. $order = self::getUserOrderDetail($uid, $uni);
  3228. if (!$order) return self::setErrorInfo('订单不存在!');
  3229. $order = self::tidyOrder($order);
  3230. if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
  3231. self::beginTrans();
  3232. if (false !== self::edit(['status' => 2], $order['id'], 'id') &&
  3233. false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
  3234. try {
  3235. OrderRepository::storeProductOrderUserTakeDelivery($order, $uid);
  3236. UserBill::where('uid', $order['uid'])->where('link_id', $order['id'])->where('type', 'pay_money')->update(['take' => 1]);
  3237. } catch (\Exception $e) {
  3238. self::rollbackTrans();
  3239. return self::setErrorInfo($e->getMessage());
  3240. }
  3241. self::commitTrans();
  3242. event('UserLevelAfter', [User::get($uni)]);
  3243. event('UserOrderTake', $uni);
  3244. //短信通知
  3245. event('ShortMssageSend', [$order['order_id'], ['Receiving', 'AdminConfirmTakeOver']]);
  3246. return true;
  3247. } else {
  3248. self::rollbackTrans();
  3249. return false;
  3250. }
  3251. }
  3252. /**
  3253. * 获取订单状态购物车等信息
  3254. * @param $order
  3255. * @param bool $detail 是否获取订单购物车详情
  3256. * @param bool $isPic 是否获取订单状态图片
  3257. * @return mixed
  3258. * @throws DataNotFoundException
  3259. * @throws ModelNotFoundException
  3260. * @throws \think\exception\DbException
  3261. */
  3262. public static function tidyOrder($order, $detail = false, $isPic = false)
  3263. {
  3264. if ($detail == true && isset($order['id'])) {
  3265. $cartInfo = StoreOrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
  3266. $info = [];
  3267. foreach ($cartInfo as $k => $cart) {
  3268. $cart = json_decode($cart, true);
  3269. $cart['unique'] = $k;
  3270. //新增是否评价字段
  3271. $cart['is_reply'] = StoreProductReply::where('unique', $k)->count();
  3272. array_push($info, $cart);
  3273. unset($cart);
  3274. }
  3275. $order['cartInfo'] = $info;
  3276. }
  3277. $status = [];
  3278. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  3279. $status['_type'] = 9;
  3280. $status['_title'] = '线下付款';
  3281. $status['_msg'] = '商家处理中,请耐心等待';
  3282. $status['_class'] = 'nobuy';
  3283. } else if (!$order['paid']) {
  3284. $status['_type'] = 0;
  3285. $status['_title'] = '未支付';
  3286. //系统预设取消订单时间段
  3287. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  3288. //获取配置
  3289. $systemValue = SystemConfigService::more($keyValue);
  3290. //格式化数据
  3291. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  3292. if ($order['pink_id'] || $order['combination_id']) {
  3293. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  3294. $time = bcadd($order['add_time'], $order_pink_time * 3600, 0);
  3295. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3296. } else if ($order['seckill_id']) {
  3297. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  3298. $time = bcadd($order['add_time'], $order_seckill_time * 3600, 0);
  3299. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3300. } else if ($order['bargain_id']) {
  3301. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  3302. $time = bcadd($order['add_time'], $order_bargain_time * 3600, 0);
  3303. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3304. } else {
  3305. $time = bcadd($order['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  3306. $status['_msg'] = '请在' . date('m-d H:i:s', $time) . '前完成支付!';
  3307. }
  3308. $status['_class'] = 'nobuy';
  3309. } else if ($order['refund_status'] == 1) {
  3310. $status['_type'] = -1;
  3311. $status['_title'] = '申请退款中';
  3312. $status['_msg'] = '商家审核中,请耐心等待';
  3313. $status['_class'] = 'state-sqtk';
  3314. } else if ($order['refund_status'] == 2) {
  3315. $status['_type'] = -2;
  3316. $status['_title'] = '已退款';
  3317. $status['_msg'] = '已为您退款,感谢您的支持';
  3318. $status['_class'] = 'state-sqtk';
  3319. } else if (!$order['status']) {
  3320. if ($order['pink_id']) {
  3321. if (StorePink::where('id', $order['pink_id'])->where('status', 1)->count()) {
  3322. $status['_type'] = 1;
  3323. $status['_title'] = '拼团中';
  3324. $status['_msg'] = '等待其他人参加拼团';
  3325. $status['_class'] = 'state-nfh';
  3326. } else {
  3327. $status['_type'] = 1;
  3328. $status['_title'] = '未发货';
  3329. $status['_msg'] = '商家未发货,请耐心等待';
  3330. $status['_class'] = 'state-nfh';
  3331. }
  3332. } else {
  3333. if ($order['shipping_type'] === 1) {
  3334. $status['_type'] = 1;
  3335. $status['_title'] = '未发货';
  3336. $status['_msg'] = '商家未发货,请耐心等待';
  3337. $status['_class'] = 'state-nfh';
  3338. } else {
  3339. $status['_type'] = 1;
  3340. $status['_title'] = '待核销';
  3341. $status['_msg'] = '待核销,请到核销点进行核销';
  3342. $status['_class'] = 'state-nfh';
  3343. }
  3344. }
  3345. } else if ($order['status'] == 1) {
  3346. if ($order['delivery_type'] == 'send') {//TODO 送货
  3347. $status['_type'] = 2;
  3348. $status['_title'] = '待收货';
  3349. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($order['id'], 'delivery')) . '服务商已送货';
  3350. $status['_class'] = 'state-ysh';
  3351. } else {//TODO 发货
  3352. $status['_type'] = 2;
  3353. $status['_title'] = '待收货';
  3354. if ($order['delivery_type'] == 'fictitious')
  3355. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_fictitious');
  3356. else
  3357. $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
  3358. $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
  3359. $status['_class'] = 'state-ysh';
  3360. }
  3361. } else if ($order['status'] == 2) {
  3362. $status['_type'] = 3;
  3363. $status['_title'] = '待评价';
  3364. $status['_msg'] = '已收货,快去评价一下吧';
  3365. $status['_class'] = 'state-ypj';
  3366. } else if ($order['status'] == 3) {
  3367. $status['_type'] = 4;
  3368. $status['_title'] = '交易完成';
  3369. $status['_msg'] = '交易完成,感谢您的支持';
  3370. $status['_class'] = 'state-ytk';
  3371. }
  3372. if (isset($order['pay_type']))
  3373. $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
  3374. if (isset($order['delivery_type']))
  3375. $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
  3376. $order['_status'] = $status;
  3377. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : date('Y-m-d H:i:s', $order['add_time']);
  3378. $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  3379. $order['_arrive_time'] = isset($order['arrive_time']) ? (strstr($order['arrive_time'], '-') === false ? date('Y-m-d H:i:s', $order['arrive_time']) : $order['arrive_time']) : '';
  3380. $order['status_pic'] = '';
  3381. $order['gift_user'] = User::get($order['gift_uid']);
  3382. $order['user'] = User::get($order['uid']);
  3383. $order['store'] = SystemStore::get($order['store_id']);
  3384. $order['point'] = SystemStorePoint::get($order['point_id']);
  3385. //获取产品状态图片
  3386. if ($isPic) {
  3387. $order_details_images = sys_data('order_details_images') ?: [];
  3388. foreach ($order_details_images as $image) {
  3389. if (isset($image['order_status']) && $image['order_status'] == $order['_status']['_type']) {
  3390. $order['status_pic'] = $image['pic'];
  3391. break;
  3392. }
  3393. }
  3394. }
  3395. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? (int)2;
  3396. return $order;
  3397. }
  3398. /**
  3399. * 设置订单查询状态
  3400. * @param $status
  3401. * @param int $uid
  3402. * @param null $model
  3403. * @return StoreOrder|null
  3404. */
  3405. public static function statusByWhere($status, $uid = 0, $model = null)
  3406. {
  3407. // $orderId = StorePink::where('uid',$uid)->where('status',1)->column('order_id','id');//获取正在拼团的订单编号
  3408. if ($model == null) $model = new self;
  3409. if ('' === $status)
  3410. return $model;
  3411. else if ($status == 0)//未支付
  3412. return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
  3413. else if ($status == 1)//待发货
  3414. return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
  3415. else if ($status == 2)//待收货
  3416. return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
  3417. else if ($status == 3)//待评价
  3418. return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
  3419. else if ($status == 4)//已完成
  3420. return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
  3421. else if ($status == -1)//退款中
  3422. return $model->where('paid', 1)->where('refund_status', 1);
  3423. else if ($status == -2)//已退款
  3424. return $model->where('paid', 1)->where('refund_status', 2);
  3425. else if ($status == -3)//退款
  3426. return $model->where('paid', 1)->where('refund_status', 'IN', '1,2');
  3427. else if ($status == 10086)//退款
  3428. return $model->where('paid', 1)->where('refund_status', 0)->where('store_id', 0)->where('shipping_type', 2);
  3429. // else if($status == 11){
  3430. // return $model->where('order_id','IN',implode(',',$orderId));
  3431. // }
  3432. else
  3433. return $model;
  3434. }
  3435. /**
  3436. * 获取订单并分页
  3437. * @param $uid
  3438. * @param string $status
  3439. * @param int $page
  3440. * @param int $limit
  3441. * @return mixed
  3442. * @throws DataNotFoundException
  3443. * @throws ModelNotFoundException
  3444. * @throws \think\exception\DbException
  3445. */
  3446. public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
  3447. {
  3448. if ($page) $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)
  3449. // ->field('pay_postage_sh,uid,add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type,gift_uid,store_id')
  3450. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  3451. else $list = self::statusByWhere($status, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)
  3452. // ->field('pay_postage_sh,uid,add_time,seckill_id,bargain_id,combination_id,id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,pink_id,delivery_type,is_del,shipping_type,gift_uid,store_id')
  3453. ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
  3454. foreach ($list as $k => $order) {
  3455. $list[$k] = self::tidyOrder($order, true);
  3456. }
  3457. return $list;
  3458. }
  3459. /**
  3460. * 获取推广人地下用户的订单金额
  3461. * @param string $uid
  3462. * @param string $status
  3463. * @return array
  3464. */
  3465. public static function getUserOrderCount($uid = '', $status = '')
  3466. {
  3467. $res = self::statusByWhere($status, $uid)->where('uid', 'IN', $uid)->column('pay_price');
  3468. return $res;
  3469. }
  3470. /**
  3471. * 搜索某个订单详细信息
  3472. * @param $uid
  3473. * @param $order_id
  3474. * @return bool|mixed
  3475. * @throws DataNotFoundException
  3476. * @throws ModelNotFoundException
  3477. * @throws \think\exception\DbException
  3478. */
  3479. public static function searchUserOrder($uid, $order_id)
  3480. {
  3481. $order = self::where('uid|gift_uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('*')
  3482. ->order('add_time DESC')->find();
  3483. if (!$order)
  3484. return false;
  3485. else
  3486. return self::tidyOrder($order->toArray(), true);
  3487. }
  3488. /**
  3489. * 订单评价信息记录
  3490. * @param $oid
  3491. * @return StoreOrderStatus|\think\Model
  3492. * @throws \Exception
  3493. */
  3494. public static function orderOver($oid)
  3495. {
  3496. $res = self::edit(['status' => '3'], $oid, 'id');
  3497. if (!$res) exception('评价后置操作失败!');
  3498. return StoreOrderStatus::status($oid, 'check_order_over', '用户评价');
  3499. }
  3500. /**
  3501. * 设置订单产品评价完毕事件
  3502. * @param $oid
  3503. * @return StoreOrderStatus|\think\Model
  3504. * @throws \Exception
  3505. */
  3506. public static function checkOrderOver($oid)
  3507. {
  3508. $uniqueList = StoreOrderCartInfo::where('oid', $oid)->column('unique', 'unique');
  3509. //订单产品全部评价完成
  3510. if (StoreProductReply::where('unique', 'IN', $uniqueList)->where('oid', $oid)->count() == count($uniqueList)) {
  3511. event('StoreProductOrderOver', [$oid]);
  3512. return self::orderOver($oid);
  3513. }
  3514. }
  3515. public static function getOrderStatusNum($uid)
  3516. {
  3517. $noBuy = (int)self::where('uid', $uid)->where('paid', 0)->where('is_del', 0)->where('pay_type', '<>', 'offline')->count();
  3518. $noPostageNoPink = (int)self::where('o.uid', $uid)->alias('o')->where('o.paid', 1)->where('o.pink_id', 0)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  3519. $noPostageYesPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 2)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  3520. $noPostage = (int)bcadd($noPostageNoPink, $noPostageYesPink, 0);
  3521. $noTake = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 1)->where('pay_type', '<>', 'offline')->count();
  3522. $noReply = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('status', 2)->count();
  3523. $noPink = (int)self::where('o.uid', $uid)->alias('o')->join('StorePink p', 'o.pink_id = p.id')->where('p.status', 1)->where('o.paid', 1)->where('o.is_del', 0)->where('o.status', 0)->where('o.pay_type', '<>', 'offline')->count();
  3524. $noRefund = (int)self::where('uid', $uid)->where('paid', 1)->where('is_del', 0)->where('refund_status', 'IN', '1,2')->count();
  3525. return compact('noBuy', 'noPostage', 'noTake', 'noReply', 'noPink', 'noRefund');
  3526. }
  3527. /**
  3528. * 购买商品赠送积分
  3529. * @param $order
  3530. * @return bool
  3531. * @throws \think\Exception
  3532. * @throws DataNotFoundException
  3533. * @throws ModelNotFoundException
  3534. * @throws \think\exception\DbException
  3535. */
  3536. public static function gainUserIntegral($order)
  3537. {
  3538. if ($order['gain_integral'] > 0) {
  3539. $userInfo = User::getUserInfo($order['uid']);
  3540. BaseModel::beginTrans();
  3541. $res1 = false != User::where('uid', $userInfo['uid'])->update(['integral' => bcadd($userInfo['integral'], $order['gain_integral'], 2)]);
  3542. $res2 = false != UserBill::income('购买商品赠送积分', $order['uid'], 'integral', 'gain', $order['gain_integral'], $order['id'], $userInfo['integral'], '购买商品赠送' . floatval($order['gain_integral']) . '积分');
  3543. $res = $res1 && $res2;
  3544. BaseModel::checkTrans($res);
  3545. return $res;
  3546. }
  3547. return true;
  3548. }
  3549. /**
  3550. * 获取当前订单中有没有拼团存在
  3551. * @param $pid
  3552. * @return int|string
  3553. */
  3554. public static function getIsOrderPink($pid = 0, $uid = 0)
  3555. {
  3556. return self::where('uid', $uid)->where('pink_id', $pid)->where('refund_status', 0)->where('is_del', 0)->count();
  3557. }
  3558. /**
  3559. * 获取order_id
  3560. * @param $pid
  3561. * @return mixed
  3562. */
  3563. public static function getStoreIdPink($pid = 0, $uid = 0)
  3564. {
  3565. return self::where('uid', $uid)->where('pink_id', $pid)->where('is_del', 0)->value('order_id');
  3566. }
  3567. /**
  3568. * 删除当前用户拼团未支付的订单
  3569. */
  3570. public static function delCombination()
  3571. {
  3572. self::where('combination', '>', 0)->where('paid', 0)->where('uid', User::getActiveUid())->delete();
  3573. }
  3574. public static function getUserPrice($uid = 0)
  3575. {
  3576. if (!$uid) return 0;
  3577. $price = self::where('paid', 1)->where('uid', $uid)->where('status', 2)->where('refund_status', 0)->column('pay_price', 'id');
  3578. $count = 0;
  3579. if ($price) {
  3580. foreach ($price as $v) {
  3581. $count = bcadd($count, $v, 2);
  3582. }
  3583. }
  3584. return $count;
  3585. }
  3586. /**
  3587. * 个人中心获取个人订单列表和订单搜索
  3588. * @param int $uid 用户uid
  3589. * @param int | string 查找订单类型
  3590. * @param int $first 分页
  3591. * @param int 每页显示多少条
  3592. * @param string $search 订单号
  3593. * @return array
  3594. * */
  3595. public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
  3596. {
  3597. if ($search) {
  3598. $order = self::searchUserOrder($uid, $search) ?: [];
  3599. $list = $order == false ? [] : [$order];
  3600. } else {
  3601. $list = self::getUserOrderList($uid, $type, $page, $limit);
  3602. }
  3603. foreach ($list as $k => $order) {
  3604. $list[$k] = self::tidyOrder($order, true);
  3605. if ($list[$k]['_status']['_type'] == 3) {
  3606. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  3607. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  3608. $list[$k]['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', $product['add_time']) : '时间错误';
  3609. }
  3610. }
  3611. }
  3612. return $list;
  3613. }
  3614. /**
  3615. * 获取用户下级的订单
  3616. * @param int $xuid 下级用户用户uid
  3617. * @param int $uid 用户uid
  3618. * @param int $type 订单类型
  3619. * @param int $first 截取行数
  3620. * @param int $limit 展示条数
  3621. * @return array
  3622. * */
  3623. public static function getSubordinateOrderlist($xUid, $uid, $type, $first, $limit)
  3624. {
  3625. $list = [];
  3626. if (!$xUid) {
  3627. $arr = User::getOneSpreadUid($uid);
  3628. foreach ($arr as $v) $list = StoreOrder::getUserOrderList($v, $type, $first, $limit);
  3629. } else $list = self::getUserOrderList($xUid, $type, $first, $limit);
  3630. foreach ($list as $k => $order) {
  3631. $list[$k] = self::tidyOrder($order, true);
  3632. if ($list[$k]['_status']['_type'] == 3) {
  3633. foreach ($order['cartInfo'] ?: [] as $key => $product) {
  3634. $list[$k]['cartInfo'][$key]['is_reply'] = StoreProductReply::isReply($product['unique'], 'product');
  3635. }
  3636. }
  3637. }
  3638. return $list;
  3639. }
  3640. /**
  3641. * 获取 今日 昨日 本月 订单金额
  3642. * @param array $where
  3643. * @return mixed
  3644. */
  3645. public static function getOrderTimeData($where = [])
  3646. {
  3647. $to_day = strtotime(date('Y-m-d'));//今日
  3648. $pre_day = strtotime(date('Y-m-d', strtotime('-1 day')));//昨日
  3649. $now_month = strtotime(date('Y-m'));//本月
  3650. //今日成交额
  3651. // $data['todayPrice'] = (float)number_format(self::where('is_del', 0)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3652. $data['todayPrice'] = number_format(self::where('is_del', 0)->where($where)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3653. //今日订单数
  3654. $data['todayCount'] = self::where('is_del', 0)->where($where)->where('pay_time', '>=', $to_day)->where('paid', 1)->where('refund_status', 0)->count();
  3655. //昨日成交额
  3656. $data['proPrice'] = number_format(self::where('is_del', 0)->where($where)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3657. //昨日订单数
  3658. $data['proCount'] = self::where('is_del', 0)->where($where)->where('pay_time', '<', $to_day)->where('pay_time', '>=', $pre_day)->where('paid', 1)->where('refund_status', 0)->count();
  3659. //本月成交额
  3660. $data['monthPrice'] = number_format(self::where('is_del', 0)->where($where)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->value('sum(pay_price)'), 2) ?? 0;
  3661. //本月订单数
  3662. $data['monthCount'] = self::where('is_del', 0)->where($where)->where('pay_time', '>=', $now_month)->where('paid', 1)->where('refund_status', 0)->count();
  3663. return $data;
  3664. }
  3665. /**
  3666. * 获取某个用户的订单统计数据
  3667. * @param $uid
  3668. * @return mixed
  3669. */
  3670. public static function getOrderData($uid)
  3671. {
  3672. //订单支付没有退款 数量
  3673. $data['order_count'] = self::where('is_del', 0)->where('paid', 1)->where('uid|gift_uid', $uid)->where('refund_status', 0)->count();
  3674. //订单支付没有退款 支付总金额
  3675. $data['sum_price'] = self::where('is_del', 0)->where('paid', 1)->where('uid|gift_uid', $uid)->where('refund_status', 0)->sum('pay_price');
  3676. //订单待支付 数量
  3677. $data['unpaid_count'] = self::statusByWhere(0, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  3678. //订单待发货 数量
  3679. $data['unshipped_count'] = self::statusByWhere(1, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  3680. //订单待收货 数量
  3681. $data['received_count'] = self::statusByWhere(2, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  3682. //订单待评价 数量
  3683. $data['evaluated_count'] = self::statusByWhere(3, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  3684. //订单已完成 数量
  3685. $data['complete_count'] = self::statusByWhere(4, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  3686. //订单退款
  3687. $data['refund_count'] = self::statusByWhere(-1, $uid)->where('is_del', 0)->where('uid|gift_uid', $uid)->count();
  3688. $data['exchange_ticket_count'] = StoreExchangeOrder::where('uid|gift_uid', $uid)->where('refund_status', 0)->where('status', 0)->count();
  3689. return $data;
  3690. }
  3691. /**
  3692. * 获取订单统计数据
  3693. * @param $uid
  3694. * @return mixed
  3695. */
  3696. public static function getOrderDataAdmin($where = [])
  3697. {
  3698. //订单支付没有退款 数量
  3699. $data['order_count'] = self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->count();
  3700. //订单支付没有退款 支付总金额
  3701. $data['sum_price'] = self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->sum('pay_price');
  3702. //订单待支付 数量
  3703. $data['unpaid_count'] = self::statusByWhere(0, 0)->where($where)->where('is_del', 0)->count();
  3704. //订单待发货 数量
  3705. $data['unshipped_count'] = self::statusByWhere(1, 0)->where($where)->where('is_del', 0)->count();
  3706. //订单待收货 数量
  3707. $data['received_count'] = self::statusByWhere(2, 0)->where($where)->where('is_del', 0)->count();
  3708. //订单待评价 数量
  3709. $data['evaluated_count'] = self::statusByWhere(3, 0)->where($where)->where('is_del', 0)->count();
  3710. //订单已完成 数量
  3711. $data['complete_count'] = self::statusByWhere(4, 0)->where($where)->where('is_del', 0)->count();
  3712. //订单退款 数量
  3713. $data['refund_count'] = self::statusByWhere(-3, 0)->where($where)->where('is_del', 0)->count();
  3714. return $data;
  3715. }
  3716. /**
  3717. * 累计消费
  3718. * @param $uid
  3719. * @return float
  3720. */
  3721. public static function getOrderStatusSum($uid)
  3722. {
  3723. return self::where('uid', $uid)->where('is_del', 0)->where('paid', 1)->sum('pay_price');
  3724. }
  3725. public static function getPinkOrderId($id)
  3726. {
  3727. return self::where('id', $id)->value('order_id');
  3728. }
  3729. /**
  3730. * 未支付订单自动取消
  3731. * @param int $limit 分页截取条数
  3732. * @param string $prefid 缓存名称
  3733. * @param int $expire 缓存时间
  3734. * @return string|null
  3735. * @throws \Psr\SimpleCache\InvalidArgumentException
  3736. */
  3737. public static function orderUnpaidCancel()
  3738. {
  3739. //系统预设取消订单时间段
  3740. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  3741. //获取配置
  3742. $systemValue = SystemConfigService::more($keyValue);
  3743. //格式化数据
  3744. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  3745. //检查是否有未支付的订单 未支付查询条件
  3746. $unPidCount = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->count();
  3747. if (!$unPidCount) return null;
  3748. try {
  3749. $res = true;
  3750. // 未支付查询条件
  3751. $orderList = self::where('paid', 0)->where('pay_type', '<>', 'offline')->where('is_del', 0)->where('status', 0)->where('refund_status', 0)->field('add_time,pink_id,order_id,seckill_id,bargain_id,combination_id,status,cart_id,use_integral,refund_status,uid,unique,back_integral,coupon_id,paid,is_del')->select();
  3752. foreach ($orderList as $order) {
  3753. if ($order['seckill_id']) {
  3754. //优先使用单独配置的过期时间
  3755. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  3756. $res = $res && self::RegressionAll($order_seckill_time, $order);
  3757. unset($order_seckill_time);
  3758. } else if ($order['bargain_id']) {
  3759. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  3760. $res = $res && self::RegressionAll($order_bargain_time, $order);
  3761. unset($order_bargain_time);
  3762. } else if ($order['pink_id'] || $order['combination_id']) {
  3763. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  3764. $res = $res && self::RegressionAll($order_pink_time, $order);
  3765. unset($order_pink_time);
  3766. } else {
  3767. $res = $res && self::RegressionAll($systemValue['order_cancel_time'], $order);
  3768. }
  3769. }
  3770. if (!$res) throw new \Exception('更新错误');
  3771. unset($orderList, $res, $pages);
  3772. return null;
  3773. } catch (PDOException $e) {
  3774. Log::error('未支付自动取消时发生数据库查询错误,错误原因为:' . $e->getMessage());
  3775. throw new \Exception($e->getMessage());
  3776. } catch (\think\Exception $e) {
  3777. Log::error('未支付自动取消时发生系统错误,错误原因为:' . $e->getMessage());
  3778. throw new \Exception($e->getMessage());
  3779. }
  3780. }
  3781. /**
  3782. * 未支付订单超过预设时间回退所有,如果不设置未支付过期时间,将不取消订单
  3783. * @param $time 预设时间
  3784. * @param $order 订单详情
  3785. * @return bool
  3786. * @throws DataNotFoundException
  3787. * @throws ModelNotFoundException
  3788. * @throws \think\exception\DbException
  3789. */
  3790. protected static function RegressionAll($time, $order)
  3791. {
  3792. if ($time == 0) return true;
  3793. if (($order['add_time'] + bcmul($time, 3600, 0)) < time()) {
  3794. $res1 = self::RegressionStock($order);
  3795. $res2 = self::RegressionIntegral($order);
  3796. $res3 = self::RegressionCoupon($order);
  3797. $res = $res1 && $res2 && $res3;
  3798. if ($res) $res = false !== self::where('order_id', $order['order_id'])->update(['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  3799. unset($res1, $res2, $res3);
  3800. return $res;
  3801. } else
  3802. return true;
  3803. }
  3804. /**
  3805. * 格式化数据
  3806. * @param array $array 原本数据键
  3807. * @param $value 需要格式化的数据
  3808. * @param int $default 默认值
  3809. * @return mixed
  3810. */
  3811. protected static function setValeTime(array $array, $value, $default = 0)
  3812. {
  3813. foreach ($array as $item) {
  3814. if (!isset($value[$item]))
  3815. $value[$item] = $default;
  3816. else if (is_string($value[$item]))
  3817. $value[$item] = (float)$value[$item];
  3818. }
  3819. return $value;
  3820. }
  3821. public static function getOrderTotalPrice($cartInfo)
  3822. {
  3823. $totalPrice = 0;
  3824. foreach ($cartInfo as $cart) {
  3825. $totalPrice = bcadd($totalPrice, bcmul($cart['cart_num'], $cart['truePrice'], 2), 2);
  3826. }
  3827. return $totalPrice;
  3828. }
  3829. public static function getOrderCostPrice($cartInfo)
  3830. {
  3831. $costPrice = 0;
  3832. foreach ($cartInfo as $cart) {
  3833. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], $cart['costPrice'], 2), 2);
  3834. }
  3835. return $costPrice;
  3836. }
  3837. public static function getCombinationOrderCostPrice($cartInfo)
  3838. {
  3839. $costPrice = 0;
  3840. foreach ($cartInfo as $cart) {
  3841. if ($cart['combination_id']) {
  3842. $costPrice = bcadd($costPrice, bcmul($cart['cart_num'], StoreCombination::where('id', $cart['combination_id'])->value('price'), 2), 2);
  3843. }
  3844. }
  3845. return (float)$costPrice;
  3846. }
  3847. public static function yueRefundAfter($order)
  3848. {
  3849. }
  3850. /**
  3851. * 获取余额支付的金额
  3852. * @param $uid
  3853. * @return float|int
  3854. */
  3855. public static function getOrderStatusYueSum($uid)
  3856. {
  3857. return self::where('uid', $uid)->where('is_del', 0)->where('is_del', 0)->where('pay_type', 'yue')->where('paid', 1)->sum('pay_price');
  3858. }
  3859. /**
  3860. * 砍价支付成功订单数量
  3861. * @param $bargain
  3862. * @return int
  3863. */
  3864. public static function getBargainPayCount($bargain)
  3865. {
  3866. return self::where('bargain_id', $bargain)->where(['paid' => 1, 'refund_status' => 0])->count();
  3867. }
  3868. /**
  3869. * 7天自动收货
  3870. * @return bool
  3871. */
  3872. public static function startTakeOrder()
  3873. {
  3874. //7天前时间戳
  3875. $systemDeliveryTime = SystemConfigService::get('system_delivery_time') ?? 0;
  3876. //0为取消自动收货功能
  3877. if ($systemDeliveryTime == 0) return true;
  3878. $sevenDay = strtotime(date('Y-m-d H:i:s', strtotime('-' . $systemDeliveryTime . ' day')));
  3879. $model = new self;
  3880. $model = $model->alias('o');
  3881. $model = $model->join('StoreOrderStatus s', 's.oid=o.id');
  3882. $model = $model->where('o.paid', 1);
  3883. $model = $model->where('s.change_type', 'in', ['delivery_goods', 'delivery', 'delivery_fictitious']);
  3884. $model = $model->where('s.change_time', '<', $sevenDay);
  3885. $model = $model->where('o.status', 1);
  3886. $model = $model->where('o.refund_status', 0);
  3887. $model = $model->where('o.is_del', 0);
  3888. $orderInfo = $model->column('id', 'id');
  3889. if (!count($orderInfo)) return true;
  3890. $res = true;
  3891. foreach ($orderInfo as $key => &$item) {
  3892. $order = self::get($item);
  3893. if ($order['status'] == 2) continue;
  3894. if ($order['paid'] == 1 && $order['status'] == 1) $data['status'] = 2;
  3895. else if ($order['pay_type'] == 'offline') $data['status'] = 2;
  3896. else continue;
  3897. if (!self::edit($data, $item, 'id')) continue;
  3898. try {
  3899. OrderRepository::storeProductOrderTakeDeliveryAdmin($order, $item);
  3900. $res = $res && true;
  3901. } catch (\Exception $e) {
  3902. Log::error($item . ':' . $e->getFile() . $e->getLine() . $e->getMessage() . json_encode($e->getTrace()));
  3903. $res = $res && false;
  3904. }
  3905. $res = $res && StoreOrderStatus::status($item, 'take_delivery', '已收货[自动收货]');
  3906. }
  3907. if (!$res) {
  3908. throw new \Exception('');
  3909. }
  3910. }
  3911. /**
  3912. * 获取订单信息
  3913. * @param $id
  3914. * @param string $field
  3915. * @return array|null|\think\Model
  3916. * @throws DataNotFoundException
  3917. * @throws ModelNotFoundException
  3918. * @throws \think\exception\DbException
  3919. */
  3920. public static function getOrderInfo($id, $field = 'order_id')
  3921. {
  3922. return self::where('id', $id)->field($field)->find();
  3923. }
  3924. /**
  3925. * 订单每月统计数据
  3926. * @param $page
  3927. * @param $limit
  3928. * @return array
  3929. */
  3930. public static function getOrderDataPriceCount($page, $limit, $start, $stop, $where = [])
  3931. {
  3932. if (!$limit) return [];
  3933. $model = self::where($where);
  3934. if ($start != '' && $stop != '') $model = $model->where('pay_time', '>', $start)->where('pay_time', '<=', $stop);
  3935. $model = $model->field('sum(pay_price) as price,count(id) as count,FROM_UNIXTIME(pay_time, \'%m-%d\') as time');
  3936. $model = $model->where('is_del', 0);
  3937. $model = $model->where('paid', 1);
  3938. $model = $model->where('refund_status', 0);
  3939. $model = $model->group("FROM_UNIXTIME(pay_time, '%Y-%m-%d')");
  3940. $model = $model->order('pay_time DESC');
  3941. if ($page) $model = $model->page($page, $limit);
  3942. return $model->select();
  3943. }
  3944. /**
  3945. * 前台订单管理订单列表获取
  3946. * @param $where
  3947. * @return mixed
  3948. */
  3949. public static function orderList($where)
  3950. {
  3951. $model = self::getOrderWhere($where, self::alias('a')->join('user r', 'r.uid=a.uid', 'LEFT'), 'a.', 'r')->field('a.*');
  3952. if ($where['order'] != '') {
  3953. $model = $model->order(self::setOrder($where['order']));
  3954. } else {
  3955. $model = $model->order('a.id desc');
  3956. }
  3957. $data = ($data = $model->page((int)$where['page'], (int)$where['limit'])->select()) && count($data) ? $data->toArray() : [];
  3958. return self::tidyAdminOrder($data);
  3959. }
  3960. /**
  3961. * 前台订单管理 订单信息设置
  3962. * @param $data
  3963. * @param bool $status
  3964. * @return mixed
  3965. * @throws DataNotFoundException
  3966. * @throws ModelNotFoundException
  3967. * @throws \think\exception\DbException
  3968. */
  3969. public static function tidyAdminOrder($data, $status = false)
  3970. {
  3971. foreach ($data as &$item) {
  3972. $_info = StoreOrderCartInfo::where('oid', $item['id'])->field('cart_info')->select()->toArray();
  3973. foreach ($_info as $k => $v) {
  3974. if (!is_array($v['cart_info']))
  3975. $_info[$k]['cart_info'] = json_decode($v['cart_info'], true);
  3976. }
  3977. foreach ($_info as $k => $v) {
  3978. unset($_info[$k]['cart_info']['type'], $_info[$k]['cart_info']['product_id'], $_info[$k]['cart_info']['combination_id'], $_info[$k]['cart_info']['seckill_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['bargain_id'], $_info[$k]['cart_info']['truePrice'], $_info[$k]['cart_info']['vip_truePrice'], $_info[$k]['cart_info']['trueStock'], $_info[$k]['cart_info']['costPrice'], $_info[$k]['cart_info']['productInfo']['id'], $_info[$k]['cart_info']['productInfo']['vip_price'], $_info[$k]['cart_info']['productInfo']['postage'], $_info[$k]['cart_info']['productInfo']['give_integral'], $_info[$k]['cart_info']['productInfo']['sales'], $_info[$k]['cart_info']['productInfo']['stock'], $_info[$k]['cart_info']['productInfo']['unit_name'], $_info[$k]['cart_info']['productInfo']['is_postage'], $_info[$k]['cart_info']['productInfo']['slider_image'], $_info[$k]['cart_info']['productInfo']['cost'], $_info[$k]['cart_info']['productInfo']['mer_id'], $_info[$k]['cart_info']['productInfo']['cate_id'], $_info[$k]['cart_info']['productInfo']['is_show'], $_info[$k]['cart_info']['productInfo']['store_info'], $_info[$k]['cart_info']['productInfo']['is_del'], $_info[$k]['cart_info']['is_pay'], $_info[$k]['cart_info']['is_del'], $_info[$k]['cart_info']['is_new'], $_info[$k]['cart_info']['add_time'], $_info[$k]['cart_info']['id'], $_info[$k]['cart_info']['uid'], $_info[$k]['cart_info']['product_attr_unique']);
  3979. $_info[$k]['cart_info']['productInfo']['suk'] = '';
  3980. if (isset($v['cart_info']['productInfo']['attrInfo'])) {
  3981. $_info[$k]['cart_info']['productInfo']['image'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['image'];
  3982. $_info[$k]['cart_info']['productInfo']['price'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['price'];
  3983. $_info[$k]['cart_info']['productInfo']['suk'] = $_info[$k]['cart_info']['productInfo']['attrInfo']['suk'];
  3984. unset($_info[$k]['cart_info']['productInfo']['attrInfo']);
  3985. }
  3986. if (!isset($v['cart_info']['productInfo']['ot_price'])) {
  3987. $_info[$k]['cart_info']['productInfo']['ot_price'] = $v['cart_info']['productInfo']['price'];
  3988. }
  3989. }
  3990. $item['_info'] = $_info;
  3991. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  3992. // if($item['pink_id'] || $item['combination_id']){
  3993. // $pinkStatus = StorePink::where('order_id_key',$item['id'])->value('status');
  3994. // switch ($pinkStatus){
  3995. // case 1:
  3996. // $item['pink_name'] = '[拼团订单]正在进行中';
  3997. // $item['color'] = '#f00';
  3998. // break;
  3999. // case 2:
  4000. // $item['pink_name'] = '[拼团订单]已完成';
  4001. // $item['color'] = '#00f';
  4002. // break;
  4003. // case 3:
  4004. // $item['pink_name'] = '[拼团订单]未完成';
  4005. // $item['color'] = '#f0f';
  4006. // break;
  4007. // default:
  4008. // $item['pink_name'] = '[拼团订单]历史订单';
  4009. // $item['color'] = '#457856';
  4010. // break;
  4011. // }
  4012. // }elseif ($item['seckill_id']){
  4013. // $item['pink_name'] = '[秒杀订单]';
  4014. // $item['color'] = '#32c5e9';
  4015. // }elseif ($item['bargain_id']){
  4016. // $item['pink_name'] = '[砍价订单]';
  4017. // $item['color'] = '#12c5e9';
  4018. // }else{
  4019. // $item['pink_name'] = '[普通订单]';
  4020. // $item['color'] = '#895612';
  4021. // }
  4022. // if($item['paid']==1){
  4023. // switch ($item['pay_type']){
  4024. // case 'weixin':
  4025. // $item['pay_type_name']='微信支付';
  4026. // break;
  4027. // case 'yue':
  4028. // $item['pay_type_name']='余额支付';
  4029. // break;
  4030. // case 'offline':
  4031. // $item['pay_type_name']='线下支付';
  4032. // break;
  4033. // default:
  4034. // $item['pay_type_name']='其他支付';
  4035. // break;
  4036. // }
  4037. // }else{
  4038. // switch ($item['pay_type']){
  4039. // default:
  4040. // $item['pay_type_name']='未支付';
  4041. // break;
  4042. // case 'offline':
  4043. // $item['pay_type_name']='线下支付';
  4044. // $item['pay_type_info']=1;
  4045. // break;
  4046. // }
  4047. // }
  4048. if ($status) {
  4049. $status = [];
  4050. if (!$item['paid'] && $item['pay_type'] == 'offline' && !$item['status'] >= 2) {
  4051. $status['_type'] = 9;
  4052. $status['_title'] = '线下付款';
  4053. $status['_msg'] = '商家处理中,请耐心等待';
  4054. $status['_class'] = 'nobuy';
  4055. } else if (!$item['paid']) {
  4056. $status['_type'] = 0;
  4057. $status['_title'] = '未支付';
  4058. //系统预设取消订单时间段
  4059. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  4060. //获取配置
  4061. $systemValue = SystemConfigService::more($keyValue);
  4062. //格式化数据
  4063. $systemValue = self::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  4064. if ($item['pink_id'] || $item['combination_id']) {
  4065. $order_pink_time = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  4066. $time = bcadd($item['add_time'], $order_pink_time * 3600, 0);
  4067. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  4068. } else if ($item['seckill_id']) {
  4069. $order_seckill_time = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  4070. $time = bcadd($item['add_time'], $order_seckill_time * 3600, 0);
  4071. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  4072. } else if ($item['bargain_id']) {
  4073. $order_bargain_time = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  4074. $time = bcadd($item['add_time'], $order_bargain_time * 3600, 0);
  4075. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  4076. } else {
  4077. $time = bcadd($item['add_time'], $systemValue['order_cancel_time'] * 3600, 0);
  4078. $status['_msg'] = '请在' . date('Y-m-d H:i:s', $time) . '前完成支付!';
  4079. }
  4080. $status['_class'] = 'nobuy';
  4081. } else if ($item['refund_status'] == 1) {
  4082. $status['_type'] = -1;
  4083. $status['_title'] = '申请退款中';
  4084. $status['_msg'] = '商家审核中,请耐心等待';
  4085. $status['_class'] = 'state-sqtk';
  4086. } else if ($item['refund_status'] == 2) {
  4087. $status['_type'] = -2;
  4088. $status['_title'] = '已退款';
  4089. $status['_msg'] = '已为您退款,感谢您的支持';
  4090. $status['_class'] = 'state-sqtk';
  4091. } else if (!$item['status']) {
  4092. if ($item['pink_id']) {
  4093. if (StorePink::where('id', $item['pink_id'])->where('status', 1)->count()) {
  4094. $status['_type'] = 11;
  4095. $status['_title'] = '拼团中';
  4096. $status['_msg'] = '等待其他人参加拼团';
  4097. $status['_class'] = 'state-nfh';
  4098. } else {
  4099. $status['_type'] = 1;
  4100. $status['_title'] = '未发货';
  4101. $status['_msg'] = '商家未发货,请耐心等待';
  4102. $status['_class'] = 'state-nfh';
  4103. }
  4104. } else {
  4105. $status['_type'] = 1;
  4106. $status['_title'] = '未发货';
  4107. $status['_msg'] = '商家未发货,请耐心等待';
  4108. $status['_class'] = 'state-nfh';
  4109. }
  4110. } else if ($item['status'] == 1) {
  4111. if ($item['delivery_type'] == 'send') {//TODO 送货
  4112. $status['_type'] = 2;
  4113. $status['_title'] = '待收货';
  4114. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery')) . '服务商已送货';
  4115. $status['_class'] = 'state-ysh';
  4116. } else {//TODO 发货
  4117. $status['_type'] = 2;
  4118. $status['_title'] = '待收货';
  4119. $status['_msg'] = date('m月d日H时i分', StoreOrderStatus::getTime($item['id'], 'delivery_goods')) . '服务商已发货';
  4120. $status['_class'] = 'state-ysh';
  4121. }
  4122. } else if ($item['status'] == 2) {
  4123. $status['_type'] = 3;
  4124. $status['_title'] = '待评价';
  4125. $status['_msg'] = '已收货,快去评价一下吧';
  4126. $status['_class'] = 'state-ypj';
  4127. } else if ($item['status'] == 3) {
  4128. $status['_type'] = 4;
  4129. $status['_title'] = '交易完成';
  4130. $status['_msg'] = '交易完成,感谢您的支持';
  4131. $status['_class'] = 'state-ytk';
  4132. }
  4133. if (isset($item['pay_type']))
  4134. $status['_payType'] = isset(self::$payType[$item['pay_type']]) ? self::$payType[$item['pay_type']] : '其他方式';
  4135. if (isset($item['delivery_type']))
  4136. $status['_deliveryType'] = isset(self::$deliveryType[$item['delivery_type']]) ? self::$deliveryType[$item['delivery_type']] : '其他方式';
  4137. $item['_status'] = $status;
  4138. } else {
  4139. if ($item['paid'] == 0 && $item['status'] == 0) {
  4140. $item['status_name'] = '未支付';
  4141. } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
  4142. $item['status_name'] = '未发货';
  4143. } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
  4144. $item['status_name'] = '待收货';
  4145. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  4146. $item['status_name'] = '待评价';
  4147. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  4148. $item['status_name'] = '已完成';
  4149. }
  4150. }
  4151. $item['store'] = SystemStore::get($item['store_id']);
  4152. $item['point'] = SystemStorePoint::get($item['point_id']);
  4153. // unset($item['refund_status']);
  4154. // else if($item['paid']==1 && $item['refund_status']==1){
  4155. // $item['status_name']=<<<HTML
  4156. //<b style="color:#f124c7">申请退款</b><br/>
  4157. //<span>退款原因:{$item['refund_reason_wap']}</span>
  4158. //HTML;
  4159. // }else if($item['paid']==1 && $item['refund_status']==2){
  4160. // $item['status_name']='已退款';
  4161. // }
  4162. // if($item['paid']==0 && $item['status']==0 && $item['refund_status']==0){
  4163. // $item['_status']=1;
  4164. // }else if($item['paid']==1 && $item['status']==0 && $item['refund_status']==0){
  4165. // $item['_status']=2;
  4166. // }else if($item['paid']==1 && $item['refund_status']==1){
  4167. // $item['_status']=3;
  4168. // }else if($item['paid']==1 && $item['status']==1 && $item['refund_status']==0){
  4169. // $item['_status']=4;
  4170. // }else if($item['paid']==1 && $item['status']==2 && $item['refund_status']==0){
  4171. // $item['_status']=5;
  4172. // }else if($item['paid']==1 && $item['status']==3 && $item['refund_status']==0){
  4173. // $item['_status']=6;
  4174. // }else if($item['paid']==1 && $item['refund_status']==2){
  4175. // $item['_status']=7;
  4176. // }
  4177. }
  4178. return $data;
  4179. }
  4180. /**
  4181. * 处理where条件
  4182. * @param $where
  4183. * @param $model
  4184. * @param string $aler
  4185. * @param string $join
  4186. * @return StoreOrder|null
  4187. */
  4188. public static function getOrderWhere($where, $model, $aler = '', $join = '')
  4189. {
  4190. if (isset($where['status']) && $where['status'] != '') $model = self::statusWhere($where['status'], $model, $aler);
  4191. if (isset($where['is_del']) && $where['is_del'] != '' && $where['is_del'] != -1) $model = $model->where($aler . 'is_del', $where['is_del']);
  4192. if (isset($where['store_id']) && $where['store_id'] != '' && $where['store_id'] != -1) $model = $model->where($aler . 'store_id', $where['store_id']);
  4193. if (isset($where['combination_id'])) {
  4194. if ($where['combination_id'] == '普通订单') {
  4195. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  4196. }
  4197. if ($where['combination_id'] == '拼团订单') {
  4198. $model = $model->where($aler . 'combination_id', ">", 0)->where($aler . 'pink_id', ">", 0);
  4199. }
  4200. if ($where['combination_id'] == '秒杀订单') {
  4201. $model = $model->where($aler . 'seckill_id', ">", 0);
  4202. }
  4203. if ($where['combination_id'] == '砍价订单') {
  4204. $model = $model->where($aler . 'bargain_id', ">", 0);
  4205. }
  4206. }
  4207. if (isset($where['type'])) {
  4208. switch ($where['type']) {
  4209. case 1:
  4210. $model = $model->where($aler . 'combination_id', 0)->where($aler . 'seckill_id', 0)->where($aler . 'bargain_id', 0);
  4211. break;
  4212. case 2:
  4213. $model = $model->where($aler . 'combination_id', ">", 0);
  4214. break;
  4215. case 3:
  4216. $model = $model->where($aler . 'seckill_id', ">", 0);
  4217. break;
  4218. case 4:
  4219. $model = $model->where($aler . 'bargain_id', ">", 0);
  4220. break;
  4221. }
  4222. }
  4223. if (isset($where['user_phone']) && $where['user_phone'] != '')
  4224. $model = $model->where($aler . 'user_phone', 'LIKE', "%$where[user_phone]%");
  4225. if (isset($where['real_name']) && $where['real_name'] != '')
  4226. $model = $model->where($aler . 'order_id|' . $aler . 'real_name|' . $aler . 'user_phone' . ($join ? '|' . $join . '.nickname|' . $join . '.uid' : ''), 'LIKE', "%$where[real_name]%");
  4227. if (isset($where['data']) && $where['data'] !== '')
  4228. $model = self::getModelTime($where, $model, $aler . 'add_time');
  4229. return $model;
  4230. }
  4231. /**
  4232. * 设置where条件
  4233. * @param $status
  4234. * @param null $model
  4235. * @param string $alert
  4236. * @return StoreOrder|null
  4237. */
  4238. public static function statusWhere($status, $model = null, $alert = '')
  4239. {
  4240. if ($model == null) $model = new self;
  4241. if ('' === $status)
  4242. return $model;
  4243. else if ($status == 0)//未支付
  4244. return $model->where($alert . 'paid', 0)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  4245. else if ($status == 1)//已支付 未发货
  4246. return $model->where($alert . 'paid', 1)->where('shipping_type', 1)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  4247. else if ($status == 5)//待核销
  4248. return $model->where($alert . 'paid', 1)->where('shipping_type', 2)->where($alert . 'status', 0)->where($alert . 'refund_status', 0);
  4249. else if ($status == 2)//已支付 待收货
  4250. return $model->where($alert . 'paid', 1)->where($alert . 'status', 1)->where($alert . 'refund_status', 0);
  4251. else if ($status == 3)// 已支付 已收货 待评价
  4252. return $model->where($alert . 'paid', 1)->where($alert . 'status', 2)->where($alert . 'refund_status', 0);
  4253. else if ($status == 4)// 交易完成
  4254. return $model->where($alert . 'paid', 1)->where($alert . 'status', 3)->where($alert . 'refund_status', 0);
  4255. else if ($status == -1)//退款中
  4256. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 1);
  4257. else if ($status == -2)//已退款
  4258. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 2);
  4259. else if ($status == -3)//退款
  4260. return $model->where($alert . 'paid', 1)->where($alert . 'refund_status', 'in', '1,2');
  4261. else
  4262. return $model;
  4263. }
  4264. /**
  4265. * 订单详情 管理员
  4266. * @param $orderId
  4267. * @param string $field
  4268. * @return array|null|\think\Model
  4269. * @throws DataNotFoundException
  4270. * @throws ModelNotFoundException
  4271. * @throws \think\exception\DbException
  4272. */
  4273. public static function getAdminOrderDetail($orderId, $field = '*', $other_where = [])
  4274. {
  4275. return self::where('order_id', $orderId)->where($other_where)->field($field)->find();
  4276. }
  4277. /**
  4278. * 获取指定时间区间的支付金额 管理员
  4279. * @param $start
  4280. * @param $stop
  4281. * @return float
  4282. */
  4283. public static function getOrderTimeBusinessVolumePrice($start, $stop, $where = [])
  4284. {
  4285. return self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->sum('pay_price');
  4286. }
  4287. /**
  4288. * 获取指定时间区间的支付订单数量 管理员
  4289. * @param $start
  4290. * @param $stop
  4291. * @return float
  4292. */
  4293. public static function getOrderTimeBusinessVolumeNumber($start, $stop, $where = [])
  4294. {
  4295. return self::where('is_del', 0)->where($where)->where('paid', 1)->where('refund_status', 0)->where('add_time', '>=', $start)->where('add_time', '<', $stop)->count();
  4296. }
  4297. /**
  4298. * 获取当前时间到指定时间的支付金额 管理员
  4299. * @param $start 开始时间
  4300. * @param $stop 结束时间
  4301. * @return mixed
  4302. */
  4303. public static function chartTimePrice($start, $stop, $where = [])
  4304. {
  4305. $model = self::where($where);
  4306. $model = $model->field('sum(pay_price) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  4307. $model = $model->where('is_del', 0);
  4308. $model = $model->where('paid', 1);
  4309. $model = $model->where('refund_status', 0);
  4310. $model = $model->where('add_time', '>=', $start);
  4311. $model = $model->where('add_time', '<', $stop);
  4312. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  4313. $model = $model->order('add_time ASC');
  4314. return $model->select();
  4315. }
  4316. /**
  4317. * 获取当前时间到指定时间的支付订单数 管理员
  4318. * @param $start 开始时间
  4319. * @param $stop 结束时间
  4320. * @return mixed
  4321. */
  4322. public static function chartTimeNumber($start, $stop, $where = [])
  4323. {
  4324. $model = self::where($where);
  4325. $model = $model->field('count(id) as num,FROM_UNIXTIME(add_time, \'%Y-%m-%d\') as time');
  4326. $model = $model->where('is_del', 0);
  4327. $model = $model->where('paid', 1);
  4328. $model = $model->where('refund_status', 0);
  4329. $model = $model->where('add_time', '>=', $start);
  4330. $model = $model->where('add_time', '<', $stop);
  4331. $model = $model->group("FROM_UNIXTIME(add_time, '%Y-%m-%d')");
  4332. $model = $model->order('add_time ASC');
  4333. return $model->select();
  4334. }
  4335. /**
  4336. * 修改支付方式为线下支付
  4337. * @param $orderId
  4338. * @return bool
  4339. */
  4340. public static function setOrderTypePayOffline($orderId)
  4341. {
  4342. return self::edit(['pay_type' => 'offline'], $orderId, 'order_id');
  4343. }
  4344. /**
  4345. * 线下付款
  4346. * @param $id
  4347. * @return $this
  4348. */
  4349. public static function updateOffline($id)
  4350. {
  4351. $count = self::where('id', $id)->count();
  4352. if (!$count) return self::setErrorInfo('订单不存在');
  4353. $count = self::where('id', $id)->where('paid', 0)->count();
  4354. if (!$count) return self::setErrorInfo('订单已支付');
  4355. $res = self::where('id', $id)->update(['paid' => 1, 'pay_time' => time()]);
  4356. return $res;
  4357. }
  4358. /**
  4359. * 向创建订单10分钟未付款的用户发送短信
  4360. */
  4361. public static function sendTen()
  4362. {
  4363. $list = self::where('paid', 0)->where('is_del', 0)->where('is_system_del', 0)->where('add_time', '>', time() - 900)->where('add_time', '<', time() - 600)->column('user_phone');
  4364. foreach ($list as $phone) {
  4365. ShortLetterRepositories::send(true, $phone, [], 'ORDER_PAY_FALSE');
  4366. }
  4367. }
  4368. public function productInfo()
  4369. {
  4370. return $this->hasMany(StoreProductReply::class, 'oid', 'id');
  4371. }
  4372. public static function setOrderProductReplyWhere($where)
  4373. {
  4374. $model = self::where('status', 3)->order('add_time desc')->whereIn('id', function ($query) {
  4375. $query->name('store_order')->alias('o')->join('store_product_reply a', 'a.oid = o.id')->group('o.id')->field('o.id')->select();
  4376. })->with('productInfo', function ($query) use ($where) {
  4377. $alias = '';
  4378. if (isset($where['title']) && $where['title'] != '')
  4379. $query->where("{$alias}comment", 'LIKE', "%$where[title]%");
  4380. if (isset($where['is_reply']) && $where['is_reply'] != '') {
  4381. if ($where['is_reply'] >= 0) {
  4382. $query->where("{$alias}is_reply", $where['is_reply']);
  4383. } else {
  4384. $query->where("{$alias}is_reply", '>', 0);
  4385. }
  4386. }
  4387. if (isset($where['producr_id']) && $where['producr_id'] != 0)
  4388. $query->where($alias . 'product_id', $where['producr_id']);
  4389. $query->where("{$alias}is_del", 0);
  4390. });
  4391. return $model;
  4392. }
  4393. public static function getOrderProductReplyList($where)
  4394. {
  4395. $list = self::setOrderProductReplyWhere($where)->page((int)$where['message_page'], (int)$where['limit'])->select();
  4396. $list = count($list) ? $list->toArray() : [];
  4397. foreach ($list as $key => $item) {
  4398. if (isset($item['productInfo']) && is_array($item['productInfo']) && count($item['productInfo'])) {
  4399. foreach ($item['productInfo'] as $k => $v) {
  4400. if (!$v['nickname'] && $v['uid']) {
  4401. $v['nickname'] = User::where('uid', $v['uid'])->value('nickname');
  4402. $v['avatar'] = User::where('uid', $v['uid'])->value('avatar');
  4403. }
  4404. $v['image'] = '';
  4405. $v['store_name'] = '';
  4406. if ($v['product_id']) {
  4407. $product = StoreProduct::where('id', $v['product_id'])->field(['image', 'store_name'])->find();
  4408. if ($product) {
  4409. $v['image'] = $product['image'];
  4410. $v['store_name'] = $product['store_name'];
  4411. }
  4412. }
  4413. $list[$key]['productInfo'][$k] = $v;
  4414. }
  4415. }
  4416. }
  4417. $count = self::setOrderProductReplyWhere($where)->count();
  4418. return compact('list', 'count');
  4419. }
  4420. /**
  4421. * 处理奖励
  4422. */
  4423. public static function treatmentAward($order_id)
  4424. {
  4425. $order = StoreOrder::get($order_id);
  4426. if (!$order) return self::setErrorInfo('找不到订单');
  4427. if (!$order['transaction_id']) return true;
  4428. $store = SystemStore::get($order['store_id']);
  4429. if (!$store) {
  4430. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  4431. return true;
  4432. }
  4433. $store_leader = SystemAdmin::where('roles', sys_config('default_store_admin', 7))
  4434. ->where('store_id', $store['id'])->where('is_del', 0)->where('status', 1)
  4435. ->find();
  4436. if (!$store_leader) {
  4437. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  4438. return true;
  4439. }
  4440. $user = User::where('admin_id', $store_leader['id'])->find();
  4441. if (!$user) {
  4442. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  4443. return true;
  4444. }
  4445. $p_user_info = WechatUser::get($user['uid']);
  4446. // 选择发起人的订单作为分账的账单
  4447. $transaction_id = $order['transaction_id']; // 微信订单号
  4448. $out_order_no = $order['order_id'];
  4449. // 计算发起人和参与者的分账金额
  4450. $price = $order['pay_price'] - $order['pay_postage_sh'] - $order['pay_postage'];
  4451. $p_amount = bcmul($price, bcdiv($store['sharing'], 100, 4), 2); //bcmul:2个任意精度数字乘法计算
  4452. $p_separate_account_amount = floor($p_amount * 100); // 发起人分账金额,以分为单位
  4453. if ($p_separate_account_amount <= 0) {
  4454. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  4455. return true;
  4456. }
  4457. $receivers[] = array(
  4458. 'type' => 'PERSONAL_OPENID',
  4459. 'account' => $p_user_info['routine_openid'],
  4460. 'amount' => $p_separate_account_amount,
  4461. 'description' => '门店订单'
  4462. );
  4463. // 记录发起人分账开始的信息
  4464. $p_separate_account_record = new StoreSeparateAccountRecord();
  4465. $p_separate_account_record['money'] = $p_amount;
  4466. $p_separate_account_record['order_id'] = $order_id; // OK
  4467. $p_separate_account_record['uid'] = $user['uid'];
  4468. $p_separate_account_record['state'] = 0; // 默认为失败
  4469. $p_separate_account_record['notice'] = "分账失败";
  4470. $p_separate_account_record['store_id'] = $order['store_id'];
  4471. $p_separate_account_record['start_time'] = time();
  4472. $p_separate_account_record['end_time'] = 0;
  4473. $p_separate_account_record->save();
  4474. // 添加发起人为分账接受方
  4475. MiniProgramService::addReceiver($p_user_info['routine_openid']); // 添加发起人为分账接受方
  4476. if ($transaction_id) {
  4477. $res = MiniProgramService::multi_profit_sharing($transaction_id, $out_order_no, $receivers);
  4478. $res = json_decode($res, true);
  4479. // var_dump($res);
  4480. $separateAccount = StoreSeparateAccountRecord::where('order_id', $order_id)->select();
  4481. if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
  4482. foreach ($separateAccount as $key => $value) {
  4483. $value['state'] = 1;
  4484. $value['notice'] = "分账成功";
  4485. $value['end_time'] = time();
  4486. $value->save();
  4487. }
  4488. }
  4489. MiniProgramService::profit_sharing_finish($order['transaction_id'], 'over_' . $order['order_id']);
  4490. }
  4491. return true;
  4492. }
  4493. >>>>>>> 5aa498cca5ff62dff451cc490e91bb06418f1a4e
  4494. }