StoreOrderServices.php 134 KB

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