StoreOrderServices.php 135 KB

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