StoreOrderServices.php 138 KB

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