StoreOrderServices.php 139 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\order;
  12. use app\dao\order\StoreOrderDao;
  13. use app\jobs\BatchHandleJob;
  14. use app\jobs\order\AutoOrderUnpaidCancelJob;
  15. use app\jobs\order\SpliteStoreOrderJob;
  16. use app\model\system\config\SystemConfig;
  17. use app\model\user\User;
  18. use app\model\user\UserBill;
  19. use app\model\user\UserBrokerage;
  20. use app\model\user\UserMoney;
  21. use app\services\activity\combination\StorePinkServices;
  22. use app\services\activity\coupon\StoreCouponIssueServices;
  23. use app\services\BaseServices;
  24. use app\services\product\branch\StoreBranchProductServices;
  25. use app\services\other\queue\QueueAuxiliaryServices;
  26. use app\services\other\queue\QueueServices;
  27. use app\services\pay\PayServices;
  28. use app\services\product\product\StoreProductLogServices;
  29. use app\services\product\product\StoreProductServices;
  30. use app\services\product\sku\StoreProductAttrValueServices;
  31. use app\services\store\finance\StoreFinanceFlowServices;
  32. use app\services\store\SystemStoreServices;
  33. use app\services\system\config\ConfigServices;
  34. use app\services\system\form\SystemFormServices;
  35. use app\services\user\AwardIntegralServices;
  36. use app\services\user\UserAwardIntegralServices;
  37. use app\services\user\UserBrokerageServices;
  38. use app\services\user\UserInvoiceServices;
  39. use app\services\user\UserServices;
  40. use app\services\product\product\StoreProductReplyServices;
  41. use app\services\user\UserAddressServices;
  42. use app\services\user\level\UserLevelServices;
  43. use crmeb\exceptions\AdminException;
  44. use crmeb\services\CacheService;
  45. use crmeb\services\FileService;
  46. use crmeb\services\FormBuilder as Form;
  47. use crmeb\services\printer\Printer;
  48. use crmeb\services\SystemConfigService;
  49. use crmeb\traits\ServicesTrait;
  50. use crmeb\utils\Arr;
  51. use think\exception\ValidateException;
  52. use think\facade\Log;
  53. /**
  54. * Class StoreOrderServices
  55. * @package app\services\order
  56. * @mixin StoreOrderDao
  57. */
  58. class StoreOrderServices extends BaseServices
  59. {
  60. use ServicesTrait;
  61. /**
  62. * 订单类型
  63. * @var string[]
  64. */
  65. protected $type = [
  66. 0 => '普通',
  67. 1 => '秒杀',
  68. 2 => '砍价',
  69. 3 => '拼团',
  70. 4 => '积分',
  71. 5 => '套餐',
  72. 6 => '预售',
  73. 7 => '新人礼',
  74. 8 => '抽奖',
  75. 9 => '拼单',
  76. 10 => '桌码'
  77. ];
  78. /**
  79. * 发货类型
  80. * @var string[]
  81. */
  82. public $deliveryType = ['send' => '商家配送', 'express' => '快递配送', 'fictitious' => '虚拟发货', 'delivery_part_split' => '拆分部分发货', 'delivery_split' => '拆分发货完成'];
  83. /**
  84. * StoreOrderProductServices constructor.
  85. * @param StoreOrderDao $dao
  86. */
  87. public function __construct(StoreOrderDao $dao)
  88. {
  89. $this->dao = $dao;
  90. }
  91. /**
  92. * 从缓存中获取购买商品个数
  93. * @param int $uid
  94. * @param int $type
  95. * @param int $id
  96. * @return int
  97. * @author 等风来
  98. * @email 136327134@qq.com
  99. * @date 2022/11/3
  100. */
  101. public function getBuyCountCache(int $uid, int $type, int $id)
  102. {
  103. $key = md5($uid . $type . $id);
  104. $res = $this->dao->cacheInfoById($key);
  105. if (null !== $res) {
  106. $num = $this->dao->getBuyCount($uid, $type, $id);
  107. $this->dao->cacheUpdate(['type' => $type, 'uid' => $uid, 'product_id' => $id, 'totalNum' => $num ?: 0], $key);
  108. } else {
  109. $num = $res['totalNum'] ?? 0;
  110. }
  111. return (int)$num;
  112. }
  113. /**
  114. * 获取门店订单统计
  115. * @param int $storeId
  116. * @return array
  117. */
  118. public function getStoreOrderHeader(int $storeId)
  119. {
  120. return [
  121. 'cashier' => $this->dao->count(['pid' => 0, 'type' => 6, 'is_system_del' => 0, 'store_id' => $storeId]),
  122. 'delivery' => $this->dao->count(['pid' => 0, 'type' => 7, 'is_system_del' => 0, 'store_id' => $storeId]),
  123. 'writeoff' => $this->dao->count(['pid' => 0, 'type' => 5, 'is_system_del' => 0, 'store_id' => $storeId]),
  124. ];
  125. }
  126. /**
  127. * 获取列表
  128. * @param array $where
  129. * @param array $field
  130. * @param array $with
  131. * @param bool $abridge
  132. * @param string $order
  133. * @return array
  134. * @throws \think\db\exception\DataNotFoundException
  135. * @throws \think\db\exception\DbException
  136. * @throws \think\db\exception\ModelNotFoundException
  137. */
  138. public function getOrderList(array $where, array $field = ['*'], array $with = [], bool $abridge = false, string $order = 'add_time DESC,id DESC')
  139. {
  140. [$page, $limit] = $this->getPageValue();
  141. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with, $order);
  142. $count = $this->dao->count($where);
  143. $stat = [];
  144. $batch_url = "file/upload/1";
  145. if ($data) {
  146. $data = $this->tidyOrderList($data, true, $abridge);
  147. foreach ($data as &$item) {
  148. $refund_num = array_sum(array_column($item['refund'], 'refund_num'));
  149. $cart_num = 0;
  150. foreach ($item['_info'] as &$items) {
  151. if (isset($items['cart_info']['is_gift']) && $items['cart_info']['is_gift']) continue;
  152. $cart_num += $items['cart_info']['cart_num'];
  153. $cart_ids = [];
  154. $cart_ids[] = ['cart_id' => $items['cart_info']['id'], 'cart_num' => $items['cart_info']['cart_num']];
  155. /** @var StoreOrderSplitServices $storeOrderSpliteServices */
  156. $storeOrderSpliteServices = app()->make(StoreOrderSplitServices::class);
  157. $cartInfos = $storeOrderSpliteServices->getSplitOrderCartInfo($item['id'], $cart_ids, $item);
  158. $total_price = $pay_postage = 0;
  159. foreach ($cartInfos as $cart) {
  160. $_info = is_string($cart['cart_info']) ? json_decode($cart['cart_info'], true) : $cart['cart_info'];
  161. $total_price = bcadd((string)$total_price, bcmul((string)($_info['truePrice'] ?? 0), (string)$cart['cart_num'], 4), 2);
  162. if (!in_array($item['shipping_type'], [2, 4])) {
  163. $pay_postage = bcadd((string)$pay_postage, (string)($_info['postage_price'] ?? 0), 2);
  164. }
  165. }
  166. //实际退款金额
  167. $refund_pay_price = bcadd((string)$total_price, (string)$pay_postage, 2);
  168. if (isset($item['change_price']) && (float)$item['change_price']) {//有改价 且是拆分
  169. //订单原实际支付金额
  170. $order_pay_price = bcadd((string)$item['change_price'], (string)$item['pay_price'], 2);
  171. $refund_price = bcmul((string)bcdiv((string)$item['pay_price'], (string)$order_pay_price, 4), (string)$refund_pay_price, 2);
  172. } else {
  173. $refund_price = $refund_pay_price;
  174. }
  175. $items['cart_info']['refund_price'] = $refund_price;
  176. }
  177. $item['is_all_refund'] = $refund_num == $cart_num;
  178. }
  179. }
  180. return compact('data', 'count', 'stat', 'batch_url');
  181. }
  182. /**获取单个订单信息
  183. * @param string $key
  184. * @param int $uid
  185. * @param array $with
  186. * @return array|\think\Model|null
  187. * @throws \think\db\exception\DataNotFoundException
  188. * @throws \think\db\exception\DbException
  189. * @throws \think\db\exception\ModelNotFoundException
  190. */
  191. public function getOneOrderList(string $key, int $uid, array $with = [])
  192. {
  193. return $this->dao->getUserOrderDetail($key, $uid, array_merge(['user', 'spread', 'refund'], $with));
  194. }
  195. /**
  196. * 获取列表
  197. * @param array $where
  198. * @return array
  199. * @throws \think\db\exception\DataNotFoundException
  200. * @throws \think\db\exception\DbException
  201. * @throws \think\db\exception\ModelNotFoundException
  202. */
  203. public function getSplitOrderList(array $where, array $field = ['*'], array $with = [])
  204. {
  205. $data = $this->dao->getOrderList($where, $field, 0, 0, $with);
  206. if ($data) {
  207. $data = $this->tidyOrderList($data);
  208. /** @var StoreOrderStatusServices $statusServices */
  209. $statusServices = app()->make(StoreOrderStatusServices::class);
  210. foreach ($data as &$item) {
  211. $log = $statusServices->getColumn(['oid' => $item['id']], 'change_time', 'change_type');
  212. if (isset($log['delivery'])) {
  213. $delivery = date('Y-m-d H:i:s', $log['delivery']);
  214. } elseif (isset($log['delivery_goods'])) {
  215. $delivery = date('Y-m-d H:i:s', $log['delivery_goods']);
  216. } elseif (isset($log['delivery_fictitious'])) {
  217. $delivery = date('Y-m-d H:i:s', $log['delivery_fictitious']);
  218. } else {
  219. $delivery = '';
  220. }
  221. $item['delivery_time'] = $delivery;
  222. }
  223. }
  224. return $data;
  225. }
  226. /**
  227. * 前端订单列表
  228. * @param array $where
  229. * @param array|string[] $field
  230. * @param array $with
  231. * @return array
  232. * @throws \think\db\exception\DataNotFoundException
  233. * @throws \think\db\exception\DbException
  234. * @throws \think\db\exception\ModelNotFoundException
  235. */
  236. public function getOrderApiList(array $where, array $field = ['*'], array $with = [])
  237. {
  238. [$page, $limit] = $this->getPageValue();
  239. if (isset($where['status']) && $where['status'] === '') {
  240. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with, 'id DESC');
  241. } else {
  242. $data = $this->dao->getOrderList($where, $field, $page, $limit, $with);
  243. }
  244. foreach ($data as &$item) {
  245. $item = $this->tidyOrder($item, true);
  246. $cart_num = 0;
  247. foreach ($item['cartInfo'] ?: [] as $key => $product) {
  248. if (isset($item['_status']['_type']) && $item['_status']['_type'] == 3) {
  249. $item['cartInfo'][$key]['add_time'] = isset($product['add_time']) ? date('Y-m-d H:i', (int)$product['add_time']) : '时间错误';
  250. }
  251. $item['cartInfo'][$key]['productInfo']['price'] = $product['truePrice'] ?? 0;
  252. if (isset($product['is_gift']) && $product['is_gift']) continue;
  253. $cart_num += $product['cart_num'];
  254. }
  255. if (count($item['refund'])) {
  256. $refund_num = array_sum(array_column($item['refund'], 'refund_num'));
  257. $item['is_all_refund'] = $refund_num == $cart_num;
  258. } else {
  259. $item['is_all_refund'] = false;
  260. }
  261. }
  262. return $data;
  263. }
  264. /**
  265. * 获取订单数量
  266. * @param int $uid
  267. * @param int $store_id
  268. * @param int $plat_type
  269. * @return array
  270. */
  271. public function getOrderData(int $uid = 0, int $store_id = -1, int $plat_type = -1)
  272. {
  273. $where = ['pid' => 0, 'uid' => $uid, 'is_del' => 0, 'is_system_del' => 0, 'plat_type' => $plat_type];
  274. $countWhere = [];
  275. if ($store_id != -1) {
  276. $where['store_id'] = $store_id;
  277. $countWhere['store_id'] = $store_id;
  278. }
  279. $data['order_count'] = (string)$this->dao->count($where);
  280. $where = $where + ['paid' => 1];
  281. $data['sum_price'] = (string)$this->dao->sum($where, 'pay_price', true);
  282. // $countWhere = $store_id != -1 ? ['pid' => 0, 'store_id' => $store_id] : ['pid' => 0];
  283. if ($uid) {
  284. $countWhere['uid'] = $uid;
  285. }
  286. if ($plat_type != -1) {
  287. $countWhere['plat_type'] = $plat_type;
  288. }
  289. $pid_where = ['pid' => 0];
  290. $not_pid_where = ['not_pid' => 1];
  291. $data['unpaid_count'] = (string)$this->dao->count(['status' => 0] + $countWhere + $pid_where);
  292. $data['unshipped_count'] = (string)$this->dao->count(['status' => 1] + $countWhere + $pid_where);
  293. $data['received_count'] = (string)$this->dao->count(['status' => 2] + $countWhere + $pid_where);
  294. $data['evaluated_count'] = (string)$this->dao->count(['status' => 3] + $countWhere + $pid_where);
  295. $data['unwritoff_count'] = (string)$this->dao->count(['status' => 5] + $countWhere);
  296. $data['complete_count'] = (string)$this->dao->count(['status' => 4] + $countWhere + $pid_where);
  297. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  298. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  299. $refund_where = ['is_cancel' => 0];
  300. if ($uid) $refund_where['uid'] = $uid;
  301. if ($store_id != -1) $refund_where['store_id'] = $store_id;
  302. $data['refunding_count'] = (string)$storeOrderRefundServices->count($refund_where + ['refund_type' => [1, 2, 4, 5]]);
  303. $data['refunded_count'] = (string)$storeOrderRefundServices->count($refund_where + ['refund_type' => [3, 6]]);
  304. $data['refund_count'] = (string)bcadd($data['refunding_count'], $data['refunded_count'], 0);
  305. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  306. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  307. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  308. return $data;
  309. }
  310. /**
  311. * 订单详情数据格式化
  312. * @param $order
  313. * @param bool $detail 是否需要订单商品详情
  314. * @param bool $isPic 是否需要订单状态图片
  315. * @return mixed
  316. */
  317. public function tidyOrder($order, bool $detail = false, bool $isPic = false)
  318. {
  319. if ($detail == true && isset($order['id'])) {
  320. /** @var StoreOrderCartInfoServices $cartServices */
  321. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  322. $cartInfos = $cartServices->getCartColunm(['oid' => $order['id']], 'cart_num,is_writeoff,surplus_num,cart_info,refund_num,product_type,is_support_refund,is_gift,promotions_id,type,relation_id,write_times,write_surplus_times,write_start,write_end', 'unique');
  323. $info = [];
  324. /** @var StoreProductReplyServices $replyServices */
  325. $replyServices = app()->make(StoreProductReplyServices::class);
  326. foreach ($cartInfos as $k => $cartInfo) {
  327. $cart = json_decode($cartInfo['cart_info'], true);
  328. $cart['cart_num'] = $cartInfo['cart_num'];
  329. $cart['is_writeoff'] = $cartInfo['is_writeoff'];
  330. $cart['surplus_num'] = $cartInfo['write_surplus_times'];
  331. $cart['refund_num'] = $cartInfo['refund_num'];
  332. $cart['write_times'] = $cartInfo['write_times'];
  333. $cart['write_surplus_times'] = $cartInfo['write_surplus_times'];
  334. $cart['write_start'] = $cartInfo['write_start'];
  335. $cart['write_end'] = $cartInfo['write_end'];
  336. $cart['write_off'] = max(bcsub((string)$cart['write_times'], (string)$cart['write_surplus_times'], 0), 0);
  337. $cart['product_type'] = $cartInfo['product_type'];
  338. $cart['supplier_id'] = $cart['store_id'] = 0;
  339. if ($cartInfo['type'] == 1) {
  340. $cart['store_id'] = $cartInfo['relation_id'] ?? 0;
  341. } elseif ($cartInfo['type'] == 2) {
  342. $cart['supplier_id'] = $cartInfo['relation_id'] ?? 0;
  343. }
  344. $cart['is_support_refund'] = $cartInfo['is_support_refund'];
  345. $cart['is_gift'] = $cartInfo['is_gift'];
  346. $cart['promotions_id'] = $cartInfo['promotions_id'];
  347. $cart['unique'] = $k;
  348. //新增是否评价字段
  349. $cart['is_reply'] = $replyServices->count(['unique' => $k]);
  350. if (isset($cart['productInfo']['attrInfo'])) {
  351. $cart['productInfo']['attrInfo'] = get_thumb_water($cart['productInfo']['attrInfo']);
  352. }
  353. $cart['productInfo'] = get_thumb_water($cart['productInfo']);
  354. //一种商品买多件 计算总优惠
  355. $cart['vip_sum_truePrice'] = bcmul($cart['vip_truePrice'], $cart['cart_num'] ? $cart['cart_num'] : 1, 2);
  356. $cart['is_valid'] = 1;
  357. array_push($info, $cart);
  358. unset($cart);
  359. }
  360. $order['cartInfo'] = $info;
  361. }
  362. /** @var StoreOrderStatusServices $statusServices */
  363. $statusServices = app()->make(StoreOrderStatusServices::class);
  364. $status = [];
  365. $storeInfo = [];
  366. if ($order['store_id']) {
  367. $storeServices = app()->make(SystemStoreServices::class);
  368. $storeInfo = $storeServices->get((int)$order['store_id']);
  369. }
  370. //系统预设取消订单时间段
  371. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  372. //获取配置
  373. $systemValue = SystemConfigService::more($keyValue);
  374. //格式化数据
  375. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  376. switch ($order['type'] ?? 0) {
  377. case 1://秒杀
  378. $secs = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  379. break;
  380. case 2://砍价
  381. $secs = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  382. break;
  383. case 3://拼团
  384. $secs = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  385. break;
  386. default:
  387. $secs = $systemValue['order_cancel_time'];
  388. break;
  389. }
  390. $order['stop_time'] = $secs * 3600 + $order['add_time'];
  391. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  392. $status['_type'] = 9;
  393. $status['_title'] = '线下付款,未支付';
  394. $status['_msg'] = '等待商家处理,请耐心等待';
  395. $status['_class'] = 'nobuy';
  396. } else if (!$order['paid']) {
  397. $status['_type'] = 0;
  398. $status['_title'] = '未支付';
  399. $status['_msg'] = '请在' . date('m-d H:i:s', $order['stop_time']) . '前完成支付!';
  400. $status['_class'] = 'nobuy';
  401. } else if ($order['refund_status'] == 2) {
  402. $status['_type'] = -2;
  403. $status['_title'] = '已退款';
  404. $status['_msg'] = '已为您退款,感谢您的支持';
  405. $status['_class'] = 'state-sqtk';
  406. } else if ($order['status'] == 4) {
  407. if ($order['delivery_type'] == 'send') {// 送货
  408. $status['_type'] = 2;
  409. $status['_title'] = '待收货';
  410. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery'], 'change_time')) . '服务商已送货';
  411. $status['_class'] = 'state-ysh';
  412. } elseif ($order['delivery_type'] == 'express') {// 发货
  413. $status['_type'] = 2;
  414. $status['_title'] = '待收货';
  415. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_goods'], 'change_time')) . '服务商已发货';
  416. $status['_class'] = 'state-ysh';
  417. } elseif ($order['delivery_type'] == 'split') {//拆分发货
  418. $status['_type'] = 2;
  419. $status['_title'] = '待收货';
  420. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_part_split'], 'change_time')) . '服务商已拆分多个包裹发货';
  421. $status['_class'] = 'state-ysh';
  422. } else {
  423. $status['_type'] = 2;
  424. $status['_title'] = '待收货';
  425. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_fictitious'], 'change_time')) . '服务商已虚拟发货';
  426. $status['_class'] = 'state-ysh';
  427. }
  428. } elseif ($order['status'] == 5) {
  429. if ($order['shipping_type'] == 2) {
  430. $status['_type'] = 5;
  431. $status['_title'] = '部分核销';
  432. $status['_msg'] = '部分核销,请继续进行核销';
  433. $status['_class'] = 'state-nfh';
  434. } else {
  435. $status['_type'] = 2;
  436. $status['_title'] = '待收货';
  437. $status['_msg'] = '部分核销收货,请继续进行核销';
  438. $status['_class'] = 'state-ysh';
  439. }
  440. } else if ($order['refund_status'] == 1) {
  441. if (in_array($order['refund_type'], [0, 1, 2])) {
  442. $status['_type'] = -1;
  443. $status['_title'] = '申请退款中';
  444. $status['_msg'] = '商家审核中,请耐心等待';
  445. $status['_class'] = 'state-sqtk';
  446. } elseif ($order['refund_type'] == 4) {
  447. $status['_type'] = -1;
  448. $status['_title'] = '申请退款中';
  449. $status['_msg'] = '商家同意退款,请填写退货订单号';
  450. $status['_class'] = 'state-sqtk';
  451. if ($order['shipping_type'] == 1 || !$storeInfo) {//平台
  452. $status['refund_name'] = sys_config('refund_name', '');
  453. $status['refund_phone'] = sys_config('refund_phone', '');
  454. $status['refund_address'] = sys_config('refund_address', '');
  455. } else {
  456. $status['refund_name'] = $storeInfo['name'];
  457. $status['refund_phone'] = $storeInfo['phone'];
  458. $status['refund_address'] = $storeInfo['detailed_address'];
  459. }
  460. } elseif ($order['refund_type'] == 5) {
  461. $status['_type'] = -1;
  462. $status['_title'] = '申请退款中';
  463. $status['_msg'] = '等待商家收货';
  464. $status['_class'] = 'state-sqtk';
  465. if ($order['shipping_type'] == 1 || !$storeInfo) {//平台
  466. $status['refund_name'] = sys_config('refund_name', '');
  467. $status['refund_phone'] = sys_config('refund_phone', '');
  468. $status['refund_address'] = sys_config('refund_address', '');
  469. } else {
  470. $status['refund_name'] = $storeInfo['name'];
  471. $status['refund_phone'] = $storeInfo['phone'];
  472. $status['refund_address'] = $storeInfo['detailed_address'];
  473. }
  474. }
  475. } else if ($order['refund_status'] == 3) {
  476. $status['_type'] = -1;
  477. $status['_title'] = '部分退款(子订单)';
  478. $status['_msg'] = '拆分发货,部分退款';
  479. $status['_class'] = 'state-sqtk';
  480. } else if ($order['refund_status'] == 4) {
  481. $status['_type'] = -1;
  482. $status['_title'] = '子订单已全部申请退款中';
  483. $status['_msg'] = '拆分发货,全部退款';
  484. $status['_class'] = 'state-sqtk';
  485. } else if (!$order['status']) {
  486. if ($order['pink_id']) {
  487. /** @var StorePinkServices $pinkServices */
  488. $pinkServices = app()->make(StorePinkServices::class);
  489. if ($pinkServices->getCount(['id' => $order['pink_id'], 'status' => 1])) {
  490. $status['_type'] = 1;
  491. $status['_title'] = '拼团中';
  492. $status['_msg'] = '等待其他人参加拼团';
  493. $status['_class'] = 'state-nfh';
  494. } else if (in_array($order['shipping_type'], [1, 3])) {
  495. $status['_type'] = 1;
  496. $status['_title'] = '未发货';
  497. $status['_msg'] = '商家未发货,请耐心等待';
  498. $status['_class'] = 'state-nfh';
  499. } else {
  500. $status['_type'] = 5;
  501. $status['_title'] = '待核销';
  502. $status['_msg'] = '待核销,请到核销点进行核销';
  503. $status['_class'] = 'state-nfh';
  504. }
  505. } else {
  506. if (in_array($order['shipping_type'], [1, 3])) {
  507. $status['_type'] = 1;
  508. $status['_title'] = '未发货';
  509. $status['_msg'] = '商家未发货,请耐心等待';
  510. $status['_class'] = 'state-nfh';
  511. } else {
  512. $status['_type'] = 5;
  513. $status['_title'] = '待核销';
  514. $status['_msg'] = '待核销,请到核销点进行核销';
  515. $status['_class'] = 'state-nfh';
  516. }
  517. }
  518. } else if ($order['status'] == 1) {
  519. if ($order['delivery_type'] == 'send') {// 配送
  520. $status['_type'] = 2;
  521. $status['_title'] = '待收货';
  522. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery'], 'change_time')) . '服务商已发货';
  523. $status['_class'] = 'state-ysh';
  524. } elseif ($order['delivery_type'] == 'express') {// 发货
  525. $status['_type'] = 2;
  526. $status['_title'] = '待收货';
  527. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_goods'], 'change_time')) . '服务商已发货';
  528. $status['_class'] = 'state-ysh';
  529. } elseif ($order['delivery_type'] == 'split') {//拆分发货
  530. $status['_type'] = 2;
  531. $status['_title'] = '待收货';
  532. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_split'], 'change_time')) . '服务商已拆分多个包裹发货';
  533. $status['_class'] = 'state-ysh';
  534. } else {
  535. $status['_type'] = 2;
  536. $status['_title'] = '待收货';
  537. $status['_msg'] = date('m月d日H时i分', $statusServices->value(['oid' => $order['id'], 'change_type' => 'delivery_fictitious'], 'change_time')) . '服务商已虚拟发货';
  538. $status['_class'] = 'state-ysh';
  539. }
  540. } else if ($order['status'] == 2) {
  541. $status['_type'] = 3;
  542. $status['_title'] = '待评价';
  543. $status['_msg'] = '已收货,快去评价一下吧';
  544. $status['_class'] = 'state-ypj';
  545. } else if ($order['status'] == 3) {
  546. $status['_type'] = 4;
  547. $status['_title'] = '交易完成';
  548. $status['_msg'] = '交易完成,感谢您的支持';
  549. $status['_class'] = 'state-ytk';
  550. }
  551. if (isset($order['pay_type']))
  552. $status['_payType'] = ($status['_type'] ?? 0) == 0 ? '' : PayServices::PAY_TYPE[$order['pay_type']] ?? '其他方式';
  553. if (isset($order['delivery_type']))
  554. $status['_deliveryType'] = isset($this->deliveryType[$order['delivery_type']]) ? $this->deliveryType[$order['delivery_type']] : '其他方式';
  555. $order['_status'] = $status;
  556. $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : '';
  557. $order['_add_time'] = isset($order['add_time']) ? (strstr((string)$order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
  558. $order['status_pic'] = '';
  559. //获取商品状态图片
  560. if ($isPic) {
  561. try {
  562. $order_details_images = sys_data('order_details_images') ?: [];
  563. $order_details_images = array_combine(array_column($order_details_images, 'order_status'), $order_details_images);
  564. $_type = $order['_status']['_type'] == 5 ? 2 : $order['_status']['_type'];
  565. $order['status_pic'] = $order_details_images[$_type]['pic'] ?? '';
  566. } catch (\Throwable $e) {
  567. }
  568. }
  569. $order['offlinePayStatus'] = (int)sys_config('offline_pay_status') ?? 2;
  570. //自购返佣
  571. if ($order['uid'] == $order['spread_uid']) {
  572. $order['spread_nickname'] = isset($order['spread_nickname']) ? $order['spread_nickname'] . '(自购)' : '';
  573. }
  574. $order['longitude'] = $order['latitude'] = '';
  575. //处理地址定位
  576. if (isset($order['user_location']) && $order['user_location']) {
  577. [$longitude, $latitude] = explode(' ', $order['user_location']);
  578. $order['longitude'] = $longitude;
  579. $order['latitude'] = $latitude;
  580. }
  581. return $order;
  582. }
  583. /**
  584. * 整理订单类型
  585. * @param $order
  586. * @param bool $abridge
  587. * @return string[]
  588. */
  589. public function tidyOrderType($order, bool $abridge = false)
  590. {
  591. $pink_name = $color = '';
  592. if ($order && isset($order['type'])) {
  593. switch ($order['type']) {
  594. case 0://普通订单
  595. if ($order['shipping_type'] == 1) {
  596. $pink_name = $abridge ? '普通' : '[普通订单]';
  597. $color = '#895612';
  598. } else if ($order['shipping_type'] == 2) {
  599. $pink_name = $abridge ? '核销' : '[核销订单]';
  600. $color = '#8956E8';
  601. } else if ($order['shipping_type'] == 3) {
  602. $pink_name = $abridge ? '分配' : '[分配订单]';
  603. $color = '#FFA21B';
  604. } else if ($order['shipping_type'] == 4) {
  605. $pink_name = $abridge ? '收银' : '[收银订单]';
  606. $color = '#2EC479';
  607. }
  608. break;
  609. case 1://秒杀
  610. $pink_name = $abridge ? '秒杀' : '[秒杀订单]';
  611. $color = '#32c5e9';
  612. break;
  613. case 2://砍价
  614. $pink_name = $abridge ? '砍价' : '[砍价订单]';
  615. $color = '#12c5e9';
  616. break;
  617. case 3://拼团
  618. if (isset($order['pinkStatus'])) {
  619. switch ($order['pinkStatus']) {
  620. case 1:
  621. $pink_name = $abridge ? '拼团' : '[拼团订单]正在进行中';
  622. $color = '#f00';
  623. break;
  624. case 2:
  625. $pink_name = $abridge ? '拼团' : '[拼团订单]已完成';
  626. $color = '#00f';
  627. break;
  628. case 3:
  629. $pink_name = $abridge ? '拼团' : '[拼团订单]未完成';
  630. $color = '#f0f';
  631. break;
  632. default:
  633. $pink_name = $abridge ? '拼团' : '[拼团订单]历史订单';
  634. $color = '#457856';
  635. break;
  636. }
  637. } else {
  638. $pink_name = $abridge ? '拼团' : '[拼团订单]历史订单';
  639. $color = '#457856';
  640. }
  641. break;
  642. case 4://积分
  643. $pink_name = $abridge ? '积分' : '[积分订单]';
  644. $color = '#12c5e9';
  645. break;
  646. case 5://套餐
  647. $pink_name = $abridge ? '优惠' : '[优惠套餐]';
  648. $color = '#12c5e9';
  649. break;
  650. case 6://预售
  651. $pink_name = $abridge ? '预售' : '[预售订单]';
  652. $color = '#12c5e9';
  653. break;
  654. case 7://新人礼
  655. $pink_name = $abridge ? '新人礼' : '[新人专享]';
  656. $color = '#12c5e9';
  657. break;
  658. case 8://抽奖
  659. $pink_name = $abridge ? '抽奖' : '[抽奖订单]';
  660. $color = '#12c5e9';
  661. break;
  662. case 9://拼单
  663. $pink_name = $abridge ? '拼单' : '[拼单订单]';
  664. $color = '#12c5e9';
  665. break;
  666. case 10://桌码
  667. $pink_name = $abridge ? '桌码' : '[桌码订单]';
  668. $color = '#F5222D';
  669. break;
  670. }
  671. }
  672. return [$pink_name, $color];
  673. }
  674. /**
  675. * 数据转换
  676. * @param array $data
  677. * @param bool $is_cart_info
  678. * @return array|null
  679. */
  680. public function tidyOrderList(array $data, bool $is_cart_info = true, bool $abridge = false)
  681. {
  682. if (!$data) {
  683. return $data;
  684. }
  685. /** @var StoreOrderCartInfoServices $services */
  686. $services = app()->make(StoreOrderCartInfoServices::class);
  687. foreach ($data as &$item) {
  688. if ($is_cart_info) $item['_info'] = $services->getOrderCartInfo((int)$item['id']);
  689. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  690. $item['_refund_time'] = isset($item['refund_reason_time']) && $item['refund_reason_time'] ? date('Y-m-d H:i:s', $item['refund_reason_time']) : '';
  691. $item['_pay_time'] = isset($item['pay_time']) && $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '';
  692. [$pink_name, $color] = $this->tidyOrderType($item, $abridge);
  693. $item['pink_name'] = $pink_name;
  694. $item['color'] = $color;
  695. if ($item['paid'] == 1) {
  696. switch ($item['pay_type']) {
  697. case PayServices::WEIXIN_PAY:
  698. $item['pay_type_name'] = '微信支付';
  699. break;
  700. case PayServices::YUE_PAY:
  701. $item['pay_type_name'] = '余额支付';
  702. break;
  703. case PayServices::OFFLINE_PAY:
  704. $item['pay_type_name'] = '线下支付';
  705. break;
  706. case PayServices::ALIAPY_PAY:
  707. $item['pay_type_name'] = '支付宝支付';
  708. break;
  709. case PayServices::CASH_PAY:
  710. $item['pay_type_name'] = '现金支付';
  711. break;
  712. default:
  713. $item['pay_type_name'] = '其他支付';
  714. break;
  715. }
  716. } else {
  717. switch ($item['pay_type']) {
  718. default:
  719. $item['pay_type_name'] = '未支付';
  720. break;
  721. case 'offline':
  722. $item['pay_type_name'] = '线下支付';
  723. $item['pay_type_info'] = 1;
  724. break;
  725. }
  726. }
  727. $status_name = ['status_name' => '', 'pics' => []];
  728. if ($item['is_del'] || $item['is_system_del']) {
  729. $status_name['status_name'] = '已删除';
  730. $item['_status'] = -1;
  731. } else if ($item['paid'] == 0 && $item['status'] == 0) {
  732. $status_name['status_name'] = '未支付';
  733. $item['_status'] = 1;//未支付
  734. } else if ($item['paid'] == 1 && $item['status'] == 4 && in_array($item['shipping_type'], [1, 3]) && $item['refund_status'] == 0) {
  735. $status_name['status_name'] = '部分发货';
  736. $item['_status'] = 8;//已支付 部分发货
  737. } else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
  738. $status_name['status_name'] = '已退款';
  739. $item['_status'] = 7;//已支付 已退款
  740. } else if ($item['paid'] == 1 && $item['status'] == 5 && $item['refund_status'] == 0) {
  741. $status_name['status_name'] = $item['shipping_type'] == 2 ? '部分核销' : '部分收货';
  742. $item['_status'] = 12;//已支付 部分核销
  743. } else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
  744. $item['_status'] = 3;//已支付 申请退款中
  745. $refundReasonTime = $item['refund_reason_time'] ? date('Y-m-d H:i', $item['refund_reason_time']) : '';
  746. $refundReasonWapImg = json_decode($item['refund_reason_wap_img'], true);
  747. $refundReasonWapImg = $refundReasonWapImg ? $refundReasonWapImg : [];
  748. $img = [];
  749. if (count($refundReasonWapImg)) {
  750. foreach ($refundReasonWapImg as $itemImg) {
  751. if (strlen(trim($itemImg)))
  752. $img[] = $itemImg;
  753. }
  754. }
  755. $status_name['status_name'] = <<<HTML
  756. <b style="color:#f124c7">申请退款</b><br/>
  757. <span>退款原因:{$item['refund_reason_wap']}</span><br/>
  758. <span>备注说明:{$item['refund_reason_wap_explain']}</span><br/>
  759. <span>退款时间:{$refundReasonTime}</span><br/>
  760. <span>退款凭证:</span>
  761. HTML;
  762. $status_name['pics'] = $img;
  763. } else if ($item['paid'] == 1 && $item['refund_status'] == 4) {
  764. $item['_status'] = 10;//拆单发货 已全部申请退款
  765. $status_name['status_name'] = '退款中';
  766. } else if ($item['paid'] == 1 && $item['status'] == 0 && in_array($item['shipping_type'], [1, 3, 4]) && $item['refund_status'] == 0) {
  767. $status_name['status_name'] = '未发货';
  768. $item['_status'] = 2;//已支付 未发货
  769. } else if ($item['paid'] == 1 && in_array($item['status'], [0, 1]) && $item['shipping_type'] == 2 && $item['refund_status'] == 0) {
  770. $status_name['status_name'] = '未核销';
  771. $item['_status'] = 11;//已支付 待核销
  772. } else if ($item['paid'] == 1 && in_array($item['status'], [1, 5]) && in_array($item['shipping_type'], [1, 3, 4]) && $item['refund_status'] == 0) {
  773. $status_name['status_name'] = '待收货';
  774. $item['_status'] = 4;//已支付 待收货
  775. } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
  776. $status_name['status_name'] = '待评价';
  777. $item['_status'] = 5;//已支付 待评价
  778. } else if ($item['paid'] == 1 && $item['status'] == 3 && $item['refund_status'] == 0) {
  779. $status_name['status_name'] = '已完成';
  780. $item['_status'] = 6;//已支付 已完成
  781. } else if ($item['paid'] == 1 && $item['refund_status'] == 3) {
  782. $item['_status'] = 9;//拆单发货 部分申请退款
  783. $status_name['status_name'] = '部分退款';
  784. }
  785. $item['status_name'] = $status_name;
  786. if ($item['store_id'] == 0 && $item['clerk_id'] == 0 && !isset($item['clerk_name'])) {
  787. $item['clerk_name'] = '总平台';
  788. }
  789. //根据核销员更改store_name
  790. if ($item['clerk_id'] && isset($item['staff_store_id']) && $item['staff_store_id']) {
  791. /** @var SystemStoreServices $store */
  792. $store = app()->make(SystemStoreServices::class);
  793. $storeOne = $store->value(['id' => $item['staff_store_id']], 'name');
  794. if ($storeOne) $item['store_name'] = $storeOne;
  795. }
  796. //自购返佣
  797. if ($item['uid'] == $item['spread_uid']) {
  798. $item['spread_nickname'] = isset($item['spread_nickname']) ? $item['spread_nickname'] . '(自购)' : '';
  799. }
  800. }
  801. return $data;
  802. }
  803. /**
  804. * 处理订单金额
  805. * @param $where
  806. * @return array
  807. */
  808. public function getOrderPrice($where)
  809. {
  810. // $where['pid'] = 0;//子订单不统计
  811. $whereData = [];
  812. $price['today_count_sum'] = 0; //今日订单总数
  813. $price['count_sum'] = 0; //订单总数
  814. $price['pay_price'] = 0;//支付金额
  815. $price['today_pay_price'] = 0;//今日支付金额
  816. if ($where['status'] == '') {
  817. $whereData['paid'] = 1;
  818. $whereData['refund_status'] = [0, 3];
  819. }
  820. $not_pid = $where;
  821. unset($not_pid['pid']);
  822. $not_pid['not_pid'] = 1;
  823. $sumNumber = $this->dao->search($where + $whereData)->field([
  824. 'count(id) as count_sum',
  825. ])->find();
  826. $price['count_sum'] = $sumNumber && $sumNumber['count_sum'] ? $sumNumber['count_sum'] : 0;
  827. $sumNumber = $this->dao->search($whereData + $where)->field([
  828. 'sum(pay_price) as sum_pay_price',
  829. ])->find();
  830. $price['pay_price'] = $sumNumber && $sumNumber['sum_pay_price'] ? $sumNumber['sum_pay_price'] : 0;
  831. $where['time'] = 'today';
  832. $not_pid['time'] = 'today';
  833. $sumNumber = $this->dao->search($where + $whereData)->field([
  834. 'count(id) as today_count_sum',
  835. ])->find();
  836. $price['today_count_sum'] = $sumNumber && $sumNumber['today_count_sum'] ? $sumNumber['today_count_sum'] : 0;
  837. $sumNumber = $this->dao->search($whereData + $where + ['paid' => 1])->field([
  838. 'sum(pay_price) as today_pay_price',
  839. ])->find();
  840. $price['today_pay_price'] = $sumNumber && $sumNumber['today_pay_price'] ? $sumNumber['today_pay_price'] : 0;
  841. return $price;
  842. }
  843. /**
  844. * 获取订单列表页面统计数据
  845. * @param $where
  846. * @return array
  847. */
  848. public function getBadge($where)
  849. {
  850. $price = $this->getOrderPrice($where);
  851. return [
  852. [
  853. 'name' => '订单数量',
  854. 'field' => '件',
  855. 'count' => $price['count_sum'],
  856. 'className' => 'md-basket',
  857. 'col' => 6
  858. ],
  859. [
  860. 'name' => '订单金额',
  861. 'field' => '元',
  862. 'count' => $price['pay_price'],
  863. 'className' => 'md-pricetags',
  864. 'col' => 6
  865. ],
  866. [
  867. 'name' => '今日订单数量',
  868. 'field' => '件',
  869. 'count' => $price['today_count_sum'],
  870. 'className' => 'ios-chatbubbles',
  871. 'col' => 6
  872. ],
  873. [
  874. 'name' => '今日支付金额',
  875. 'field' => '元',
  876. 'count' => $price['today_pay_price'],
  877. 'className' => 'ios-cash',
  878. 'col' => 6
  879. ],
  880. ];
  881. }
  882. /**
  883. *
  884. * @param array $where
  885. * @return mixed
  886. */
  887. public function orderStoreCount(array $where)
  888. {
  889. $defaultWhere = ['time' => $where['time'], 'store_id' => $where['store_id'] ?? 0, 'is_system_del' => 0];
  890. if (isset($where['store_id'])) {
  891. $defaultWhere['store_id'] = $where['store_id'];
  892. }
  893. //全部订单
  894. $data['all'] = (string)$this->dao->count(['pid' => 0] + $defaultWhere);
  895. //普通订单
  896. $data['general'] = (string)$this->dao->count(['pid' => 0, 'type' => 0] + $defaultWhere);
  897. //拼团订单
  898. $data['pink'] = (string)$this->dao->count(['pid' => 0, 'type' => 3] + $defaultWhere);
  899. //秒杀订单
  900. $data['seckill'] = (string)$this->dao->count(['pid' => 0, 'type' => 1] + $defaultWhere);
  901. //砍价订单
  902. $data['bargain'] = (string)$this->dao->count(['pid' => 0, 'type' => 2] + $defaultWhere);
  903. //收银订单
  904. $data['cashier'] = (string)$this->dao->count(['pid' => 0, 'type' => 6] + $defaultWhere);
  905. $data['write_off'] = (string)$this->dao->count(['pid' => 0, 'type' => 5] + $defaultWhere);
  906. $data['delivery'] = (string)$this->dao->count(['pid' => 0, 'type' => 7] + $defaultWhere);
  907. //预售订单
  908. $data['presale'] = (string)$this->dao->count(['pid' => 0, 'type' => 8] + $defaultWhere);
  909. switch ($where['type']) {
  910. case 0:
  911. $data['statusAll'] = $data['general'];
  912. break;
  913. case 1:
  914. $data['statusAll'] = $data['seckill'];
  915. break;
  916. case 2:
  917. $data['statusAll'] = $data['bargain'];
  918. break;
  919. case 3:
  920. $data['statusAll'] = $data['pink'];
  921. break;
  922. case 4:
  923. break;
  924. case 5:
  925. $data['statusAll'] = $data['write_off'];
  926. break;
  927. case 6:
  928. $data['statusAll'] = $data['cashier'];
  929. break;
  930. case 7:
  931. $data['statusAll'] = $data['delivery'];
  932. break;
  933. case 8:
  934. $data['statusAll'] = $data['presale'];
  935. break;
  936. default:
  937. $data['statusAll'] = $data['all'];
  938. }
  939. $count_where = ['pid' => 0, 'type' => $where['type']] + $defaultWhere;
  940. //未支付
  941. $data['unpaid'] = (string)$this->dao->count($count_where + ['status' => 0]);
  942. //未发货
  943. $data['unshipped'] = (string)$this->dao->count($count_where + ['status' => 1]);
  944. //部分发货
  945. $data['partshipped'] = (string)$this->dao->count($count_where + ['status' => 7]);
  946. //待收货
  947. $data['untake'] = (string)$this->dao->count($count_where + ['status' => 2]);
  948. //待核销
  949. $data['write_off'] = (string)$this->dao->count($count_where + ['status' => 5]);
  950. //已核销
  951. $data['write_offed'] = (string)$this->dao->count($count_where + ['status' => 6]);
  952. //待评价
  953. $data['unevaluate'] = (string)$this->dao->count($count_where + ['status' => 3]);
  954. //交易完成
  955. $data['complete'] = (string)$this->dao->count($count_where + ['status' => 4]);
  956. //退款中
  957. // $data['refunding'] = (string)$this->dao->count(['status' => -1, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  958. //已退款
  959. // $data['refund'] = (string)$this->dao->count(['status' => -2, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  960. //删除订单
  961. $data['del'] = (string)$this->dao->count($count_where + ['status' => -4]);
  962. return $data;
  963. }
  964. /**
  965. *
  966. * @param array $where
  967. * @return mixed
  968. */
  969. public function orderCount(array $where)
  970. {
  971. $default_where = [
  972. 'pid' => [0, -1],
  973. 'time' => $where['time'],
  974. 'status' => $where['status'],
  975. 'pay_type' => $where['pay_type'],
  976. 'field_key' => $where['field_key'],
  977. 'real_name' => $where['real_name'],
  978. 'is_system_del' => 0
  979. ];
  980. $count_where = ['type' => $where['type'] ?? 0, 'store_id' => $where['store_id'] ?? 0, 'supplier_id' => $where['supplier_id'] ?? 0];
  981. // if ($count_where['store_id'] || $count_where['supplier_id'] || (isset($where['plat_type']) && in_array($where['plat_type'], [1, 2]))) {
  982. // $default_where['pid'] = 0;
  983. // }
  984. //全部订单
  985. $data['all'] = (string)$this->dao->count($default_where + $count_where);
  986. //普通订单
  987. $data['general'] = (string)$this->dao->count(['type' => 0] + $default_where + $count_where);
  988. //平台订单
  989. $data['plat'] = (string)$this->dao->count(['plat_type' => 0, 'pid' => 0] + $default_where + $count_where);
  990. //门店订单
  991. $data['store'] = (string)$this->dao->count(['plat_type' => 1, 'pid' => 0] + $default_where + $count_where);
  992. //供应商订单
  993. $data['supplier'] = (string)$this->dao->count(['plat_type' => 2, 'pid' => 0] + $default_where + $count_where);
  994. //拼团订单
  995. $data['pink'] = (string)$this->dao->count(['type' => 3] + $default_where);
  996. //秒杀订单
  997. $data['seckill'] = (string)$this->dao->count(['type' => 1] + $default_where);
  998. //砍价订单
  999. $data['bargain'] = (string)$this->dao->count(['type' => 2] + $default_where);
  1000. //预售订单
  1001. $data['presale'] = (string)$this->dao->count(['type' => 8] + $default_where);
  1002. $data['statusAll'] = $data['all'];
  1003. if (trim($where['type'], ' ') !== '') {
  1004. switch ($where['type']) {
  1005. case 0:
  1006. $data['statusAll'] = $data['general'];
  1007. break;
  1008. case 1:
  1009. $data['statusAll'] = $data['seckill'];
  1010. break;
  1011. case 2:
  1012. $data['statusAll'] = $data['bargain'];
  1013. break;
  1014. case 3:
  1015. $data['statusAll'] = $data['pink'];
  1016. break;
  1017. case 4:
  1018. break;
  1019. case 8:
  1020. $data['statusAll'] = $data['presale'];
  1021. break;
  1022. default:
  1023. $data['statusAll'] = $data['all'];
  1024. }
  1025. }
  1026. $count_where = ['type' => $where['type']] + $default_where;
  1027. //未支付
  1028. $data['unpaid'] = (string)$this->dao->count($count_where + ['status' => 0]);
  1029. //未发货
  1030. $data['unshipped'] = (string)$this->dao->count($count_where + ['status' => 1, 'shipping_type' => 1]);
  1031. //部分发货
  1032. $data['partshipped'] = (string)$this->dao->count($count_where + ['status' => 7, 'shipping_type' => 1]);
  1033. //待收货
  1034. $data['untake'] = (string)$this->dao->count($count_where + ['status' => 2, 'shipping_type' => 1]);
  1035. //待核销
  1036. $data['write_off'] = (string)$this->dao->count($count_where + ['status' => 5]);
  1037. //已核销
  1038. $data['write_offed'] = (string)$this->dao->count($count_where + ['status' => 6]);
  1039. //待评价
  1040. $data['unevaluate'] = (string)$this->dao->count($count_where + ['status' => 3]);
  1041. //交易完成
  1042. $data['complete'] = (string)$this->dao->count($count_where + ['status' => 4]);
  1043. //退款中
  1044. // $data['refunding'] = (string)$this->dao->count(['status' => -1, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  1045. //已退款
  1046. // $data['refund'] = (string)$this->dao->count(['status' => -2, 'time' => $where['time'], 'is_system_del' => 0, 'type' => $where['type']]);
  1047. //删除订单
  1048. $data['del'] = (string)$this->dao->count($count_where + ['status' => -4]);
  1049. return $data;
  1050. }
  1051. /**
  1052. * 创建修改订单表单
  1053. * @param int $id
  1054. * @return array
  1055. * @throws \FormBuilder\Exception\FormBuilderException
  1056. */
  1057. public function updateForm(int $id)
  1058. {
  1059. $product = $this->dao->get($id);
  1060. if (!$product) {
  1061. throw new ValidateException('Data does not exist!');
  1062. }
  1063. $f = [];
  1064. $f[] = Form::input('order_id', '订单编号', $product->getData('order_id'))->disabled(true);
  1065. $f[] = Form::number('total_price', '商品总价', (float)$product->getData('total_price'))->min(0)->disabled(true);
  1066. $f[] = Form::number('total_postage', '原始邮费', (float)$product->getData('total_postage'))->min(0)->disabled(true);
  1067. $f[] = Form::number('pay_postage', '实际支付邮费', (float)$product->getData('pay_postage') ?: 0)->disabled(true);
  1068. $f[] = Form::number('pay_price', '实际支付金额', (float)$product->getData('pay_price'))->min(0);
  1069. $f[] = Form::number('gain_integral', '赠送积分', (float)$product->getData('gain_integral') ?: 0)->precision(0);
  1070. return create_form('修改订单', $f, $this->url('/order/update/' . $id), 'PUT');
  1071. }
  1072. /**
  1073. * 修改订单
  1074. * @param int $id
  1075. * @param array $data
  1076. * @return mixed
  1077. * @throws \Exception
  1078. */
  1079. public function updateOrder(int $id, array $data)
  1080. {
  1081. $order = $this->dao->getOne(['id' => $id, 'is_del' => 0]);
  1082. if (!$order) {
  1083. throw new ValidateException('订单不存在或已删除');
  1084. }
  1085. if ($order['paid']) {
  1086. throw new ValidateException('订单已支付');
  1087. }
  1088. //限制改价金额两位小数
  1089. $data['pay_price'] = sprintf("%.2f", $data['pay_price']);
  1090. $pay_price = $order['pay_price'];
  1091. if ($order['change_price']) {//已经改过一次价
  1092. $pay_price = bcadd((string)$pay_price, (string)$order['change_price'], 2);
  1093. }
  1094. //记录改价优惠金额
  1095. $data['change_price'] = (float)bcsub((string)$pay_price, (string)($data['pay_price'] ?? 0), 2);
  1096. /** @var StoreOrderStatusServices $services */
  1097. $services = app()->make(StoreOrderStatusServices::class);
  1098. $this->transaction(function () use ($id, $order, $data, $services) {
  1099. $res = $this->dao->update($id, $data);
  1100. $res = $res && $services->save([
  1101. 'oid' => $id,
  1102. 'change_type' => 'order_edit',
  1103. 'change_time' => time(),
  1104. 'change_message' => '商品总价为:' . $order['pay_price'] . ' 修改实际支付金额为:' . $data['pay_price']
  1105. ]);
  1106. if ($res) {
  1107. return true;
  1108. } else {
  1109. throw new ValidateException('Modification failed');
  1110. }
  1111. });
  1112. //新订单号
  1113. // $order['order_id'] = $data['order_id'];
  1114. //改价提醒
  1115. event('order.price', [$order, $data['pay_price']]);
  1116. return true;
  1117. }
  1118. /**
  1119. * 订单图表
  1120. * @param $cycle
  1121. * @return array
  1122. */
  1123. public function orderCharts($cycle)
  1124. {
  1125. $datalist = [];
  1126. $where = [];
  1127. $series1 = ['normal' => ['color' => [
  1128. 'x' => 0, 'y' => 0, 'x2' => 0, 'y2' => 1,
  1129. 'colorStops' => [
  1130. [
  1131. 'offset' => 0,
  1132. 'color' => '#69cdff'
  1133. ],
  1134. [
  1135. 'offset' => 0.5,
  1136. 'color' => '#3eb3f7'
  1137. ],
  1138. [
  1139. 'offset' => 1,
  1140. 'color' => '#1495eb'
  1141. ]
  1142. ]
  1143. ]]
  1144. ];
  1145. $series2 = ['normal' => ['color' => [
  1146. 'x' => 0, 'y' => 0, 'x2' => 0, 'y2' => 1,
  1147. 'colorStops' => [
  1148. [
  1149. 'offset' => 0,
  1150. 'color' => '#6fdeab'
  1151. ],
  1152. [
  1153. 'offset' => 0.5,
  1154. 'color' => '#44d693'
  1155. ],
  1156. [
  1157. 'offset' => 1,
  1158. 'color' => '#2cc981'
  1159. ]
  1160. ]
  1161. ]]
  1162. ];
  1163. $chartdata = [];
  1164. $data = [];//临时
  1165. $chartdata['yAxis']['maxnum'] = 0;//最大值数量
  1166. $chartdata['yAxis']['maxprice'] = 0;//最大值金额
  1167. switch ($cycle) {
  1168. case 'thirtyday':
  1169. //上期
  1170. $datebefor = date('Y-m-d 00:00:00', strtotime('-59 day'));
  1171. $dateafter = date('Y-m-d 23:59:59', strtotime('-29 day'));
  1172. //当前
  1173. $now_datebefor = date('Y-m-d 00:00:00', strtotime('-29 day'));
  1174. $now_dateafter = date('Y-m-d 23:59:59');
  1175. for ($i = -29; $i <= 0; $i++) {
  1176. $datalist[date('Y-m-d', strtotime($i . ' day'))] = date('Y-m-d', strtotime($i . ' day'));
  1177. }
  1178. $order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'day');
  1179. if (empty($order_list)) return ['yAxis' => [], 'legend' => [], 'xAxis' => [], 'serise' => [], 'pre_cycle' => [], 'cycle' => []];
  1180. $order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1181. $cycle_list = [];
  1182. foreach ($datalist as $dk => $dd) {
  1183. if (isset($order_list[$dk]) && !empty($order_list[$dd])) {
  1184. $cycle_list[$dd] = $order_list[$dd];
  1185. } else {
  1186. $cycle_list[$dd] = ['count' => 0, 'day' => $dd, 'price' => ''];
  1187. }
  1188. }
  1189. foreach ($cycle_list as $k => $v) {
  1190. $data['day'][] = $v['day'];
  1191. $data['count'][] = $v['count'];
  1192. $data['price'][] = round($v['price'], 2);
  1193. if ($chartdata['yAxis']['maxnum'] < $v['count'])
  1194. $chartdata['yAxis']['maxnum'] = $v['count'];//日最大订单数
  1195. if ($chartdata['yAxis']['maxprice'] < $v['price'])
  1196. $chartdata['yAxis']['maxprice'] = $v['price'];//日最大金额
  1197. }
  1198. $chartdata['legend'] = ['订单金额', '订单数'];//分类
  1199. $chartdata['xAxis'] = $data['day'];//X轴值
  1200. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['price']];//分类1值
  1201. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['count'], 'yAxisIndex' => 1];//分类2值
  1202. break;
  1203. case 'week':
  1204. $weekarray = [['周日'], ['周一'], ['周二'], ['周三'], ['周四'], ['周五'], ['周六']];
  1205. $datebefor = date('Y-m-d 00:00:00', strtotime('-1 week Monday'));
  1206. $dateafter = date('Y-m-d 23:59:59', strtotime('-1 week Sunday'));
  1207. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], 'week');
  1208. //数据查询重新处理
  1209. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1210. $now_datebefor = date('Y-m-d 00:00:00', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
  1211. $now_dateafter = date('Y-m-d 23:59:59', strtotime("+1 day"));
  1212. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'week');
  1213. //数据查询重新处理 key 变为当前值
  1214. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1215. foreach ($weekarray as $dk => $dd) {
  1216. if (isset($new_order_list[$dk]) && !empty($new_order_list[$dk])) {
  1217. $weekarray[$dk]['pre'] = $new_order_list[$dk];
  1218. } else {
  1219. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1220. }
  1221. if (isset($new_now_order_list[$dk]) && !empty($new_now_order_list[$dk])) {
  1222. $weekarray[$dk]['now'] = $new_now_order_list[$dk];
  1223. } else {
  1224. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1225. }
  1226. }
  1227. foreach ($weekarray as $k => $v) {
  1228. $data['day'][] = $v[0];
  1229. $data['pre']['count'][] = $v['pre']['count'];
  1230. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1231. $data['now']['count'][] = $v['now']['count'];
  1232. $data['now']['price'][] = round($v['now']['price'], 2);
  1233. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1234. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1235. }
  1236. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1237. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1238. }
  1239. }
  1240. $chartdata['legend'] = ['上周金额', '本周金额', '上周订单数', '本周订单数'];//分类
  1241. $chartdata['xAxis'] = $data['day'];//X轴值
  1242. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1243. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1244. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1245. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1246. break;
  1247. case 'month':
  1248. $weekarray = ['01' => ['1'], '02' => ['2'], '03' => ['3'], '04' => ['4'], '05' => ['5'], '06' => ['6'], '07' => ['7'], '08' => ['8'], '09' => ['9'], '10' => ['10'], '11' => ['11'], '12' => ['12'], '13' => ['13'], '14' => ['14'], '15' => ['15'], '16' => ['16'], '17' => ['17'], '18' => ['18'], '19' => ['19'], '20' => ['20'], '21' => ['21'], '22' => ['22'], '23' => ['23'], '24' => ['24'], '25' => ['25'], '26' => ['26'], '27' => ['27'], '28' => ['28'], '29' => ['29'], '30' => ['30'], '31' => ['31']];
  1249. $datebefor = date('Y-m-01 00:00:00', strtotime('-1 month'));
  1250. $dateafter = date('Y-m-d 23:59:59', strtotime(date('Y-m-01')));
  1251. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], "month");
  1252. //数据查询重新处理
  1253. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1254. $now_datebefor = date('Y-m-01 00:00:00');
  1255. $now_dateafter = date('Y-m-d', strtotime("+1 day"));
  1256. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], "month");
  1257. //数据查询重新处理 key 变为当前值
  1258. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1259. foreach ($weekarray as $dk => $dd) {
  1260. if (isset($new_order_list[$dk]) && !empty($new_order_list[$dk])) {
  1261. $weekarray[$dk]['pre'] = $new_order_list[$dk];
  1262. } else {
  1263. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1264. }
  1265. if (isset($new_now_order_list[$dk]) && !empty($new_now_order_list[$dk])) {
  1266. $weekarray[$dk]['now'] = $new_now_order_list[$dk];
  1267. } else {
  1268. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1269. }
  1270. }
  1271. foreach ($weekarray as $k => $v) {
  1272. $data['day'][] = $v[0];
  1273. $data['pre']['count'][] = $v['pre']['count'];
  1274. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1275. $data['now']['count'][] = $v['now']['count'];
  1276. $data['now']['price'][] = round($v['now']['price'], 2);
  1277. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1278. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1279. }
  1280. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1281. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1282. }
  1283. }
  1284. $chartdata['legend'] = ['上月金额', '本月金额', '上月订单数', '本月订单数'];//分类
  1285. $chartdata['xAxis'] = $data['day'];//X轴值
  1286. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1287. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1288. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1289. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1290. break;
  1291. case 'year':
  1292. $weekarray = ['01' => ['一月'], '02' => ['二月'], '03' => ['三月'], '04' => ['四月'], '05' => ['五月'], '06' => ['六月'], '07' => ['七月'], '08' => ['八月'], '09' => ['九月'], '10' => ['十月'], '11' => ['十一月'], '12' => ['十二月']];
  1293. $datebefor = date('Y-01-01 00:00:00', strtotime('-1 year'));
  1294. $dateafter = date('Y-12-31 23:59:59', strtotime('-1 year'));
  1295. $order_list = $this->dao->orderAddTimeList($where, [$datebefor, $dateafter], 'year');
  1296. //数据查询重新处理
  1297. $new_order_list = array_combine(array_column($order_list, 'day'), $order_list);
  1298. $now_datebefor = date('Y-01-01 00:00:00');
  1299. $now_dateafter = date('Y-12-31 23:59:59');
  1300. $now_order_list = $this->dao->orderAddTimeList($where, [$now_datebefor, $now_dateafter], 'year');
  1301. //数据查询重新处理 key 变为当前值
  1302. $new_now_order_list = array_combine(array_column($now_order_list, 'day'), $now_order_list);
  1303. $y = date('Y');
  1304. foreach ($weekarray as $dk => $dd) {
  1305. $order_dk = $y . '-' . $dk;
  1306. if (isset($new_order_list[$order_dk]) && !empty($new_order_list[$order_dk])) {
  1307. $weekarray[$dk]['pre'] = $new_order_list[$order_dk];
  1308. } else {
  1309. $weekarray[$dk]['pre'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1310. }
  1311. if (isset($new_now_order_list[$order_dk]) && !empty($new_now_order_list[$order_dk])) {
  1312. $weekarray[$dk]['now'] = $new_now_order_list[$order_dk];
  1313. } else {
  1314. $weekarray[$dk]['now'] = ['count' => 0, 'day' => $weekarray[$dk][0], 'price' => '0'];
  1315. }
  1316. }
  1317. foreach ($weekarray as $k => $v) {
  1318. $data['day'][] = $v[0];
  1319. $data['pre']['count'][] = $v['pre']['count'];
  1320. $data['pre']['price'][] = round($v['pre']['price'], 2);
  1321. $data['now']['count'][] = $v['now']['count'];
  1322. $data['now']['price'][] = round($v['now']['price'], 2);
  1323. if ($chartdata['yAxis']['maxnum'] < $v['pre']['count'] || $chartdata['yAxis']['maxnum'] < $v['now']['count']) {
  1324. $chartdata['yAxis']['maxnum'] = $v['pre']['count'] > $v['now']['count'] ? $v['pre']['count'] : $v['now']['count'];//日最大订单数
  1325. }
  1326. if ($chartdata['yAxis']['maxprice'] < $v['pre']['price'] || $chartdata['yAxis']['maxprice'] < $v['now']['price']) {
  1327. $chartdata['yAxis']['maxprice'] = $v['pre']['price'] > $v['now']['price'] ? $v['pre']['price'] : $v['now']['price'];//日最大金额
  1328. }
  1329. }
  1330. $chartdata['legend'] = ['去年金额', '今年金额', '去年订单数', '今年订单数'];//分类
  1331. $chartdata['xAxis'] = $data['day'];//X轴值
  1332. $chartdata['series'][] = ['name' => $chartdata['legend'][0], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['pre']['price']];//分类1值
  1333. $chartdata['series'][] = ['name' => $chartdata['legend'][1], 'type' => 'bar', 'itemStyle' => $series1, 'data' => $data['now']['price']];//分类1值
  1334. $chartdata['series'][] = ['name' => $chartdata['legend'][2], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['pre']['count'], 'yAxisIndex' => 1];//分类2值
  1335. $chartdata['series'][] = ['name' => $chartdata['legend'][3], 'type' => 'line', 'itemStyle' => $series2, 'data' => $data['now']['count'], 'yAxisIndex' => 1];//分类2值
  1336. break;
  1337. default:
  1338. break;
  1339. }
  1340. //统计总数上期
  1341. $pre_total = $this->dao->preTotalFind($where, [$datebefor, $dateafter]);
  1342. if ($pre_total) {
  1343. $chartdata['pre_cycle']['count'] = [
  1344. 'data' => $pre_total['count'] ?: 0
  1345. ];
  1346. $chartdata['pre_cycle']['price'] = [
  1347. 'data' => $pre_total['price'] ?: 0
  1348. ];
  1349. }
  1350. //统计总数
  1351. $total = $this->dao->preTotalFind($where, [$now_datebefor, $now_dateafter]);
  1352. if ($total) {
  1353. $cha_count = intval($pre_total['count']) - intval($total['count']);
  1354. $pre_total['count'] = $pre_total['count'] == 0 ? 1 : $pre_total['count'];
  1355. $chartdata['cycle']['count'] = [
  1356. 'data' => $total['count'] ?: 0,
  1357. 'percent' => round((abs($cha_count) / intval($pre_total['count']) * 100), 2),
  1358. 'is_plus' => $cha_count > 0 ? -1 : ($cha_count == 0 ? 0 : 1)
  1359. ];
  1360. $cha_price = round($pre_total['price'], 2) - round($total['price'], 2);
  1361. $pre_total['price'] = $pre_total['price'] == 0 ? 1 : $pre_total['price'];
  1362. $chartdata['cycle']['price'] = [
  1363. 'data' => $total['price'] ?: 0,
  1364. 'percent' => round(abs($cha_price) / $pre_total['price'] * 100, 2),
  1365. 'is_plus' => $cha_price > 0 ? -1 : ($cha_price == 0 ? 0 : 1)
  1366. ];
  1367. }
  1368. return $chartdata;
  1369. }
  1370. /**
  1371. * 获取订单数量
  1372. * @param int $store_id
  1373. * @param int $type
  1374. * @param string $field
  1375. * @return int
  1376. */
  1377. public function storeOrderCount(int $store_id = 0, int $type = -1, string $field = 'store_id')
  1378. {
  1379. return $this->dao->storeOrderCount($store_id, $type, $field);
  1380. }
  1381. /**
  1382. * 首页头部统计
  1383. * @return array
  1384. */
  1385. public function homeStatics()
  1386. {
  1387. /** @var UserServices $uSercice */
  1388. $uSercice = app()->make(UserServices::class);
  1389. /** @var StoreProductLogServices $productLogServices */
  1390. $productLogServices = app()->make(StoreProductLogServices::class);
  1391. // 销售额
  1392. //今日销售额
  1393. $today_sales = $this->dao->totalSales('today');
  1394. //昨日销售额
  1395. $yesterday_sales = $this->dao->totalSales('yesterday');
  1396. //日同比
  1397. $sales_today_ratio = $this->countRate($today_sales, $yesterday_sales);
  1398. //周销售额
  1399. // //本周
  1400. // $this_week_sales = $this->dao->totalSales('week');
  1401. // //上周
  1402. // $last_week_sales = $this->dao->totalSales('last week');
  1403. // //周同比
  1404. // $sales_week_ratio = $this->countRate($this_week_sales, $last_week_sales);
  1405. //总销售额
  1406. $total_sales = $this->dao->totalSales('month');
  1407. $sales = [
  1408. 'today' => $today_sales,
  1409. 'yesterday' => $yesterday_sales,
  1410. 'today_ratio' => $sales_today_ratio,
  1411. // 'week' => $this_week_sales,
  1412. // 'last_week' => $last_week_sales,
  1413. // 'week_ratio' => $sales_week_ratio,
  1414. 'total' => $total_sales . '元',
  1415. 'date' => '今日'
  1416. ];
  1417. //用户访问量
  1418. //今日访问量
  1419. $today_visits = $productLogServices->count(['time' => 'today', 'type' => 'visit']);
  1420. //昨日访问量
  1421. $yesterday_visits = $productLogServices->count(['time' => 'yesterday', 'type' => 'visit']);
  1422. //日同比
  1423. $visits_today_ratio = $this->countRate($today_visits, $yesterday_visits);
  1424. // //本周访问量
  1425. // $this_week_visits = $productLogServices->count(['time' => 'week', 'type' => 'visit']);
  1426. // //上周访问量
  1427. // $last_week_visits = $productLogServices->count(['time' => 'last week', 'type' => 'visit']);
  1428. // //周同比
  1429. // $visits_week_ratio = $this->countRate($this_week_visits, $last_week_visits);
  1430. //总访问量
  1431. $total_visits = $productLogServices->count(['time' => 'month', 'type' => 'visit']);
  1432. $visits = [
  1433. 'today' => $today_visits,
  1434. 'yesterday' => $yesterday_visits,
  1435. 'today_ratio' => $visits_today_ratio,
  1436. // 'week' => $this_week_visits,
  1437. // 'last_week' => $last_week_visits,
  1438. // 'week_ratio' => $visits_week_ratio,
  1439. 'total' => $total_visits . 'Pv',
  1440. 'date' => '今日'
  1441. ];
  1442. // 订单量
  1443. //今日订单量
  1444. $today_order = $this->dao->totalOrderCount('today');
  1445. //昨日订单量
  1446. $yesterday_order = $this->dao->totalOrderCount('yesterday');
  1447. //订单日同比
  1448. $order_today_ratio = $this->countRate($today_order, $yesterday_order);
  1449. // //本周订单量
  1450. // $this_week_order = $this->dao->totalOrderCount('week');
  1451. // //上周订单量
  1452. // $last_week_order = $this->dao->totalOrderCount('last week');
  1453. // //订单周同比
  1454. // $order_week_ratio = $this->countRate($this_week_order, $last_week_order);
  1455. //总订单量
  1456. $total_order = $this->dao->totalOrderCount('month');
  1457. $order = [
  1458. 'today' => $today_order,
  1459. 'yesterday' => $yesterday_order,
  1460. 'today_ratio' => $order_today_ratio,
  1461. // 'week' => $this_week_order,
  1462. // 'last_week' => $last_week_order,
  1463. // 'week_ratio' => $order_week_ratio,
  1464. 'total' => $total_order . '单',
  1465. 'date' => '今日'
  1466. ];
  1467. // 用户
  1468. //今日新增用户
  1469. $today_user = $uSercice->totalUserCount('today');
  1470. //昨日新增用户
  1471. $yesterday_user = $uSercice->totalUserCount('yesterday');
  1472. //新增用户日同比
  1473. $user_today_ratio = $this->countRate($today_user, $yesterday_user);
  1474. // //本周新增用户
  1475. // $this_week_user = $uSercice->totalUserCount('week');
  1476. // //上周新增用户
  1477. // $last_week_user = $uSercice->totalUserCount('last week');
  1478. // //新增用户周同比
  1479. // $user_week_ratio = $this->countRate($this_week_user, $last_week_user);
  1480. //本月新增用户
  1481. $total_user = $uSercice->totalUserCount('month');
  1482. $user = [
  1483. 'today' => $today_user,
  1484. 'yesterday' => $yesterday_user,
  1485. 'today_ratio' => $user_today_ratio,
  1486. // 'week' => $this_week_user,
  1487. // 'last_week' => $last_week_user,
  1488. // 'week_ratio' => $user_week_ratio,
  1489. 'total' => $total_user . '人',
  1490. 'date' => '今日'
  1491. ];
  1492. $integralService = app()->make(AwardIntegralServices::class);
  1493. $today = $integralService->getIntegralSum(['add_time_date' => 'today']);
  1494. $yesterday = $integralService->getIntegralSum(['add_time_date' => 'yesterday']);
  1495. $today_ratio = $this->countRate($today, $yesterday);
  1496. $lack = [
  1497. 'today' => $today,
  1498. 'yesterday' => $yesterday,
  1499. 'today_ratio' => $today_ratio,
  1500. 'total' => bcsub((string)$integralService->getIntegralSum([], 'num'), (string)$integralService->getIntegralSum([], 'sent_num'), 2),
  1501. 'date' => '今日'
  1502. ];
  1503. $today = UserBrokerage::where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1504. $yesterday = UserBrokerage::where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1505. $today_ratio = $this->countRate($today, $yesterday);
  1506. $s_integral = [
  1507. 'today' => $today,
  1508. 'yesterday' => $yesterday,
  1509. 'today_ratio' => $today_ratio,
  1510. 'total' => User::sum('brokerage_price'),
  1511. 'date' => '今日'
  1512. ];
  1513. $today = UserBill::where('category', 'integral')->where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1514. $yesterday = UserBill::where('category', 'integral')->where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1515. $today_ratio = $this->countRate($today, $yesterday);
  1516. $a_integral = [
  1517. 'today' => $today,
  1518. 'yesterday' => $yesterday,
  1519. 'today_ratio' => $today_ratio,
  1520. 'total' => User::sum('integral'),
  1521. 'date' => '今日'
  1522. ];
  1523. $today = UserBill::where('category', 'energy')->where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1524. $yesterday = UserBill::where('category', 'energy')->where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1525. $today_ratio = $this->countRate($today, $yesterday);
  1526. $l_price = [
  1527. 'today' => $today,
  1528. 'yesterday' => $yesterday,
  1529. 'today_ratio' => $today_ratio,
  1530. 'total' => User::sum('energy'),
  1531. 'date' => '今日'
  1532. ];
  1533. $today = UserMoney::where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1534. $yesterday = UserMoney::where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1535. $today_ratio = $this->countRate($today, $yesterday);
  1536. $now_money = [
  1537. 'today' => $today,
  1538. 'yesterday' => $yesterday,
  1539. 'today_ratio' => $today_ratio,
  1540. 'total' => User::sum('now_money'),
  1541. 'date' => '今日'
  1542. ];
  1543. $today = UserBill::where('category', 'award_integral')->where('pm', 1)->whereTime('add_time', 'today')->sum('number');
  1544. $yesterday = UserBill::where('category', 'award_integral')->where('pm', 1)->whereTime('add_time', 'yesterday')->sum('number');
  1545. $today_ratio = $this->countRate($today, $yesterday);
  1546. $send_price = [
  1547. 'today' => $today,
  1548. 'yesterday' => $yesterday,
  1549. 'today_ratio' => $today_ratio,
  1550. 'total' => UserBill::where('category', 'award_integral')->where('pm', 1)->whereTime('add_time', 'month')->sum('number'),
  1551. 'date' => '今日'
  1552. ];
  1553. $today = UserBill::where('category', 'award_integral')->where('pm', 0)->whereTime('add_time', 'today')->sum('number');
  1554. $yesterday = UserBill::where('category', 'award_integral')->where('pm', 0)->whereTime('add_time', 'yesterday')->sum('number');
  1555. $today_ratio = $this->countRate($today, $yesterday);
  1556. $extract_price = [
  1557. 'today' => $today,
  1558. 'yesterday' => $yesterday,
  1559. 'today_ratio' => $today_ratio,
  1560. 'total' => UserBill::where('category', 'award_integral')->where('pm', 0)->whereTime('add_time', 'month')->sum('number'),
  1561. 'date' => '今日'
  1562. ];
  1563. $info = array_values(compact('sales', 'visits', 'order', 'user', 'lack', 'a_integral', 's_integral', 'l_price', 'send_price', 'extract_price', 'now_money'));
  1564. $info[0]['title'] = '销售额';
  1565. $info[1]['title'] = '用户访问量';
  1566. $info[2]['title'] = '订单量';
  1567. $info[3]['title'] = '新增用户';
  1568. $info[4]['title'] = '参考分';
  1569. $info[5]['title'] = '消费分';
  1570. $info[6]['title'] = '佣金';
  1571. $info[7]['title'] = '能量';
  1572. $info[8]['title'] = '释放参考分';
  1573. $info[9]['title'] = '提取参考分';
  1574. $info[10]['title'] = '余额';
  1575. $info[0]['total_name'] = '本月销售额';
  1576. $info[1]['total_name'] = '本月访问量';
  1577. $info[2]['total_name'] = '本月订单量';
  1578. $info[3]['total_name'] = '本月新增用户';
  1579. $info[4]['total_name'] = '待释放';
  1580. $info[5]['total_name'] = '剩余消费分';
  1581. $info[6]['total_name'] = '剩余佣金';
  1582. $info[7]['total_name'] = '剩余能量值';
  1583. $info[8]['total_name'] = '本月释放';
  1584. $info[9]['total_name'] = '本月提取';
  1585. $info[10]['total_name'] = '剩余余额';
  1586. return $info;
  1587. }
  1588. /**
  1589. * 打印订单
  1590. * @param int $id
  1591. * @param bool $isTable
  1592. * @return bool
  1593. */
  1594. public function orderPrint(int $id, int $type = -1, int $relation_id = -1, bool $isTable = false)
  1595. {
  1596. $order = $this->dao->get($id);
  1597. if (!$order) {
  1598. throw new ValidateException('订单信息不存在!');
  1599. }
  1600. $order = $order->toArray();
  1601. /** @var StoreOrderCartInfoServices $cartServices */
  1602. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  1603. $product = $cartServices->getCartInfoPrintProduct((int)$order['id']);
  1604. if (!$product) {
  1605. throw new ValidateException('订单商品获取失败,无法打印!');
  1606. }
  1607. if ($type == -1 && $relation_id == -1) {//取订单属于那一端
  1608. $type = $relation_id = 0;
  1609. if (isset($order['store_id']) && $order['store_id']) {
  1610. $store_id = (int)$order['store_id'];
  1611. if ($isTable) {
  1612. if (isset($order['type']) && $order['type'] == 10) {
  1613. $print = store_config($store_id, 'store_printing_timing');
  1614. if (!$print || !is_array($print) || !in_array(2, $print)) {
  1615. return true;
  1616. }
  1617. }
  1618. }
  1619. $type = 1;
  1620. $relation_id = $store_id;
  1621. } elseif (isset($order['supplier_id']) && $order['supplier_id']) {
  1622. $supplier_id = (int)$order['supplier_id'];
  1623. $type = 2;
  1624. $relation_id = $supplier_id;
  1625. }
  1626. }
  1627. /** @var ConfigServices $configServices */
  1628. $configServices = app()->make(ConfigServices::class);
  1629. [$switch, $name, $configData] = $configServices->getPrintingConfig($type, $relation_id);
  1630. if (!$switch) {
  1631. throw new ValidateException('请先开启小票打印');
  1632. }
  1633. foreach ($configData as $value) {
  1634. if (!$value) {
  1635. throw new ValidateException('请先配置小票打印开发者');
  1636. }
  1637. }
  1638. $printer = new Printer($name, $configData);
  1639. $printer->setPrinterContent([
  1640. 'name' => sys_config('site_name'),
  1641. 'orderInfo' => is_object($order) ? $order->toArray() : $order,
  1642. 'product' => $product
  1643. ])->startPrinter();
  1644. return true;
  1645. }
  1646. /**
  1647. * 获取订单确认数据
  1648. * @param array $user
  1649. * @param $cartId
  1650. * @param bool $new
  1651. * @param int $addressId
  1652. * @param int $shipping_type
  1653. * @param int $store_id
  1654. * @param int $coupon_id
  1655. * @return array
  1656. * @throws \Psr\SimpleCache\InvalidArgumentException
  1657. * @throws \think\db\exception\DataNotFoundException
  1658. * @throws \think\db\exception\DbException
  1659. * @throws \think\db\exception\ModelNotFoundException
  1660. */
  1661. public function getOrderConfirmData(array $user, $cartId, bool $new, int $addressId, int $shipping_type = 1, int $store_id = 0, int $coupon_id = 0)
  1662. {
  1663. $addr = $data = [];
  1664. $uid = (int)$user['uid'];
  1665. /** @var UserAddressServices $addressServices */
  1666. $addressServices = app()->make(UserAddressServices::class);
  1667. if ($addressId) {
  1668. $addr = $addressServices->getAdderssCache($addressId);
  1669. }
  1670. //没传地址id或地址已删除未找到 ||获取默认地址
  1671. if (!$addr) {
  1672. $addr = $addressServices->getUserDefaultAddressCache($uid);
  1673. }
  1674. $data['upgrade_addr'] = 0;
  1675. if ($addr) {
  1676. $addr = is_object($addr) ? $addr->toArray() : $addr;
  1677. if (isset($addr['upgrade']) && $addr['upgrade'] == 0) {
  1678. $data['upgrade_addr'] = 1;
  1679. }
  1680. } else {
  1681. $addr = [];
  1682. }
  1683. if ($store_id) {
  1684. /** @var SystemStoreServices $storeServices */
  1685. $storeServices = app()->make(SystemStoreServices::class);
  1686. $storeServices->getStoreInfo($store_id);
  1687. }
  1688. /** @var StoreCartServices $cartServices */
  1689. $cartServices = app()->make(StoreCartServices::class);
  1690. //获取购物车信息
  1691. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, $new, $addr, $shipping_type, $store_id, $coupon_id);
  1692. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  1693. $data['storeFreePostage'] = $storeFreePostage;
  1694. $validCartInfo = $cartGroup['valid'];
  1695. $giveCartList = $cartGroup['giveCartList'] ?? [];
  1696. /** @var StoreOrderComputedServices $computedServices */
  1697. $computedServices = app()->make(StoreOrderComputedServices::class);
  1698. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  1699. $priceGroup['couponPrice'] = $cartGroup['couponPrice'] ?? 0;
  1700. $priceGroup['firstOrderPrice'] = $cartGroup['firstOrderPrice'] ?? 0;
  1701. $validCartInfo = array_merge($priceGroup['cartInfo'] ?? $validCartInfo, $giveCartList);
  1702. $other = [
  1703. 'offlinePostage' => sys_config('offline_postage'),
  1704. 'integralRatio' => sys_config('integral_ratio'),
  1705. 'give_integral' => $cartGroup['giveIntegral'] ?? 0,
  1706. 'give_coupon' => $cartGroup['giveCoupon'] ?? [],
  1707. 'give_product' => $cartGroup['giveProduct'],
  1708. 'promotions' => $cartGroup['promotions']
  1709. ];
  1710. $deduction = $cartGroup['deduction'];
  1711. $data['product_type'] = $deduction['product_type'] ?? 0;
  1712. $data['valid_count'] = count($validCartInfo);
  1713. $data['addressInfo'] = $addr;
  1714. $data['type'] = $deduction['type'] ?? 0;
  1715. $data['activity_id'] = $deduction['activity_id'] ?? 0;
  1716. $data['seckill_id'] = $deduction['type'] == 1 ? $deduction['activity_id'] : 0;
  1717. $data['bargain_id'] = $deduction['type'] == 2 ? $deduction['activity_id'] : 0;
  1718. $data['combination_id'] = $deduction['type'] == 3 ? $deduction['activity_id'] : 0;
  1719. $data['luck_record_id'] = $deduction['type'] == 8 ? $deduction['activity_id'] : 0;
  1720. $data['collate_code_id'] = $deduction['type'] == 9 || $deduction['type'] == 10 ? $deduction['collate_code_id'] : 0;
  1721. $data['discount_id'] = $deduction['type'] == 5 ? $deduction['activity_id'] : 0;
  1722. $data['newcomer_id'] = $deduction['type'] == 7 ? $deduction['activity_id'] : 0;
  1723. $data['deduction'] = in_array($deduction['product_type'], [1, 2]) || $deduction['activity_id'] > 0;
  1724. $data['cartInfo'] = array_merge($cartGroup['cartInfo'], $giveCartList);
  1725. // $data['giveCartInfo'] = $giveCartList;
  1726. $data['custom_form'] = [];
  1727. if (isset($cartGroup['cartInfo'][0]['productInfo']['system_form_id']) && $cartGroup['cartInfo'][0]['productInfo']['system_form_id']) {
  1728. /** @var SystemFormServices $systemFormServices */
  1729. $systemFormServices = app()->make(SystemFormServices::class);
  1730. $formInfo = $systemFormServices->value(['id' => $cartGroup['cartInfo'][0]['productInfo']['system_form_id']], 'value');
  1731. if ($formInfo) {
  1732. $data['custom_form'] = is_string($formInfo) ? json_decode($formInfo, true) : $formInfo;
  1733. }
  1734. }
  1735. $data['give_integral'] = $other['give_integral'];
  1736. $data['give_coupon'] = [];
  1737. if ($other['give_coupon']) {
  1738. /** @var StoreCouponIssueServices $couponIssueService */
  1739. $couponIssueService = app()->make(StoreCouponIssueServices::class);
  1740. $data['give_coupon'] = $couponIssueService->getColumn([['id', 'IN', $other['give_coupon']]], 'id,coupon_title');
  1741. }
  1742. $data['priceGroup'] = $priceGroup;
  1743. $data['orderKey'] = $this->cacheOrderInfo($uid, $validCartInfo, $priceGroup, $other, $addr, $cartGroup['invalid'] ?? [], $deduction);
  1744. $data['offlinePostage'] = $other['offlinePostage'];
  1745. if (isset($user['pwd'])) unset($user['pwd']);
  1746. $user['vip'] = isset($priceGroup['vipPrice']) && $priceGroup['vipPrice'] > 0;
  1747. $user['vip_id'] = 0;
  1748. $user['discount'] = 0;
  1749. //用户等级是否开启
  1750. if (sys_config('member_func_status', 1)) {
  1751. /** @var UserLevelServices $levelServices */
  1752. $levelServices = app()->make(UserLevelServices::class);
  1753. $userLevel = $levelServices->getUerLevelInfoByUid($uid);
  1754. if ($user['vip'] || $userLevel) {
  1755. $user['vip'] = true;
  1756. $user['vip_id'] = $userLevel['id'] ?? 0;
  1757. $user['discount'] = $userLevel['discount'] ?? 0;
  1758. }
  1759. }
  1760. $user['record_pone'] = !isset($user['record_pone']) || !$user['record_pone'] ? '' : $user['record_pone'];
  1761. $data['userInfo'] = $user;
  1762. $data['integralRatio'] = $other['integralRatio'];
  1763. $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1764. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  1765. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  1766. $data['store_func_status'] = (int)(sys_config('store_func_status', 1));//门店是否开启
  1767. $data['store_self_mention'] = false;//门店自提
  1768. $data['store_delivery_status'] = false;//门店配送
  1769. if ($data['store_func_status']) {
  1770. //门店自提是否开启
  1771. /** @var SystemStoreServices $systemStoreServices */
  1772. $systemStoreServices = app()->make(SystemStoreServices::class);
  1773. $data['store_self_mention'] = sys_config('store_self_mention') && $systemStoreServices->count(['type' => 0, 'is_store' => 1]);
  1774. $data['store_delivery_status'] = !!$systemStoreServices->count(['type' => 0]);
  1775. }
  1776. $data['store_func_status'] = $data['store_func_status'] && ($data['store_self_mention'] || $data['store_delivery_status']);
  1777. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  1778. $data['system_store'] = [];//门店信息
  1779. /** @var UserInvoiceServices $userInvoice */
  1780. $userInvoice = app()->make(UserInvoiceServices::class);
  1781. $invoice_func = $userInvoice->invoiceFuncStatus();
  1782. $data['invoice_func'] = $invoice_func['invoice_func'];
  1783. $data['special_invoice'] = $invoice_func['special_invoice'];
  1784. $data['integral_ratio_status'] = (int)sys_config('integral_ratio_status', 1);
  1785. return $data;
  1786. }
  1787. /**
  1788. * 缓存订单信息
  1789. * @param int $uid
  1790. * @param array $cartInfo
  1791. * @param array $priceGroup
  1792. * @param array $other
  1793. * @param array $addr
  1794. * @param array $invalidCartInfo
  1795. * @param array $deduction
  1796. * @param int $cacheTime
  1797. * @return string
  1798. * @throws \Psr\SimpleCache\InvalidArgumentException
  1799. */
  1800. public function cacheOrderInfo(int $uid, array $cartInfo, array $priceGroup, array $other = [], array $addr = [], array $invalidCartInfo = [], array $deduction = [], int $cacheTime = 600)
  1801. {
  1802. /** @var StoreOrderCreateServices $storeOrderCreateService */
  1803. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  1804. $key = md5($storeOrderCreateService->getNewOrderId((string)$uid) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8));
  1805. CacheService::redisHandler()->set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other', 'addr', 'invalidCartInfo', 'deduction'), $cacheTime);
  1806. return $key;
  1807. }
  1808. /**
  1809. * 获取订单缓存信息
  1810. * @param int $uid
  1811. * @param string $key
  1812. * @return |null
  1813. */
  1814. public function getCacheOrderInfo(int $uid, string $key)
  1815. {
  1816. $cacheName = 'user_order_' . $uid . $key;
  1817. if (!CacheService::redisHandler()->has($cacheName)) return null;
  1818. return CacheService::redisHandler()->get($cacheName);
  1819. }
  1820. /**
  1821. * 获取用户购买活动产品的次数
  1822. * @param $uid
  1823. * @param $seckill_id
  1824. * @return int
  1825. */
  1826. public function activityProductCount(array $where)
  1827. {
  1828. return $this->dao->count($where);
  1829. }
  1830. /**
  1831. * 获取拼团的订单id
  1832. * @param int $pid
  1833. * @param int $uid
  1834. * @return mixed
  1835. */
  1836. public function getStoreIdPink(int $pid, int $uid)
  1837. {
  1838. return $this->dao->value(['uid' => $uid, 'pink_id' => $pid, 'is_del' => 0], 'order_id');
  1839. }
  1840. /**
  1841. * 判断当前订单中是否有拼团
  1842. * @param int $pid
  1843. * @param int $uid
  1844. * @return int
  1845. */
  1846. public function getIsOrderPink($pid = 0, $uid = 0)
  1847. {
  1848. return $this->dao->count(['uid' => $uid, 'pink_id' => $pid, 'refund_status' => 0, 'is_del' => 0]);
  1849. }
  1850. /**
  1851. * 判断支付方式是否开启
  1852. * @param $payType
  1853. * @return bool
  1854. */
  1855. public function checkPaytype(string $payType)
  1856. {
  1857. $res = false;
  1858. switch ($payType) {
  1859. case PayServices::WEIXIN_PAY:
  1860. $res = (bool)sys_config('pay_weixin_open');
  1861. break;
  1862. case PayServices::YUE_PAY:
  1863. $res = sys_config('balance_func_status') && sys_config('yue_pay_status') == 1;
  1864. break;
  1865. case 'offline':
  1866. $res = sys_config('offline_pay_status') == 1;
  1867. break;
  1868. case PayServices::ALIAPY_PAY:
  1869. $res = sys_config('ali_pay_status') == 1;
  1870. break;
  1871. }
  1872. return $res;
  1873. }
  1874. /**
  1875. * 修改支付方式为线下支付
  1876. * @param string $orderId
  1877. * @return bool
  1878. */
  1879. public function setOrderTypePayOffline(string $orderId)
  1880. {
  1881. return $this->dao->update($orderId, ['pay_type' => 'offline'], 'order_id');
  1882. }
  1883. /**
  1884. * 删除订单
  1885. * @param $uni
  1886. * @param $uid
  1887. * @return bool
  1888. */
  1889. public function removeOrder(string $uni, int $uid)
  1890. {
  1891. $order = $this->getUserOrderDetail($uni, $uid);
  1892. if (!$order) {
  1893. throw new ValidateException('订单不存在!');
  1894. }
  1895. $order = $this->tidyOrder($order);
  1896. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  1897. throw new ValidateException('该订单无法删除!');
  1898. $order->is_del = 1;
  1899. /** @var StoreOrderStatusServices $statusService */
  1900. $statusService = app()->make(StoreOrderStatusServices::class);
  1901. $res = $statusService->save([
  1902. 'oid' => $order['id'],
  1903. 'change_type' => 'remove_order',
  1904. 'change_message' => '删除订单',
  1905. 'change_time' => time()
  1906. ]);
  1907. if ($order->save() && $res) {
  1908. //未支付和已退款的状态下才可以退积分退库存退优惠券
  1909. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  1910. /** @var StoreOrderRefundServices $refundServices */
  1911. $refundServices = app()->make(StoreOrderRefundServices::class);
  1912. $this->transaction(function () use ($order, $refundServices) {
  1913. //回退积分和优惠卷
  1914. $res = $refundServices->integralAndCouponBack($order);
  1915. //回退库存
  1916. $res = $res && $refundServices->regressionStock($order);
  1917. if (!$res) {
  1918. throw new ValidateException('取消订单失败!');
  1919. }
  1920. });
  1921. }
  1922. return true;
  1923. } else
  1924. throw new ValidateException('订单删除失败!');
  1925. }
  1926. /**
  1927. * 取消订单
  1928. * @param $order_id
  1929. * @param int $uid
  1930. * @return bool
  1931. * @throws \think\db\exception\DataNotFoundException
  1932. * @throws \think\db\exception\DbException
  1933. * @throws \think\db\exception\ModelNotFoundException
  1934. */
  1935. public function cancelOrder($order_id, int $uid)
  1936. {
  1937. $order = $this->dao->getOne(['order_id' => $order_id, 'uid' => $uid, 'is_del' => 0]);
  1938. if (!$order) {
  1939. throw new ValidateException('没有查到此订单');
  1940. }
  1941. if ($order->paid) {
  1942. throw new ValidateException('订单已经支付无法取消');
  1943. }
  1944. /** @var StoreOrderRefundServices $refundServices */
  1945. $refundServices = app()->make(StoreOrderRefundServices::class);
  1946. $this->transaction(function () use ($refundServices, $order) {
  1947. //回退积分和优惠卷
  1948. $res = $refundServices->integralAndCouponBack($order);
  1949. //回退库存和销量
  1950. $res = $res && $refundServices->regressionStock($order);
  1951. $order->is_del = 1;
  1952. if (!($res && $order->save())) {
  1953. throw new ValidateException('取消订单失败');
  1954. }
  1955. });
  1956. //订单取消事件
  1957. event('order.cancel', [$order]);
  1958. return true;
  1959. }
  1960. /**
  1961. * 判断订单完成
  1962. * @param StoreProductReplyServices $replyServices
  1963. * @param array $uniqueList
  1964. * @param $oid
  1965. * @return mixed
  1966. */
  1967. public function checkOrderOver($replyServices, array $uniqueList, $oid)
  1968. {
  1969. //订单商品全部评价完成
  1970. $replyServices->count(['unique' => $uniqueList, 'oid' => $oid]);
  1971. if ($replyServices->count(['unique' => $uniqueList, 'oid' => $oid]) == count($uniqueList)) {
  1972. $res = $this->dao->update($oid, ['status' => '3']);
  1973. if (!$res) throw new ValidateException('评价后置操作失败!');
  1974. /** @var StoreOrderStatusServices $statusService */
  1975. $statusService = app()->make(StoreOrderStatusServices::class);
  1976. $statusService->save([
  1977. 'oid' => $oid,
  1978. 'change_type' => 'check_order_over',
  1979. 'change_message' => '用户评价',
  1980. 'change_time' => time()
  1981. ]);
  1982. }
  1983. }
  1984. /**
  1985. * 某个用户订单
  1986. * @param int $uid
  1987. * @param UserServices $userServices
  1988. * @return array
  1989. * @throws \think\db\exception\DataNotFoundException
  1990. * @throws \think\db\exception\DbException
  1991. * @throws \think\db\exception\ModelNotFoundException
  1992. */
  1993. public function getUserOrderList(int $uid)
  1994. {
  1995. /** @var UserServices $userServices */
  1996. $userServices = app()->make(UserServices::class);
  1997. $user = $userServices->getUserWithTrashedInfo($uid);
  1998. if (!$user) {
  1999. throw new ValidateException('数据不存在');
  2000. }
  2001. [$page, $limit] = $this->getPageValue();
  2002. $where = ['uid' => $uid, 'pid' => [0, -1], 'paid' => 1, 'is_del' => 0, 'is_system_del' => 0];
  2003. $list = $this->dao->getStairOrderList($where, 'order_id,real_name,total_num,total_price,pay_price,FROM_UNIXTIME(pay_time,"%Y-%m-%d") as pay_time,paid,pay_type,type,activity_id,activity_append', $page, $limit);
  2004. $count = $this->dao->count($where);
  2005. return compact('list', 'count');
  2006. }
  2007. /**
  2008. * 获取推广订单列表
  2009. * @param int $uid
  2010. * @param $where
  2011. * @return array
  2012. * @throws \think\db\exception\DataNotFoundException
  2013. * @throws \think\db\exception\DbException
  2014. * @throws \think\db\exception\ModelNotFoundException
  2015. */
  2016. public function getUserStairOrderList(int $uid, $where)
  2017. {
  2018. $where_data = [];
  2019. if (isset($where['type'])) {
  2020. switch ((int)$where['type']) {
  2021. case 1:
  2022. $where_data['spread_uid'] = $uid;
  2023. break;
  2024. case 2:
  2025. $where_data['spread_two_uid'] = $uid;
  2026. break;
  2027. default:
  2028. $where_data['spread_or_uid'] = $uid;
  2029. break;
  2030. }
  2031. }
  2032. if (isset($where['data']) && $where['data']) {
  2033. $where_data['time'] = $where['data'];
  2034. }
  2035. if (isset($where['order_id']) && $where['order_id']) {
  2036. $where_data['order_id'] = $where['order_id'];
  2037. }
  2038. if (isset($where['nickname']) && $where['nickname']) {
  2039. $where_data['real_name'] = $where['nickname'];
  2040. }
  2041. //推广订单只显示支付过并且未退款的订单
  2042. $where_data['pid'] = 0;
  2043. $where_data['paid'] = 1;
  2044. $where_data['refund_status'] = 0;
  2045. [$page, $limit] = $this->getPageValue();
  2046. $list = $this->dao->getStairOrderList($where_data, '*', $page, $limit);
  2047. $count = $this->dao->count($where_data);
  2048. return compact('list', 'count');
  2049. }
  2050. /**
  2051. * 订单导出
  2052. * @param array $where
  2053. * @return array
  2054. * @throws \think\db\exception\DataNotFoundException
  2055. * @throws \think\db\exception\DbException
  2056. * @throws \think\db\exception\ModelNotFoundException
  2057. */
  2058. public function getExportList(array $where, array $with = [], int $limit = 0)
  2059. {
  2060. if ($limit) {
  2061. [$page] = $this->getPageValue();
  2062. } else {
  2063. [$page, $limit] = $this->getPageValue();
  2064. }
  2065. $list = $this->dao->search($where)->with($with)->page($page, $limit)->order('id asc')->select()->toArray();
  2066. if ($list) {
  2067. /** @var $userServices */
  2068. $userServices = app()->make(UserServices::class);
  2069. $userSex = $userServices->getColumn([['uid', 'IN', array_unique(array_column($list, 'uid'))]], 'uid,sex', 'uid');
  2070. foreach ($list as &$item) {
  2071. /** @var StoreOrderCartInfoServices $orderCart */
  2072. $orderCart = app()->make(StoreOrderCartInfoServices::class);
  2073. $_info = $orderCart->getCartColunm(['oid' => $item['id']], 'cart_info', 'unique');
  2074. foreach ($_info as $k => $v) {
  2075. $cart_info = is_string($v) ? json_decode($v, true) : $v;
  2076. if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
  2077. $_info[$k] = $cart_info;
  2078. unset($cart_info);
  2079. }
  2080. $item['_info'] = $_info;
  2081. $item['sex'] = $userSex[$item['uid']]['sex'] ?? '';
  2082. [$pink_name, $color] = $this->tidyOrderType($item);
  2083. $item['pink_name'] = $pink_name;
  2084. $item['color'] = $color;
  2085. }
  2086. }
  2087. return $list;
  2088. }
  2089. /**
  2090. * 自动取消订单
  2091. * @return bool
  2092. * @throws \think\db\exception\DataNotFoundException
  2093. * @throws \think\db\exception\DbException
  2094. * @throws \think\db\exception\ModelNotFoundException
  2095. */
  2096. public function runOrderUnpaidCancel(int $page = 0, int $limit = 0)
  2097. {
  2098. $list = $this->dao->getOrderUnPaid(0, $page, $limit)->field(['*'])->select();
  2099. if (!$list) {
  2100. return true;
  2101. }
  2102. //系统预设取消订单时间段
  2103. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  2104. //获取配置
  2105. $systemValue = SystemConfigService::more($keyValue);
  2106. //格式化数据
  2107. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  2108. $secsArr = [];
  2109. //秒杀
  2110. $secsArr[1] = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  2111. //砍价
  2112. $secsArr[2] = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  2113. //拼团
  2114. $secsArr[3] = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  2115. //默认
  2116. $secsArr[0] = $systemValue['order_cancel_time'];
  2117. /** @var StoreOrderRefundServices $refundServices */
  2118. $refundServices = app()->make(StoreOrderRefundServices::class);
  2119. foreach ($list as $order) {
  2120. $type = $order['type'];
  2121. $secs = $secsArr[$type] ?? $secsArr[0];
  2122. if ($secs == 0) continue;
  2123. if (($order['add_time'] + bcmul($secs, '3600', 0)) < time()) {
  2124. try {
  2125. $this->transaction(function () use ($order, $refundServices) {
  2126. //回退积分和优惠卷
  2127. $res = $refundServices->integralAndCouponBack($order);
  2128. //回退库存和销量
  2129. $res = $res && $refundServices->regressionStock($order);
  2130. //修改订单状态
  2131. $res = $res && $this->dao->update($order['id'], ['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  2132. if (!$res) {
  2133. throw new ValidateException('订单号' . $order['order_id'] . '自动取消订单失败');
  2134. }
  2135. return true;
  2136. });
  2137. //订单取消事件
  2138. event('order.cancel', [$order]);
  2139. } catch (\Throwable $e) {
  2140. Log::error('自动取消订单失败,失败原因:' . $e->getMessage(), $e->getTrace());
  2141. }
  2142. }
  2143. }
  2144. return true;
  2145. }
  2146. /**
  2147. * 批量加入对接
  2148. * @param int $count
  2149. * @param int $limit
  2150. */
  2151. public function batchJoinJob(int $count, int $limit)
  2152. {
  2153. $pages = ceil($limit / $count);
  2154. for ($i = 1; $i <= $pages; $i++) {
  2155. AutoOrderUnpaidCancelJob::dispatch([$i, $limit]);
  2156. }
  2157. return true;
  2158. }
  2159. /**
  2160. * 自动取消订单
  2161. * @return bool
  2162. * @throws \think\db\exception\DataNotFoundException
  2163. * @throws \think\db\exception\DbException
  2164. * @throws \think\db\exception\ModelNotFoundException
  2165. */
  2166. public function orderUnpaidCancel()
  2167. {
  2168. $count = $this->dao->getOrderUnPaid()->count();
  2169. $maxLimit = 100;
  2170. if ($count > $maxLimit) {
  2171. return $this->batchJoinJob($count, $maxLimit);
  2172. }
  2173. return $this->runOrderUnpaidCancel();
  2174. }
  2175. /**
  2176. * 根据时间获取当天或昨天订单营业额
  2177. * @param array $where
  2178. * @return float|int
  2179. */
  2180. public function getOrderMoneyByWhere(array $where, string $sum_field, string $selectType, string $group = "")
  2181. {
  2182. switch ($selectType) {
  2183. case "sum" :
  2184. return $this->dao->getDayTotalMoney($where, $sum_field);
  2185. case "group" :
  2186. return $this->dao->getDayGroupMoney($where, $sum_field, $group);
  2187. }
  2188. }
  2189. /**
  2190. * 统计时间段订单数
  2191. * @param array $where
  2192. * @param string $sum_field
  2193. */
  2194. public function getOrderCountByWhere(array $where)
  2195. {
  2196. return $this->dao->getDayOrderCount($where);
  2197. }
  2198. /**
  2199. * 分组统计时间段订单数
  2200. * @param $where
  2201. * @return mixed
  2202. */
  2203. public function getOrderGroupCountByWhere($where)
  2204. {
  2205. return $this->dao->getOrderGroupCount($where);
  2206. }
  2207. /**
  2208. * 时间段支付订单人数
  2209. * @param $where
  2210. * @return mixed
  2211. */
  2212. public function getPayOrderPeopleByWhere($where)
  2213. {
  2214. return $this->dao->getPayOrderPeople($where);
  2215. }
  2216. /**
  2217. * 时间段分组统计支付订单人数
  2218. * @param $where
  2219. * @return mixed
  2220. */
  2221. public function getPayOrderGroupPeopleByWhere($where)
  2222. {
  2223. return $this->dao->getPayOrderGroupPeople($where);
  2224. }
  2225. /**
  2226. * 批量更新数据
  2227. * @param array $ids
  2228. * @param array $data
  2229. * @param string|null $key
  2230. * @return BaseModel
  2231. */
  2232. public function orderDel(array $ids, $redisKey, $queueId)
  2233. {
  2234. /** @var QueueServices $queueService */
  2235. $queueService = app()->make(QueueServices::class);
  2236. $res = $this->dao->batchUpdateOrder($ids, ['is_system_del' => 1]);
  2237. if ($res) {
  2238. $queueService->doSuccessSremRedis($ids, $redisKey, $queueId['type']);
  2239. } else {
  2240. $queueService->addQueueFail($queueId['id'], $redisKey);
  2241. throw new AdminException('删除失败');
  2242. }
  2243. }
  2244. /**获取发货excel文件数据
  2245. * @param string $file
  2246. * @param $row
  2247. * @return array
  2248. * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
  2249. */
  2250. public function readExpreExcel(string $file, $row = 2)
  2251. {
  2252. if (!$file) throw new AdminException('请上传发货数据表');
  2253. /** @var FileService $readExcelService */
  2254. $readExcelService = app()->make(FileService::class);
  2255. $exprData = $readExcelService->readExcel($file, $row);
  2256. if (!$exprData) throw new AdminException('发货数据为空');
  2257. return $exprData;
  2258. }
  2259. /**
  2260. * 队列发货
  2261. * @return bool
  2262. * @throws \think\db\exception\DataNotFoundException
  2263. * @throws \think\db\exception\DbException
  2264. * @throws \think\db\exception\ModelNotFoundException
  2265. */
  2266. public function adminQueueOrderDo(array $data, bool $is_again = false)
  2267. {
  2268. if (!$data) return false;
  2269. /** @var QueueServices $queueService */
  2270. $queueService = app()->make(QueueServices::class);
  2271. /** @var QueueAuxiliaryServices $auxiliaryService */
  2272. $auxiliaryService = app()->make(QueueAuxiliaryServices::class);
  2273. $queueWhere['type'] = $data['queueType'];
  2274. $queueWhere['status'] = 0;
  2275. if (isset($data['queueId']) && $data['queueId']) $queueWhere['id'] = $data['queueId'];
  2276. $queueInfo = $queueService->getQueueOne($queueWhere);
  2277. $ids = $auxiliaryService->getCacheOidList($queueInfo['id'], $data['cacheType']);
  2278. $data['ids'] = array_column($ids, 'relation_id');
  2279. $data['queueId'] = $queueInfo['id'];
  2280. //if ($queueInfo['status'] == 2) throw new ValidateException('任务已完成');
  2281. //把队列需要执行的入参数据存起来,以便队列执行失败后接着执行,同时队列状态改为正在执行状态。
  2282. $queueService->setQueueDoing($data, $queueInfo['id'], $is_again);
  2283. $oids = $auxiliaryService->getOrderExpreList(['binding_id' => $queueInfo['id'], 'type' => $data['cacheType'], 'status' => [0, 2]]);
  2284. $oids = $oids ? array_column($oids, 'relation_id') : [];
  2285. // $chunkPids = array_chunk($oids, 1000, true);
  2286. $data['queueId'] = $queueInfo['id'];
  2287. foreach ($oids as $v) {
  2288. //加入队列
  2289. BatchHandleJob::dispatch([$v, $data['queueType'], $data]);
  2290. }
  2291. return true;
  2292. }
  2293. /**
  2294. * 对外接口获取订单状态
  2295. * @param int $oid
  2296. */
  2297. public function outGetStatus(string $oid)
  2298. {
  2299. $order = $this->dao->getOne(['order_id' => $oid]);
  2300. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  2301. $status_name = '线下支付';
  2302. } else if (!$order['paid']) {
  2303. $status_name = '未支付';
  2304. } else if ($order['status'] == 0 && $order['refund_status'] == 0) {
  2305. $status_name = '待发货';
  2306. } else if ($order['refund_status'] == 1) {
  2307. $status_name = '申请退款中';
  2308. } else if ($order['refund_status'] == 2) {
  2309. $status_name = '已退款';
  2310. } else if ($order['refund_status'] == 3) {
  2311. $status_name = '部分退款(子订单)';
  2312. } else if ($order['refund_status'] == 4) {
  2313. $status_name = '子订单已全部申请退款中';
  2314. } else if (!$order['status']) {
  2315. $status_name = '未发货';
  2316. } else if ($order['status'] == 1) {
  2317. $status_name = '待收货';
  2318. } else if ($order['status'] == 2) {
  2319. $status_name = '待评价';
  2320. } else if ($order['status'] == 3) {
  2321. $status_name = '交易完成';
  2322. }
  2323. $data = [];
  2324. $data['status_name'] = $status_name;
  2325. $data['status'] = $order['status'];
  2326. $data['paid'] = $order['paid'];
  2327. $data['pay_type'] = $order['pay_type'];
  2328. $data['refund_status'] = $order['refund_status'];
  2329. return $data;
  2330. }
  2331. /**
  2332. * 对外接口根据订单id查询收货方式
  2333. * @param string $oid
  2334. * @return array
  2335. */
  2336. public function outGetShippingType(string $oid)
  2337. {
  2338. $shipping_type = $this->dao->value(['order_id' => $oid], 'shipping_type');
  2339. $shipping_type = $shipping_type == 1 ? '商家配送' : '到店自提';
  2340. return compact('shipping_type');
  2341. }
  2342. /**
  2343. * 对外接口根据订单id查询配送信息
  2344. * @param string $oid
  2345. * @return array|\think\Model|null
  2346. * @throws \think\db\exception\DataNotFoundException
  2347. * @throws \think\db\exception\DbException
  2348. * @throws \think\db\exception\ModelNotFoundException
  2349. */
  2350. public function OutDeliveryType(string $oid)
  2351. {
  2352. $info = $this->dao->getOne(['order_id' => $oid], 'order_id,delivery_type,delivery_name,delivery_id');
  2353. return $info ? $info->toArray() : [];
  2354. }
  2355. /**
  2356. * 对外接口获取运费
  2357. * @param int $cartId
  2358. * @param int $uid
  2359. * @param int $addressId
  2360. * @return array
  2361. * @throws \Psr\SimpleCache\InvalidArgumentException
  2362. */
  2363. public function outGetPostage($cartId, int $uid, int $addressId, int $couponId = 0)
  2364. {
  2365. $addr = [];
  2366. /** @var UserAddressServices $addressServices */
  2367. $addressServices = app()->make(UserAddressServices::class);
  2368. /** @var UserServices $userServices */
  2369. $userServices = app()->make(UserServices::class);
  2370. $user = $userServices->get($uid);
  2371. if ($addressId) {
  2372. $addr = $addressServices->getAdderssCache($addressId);
  2373. }
  2374. //没传地址id或地址已删除未找到 ||获取默认地址
  2375. if (!$addr) {
  2376. $addr = $addressServices->getUserDefaultAddressCache($uid);
  2377. }
  2378. /** @var StoreCartServices $cartServices */
  2379. $cartServices = app()->make(StoreCartServices::class);
  2380. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, true, $addr);
  2381. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  2382. $validCartInfo = $cartGroup['valid'];
  2383. /** @var StoreOrderComputedServices $computedServices */
  2384. $computedServices = app()->make(StoreOrderComputedServices::class);
  2385. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  2386. $postage = $priceGroup['storePostage'] ?? 0;
  2387. return compact('postage');
  2388. }
  2389. /**
  2390. * 获取配送员订单统计列表
  2391. * @param array $where
  2392. * @return array
  2393. * @throws \think\db\exception\DataNotFoundException
  2394. * @throws \think\db\exception\DbException
  2395. * @throws \think\db\exception\ModelNotFoundException
  2396. */
  2397. public function getDeliveryStatistics(array $where)
  2398. {
  2399. [$page, $limit] = $this->getPageValue();
  2400. $where['is_del'] = 0;
  2401. $where['paid'] = 1;
  2402. $where['is_system_del'] = 0;
  2403. $where['delivery_type'] = 'send';
  2404. $where['refund_status'] = [0, 3];
  2405. $list = $this->dao->getList((array)$where, ['*'], (int)$page, (int)$limit, ['user']);
  2406. if ($list) {
  2407. $list = $this->tidyOrderList($list, false);
  2408. }
  2409. $count = $this->dao->count($where);
  2410. return compact('list', 'count');
  2411. }
  2412. /**
  2413. * 配送员订单统计
  2414. * @param $store_id
  2415. * @param $delivery_uid
  2416. * @param $time
  2417. * @return array
  2418. * @throws \think\db\exception\DataNotFoundException
  2419. * @throws \think\db\exception\DbException
  2420. * @throws \think\db\exception\ModelNotFoundException
  2421. */
  2422. public function getStatisticsHeader($store_id, $delivery_uid, $time)
  2423. {
  2424. $where['is_del'] = 0;
  2425. $where['paid'] = 1;
  2426. $where['is_system_del'] = 0;
  2427. $where['delivery_type'] = 'send';
  2428. $where['store_id'] = $store_id;
  2429. $where['refund_status'] = [0, 3];
  2430. if ($delivery_uid) {
  2431. $where['delivery_uid'] = $delivery_uid;
  2432. }
  2433. [$start, $end, $timeType, $xAxis] = $time;
  2434. $order = $this->dao->orderAddTimeList($where, [$start, $end], $timeType, false);
  2435. $price = array_column($order, 'price', 'day');
  2436. $count = array_column($order, 'count', 'day');
  2437. $data = $series = [];
  2438. foreach ($xAxis as $key) {
  2439. $data['配送订单金额'][] = isset($price[$key]) ? floatval($price[$key]) : 0;
  2440. $data['配送单数'][] = isset($count[$key]) ? floatval($count[$key]) : 0;
  2441. }
  2442. foreach ($data as $key => $item) {
  2443. $series[] = [
  2444. 'name' => $key,
  2445. 'data' => $item,
  2446. 'type' => 'line',
  2447. 'smooth' => 'true',
  2448. 'yAxisIndex' => 1,
  2449. ];
  2450. }
  2451. return compact('xAxis', 'series');
  2452. }
  2453. /**
  2454. * 门店线上支付订单详情
  2455. * @param int $store
  2456. * @param int $uid
  2457. * @return mixed
  2458. * @throws \think\db\exception\DataNotFoundException
  2459. * @throws \think\db\exception\DbException
  2460. * @throws \think\db\exception\ModelNotFoundException
  2461. */
  2462. public function payCashierOrder(int $store, int $uid)
  2463. {
  2464. $order = $this->dao->payCashierOrder($store, $uid);
  2465. if (!$order) throw new ValidateException('订单不存在');
  2466. $order = $order->toArray();
  2467. $order = $this->tidyOrder($order, true);
  2468. $order['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  2469. $order['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  2470. $order['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  2471. return $order;
  2472. }
  2473. /**
  2474. * 订单分配|重新分配给你门店
  2475. * @param int $id
  2476. * @param int $store_id
  2477. * @return mixed
  2478. * @throws \think\db\exception\DataNotFoundException
  2479. * @throws \think\db\exception\DbException
  2480. * @throws \think\db\exception\ModelNotFoundException
  2481. */
  2482. public function shareOrder(int $id, int $store_id)
  2483. {
  2484. $orderInfo = $this->dao->get((int)$id);
  2485. if (!$orderInfo) {
  2486. throw new ValidateException('订单不存在');
  2487. }
  2488. //卡密商品
  2489. if ($orderInfo['product_type'] == 1) {
  2490. throw new ValidateException('订单中卡密商品门店暂不支持');
  2491. }
  2492. /** @var SystemStoreServices $storeServices */
  2493. $storeServices = app()->make(SystemStoreServices::class);
  2494. $storeInfo = $storeServices->getStoreInfo($store_id);
  2495. if ($orderInfo['status'] != 0) {
  2496. throw new ValidateException('订单已发货');
  2497. }
  2498. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  2499. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  2500. $cart_info = $storeOrderCartInfoServices->getSplitCartList($id, 'cart_info');
  2501. if (!$cart_info) {
  2502. throw new ValidateException('订单已发货');
  2503. }
  2504. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  2505. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  2506. if ($storeOrderRefundServices->count(['store_order_id' => $id, 'refund_type' => [1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
  2507. throw new ValidateException('订单有售后申请请先处理');
  2508. }
  2509. $platProductIds = [];
  2510. $platStoreProductIds = [];
  2511. $storeProductIds = [];
  2512. foreach ($cart_info as $cart) {
  2513. $productInfo = $cart['productInfo'] ?? [];
  2514. if (isset($productInfo['store_delivery']) && !$productInfo['store_delivery']) {//有商品不支持门店配送
  2515. return [[], $cart_info];
  2516. }
  2517. switch ($productInfo['type'] ?? 0) {
  2518. case 0://平台
  2519. case 2://供应商
  2520. $platProductIds[] = $cart['product_id'];
  2521. break;
  2522. case 1://门店
  2523. if ($productInfo['pid']) {//门店自有商品
  2524. $storeProductIds[] = $cart['product_id'];
  2525. } else {
  2526. $platStoreProductIds[] = $cart['product_id'];
  2527. }
  2528. break;
  2529. }
  2530. }
  2531. if ($storeProductIds && $store_id != $orderInfo['store_id']) {
  2532. throw new ValidateException('该门店商品未上架或未设置库存');
  2533. }
  2534. /** @var StoreBranchProductServices $branchProductServics */
  2535. $branchProductServics = app()->make(StoreBranchProductServices::class);
  2536. //转换成平台商品
  2537. if ($platStoreProductIds) {
  2538. $ids = $branchProductServics->getStoreProductIds($platStoreProductIds);
  2539. $platProductIds = array_merge($platProductIds, $ids);
  2540. }
  2541. $productCount = count($platProductIds);
  2542. //商品没下架 && 库存足够
  2543. if ($productCount != $branchProductServics->count(['pid' => $platProductIds, 'is_show' => 1, 'is_del' => 0, 'type' => 1, 'relation_id' => $store_id])) {
  2544. throw new ValidateException('该门店商品未上架或未设置库存');
  2545. }
  2546. /** @var StoreProductAttrValueServices $skuValueServices */
  2547. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  2548. foreach ($cart_info as $cart) {
  2549. if (isset($cart['productInfo']['store_delivery']) && !$cart['productInfo']['store_delivery']) {//有商品不支持门店配送
  2550. throw new ValidateException('有商品不支持门店配送');
  2551. }
  2552. switch ($cart['type']) {
  2553. case 0:
  2554. case 6:
  2555. case 8:
  2556. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['product_id'], 'type' => 0], 'suk');
  2557. break;
  2558. case 1:
  2559. case 2:
  2560. case 3:
  2561. case 5:
  2562. case 7:
  2563. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['activity_id'], 'type' => $cart['type']], 'suk');
  2564. break;
  2565. }
  2566. $branchProductInfo = $branchProductServics->isValidStoreProduct((int)$cart['product_id'], $store_id);
  2567. if (!$branchProductInfo) {
  2568. throw new ValidateException('该门店商品库存不足');
  2569. }
  2570. $attrValue = $skuValueServices->get(['suk' => $suk, 'product_id' => $branchProductInfo['id'], 'type' => 0]);
  2571. if (!$attrValue) {
  2572. throw new ValidateException('该门店商品库存不足');
  2573. }
  2574. }
  2575. $res = $this->transaction(function () use ($id, $store_id, $orderInfo, $storeInfo, $cart_info, $branchProductServics) {
  2576. if ($orderInfo['store_id'] > 0) {//重新分配门店
  2577. //返还原来门店库存
  2578. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 0);
  2579. } else {
  2580. //返还平台库存
  2581. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, 0, -1);
  2582. }
  2583. //扣门店库存
  2584. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 1, $store_id);
  2585. $res = $res && $this->dao->update($id, ['store_id' => $storeInfo['id'], 'shipping_type' => $orderInfo['shipping_type'] == 1 ? 3 : $orderInfo['shipping_type']]);
  2586. return $res;
  2587. });
  2588. $orderInfo['store_id'] = $storeInfo['id'];
  2589. //删除之前的账单记录
  2590. /** @var StoreFinanceFlowServices $storeFinanceFlowServices */
  2591. $storeFinanceFlowServices = app()->make(StoreFinanceFlowServices::class);
  2592. $storeFinanceFlowServices->update(['link_id' => $orderInfo['order_id']], ['is_del' => 1]);
  2593. //分配后置方法
  2594. SpliteStoreOrderJob::dispatchDo('splitAfter', [$orderInfo, true]);
  2595. return $res;
  2596. }
  2597. /**
  2598. * 获取退货商品列表
  2599. * @param array $cart_ids
  2600. * @param int $id
  2601. * @return array
  2602. * @throws \think\db\exception\DataNotFoundException
  2603. * @throws \think\db\exception\DbException
  2604. * @throws \think\db\exception\ModelNotFoundException
  2605. */
  2606. public function refundCartInfoList(array $cart_ids = [], int $id = 0)
  2607. {
  2608. $orderInfo = $this->dao->get($id);
  2609. if (!$orderInfo) {
  2610. throw new ValidateException('订单不存在');
  2611. }
  2612. $orderInfo = $this->tidyOrder($orderInfo, true);
  2613. $cartInfo = $orderInfo['cartInfo'] ?? [];
  2614. $data = [];
  2615. if ($cart_ids) {
  2616. foreach ($cart_ids as $cart) {
  2617. if (!isset($cart['cart_id']) || !$cart['cart_id']) {
  2618. throw new ValidateException('请重新选择退款商品,或件数');
  2619. }
  2620. }
  2621. $cart_ids = array_combine(array_column($cart_ids, 'cart_id'), $cart_ids);
  2622. $i = 0;
  2623. foreach ($cartInfo as $item) {
  2624. if (isset($cart_ids[$item['id']])) {
  2625. $data['cartInfo'][$i] = $item;
  2626. if (isset($cart_ids[$item['id']]['cart_num'])) $data['cartInfo'][$i]['cart_num'] = $cart_ids[$item['id']]['cart_num'];
  2627. $i++;
  2628. }
  2629. }
  2630. }
  2631. $data['_status'] = $orderInfo['_status'] ?? [];
  2632. $data['cartInfo'] = $data['cartInfo'] ?? $cartInfo;
  2633. return $data;
  2634. }
  2635. /**
  2636. * 拆单的发货订单数量
  2637. * @param int $id
  2638. * @param $order
  2639. * @return int
  2640. * @throws \think\db\exception\DataNotFoundException
  2641. * @throws \think\db\exception\DbException
  2642. * @throws \think\db\exception\ModelNotFoundException
  2643. */
  2644. public function getDeliverNum(int $id, $order): int
  2645. {
  2646. if (!$order) {
  2647. $order = $this->get($id);
  2648. }
  2649. $ids = $id;
  2650. $pid = (int)$order['pid'];
  2651. if ($pid > 0) {
  2652. $ids = $this->Value([['pid', '=', $pid], ['status', '=', 1]], 'GROUP_CONCAT(id)');
  2653. if (!empty($ids)) {
  2654. $ids = array_map('intval', array_filter(explode(',', $ids)));
  2655. }
  2656. }
  2657. return $this->getCount(['id' => $ids, 'status' => 1]);
  2658. }
  2659. /**
  2660. * 获取确认订单页面是否展示快递配送和到店自提
  2661. * @param $uid
  2662. * @param $cartIds
  2663. * @param $new
  2664. * @return array
  2665. * @throws \Psr\SimpleCache\InvalidArgumentException
  2666. */
  2667. public function checkShipping($uid, $cartIds, $new)
  2668. {
  2669. if ($new) {
  2670. $cartIds = explode(',', $cartIds);
  2671. $cartInfo = [];
  2672. $redis = CacheService::redisHandler();
  2673. foreach ($cartIds as $key) {
  2674. $info = $redis->get($key);
  2675. if ($info) {
  2676. $cartInfo[] = $info;
  2677. }
  2678. }
  2679. } else {
  2680. /** @var StoreCartServices $cartServices */
  2681. $cartServices = app()->make(StoreCartServices::class);
  2682. $cartInfo = $cartServices->getCartList(['uid' => $uid, 'status' => 1, 'id' => $cartIds], 0, 0, ['productInfo', 'attrInfo']);
  2683. }
  2684. if (!$cartInfo) {
  2685. throw new ValidateException('获取购物车信息失败');
  2686. }
  2687. $arr = [];
  2688. $store_id = [];
  2689. //delivery_type :1、快递,2、到店自提,3、门店配送
  2690. foreach ($cartInfo as $item) {
  2691. $delivery_type = is_string($item['productInfo']['delivery_type']) ? explode(',', $item['productInfo']['delivery_type']) : $item['productInfo']['delivery_type'];
  2692. if (in_array(1, $delivery_type)) {//支持平台配送 验证平台该商品
  2693. $productInfo = $item['productInfo'] ?? [];
  2694. if ($productInfo && isset($productInfo['type']) && $productInfo['type'] == 1 && isset($productInfo['pid']) && $productInfo['pid']) {
  2695. /** @var StoreProductServices $productServices */
  2696. $productServices = app()->make(StoreProductServices::class);
  2697. $platInfo = $productServices->getCacheProductInfo((int)$productInfo['pid']);
  2698. if (!$platInfo || $platInfo['stock'] <= 0) {
  2699. unset($delivery_type[array_search('1', $delivery_type)]);
  2700. }
  2701. }
  2702. }
  2703. $arr = array_merge($arr, $delivery_type);
  2704. if (isset($item['productInfo']['type']) && isset($item['productInfo']['relation_id']) && $item['productInfo']['type'] == 1 && $item['productInfo']['relation_id']) {
  2705. $store_id[] = $item['productInfo']['relation_id'];
  2706. }
  2707. }
  2708. $count = count($arr);
  2709. if (!$count) {
  2710. $arr = [1, 2, 3];
  2711. }
  2712. // 门店总开关
  2713. if (!sys_config('store_func_status', 1)) {
  2714. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2715. if (in_array(3, $arr)) unset($arr[array_search(3, $arr)]);
  2716. } elseif (sys_config('store_self_mention', 1)) {
  2717. //判断有没有满足自提的店铺
  2718. $where['id'] = $store_id;
  2719. $where['is_store'] = 1;
  2720. $where['is_show'] = 1;
  2721. $where['is_del'] = 0;
  2722. /** @var SystemStoreServices $SystemStoreServe */
  2723. $SystemStoreServe = app()->make(SystemStoreServices::class);
  2724. $store_list = $SystemStoreServe->count($where);
  2725. if (!$store_list) {
  2726. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2727. }
  2728. } else {
  2729. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2730. }
  2731. $arr = array_merge(array_unique($arr));
  2732. return ['type' => $arr];
  2733. }
  2734. /**
  2735. * @param int $pid
  2736. * @param int $order_id
  2737. * @return bool
  2738. * @throws \think\db\exception\DbException
  2739. */
  2740. public function checkSubOrderNotSend(int $pid, int $order_id)
  2741. {
  2742. $order_count = $this->dao->getSubOrderNotSend($pid, $order_id);
  2743. if ($order_count > 0) {
  2744. return false;
  2745. } else {
  2746. return true;
  2747. }
  2748. }
  2749. /**
  2750. * @param int $pid
  2751. * @param int $order_id
  2752. * @return bool
  2753. * @throws \think\db\exception\DbException
  2754. */
  2755. public function checkSubOrderNotTake(int $pid, int $order_id)
  2756. {
  2757. $order_count = $this->dao->getSubOrderNotTake($pid, $order_id);
  2758. if ($order_count > 0) {
  2759. return false;
  2760. } else {
  2761. return true;
  2762. }
  2763. }
  2764. /**
  2765. * 地区返佣
  2766. * @param $orderInfo
  2767. * @param $userInfo
  2768. * @return bool
  2769. */
  2770. public function backAreaBrokerage()
  2771. {
  2772. //商城分销功能是否开启 0关闭1开启
  2773. if (!sys_config('brokerage_func_status')) return true;
  2774. if (sys_config('area_award_time') <= 0) return true;
  2775. $last_time = sys_config('area_award_last_time');
  2776. if ($last_time + (3600 * (sys_config('area_award_time'))) > time()) {
  2777. return true;
  2778. }
  2779. //冻结时间
  2780. $broken_time = intval(sys_config('extract_time'));
  2781. $frozen_time = time() + $broken_time * 86400;
  2782. $userServices = app()->make(UserServices::class);
  2783. $storeOrderServices = app()->make(StoreOrderServices::class);
  2784. $res = true;
  2785. // 获取上级推广员信息
  2786. /** @var UserServices $userServices */
  2787. //找有代理的省
  2788. $provinces = $userServices->search()->where('area_admin', 3)->column('area_admin_province');
  2789. $provinces = array_unique($provinces);
  2790. foreach ($provinces as $value) {
  2791. $order_price = $storeOrderServices->search(['pid' => 0])->where('order_province', $value)
  2792. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2793. ->where('send_area_award', 0)
  2794. ->where('paid', 1)
  2795. ->where('is_del', 0)
  2796. ->where('is_system_del', 0)
  2797. ->where('refund_status', 0)
  2798. ->whereIn('status', [2, 3])
  2799. ->field('sum(total_price-cost) as total_price_sum')
  2800. ->find();
  2801. $order_price = $order_price['total_price_sum'] ?? 0;
  2802. if ($order_price <= 0) {
  2803. continue;
  2804. }
  2805. //找省代
  2806. $admins = $userServices->search()->where('area_admin', 3)->where('area_admin_province', $value)->select();
  2807. if (count($admins) > 0) {
  2808. $award = bcdiv(bcmul((string)sys_config('province_award'), (string)$order_price, 2), 100, 2);
  2809. if ($award > 0) {
  2810. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2811. if ($brokeragePrice > 0) {
  2812. foreach ($admins as $v) {
  2813. $spreadPrice = (string)$v['brokerage_price'];
  2814. // 上级推广员返佣之后的金额
  2815. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2816. // 添加佣金记录
  2817. /** @var UserBrokerageServices $userBrokerageServices */
  2818. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2819. $type = 'get_area_award';
  2820. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2821. 'pay_price' => floatval($order_price),
  2822. 'area' => $value . '省级',
  2823. 'number' => floatval($brokeragePrice),
  2824. 'frozen_time' => $frozen_time
  2825. ], $balance, 0);
  2826. // 添加用户佣金
  2827. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2828. $res = $res1 && $res2 && $res;
  2829. }
  2830. }
  2831. }
  2832. }
  2833. }
  2834. $citys = $userServices->search()->where('area_admin', 2)->select();
  2835. $pc = [];
  2836. foreach ($citys as $v) {
  2837. $p = $v['area_admin_province'];
  2838. $c = $v['area_admin_city'];
  2839. if (!in_array(compact('p', 'c'), $pc)) {
  2840. $pc[] = compact('p', 'c');
  2841. }
  2842. }
  2843. foreach ($pc as $value) {
  2844. $order_price = $storeOrderServices->search(['pid' => 0])->where('order_province', $value['p'])->where('order_city', $value['c'])
  2845. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2846. ->where('send_area_award', 0)
  2847. ->where('paid', 1)
  2848. ->where('is_del', 0)
  2849. ->where('is_system_del', 0)
  2850. ->where('refund_status', 0)
  2851. ->whereIn('status', [2, 3])
  2852. ->field('sum(total_price-cost) as total_price_sum')
  2853. ->find();
  2854. $order_price = $order_price['total_price_sum'] ?? 0;
  2855. if ($order_price <= 0) {
  2856. continue;
  2857. }
  2858. //找市代
  2859. $admins = $userServices->search()->where('area_admin', 2)->where('area_admin_province', $value['p'])
  2860. ->where('area_admin_city', $value['c'])->select();
  2861. if (count($admins) > 0) {
  2862. $award = bcdiv(bcmul((string)sys_config('city_award'), (string)$order_price, 2), 100, 2);
  2863. if ($award > 0) {
  2864. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2865. if ($brokeragePrice > 0) {
  2866. foreach ($admins as $v) {
  2867. $spreadPrice = (string)$v['brokerage_price'];
  2868. // 上级推广员返佣之后的金额
  2869. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2870. // 添加佣金记录
  2871. /** @var UserBrokerageServices $userBrokerageServices */
  2872. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2873. $type = 'get_area_brokerage';
  2874. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2875. 'pay_price' => floatval($order_price),
  2876. 'area' => $value['p'] . $value['c'] . '级',
  2877. 'number' => floatval($brokeragePrice),
  2878. 'frozen_time' => $frozen_time
  2879. ], $balance, 0);
  2880. // 添加用户佣金
  2881. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2882. $res = $res1 && $res2 && $res;
  2883. }
  2884. }
  2885. }
  2886. }
  2887. }
  2888. $citys = $userServices->search()->where('area_admin', 1)->select();
  2889. $pcd = [];
  2890. foreach ($citys as $v) {
  2891. $p = $v['area_admin_province'];
  2892. $c = $v['area_admin_city'];
  2893. $d = $v['area_admin_district'];
  2894. if (!in_array(compact('p', 'c', 'd'), $pcd)) {
  2895. $pcd[] = compact('p', 'c', 'd');
  2896. }
  2897. }
  2898. foreach ($pcd as $value) {
  2899. $order_price = $storeOrderServices->search(['pid' => 0])
  2900. ->where('order_province', $value['p'])
  2901. ->where('order_city', $value['c'])
  2902. ->where('order_district', $value['d'])
  2903. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2904. ->where('send_area_award', 0)
  2905. ->where('paid', 1)
  2906. ->where('is_del', 0)
  2907. ->where('is_system_del', 0)
  2908. ->where('refund_status', 0)
  2909. ->whereIn('status', [2, 3])
  2910. ->field('sum(total_price-cost) as total_price_sum')
  2911. ->find();
  2912. $order_price = $order_price['total_price_sum'] ?? 0;
  2913. if ($order_price <= 0) {
  2914. continue;
  2915. }
  2916. //找区代
  2917. $admins = $userServices->search()->where('area_admin', 1)
  2918. ->where('area_admin_province', $value['p'])
  2919. ->where('area_admin_city', $value['c'])
  2920. ->where('area_admin_district', $value['d'])
  2921. ->select();
  2922. if (count($admins) > 0) {
  2923. $award = bcdiv(bcmul((string)sys_config('district_award'), (string)$order_price, 2), 100, 2);
  2924. if ($award > 0) {
  2925. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2926. if ($brokeragePrice > 0) {
  2927. foreach ($admins as $v) {
  2928. $spreadPrice = (string)$v['brokerage_price'];
  2929. // 上级推广员返佣之后的金额
  2930. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2931. // 添加佣金记录
  2932. /** @var UserBrokerageServices $userBrokerageServices */
  2933. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2934. $type = 'get_area_brokerage';
  2935. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2936. 'pay_price' => floatval($order_price),
  2937. 'area' => $value['p'] . $value['c'] . $value['d'] . '级',
  2938. 'number' => floatval($brokeragePrice),
  2939. 'frozen_time' => $frozen_time
  2940. ], $balance, 0);
  2941. // 添加用户佣金
  2942. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2943. $res = $res1 && $res2 && $res;
  2944. }
  2945. }
  2946. }
  2947. }
  2948. }
  2949. return $res
  2950. && $storeOrderServices->search()->where('send_area_award', 0)->update(['send_area_award' => 1])
  2951. && SystemConfig::where('menu_name', 'area_award_last_time')->update(['value' => time()]);
  2952. }
  2953. }