StoreOrderServices.php 137 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004
  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. $today = $integralService->getLake('today');
  1489. $yesterday = $integralService->getLake('yesterday');
  1490. $today_ratio = $this->countRate($today, $yesterday);
  1491. $lack = [
  1492. 'today' => $today,
  1493. 'yesterday' => $yesterday,
  1494. 'today_ratio' => $today_ratio,
  1495. 'total' => $integralService->getLake() . '元',
  1496. 'date' => '今日'
  1497. ];
  1498. $today = $integralService->getIntegralSum(['time' => 'today', 'timeKey' => 'add_time', 'status' => 0, 'type' => 0]);
  1499. $yesterday = $integralService->getIntegralSum(['time' => 'yesterday', 'timeKey' => 'add_time', 'status' => 0, 'type' => 0]);
  1500. $today_ratio = $this->countRate($today, $yesterday);
  1501. $a_integral = [
  1502. 'today' => $today,
  1503. 'yesterday' => $yesterday,
  1504. 'today_ratio' => $today_ratio,
  1505. 'total' => $integralService->getIntegralSum(['status' => 0, 'type' => 0]),
  1506. 'date' => '今日'
  1507. ];
  1508. $today = $integralService->getIntegralSum(['time' => 'today', 'timeKey' => 'add_time', 'status' => 0, 'type' => 1]);
  1509. $yesterday = $integralService->getIntegralSum(['time' => 'yesterday', 'timeKey' => 'add_time', 'status' => 0, 'type' => 1]);
  1510. $today_ratio = $this->countRate($today, $yesterday);
  1511. $s_integral = [
  1512. 'today' => $today,
  1513. 'yesterday' => $yesterday,
  1514. 'today_ratio' => $today_ratio,
  1515. 'total' => $integralService->getIntegralSum(['status' => 0, 'type' => 1]),
  1516. 'date' => '今日'
  1517. ];
  1518. $today = $integralService->getPrice();
  1519. $yesterday = $integralService->search()->whereTime('add_time', 'yesterday')->order('add_time', 'desc')->value('value');
  1520. $today_ratio = $this->countRate($today, $yesterday);
  1521. $l_price = [
  1522. 'today' => $today,
  1523. 'yesterday' => $yesterday,
  1524. 'today_ratio' => $today_ratio,
  1525. 'total' => $today . '元',
  1526. 'date' => '今日'
  1527. ];
  1528. $info = array_values(compact('sales', 'visits', 'order', 'user', 'lack', 'a_integral', 's_integral', 'l_price'));
  1529. $info[0]['title'] = '销售额';
  1530. $info[1]['title'] = '用户访问量';
  1531. $info[2]['title'] = '订单量';
  1532. $info[3]['title'] = '新增用户';
  1533. $info[4]['title'] = '资金池';
  1534. $info[5]['title'] = '消费分';
  1535. $info[6]['title'] = '贡献分';
  1536. $info[7]['title'] = '参考值';
  1537. $info[0]['total_name'] = '本月销售额';
  1538. $info[1]['total_name'] = '本月访问量';
  1539. $info[2]['total_name'] = '本月订单量';
  1540. $info[3]['total_name'] = '本月新增用户';
  1541. $info[4]['total_name'] = '资金池累计';
  1542. $info[5]['total_name'] = '剩余消费分';
  1543. $info[6]['total_name'] = '剩余贡献分';
  1544. $info[7]['total_name'] = '当前参考值';
  1545. return $info;
  1546. }
  1547. /**
  1548. * 打印订单
  1549. * @param int $id
  1550. * @param bool $isTable
  1551. * @return bool
  1552. */
  1553. public function orderPrint(int $id, int $type = -1, int $relation_id = -1, bool $isTable = false)
  1554. {
  1555. $order = $this->dao->get($id);
  1556. if (!$order) {
  1557. throw new ValidateException('订单信息不存在!');
  1558. }
  1559. $order = $order->toArray();
  1560. /** @var StoreOrderCartInfoServices $cartServices */
  1561. $cartServices = app()->make(StoreOrderCartInfoServices::class);
  1562. $product = $cartServices->getCartInfoPrintProduct((int)$order['id']);
  1563. if (!$product) {
  1564. throw new ValidateException('订单商品获取失败,无法打印!');
  1565. }
  1566. if ($type == -1 && $relation_id == -1) {//取订单属于那一端
  1567. $type = $relation_id = 0;
  1568. if (isset($order['store_id']) && $order['store_id']) {
  1569. $store_id = (int)$order['store_id'];
  1570. if ($isTable) {
  1571. if (isset($order['type']) && $order['type'] == 10) {
  1572. $print = store_config($store_id, 'store_printing_timing');
  1573. if (!$print || !is_array($print) || !in_array(2, $print)) {
  1574. return true;
  1575. }
  1576. }
  1577. }
  1578. $type = 1;
  1579. $relation_id = $store_id;
  1580. } elseif (isset($order['supplier_id']) && $order['supplier_id']) {
  1581. $supplier_id = (int)$order['supplier_id'];
  1582. $type = 2;
  1583. $relation_id = $supplier_id;
  1584. }
  1585. }
  1586. /** @var ConfigServices $configServices */
  1587. $configServices = app()->make(ConfigServices::class);
  1588. [$switch, $name, $configData] = $configServices->getPrintingConfig($type, $relation_id);
  1589. if (!$switch) {
  1590. throw new ValidateException('请先开启小票打印');
  1591. }
  1592. foreach ($configData as $value) {
  1593. if (!$value) {
  1594. throw new ValidateException('请先配置小票打印开发者');
  1595. }
  1596. }
  1597. $printer = new Printer($name, $configData);
  1598. $printer->setPrinterContent([
  1599. 'name' => sys_config('site_name'),
  1600. 'orderInfo' => is_object($order) ? $order->toArray() : $order,
  1601. 'product' => $product
  1602. ])->startPrinter();
  1603. return true;
  1604. }
  1605. /**
  1606. * 获取订单确认数据
  1607. * @param array $user
  1608. * @param $cartId
  1609. * @param bool $new
  1610. * @param int $addressId
  1611. * @param int $shipping_type
  1612. * @param int $store_id
  1613. * @param int $coupon_id
  1614. * @return array
  1615. * @throws \Psr\SimpleCache\InvalidArgumentException
  1616. * @throws \think\db\exception\DataNotFoundException
  1617. * @throws \think\db\exception\DbException
  1618. * @throws \think\db\exception\ModelNotFoundException
  1619. */
  1620. public function getOrderConfirmData(array $user, $cartId, bool $new, int $addressId, int $shipping_type = 1, int $store_id = 0, int $coupon_id = 0)
  1621. {
  1622. $addr = $data = [];
  1623. $uid = (int)$user['uid'];
  1624. /** @var UserAddressServices $addressServices */
  1625. $addressServices = app()->make(UserAddressServices::class);
  1626. if ($addressId) {
  1627. $addr = $addressServices->getAdderssCache($addressId);
  1628. }
  1629. //没传地址id或地址已删除未找到 ||获取默认地址
  1630. if (!$addr) {
  1631. $addr = $addressServices->getUserDefaultAddressCache($uid);
  1632. }
  1633. $data['upgrade_addr'] = 0;
  1634. if ($addr) {
  1635. $addr = is_object($addr) ? $addr->toArray() : $addr;
  1636. if (isset($addr['upgrade']) && $addr['upgrade'] == 0) {
  1637. $data['upgrade_addr'] = 1;
  1638. }
  1639. } else {
  1640. $addr = [];
  1641. }
  1642. if ($store_id) {
  1643. /** @var SystemStoreServices $storeServices */
  1644. $storeServices = app()->make(SystemStoreServices::class);
  1645. $storeServices->getStoreInfo($store_id);
  1646. }
  1647. /** @var StoreCartServices $cartServices */
  1648. $cartServices = app()->make(StoreCartServices::class);
  1649. //获取购物车信息
  1650. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, $new, $addr, $shipping_type, $store_id, $coupon_id);
  1651. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  1652. $data['storeFreePostage'] = $storeFreePostage;
  1653. $validCartInfo = $cartGroup['valid'];
  1654. $giveCartList = $cartGroup['giveCartList'] ?? [];
  1655. /** @var StoreOrderComputedServices $computedServices */
  1656. $computedServices = app()->make(StoreOrderComputedServices::class);
  1657. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  1658. $priceGroup['couponPrice'] = $cartGroup['couponPrice'] ?? 0;
  1659. $priceGroup['firstOrderPrice'] = $cartGroup['firstOrderPrice'] ?? 0;
  1660. $validCartInfo = array_merge($priceGroup['cartInfo'] ?? $validCartInfo, $giveCartList);
  1661. $other = [
  1662. 'offlinePostage' => sys_config('offline_postage'),
  1663. 'integralRatio' => sys_config('integral_ratio'),
  1664. 'give_integral' => $cartGroup['giveIntegral'] ?? 0,
  1665. 'give_coupon' => $cartGroup['giveCoupon'] ?? [],
  1666. 'give_product' => $cartGroup['giveProduct'],
  1667. 'promotions' => $cartGroup['promotions']
  1668. ];
  1669. $deduction = $cartGroup['deduction'];
  1670. $data['product_type'] = $deduction['product_type'] ?? 0;
  1671. $data['valid_count'] = count($validCartInfo);
  1672. $data['addressInfo'] = $addr;
  1673. $data['type'] = $deduction['type'] ?? 0;
  1674. $data['activity_id'] = $deduction['activity_id'] ?? 0;
  1675. $data['seckill_id'] = $deduction['type'] == 1 ? $deduction['activity_id'] : 0;
  1676. $data['bargain_id'] = $deduction['type'] == 2 ? $deduction['activity_id'] : 0;
  1677. $data['combination_id'] = $deduction['type'] == 3 ? $deduction['activity_id'] : 0;
  1678. $data['luck_record_id'] = $deduction['type'] == 8 ? $deduction['activity_id'] : 0;
  1679. $data['collate_code_id'] = $deduction['type'] == 9 || $deduction['type'] == 10 ? $deduction['collate_code_id'] : 0;
  1680. $data['discount_id'] = $deduction['type'] == 5 ? $deduction['activity_id'] : 0;
  1681. $data['newcomer_id'] = $deduction['type'] == 7 ? $deduction['activity_id'] : 0;
  1682. $data['deduction'] = in_array($deduction['product_type'], [1, 2]) || $deduction['activity_id'] > 0;
  1683. $data['cartInfo'] = array_merge($cartGroup['cartInfo'], $giveCartList);
  1684. // $data['giveCartInfo'] = $giveCartList;
  1685. $data['custom_form'] = [];
  1686. if (isset($cartGroup['cartInfo'][0]['productInfo']['system_form_id']) && $cartGroup['cartInfo'][0]['productInfo']['system_form_id']) {
  1687. /** @var SystemFormServices $systemFormServices */
  1688. $systemFormServices = app()->make(SystemFormServices::class);
  1689. $formInfo = $systemFormServices->value(['id' => $cartGroup['cartInfo'][0]['productInfo']['system_form_id']], 'value');
  1690. if ($formInfo) {
  1691. $data['custom_form'] = is_string($formInfo) ? json_decode($formInfo, true) : $formInfo;
  1692. }
  1693. }
  1694. $data['give_integral'] = $other['give_integral'];
  1695. $data['give_coupon'] = [];
  1696. if ($other['give_coupon']) {
  1697. /** @var StoreCouponIssueServices $couponIssueService */
  1698. $couponIssueService = app()->make(StoreCouponIssueServices::class);
  1699. $data['give_coupon'] = $couponIssueService->getColumn([['id', 'IN', $other['give_coupon']]], 'id,coupon_title');
  1700. }
  1701. $data['priceGroup'] = $priceGroup;
  1702. $data['orderKey'] = $this->cacheOrderInfo($uid, $validCartInfo, $priceGroup, $other, $addr, $cartGroup['invalid'] ?? [], $deduction);
  1703. $data['offlinePostage'] = $other['offlinePostage'];
  1704. if (isset($user['pwd'])) unset($user['pwd']);
  1705. $user['vip'] = isset($priceGroup['vipPrice']) && $priceGroup['vipPrice'] > 0;
  1706. $user['vip_id'] = 0;
  1707. $user['discount'] = 0;
  1708. //用户等级是否开启
  1709. if (sys_config('member_func_status', 1)) {
  1710. /** @var UserLevelServices $levelServices */
  1711. $levelServices = app()->make(UserLevelServices::class);
  1712. $userLevel = $levelServices->getUerLevelInfoByUid($uid);
  1713. if ($user['vip'] || $userLevel) {
  1714. $user['vip'] = true;
  1715. $user['vip_id'] = $userLevel['id'] ?? 0;
  1716. $user['discount'] = $userLevel['discount'] ?? 0;
  1717. }
  1718. }
  1719. $user['record_pone'] = !isset($user['record_pone']) || !$user['record_pone'] ? '' : $user['record_pone'];
  1720. $data['userInfo'] = $user;
  1721. $data['integralRatio'] = $other['integralRatio'];
  1722. $data['offline_pay_status'] = (int)sys_config('offline_pay_status') ?? (int)2;
  1723. $data['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  1724. $data['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  1725. $data['store_func_status'] = (int)(sys_config('store_func_status', 1));//门店是否开启
  1726. $data['store_self_mention'] = false;//门店自提
  1727. $data['store_delivery_status'] = false;//门店配送
  1728. if ($data['store_func_status']) {
  1729. //门店自提是否开启
  1730. /** @var SystemStoreServices $systemStoreServices */
  1731. $systemStoreServices = app()->make(SystemStoreServices::class);
  1732. $data['store_self_mention'] = sys_config('store_self_mention') && $systemStoreServices->count(['type' => 0, 'is_store' => 1]);
  1733. $data['store_delivery_status'] = !!$systemStoreServices->count(['type' => 0]);
  1734. }
  1735. $data['store_func_status'] = $data['store_func_status'] && ($data['store_self_mention'] || $data['store_delivery_status']);
  1736. $data['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  1737. $data['system_store'] = [];//门店信息
  1738. /** @var UserInvoiceServices $userInvoice */
  1739. $userInvoice = app()->make(UserInvoiceServices::class);
  1740. $invoice_func = $userInvoice->invoiceFuncStatus();
  1741. $data['invoice_func'] = $invoice_func['invoice_func'];
  1742. $data['special_invoice'] = $invoice_func['special_invoice'];
  1743. $data['integral_ratio_status'] = (int)sys_config('integral_ratio_status', 1);
  1744. return $data;
  1745. }
  1746. /**
  1747. * 缓存订单信息
  1748. * @param int $uid
  1749. * @param array $cartInfo
  1750. * @param array $priceGroup
  1751. * @param array $other
  1752. * @param array $addr
  1753. * @param array $invalidCartInfo
  1754. * @param array $deduction
  1755. * @param int $cacheTime
  1756. * @return string
  1757. * @throws \Psr\SimpleCache\InvalidArgumentException
  1758. */
  1759. public function cacheOrderInfo(int $uid, array $cartInfo, array $priceGroup, array $other = [], array $addr = [], array $invalidCartInfo = [], array $deduction = [], int $cacheTime = 600)
  1760. {
  1761. /** @var StoreOrderCreateServices $storeOrderCreateService */
  1762. $storeOrderCreateService = app()->make(StoreOrderCreateServices::class);
  1763. $key = md5($storeOrderCreateService->getNewOrderId((string)$uid) . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8));
  1764. CacheService::redisHandler()->set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup', 'other', 'addr', 'invalidCartInfo', 'deduction'), $cacheTime);
  1765. return $key;
  1766. }
  1767. /**
  1768. * 获取订单缓存信息
  1769. * @param int $uid
  1770. * @param string $key
  1771. * @return |null
  1772. */
  1773. public function getCacheOrderInfo(int $uid, string $key)
  1774. {
  1775. $cacheName = 'user_order_' . $uid . $key;
  1776. if (!CacheService::redisHandler()->has($cacheName)) return null;
  1777. return CacheService::redisHandler()->get($cacheName);
  1778. }
  1779. /**
  1780. * 获取用户购买活动产品的次数
  1781. * @param $uid
  1782. * @param $seckill_id
  1783. * @return int
  1784. */
  1785. public function activityProductCount(array $where)
  1786. {
  1787. return $this->dao->count($where);
  1788. }
  1789. /**
  1790. * 获取拼团的订单id
  1791. * @param int $pid
  1792. * @param int $uid
  1793. * @return mixed
  1794. */
  1795. public function getStoreIdPink(int $pid, int $uid)
  1796. {
  1797. return $this->dao->value(['uid' => $uid, 'pink_id' => $pid, 'is_del' => 0], 'order_id');
  1798. }
  1799. /**
  1800. * 判断当前订单中是否有拼团
  1801. * @param int $pid
  1802. * @param int $uid
  1803. * @return int
  1804. */
  1805. public function getIsOrderPink($pid = 0, $uid = 0)
  1806. {
  1807. return $this->dao->count(['uid' => $uid, 'pink_id' => $pid, 'refund_status' => 0, 'is_del' => 0]);
  1808. }
  1809. /**
  1810. * 判断支付方式是否开启
  1811. * @param $payType
  1812. * @return bool
  1813. */
  1814. public function checkPaytype(string $payType)
  1815. {
  1816. $res = false;
  1817. switch ($payType) {
  1818. case PayServices::WEIXIN_PAY:
  1819. $res = (bool)sys_config('pay_weixin_open');
  1820. break;
  1821. case PayServices::YUE_PAY:
  1822. $res = sys_config('balance_func_status') && sys_config('yue_pay_status') == 1;
  1823. break;
  1824. case 'offline':
  1825. $res = sys_config('offline_pay_status') == 1;
  1826. break;
  1827. case PayServices::ALIAPY_PAY:
  1828. $res = sys_config('ali_pay_status') == 1;
  1829. break;
  1830. }
  1831. return $res;
  1832. }
  1833. /**
  1834. * 修改支付方式为线下支付
  1835. * @param string $orderId
  1836. * @return bool
  1837. */
  1838. public function setOrderTypePayOffline(string $orderId)
  1839. {
  1840. return $this->dao->update($orderId, ['pay_type' => 'offline'], 'order_id');
  1841. }
  1842. /**
  1843. * 删除订单
  1844. * @param $uni
  1845. * @param $uid
  1846. * @return bool
  1847. */
  1848. public function removeOrder(string $uni, int $uid)
  1849. {
  1850. $order = $this->getUserOrderDetail($uni, $uid);
  1851. if (!$order) {
  1852. throw new ValidateException('订单不存在!');
  1853. }
  1854. $order = $this->tidyOrder($order);
  1855. if ($order['_status']['_type'] != 0 && $order['_status']['_type'] != -2 && $order['_status']['_type'] != 4)
  1856. throw new ValidateException('该订单无法删除!');
  1857. $order->is_del = 1;
  1858. /** @var StoreOrderStatusServices $statusService */
  1859. $statusService = app()->make(StoreOrderStatusServices::class);
  1860. $res = $statusService->save([
  1861. 'oid' => $order['id'],
  1862. 'change_type' => 'remove_order',
  1863. 'change_message' => '删除订单',
  1864. 'change_time' => time()
  1865. ]);
  1866. if ($order->save() && $res) {
  1867. //未支付和已退款的状态下才可以退积分退库存退优惠券
  1868. if ($order['_status']['_type'] == 0 || $order['_status']['_type'] == -2) {
  1869. /** @var StoreOrderRefundServices $refundServices */
  1870. $refundServices = app()->make(StoreOrderRefundServices::class);
  1871. $this->transaction(function () use ($order, $refundServices) {
  1872. //回退积分和优惠卷
  1873. $res = $refundServices->integralAndCouponBack($order);
  1874. //回退库存
  1875. $res = $res && $refundServices->regressionStock($order);
  1876. if (!$res) {
  1877. throw new ValidateException('取消订单失败!');
  1878. }
  1879. });
  1880. }
  1881. return true;
  1882. } else
  1883. throw new ValidateException('订单删除失败!');
  1884. }
  1885. /**
  1886. * 取消订单
  1887. * @param $order_id
  1888. * @param int $uid
  1889. * @return bool
  1890. * @throws \think\db\exception\DataNotFoundException
  1891. * @throws \think\db\exception\DbException
  1892. * @throws \think\db\exception\ModelNotFoundException
  1893. */
  1894. public function cancelOrder($order_id, int $uid)
  1895. {
  1896. $order = $this->dao->getOne(['order_id' => $order_id, 'uid' => $uid, 'is_del' => 0]);
  1897. if (!$order) {
  1898. throw new ValidateException('没有查到此订单');
  1899. }
  1900. if ($order->paid) {
  1901. throw new ValidateException('订单已经支付无法取消');
  1902. }
  1903. /** @var StoreOrderRefundServices $refundServices */
  1904. $refundServices = app()->make(StoreOrderRefundServices::class);
  1905. $this->transaction(function () use ($refundServices, $order) {
  1906. //回退积分和优惠卷
  1907. $res = $refundServices->integralAndCouponBack($order);
  1908. //回退库存和销量
  1909. $res = $res && $refundServices->regressionStock($order);
  1910. $order->is_del = 1;
  1911. if (!($res && $order->save())) {
  1912. throw new ValidateException('取消订单失败');
  1913. }
  1914. });
  1915. //订单取消事件
  1916. event('order.cancel', [$order]);
  1917. return true;
  1918. }
  1919. /**
  1920. * 判断订单完成
  1921. * @param StoreProductReplyServices $replyServices
  1922. * @param array $uniqueList
  1923. * @param $oid
  1924. * @return mixed
  1925. */
  1926. public function checkOrderOver($replyServices, array $uniqueList, $oid)
  1927. {
  1928. //订单商品全部评价完成
  1929. $replyServices->count(['unique' => $uniqueList, 'oid' => $oid]);
  1930. if ($replyServices->count(['unique' => $uniqueList, 'oid' => $oid]) == count($uniqueList)) {
  1931. $res = $this->dao->update($oid, ['status' => '3']);
  1932. if (!$res) throw new ValidateException('评价后置操作失败!');
  1933. /** @var StoreOrderStatusServices $statusService */
  1934. $statusService = app()->make(StoreOrderStatusServices::class);
  1935. $statusService->save([
  1936. 'oid' => $oid,
  1937. 'change_type' => 'check_order_over',
  1938. 'change_message' => '用户评价',
  1939. 'change_time' => time()
  1940. ]);
  1941. }
  1942. }
  1943. /**
  1944. * 某个用户订单
  1945. * @param int $uid
  1946. * @param UserServices $userServices
  1947. * @return array
  1948. * @throws \think\db\exception\DataNotFoundException
  1949. * @throws \think\db\exception\DbException
  1950. * @throws \think\db\exception\ModelNotFoundException
  1951. */
  1952. public function getUserOrderList(int $uid)
  1953. {
  1954. /** @var UserServices $userServices */
  1955. $userServices = app()->make(UserServices::class);
  1956. $user = $userServices->getUserWithTrashedInfo($uid);
  1957. if (!$user) {
  1958. throw new ValidateException('数据不存在');
  1959. }
  1960. [$page, $limit] = $this->getPageValue();
  1961. $where = ['uid' => $uid, 'pid' => [0, -1], 'paid' => 1, 'is_del' => 0, 'is_system_del' => 0];
  1962. $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);
  1963. $count = $this->dao->count($where);
  1964. return compact('list', 'count');
  1965. }
  1966. /**
  1967. * 获取推广订单列表
  1968. * @param int $uid
  1969. * @param $where
  1970. * @return array
  1971. * @throws \think\db\exception\DataNotFoundException
  1972. * @throws \think\db\exception\DbException
  1973. * @throws \think\db\exception\ModelNotFoundException
  1974. */
  1975. public function getUserStairOrderList(int $uid, $where)
  1976. {
  1977. $where_data = [];
  1978. if (isset($where['type'])) {
  1979. switch ((int)$where['type']) {
  1980. case 1:
  1981. $where_data['spread_uid'] = $uid;
  1982. break;
  1983. case 2:
  1984. $where_data['spread_two_uid'] = $uid;
  1985. break;
  1986. default:
  1987. $where_data['spread_or_uid'] = $uid;
  1988. break;
  1989. }
  1990. }
  1991. if (isset($where['data']) && $where['data']) {
  1992. $where_data['time'] = $where['data'];
  1993. }
  1994. if (isset($where['order_id']) && $where['order_id']) {
  1995. $where_data['order_id'] = $where['order_id'];
  1996. }
  1997. if (isset($where['nickname']) && $where['nickname']) {
  1998. $where_data['real_name'] = $where['nickname'];
  1999. }
  2000. //推广订单只显示支付过并且未退款的订单
  2001. $where_data['pid'] = 0;
  2002. $where_data['paid'] = 1;
  2003. $where_data['refund_status'] = 0;
  2004. [$page, $limit] = $this->getPageValue();
  2005. $list = $this->dao->getStairOrderList($where_data, '*', $page, $limit);
  2006. $count = $this->dao->count($where_data);
  2007. return compact('list', 'count');
  2008. }
  2009. /**
  2010. * 订单导出
  2011. * @param array $where
  2012. * @return array
  2013. * @throws \think\db\exception\DataNotFoundException
  2014. * @throws \think\db\exception\DbException
  2015. * @throws \think\db\exception\ModelNotFoundException
  2016. */
  2017. public function getExportList(array $where, array $with = [], int $limit = 0)
  2018. {
  2019. if ($limit) {
  2020. [$page] = $this->getPageValue();
  2021. } else {
  2022. [$page, $limit] = $this->getPageValue();
  2023. }
  2024. $list = $this->dao->search($where)->with($with)->page($page, $limit)->order('id asc')->select()->toArray();
  2025. if ($list) {
  2026. /** @var $userServices */
  2027. $userServices = app()->make(UserServices::class);
  2028. $userSex = $userServices->getColumn([['uid', 'IN', array_unique(array_column($list, 'uid'))]], 'uid,sex', 'uid');
  2029. foreach ($list as &$item) {
  2030. /** @var StoreOrderCartInfoServices $orderCart */
  2031. $orderCart = app()->make(StoreOrderCartInfoServices::class);
  2032. $_info = $orderCart->getCartColunm(['oid' => $item['id']], 'cart_info', 'unique');
  2033. foreach ($_info as $k => $v) {
  2034. $cart_info = is_string($v) ? json_decode($v, true) : $v;
  2035. if (!isset($cart_info['productInfo'])) $cart_info['productInfo'] = [];
  2036. $_info[$k] = $cart_info;
  2037. unset($cart_info);
  2038. }
  2039. $item['_info'] = $_info;
  2040. $item['sex'] = $userSex[$item['uid']]['sex'] ?? '';
  2041. [$pink_name, $color] = $this->tidyOrderType($item);
  2042. $item['pink_name'] = $pink_name;
  2043. $item['color'] = $color;
  2044. }
  2045. }
  2046. return $list;
  2047. }
  2048. /**
  2049. * 自动取消订单
  2050. * @return bool
  2051. * @throws \think\db\exception\DataNotFoundException
  2052. * @throws \think\db\exception\DbException
  2053. * @throws \think\db\exception\ModelNotFoundException
  2054. */
  2055. public function runOrderUnpaidCancel(int $page = 0, int $limit = 0)
  2056. {
  2057. $list = $this->dao->getOrderUnPaid(0, $page, $limit)->field(['*'])->select();
  2058. if (!$list) {
  2059. return true;
  2060. }
  2061. //系统预设取消订单时间段
  2062. $keyValue = ['order_cancel_time', 'order_activity_time', 'order_bargain_time', 'order_seckill_time', 'order_pink_time'];
  2063. //获取配置
  2064. $systemValue = SystemConfigService::more($keyValue);
  2065. //格式化数据
  2066. $systemValue = Arr::setValeTime($keyValue, is_array($systemValue) ? $systemValue : []);
  2067. $secsArr = [];
  2068. //秒杀
  2069. $secsArr[1] = $systemValue['order_seckill_time'] ? $systemValue['order_seckill_time'] : $systemValue['order_activity_time'];
  2070. //砍价
  2071. $secsArr[2] = $systemValue['order_bargain_time'] ? $systemValue['order_bargain_time'] : $systemValue['order_activity_time'];
  2072. //拼团
  2073. $secsArr[3] = $systemValue['order_pink_time'] ? $systemValue['order_pink_time'] : $systemValue['order_activity_time'];
  2074. //默认
  2075. $secsArr[0] = $systemValue['order_cancel_time'];
  2076. /** @var StoreOrderRefundServices $refundServices */
  2077. $refundServices = app()->make(StoreOrderRefundServices::class);
  2078. foreach ($list as $order) {
  2079. $type = $order['type'];
  2080. $secs = $secsArr[$type] ?? $secsArr[0];
  2081. if ($secs == 0) continue;
  2082. if (($order['add_time'] + bcmul($secs, '3600', 0)) < time()) {
  2083. try {
  2084. $this->transaction(function () use ($order, $refundServices) {
  2085. //回退积分和优惠卷
  2086. $res = $refundServices->integralAndCouponBack($order);
  2087. //回退库存和销量
  2088. $res = $res && $refundServices->regressionStock($order);
  2089. //修改订单状态
  2090. $res = $res && $this->dao->update($order['id'], ['is_del' => 1, 'mark' => '订单未支付已超过系统预设时间']);
  2091. if (!$res) {
  2092. throw new ValidateException('订单号' . $order['order_id'] . '自动取消订单失败');
  2093. }
  2094. return true;
  2095. });
  2096. //订单取消事件
  2097. event('order.cancel', [$order]);
  2098. } catch (\Throwable $e) {
  2099. Log::error('自动取消订单失败,失败原因:' . $e->getMessage(), $e->getTrace());
  2100. }
  2101. }
  2102. }
  2103. return true;
  2104. }
  2105. /**
  2106. * 批量加入对接
  2107. * @param int $count
  2108. * @param int $limit
  2109. */
  2110. public function batchJoinJob(int $count, int $limit)
  2111. {
  2112. $pages = ceil($limit / $count);
  2113. for ($i = 1; $i <= $pages; $i++) {
  2114. AutoOrderUnpaidCancelJob::dispatch([$i, $limit]);
  2115. }
  2116. return true;
  2117. }
  2118. /**
  2119. * 自动取消订单
  2120. * @return bool
  2121. * @throws \think\db\exception\DataNotFoundException
  2122. * @throws \think\db\exception\DbException
  2123. * @throws \think\db\exception\ModelNotFoundException
  2124. */
  2125. public function orderUnpaidCancel()
  2126. {
  2127. $count = $this->dao->getOrderUnPaid()->count();
  2128. $maxLimit = 100;
  2129. if ($count > $maxLimit) {
  2130. return $this->batchJoinJob($count, $maxLimit);
  2131. }
  2132. return $this->runOrderUnpaidCancel();
  2133. }
  2134. /**
  2135. * 根据时间获取当天或昨天订单营业额
  2136. * @param array $where
  2137. * @return float|int
  2138. */
  2139. public function getOrderMoneyByWhere(array $where, string $sum_field, string $selectType, string $group = "")
  2140. {
  2141. switch ($selectType) {
  2142. case "sum" :
  2143. return $this->dao->getDayTotalMoney($where, $sum_field);
  2144. case "group" :
  2145. return $this->dao->getDayGroupMoney($where, $sum_field, $group);
  2146. }
  2147. }
  2148. /**
  2149. * 统计时间段订单数
  2150. * @param array $where
  2151. * @param string $sum_field
  2152. */
  2153. public function getOrderCountByWhere(array $where)
  2154. {
  2155. return $this->dao->getDayOrderCount($where);
  2156. }
  2157. /**
  2158. * 分组统计时间段订单数
  2159. * @param $where
  2160. * @return mixed
  2161. */
  2162. public function getOrderGroupCountByWhere($where)
  2163. {
  2164. return $this->dao->getOrderGroupCount($where);
  2165. }
  2166. /**
  2167. * 时间段支付订单人数
  2168. * @param $where
  2169. * @return mixed
  2170. */
  2171. public function getPayOrderPeopleByWhere($where)
  2172. {
  2173. return $this->dao->getPayOrderPeople($where);
  2174. }
  2175. /**
  2176. * 时间段分组统计支付订单人数
  2177. * @param $where
  2178. * @return mixed
  2179. */
  2180. public function getPayOrderGroupPeopleByWhere($where)
  2181. {
  2182. return $this->dao->getPayOrderGroupPeople($where);
  2183. }
  2184. /**
  2185. * 批量更新数据
  2186. * @param array $ids
  2187. * @param array $data
  2188. * @param string|null $key
  2189. * @return BaseModel
  2190. */
  2191. public function orderDel(array $ids, $redisKey, $queueId)
  2192. {
  2193. /** @var QueueServices $queueService */
  2194. $queueService = app()->make(QueueServices::class);
  2195. $res = $this->dao->batchUpdateOrder($ids, ['is_system_del' => 1]);
  2196. if ($res) {
  2197. $queueService->doSuccessSremRedis($ids, $redisKey, $queueId['type']);
  2198. } else {
  2199. $queueService->addQueueFail($queueId['id'], $redisKey);
  2200. throw new AdminException('删除失败');
  2201. }
  2202. }
  2203. /**获取发货excel文件数据
  2204. * @param string $file
  2205. * @param $row
  2206. * @return array
  2207. * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
  2208. */
  2209. public function readExpreExcel(string $file, $row = 2)
  2210. {
  2211. if (!$file) throw new AdminException('请上传发货数据表');
  2212. /** @var FileService $readExcelService */
  2213. $readExcelService = app()->make(FileService::class);
  2214. $exprData = $readExcelService->readExcel($file, $row);
  2215. if (!$exprData) throw new AdminException('发货数据为空');
  2216. return $exprData;
  2217. }
  2218. /**
  2219. * 队列发货
  2220. * @return bool
  2221. * @throws \think\db\exception\DataNotFoundException
  2222. * @throws \think\db\exception\DbException
  2223. * @throws \think\db\exception\ModelNotFoundException
  2224. */
  2225. public function adminQueueOrderDo(array $data, bool $is_again = false)
  2226. {
  2227. if (!$data) return false;
  2228. /** @var QueueServices $queueService */
  2229. $queueService = app()->make(QueueServices::class);
  2230. /** @var QueueAuxiliaryServices $auxiliaryService */
  2231. $auxiliaryService = app()->make(QueueAuxiliaryServices::class);
  2232. $queueWhere['type'] = $data['queueType'];
  2233. $queueWhere['status'] = 0;
  2234. if (isset($data['queueId']) && $data['queueId']) $queueWhere['id'] = $data['queueId'];
  2235. $queueInfo = $queueService->getQueueOne($queueWhere);
  2236. $ids = $auxiliaryService->getCacheOidList($queueInfo['id'], $data['cacheType']);
  2237. $data['ids'] = array_column($ids, 'relation_id');
  2238. $data['queueId'] = $queueInfo['id'];
  2239. //if ($queueInfo['status'] == 2) throw new ValidateException('任务已完成');
  2240. //把队列需要执行的入参数据存起来,以便队列执行失败后接着执行,同时队列状态改为正在执行状态。
  2241. $queueService->setQueueDoing($data, $queueInfo['id'], $is_again);
  2242. $oids = $auxiliaryService->getOrderExpreList(['binding_id' => $queueInfo['id'], 'type' => $data['cacheType'], 'status' => [0, 2]]);
  2243. $oids = $oids ? array_column($oids, 'relation_id') : [];
  2244. // $chunkPids = array_chunk($oids, 1000, true);
  2245. $data['queueId'] = $queueInfo['id'];
  2246. foreach ($oids as $v) {
  2247. //加入队列
  2248. BatchHandleJob::dispatch([$v, $data['queueType'], $data]);
  2249. }
  2250. return true;
  2251. }
  2252. /**
  2253. * 对外接口获取订单状态
  2254. * @param int $oid
  2255. */
  2256. public function outGetStatus(string $oid)
  2257. {
  2258. $order = $this->dao->getOne(['order_id' => $oid]);
  2259. if (!$order['paid'] && $order['pay_type'] == 'offline' && !$order['status'] >= 2) {
  2260. $status_name = '线下支付';
  2261. } else if (!$order['paid']) {
  2262. $status_name = '未支付';
  2263. } else if ($order['status'] == 0 && $order['refund_status'] == 0) {
  2264. $status_name = '待发货';
  2265. } else if ($order['refund_status'] == 1) {
  2266. $status_name = '申请退款中';
  2267. } else if ($order['refund_status'] == 2) {
  2268. $status_name = '已退款';
  2269. } else if ($order['refund_status'] == 3) {
  2270. $status_name = '部分退款(子订单)';
  2271. } else if ($order['refund_status'] == 4) {
  2272. $status_name = '子订单已全部申请退款中';
  2273. } else if (!$order['status']) {
  2274. $status_name = '未发货';
  2275. } else if ($order['status'] == 1) {
  2276. $status_name = '待收货';
  2277. } else if ($order['status'] == 2) {
  2278. $status_name = '待评价';
  2279. } else if ($order['status'] == 3) {
  2280. $status_name = '交易完成';
  2281. }
  2282. $data = [];
  2283. $data['status_name'] = $status_name;
  2284. $data['status'] = $order['status'];
  2285. $data['paid'] = $order['paid'];
  2286. $data['pay_type'] = $order['pay_type'];
  2287. $data['refund_status'] = $order['refund_status'];
  2288. return $data;
  2289. }
  2290. /**
  2291. * 对外接口根据订单id查询收货方式
  2292. * @param string $oid
  2293. * @return array
  2294. */
  2295. public function outGetShippingType(string $oid)
  2296. {
  2297. $shipping_type = $this->dao->value(['order_id' => $oid], 'shipping_type');
  2298. $shipping_type = $shipping_type == 1 ? '商家配送' : '到店自提';
  2299. return compact('shipping_type');
  2300. }
  2301. /**
  2302. * 对外接口根据订单id查询配送信息
  2303. * @param string $oid
  2304. * @return array|\think\Model|null
  2305. * @throws \think\db\exception\DataNotFoundException
  2306. * @throws \think\db\exception\DbException
  2307. * @throws \think\db\exception\ModelNotFoundException
  2308. */
  2309. public function OutDeliveryType(string $oid)
  2310. {
  2311. $info = $this->dao->getOne(['order_id' => $oid], 'order_id,delivery_type,delivery_name,delivery_id');
  2312. return $info ? $info->toArray() : [];
  2313. }
  2314. /**
  2315. * 对外接口获取运费
  2316. * @param int $cartId
  2317. * @param int $uid
  2318. * @param int $addressId
  2319. * @return array
  2320. * @throws \Psr\SimpleCache\InvalidArgumentException
  2321. */
  2322. public function outGetPostage($cartId, int $uid, int $addressId, int $couponId = 0)
  2323. {
  2324. $addr = [];
  2325. /** @var UserAddressServices $addressServices */
  2326. $addressServices = app()->make(UserAddressServices::class);
  2327. /** @var UserServices $userServices */
  2328. $userServices = app()->make(UserServices::class);
  2329. $user = $userServices->get($uid);
  2330. if ($addressId) {
  2331. $addr = $addressServices->getAdderssCache($addressId);
  2332. }
  2333. //没传地址id或地址已删除未找到 ||获取默认地址
  2334. if (!$addr) {
  2335. $addr = $addressServices->getUserDefaultAddressCache($uid);
  2336. }
  2337. /** @var StoreCartServices $cartServices */
  2338. $cartServices = app()->make(StoreCartServices::class);
  2339. $cartGroup = $cartServices->getUserProductCartListV1($uid, $cartId, true, $addr);
  2340. $storeFreePostage = floatval(sys_config('store_free_postage')) ?: 0;//满额包邮金额
  2341. $validCartInfo = $cartGroup['valid'];
  2342. /** @var StoreOrderComputedServices $computedServices */
  2343. $computedServices = app()->make(StoreOrderComputedServices::class);
  2344. $priceGroup = $computedServices->getOrderPriceGroup($validCartInfo, $addr, $user, $storeFreePostage);
  2345. $postage = $priceGroup['storePostage'] ?? 0;
  2346. return compact('postage');
  2347. }
  2348. /**
  2349. * 获取配送员订单统计列表
  2350. * @param array $where
  2351. * @return array
  2352. * @throws \think\db\exception\DataNotFoundException
  2353. * @throws \think\db\exception\DbException
  2354. * @throws \think\db\exception\ModelNotFoundException
  2355. */
  2356. public function getDeliveryStatistics(array $where)
  2357. {
  2358. [$page, $limit] = $this->getPageValue();
  2359. $where['is_del'] = 0;
  2360. $where['paid'] = 1;
  2361. $where['is_system_del'] = 0;
  2362. $where['delivery_type'] = 'send';
  2363. $where['refund_status'] = [0, 3];
  2364. $list = $this->dao->getList((array)$where, ['*'], (int)$page, (int)$limit, ['user']);
  2365. if ($list) {
  2366. $list = $this->tidyOrderList($list, false);
  2367. }
  2368. $count = $this->dao->count($where);
  2369. return compact('list', 'count');
  2370. }
  2371. /**
  2372. * 配送员订单统计
  2373. * @param $store_id
  2374. * @param $delivery_uid
  2375. * @param $time
  2376. * @return array
  2377. * @throws \think\db\exception\DataNotFoundException
  2378. * @throws \think\db\exception\DbException
  2379. * @throws \think\db\exception\ModelNotFoundException
  2380. */
  2381. public function getStatisticsHeader($store_id, $delivery_uid, $time)
  2382. {
  2383. $where['is_del'] = 0;
  2384. $where['paid'] = 1;
  2385. $where['is_system_del'] = 0;
  2386. $where['delivery_type'] = 'send';
  2387. $where['store_id'] = $store_id;
  2388. $where['refund_status'] = [0, 3];
  2389. if ($delivery_uid) {
  2390. $where['delivery_uid'] = $delivery_uid;
  2391. }
  2392. [$start, $end, $timeType, $xAxis] = $time;
  2393. $order = $this->dao->orderAddTimeList($where, [$start, $end], $timeType, false);
  2394. $price = array_column($order, 'price', 'day');
  2395. $count = array_column($order, 'count', 'day');
  2396. $data = $series = [];
  2397. foreach ($xAxis as $key) {
  2398. $data['配送订单金额'][] = isset($price[$key]) ? floatval($price[$key]) : 0;
  2399. $data['配送单数'][] = isset($count[$key]) ? floatval($count[$key]) : 0;
  2400. }
  2401. foreach ($data as $key => $item) {
  2402. $series[] = [
  2403. 'name' => $key,
  2404. 'data' => $item,
  2405. 'type' => 'line',
  2406. 'smooth' => 'true',
  2407. 'yAxisIndex' => 1,
  2408. ];
  2409. }
  2410. return compact('xAxis', 'series');
  2411. }
  2412. /**
  2413. * 门店线上支付订单详情
  2414. * @param int $store
  2415. * @param int $uid
  2416. * @return mixed
  2417. * @throws \think\db\exception\DataNotFoundException
  2418. * @throws \think\db\exception\DbException
  2419. * @throws \think\db\exception\ModelNotFoundException
  2420. */
  2421. public function payCashierOrder(int $store, int $uid)
  2422. {
  2423. $order = $this->dao->payCashierOrder($store, $uid);
  2424. if (!$order) throw new ValidateException('订单不存在');
  2425. $order = $order->toArray();
  2426. $order = $this->tidyOrder($order, true);
  2427. $order['yue_pay_status'] = (int)sys_config('balance_func_status') && (int)sys_config('yue_pay_status') == 1 ? (int)1 : (int)2;//余额支付 1 开启 2 关闭
  2428. $order['pay_weixin_open'] = (int)sys_config('pay_weixin_open') ?? 0;//微信支付 1 开启 0 关闭
  2429. $order['ali_pay_status'] = (bool)sys_config('ali_pay_status');//支付包支付 1 开启 0 关闭
  2430. return $order;
  2431. }
  2432. /**
  2433. * 订单分配|重新分配给你门店
  2434. * @param int $id
  2435. * @param int $store_id
  2436. * @return mixed
  2437. * @throws \think\db\exception\DataNotFoundException
  2438. * @throws \think\db\exception\DbException
  2439. * @throws \think\db\exception\ModelNotFoundException
  2440. */
  2441. public function shareOrder(int $id, int $store_id)
  2442. {
  2443. $orderInfo = $this->dao->get((int)$id);
  2444. if (!$orderInfo) {
  2445. throw new ValidateException('订单不存在');
  2446. }
  2447. //卡密商品
  2448. if ($orderInfo['product_type'] == 1) {
  2449. throw new ValidateException('订单中卡密商品门店暂不支持');
  2450. }
  2451. /** @var SystemStoreServices $storeServices */
  2452. $storeServices = app()->make(SystemStoreServices::class);
  2453. $storeInfo = $storeServices->getStoreInfo($store_id);
  2454. if ($orderInfo['status'] != 0) {
  2455. throw new ValidateException('订单已发货');
  2456. }
  2457. /** @var StoreOrderCartInfoServices $storeOrderCartInfoServices */
  2458. $storeOrderCartInfoServices = app()->make(StoreOrderCartInfoServices::class);
  2459. $cart_info = $storeOrderCartInfoServices->getSplitCartList($id, 'cart_info');
  2460. if (!$cart_info) {
  2461. throw new ValidateException('订单已发货');
  2462. }
  2463. /** @var StoreOrderRefundServices $storeOrderRefundServices */
  2464. $storeOrderRefundServices = app()->make(StoreOrderRefundServices::class);
  2465. if ($storeOrderRefundServices->count(['store_order_id' => $id, 'refund_type' => [1, 2, 4, 5, 6], 'is_cancel' => 0, 'is_del' => 0])) {
  2466. throw new ValidateException('订单有售后申请请先处理');
  2467. }
  2468. $platProductIds = [];
  2469. $platStoreProductIds = [];
  2470. $storeProductIds = [];
  2471. foreach ($cart_info as $cart) {
  2472. $productInfo = $cart['productInfo'] ?? [];
  2473. if (isset($productInfo['store_delivery']) && !$productInfo['store_delivery']) {//有商品不支持门店配送
  2474. return [[], $cart_info];
  2475. }
  2476. switch ($productInfo['type'] ?? 0) {
  2477. case 0://平台
  2478. case 2://供应商
  2479. $platProductIds[] = $cart['product_id'];
  2480. break;
  2481. case 1://门店
  2482. if ($productInfo['pid']) {//门店自有商品
  2483. $storeProductIds[] = $cart['product_id'];
  2484. } else {
  2485. $platStoreProductIds[] = $cart['product_id'];
  2486. }
  2487. break;
  2488. }
  2489. }
  2490. if ($storeProductIds && $store_id != $orderInfo['store_id']) {
  2491. throw new ValidateException('该门店商品未上架或未设置库存');
  2492. }
  2493. /** @var StoreBranchProductServices $branchProductServics */
  2494. $branchProductServics = app()->make(StoreBranchProductServices::class);
  2495. //转换成平台商品
  2496. if ($platStoreProductIds) {
  2497. $ids = $branchProductServics->getStoreProductIds($platStoreProductIds);
  2498. $platProductIds = array_merge($platProductIds, $ids);
  2499. }
  2500. $productCount = count($platProductIds);
  2501. //商品没下架 && 库存足够
  2502. if ($productCount != $branchProductServics->count(['pid' => $platProductIds, 'is_show' => 1, 'is_del' => 0, 'type' => 1, 'relation_id' => $store_id])) {
  2503. throw new ValidateException('该门店商品未上架或未设置库存');
  2504. }
  2505. /** @var StoreProductAttrValueServices $skuValueServices */
  2506. $skuValueServices = app()->make(StoreProductAttrValueServices::class);
  2507. foreach ($cart_info as $cart) {
  2508. if (isset($cart['productInfo']['store_delivery']) && !$cart['productInfo']['store_delivery']) {//有商品不支持门店配送
  2509. throw new ValidateException('有商品不支持门店配送');
  2510. }
  2511. switch ($cart['type']) {
  2512. case 0:
  2513. case 6:
  2514. case 8:
  2515. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['product_id'], 'type' => 0], 'suk');
  2516. break;
  2517. case 1:
  2518. case 2:
  2519. case 3:
  2520. case 5:
  2521. case 7:
  2522. $suk = $skuValueServices->value(['unique' => $cart['product_attr_unique'], 'product_id' => $cart['activity_id'], 'type' => $cart['type']], 'suk');
  2523. break;
  2524. }
  2525. $branchProductInfo = $branchProductServics->isValidStoreProduct((int)$cart['product_id'], $store_id);
  2526. if (!$branchProductInfo) {
  2527. throw new ValidateException('该门店商品库存不足');
  2528. }
  2529. $attrValue = $skuValueServices->get(['suk' => $suk, 'product_id' => $branchProductInfo['id'], 'type' => 0]);
  2530. if (!$attrValue) {
  2531. throw new ValidateException('该门店商品库存不足');
  2532. }
  2533. }
  2534. $res = $this->transaction(function () use ($id, $store_id, $orderInfo, $storeInfo, $cart_info, $branchProductServics) {
  2535. if ($orderInfo['store_id'] > 0) {//重新分配门店
  2536. //返还原来门店库存
  2537. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 0);
  2538. } else {
  2539. //返还平台库存
  2540. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, 0, -1);
  2541. }
  2542. //扣门店库存
  2543. $res = $branchProductServics->regressionBranchProductStock($orderInfo, $cart_info, -1, 1, $store_id);
  2544. $res = $res && $this->dao->update($id, ['store_id' => $storeInfo['id'], 'shipping_type' => $orderInfo['shipping_type'] == 1 ? 3 : $orderInfo['shipping_type']]);
  2545. return $res;
  2546. });
  2547. $orderInfo['store_id'] = $storeInfo['id'];
  2548. //删除之前的账单记录
  2549. /** @var StoreFinanceFlowServices $storeFinanceFlowServices */
  2550. $storeFinanceFlowServices = app()->make(StoreFinanceFlowServices::class);
  2551. $storeFinanceFlowServices->update(['link_id' => $orderInfo['order_id']], ['is_del' => 1]);
  2552. //分配后置方法
  2553. SpliteStoreOrderJob::dispatchDo('splitAfter', [$orderInfo, true]);
  2554. return $res;
  2555. }
  2556. /**
  2557. * 获取退货商品列表
  2558. * @param array $cart_ids
  2559. * @param int $id
  2560. * @return array
  2561. * @throws \think\db\exception\DataNotFoundException
  2562. * @throws \think\db\exception\DbException
  2563. * @throws \think\db\exception\ModelNotFoundException
  2564. */
  2565. public function refundCartInfoList(array $cart_ids = [], int $id = 0)
  2566. {
  2567. $orderInfo = $this->dao->get($id);
  2568. if (!$orderInfo) {
  2569. throw new ValidateException('订单不存在');
  2570. }
  2571. $orderInfo = $this->tidyOrder($orderInfo, true);
  2572. $cartInfo = $orderInfo['cartInfo'] ?? [];
  2573. $data = [];
  2574. if ($cart_ids) {
  2575. foreach ($cart_ids as $cart) {
  2576. if (!isset($cart['cart_id']) || !$cart['cart_id']) {
  2577. throw new ValidateException('请重新选择退款商品,或件数');
  2578. }
  2579. }
  2580. $cart_ids = array_combine(array_column($cart_ids, 'cart_id'), $cart_ids);
  2581. $i = 0;
  2582. foreach ($cartInfo as $item) {
  2583. if (isset($cart_ids[$item['id']])) {
  2584. $data['cartInfo'][$i] = $item;
  2585. if (isset($cart_ids[$item['id']]['cart_num'])) $data['cartInfo'][$i]['cart_num'] = $cart_ids[$item['id']]['cart_num'];
  2586. $i++;
  2587. }
  2588. }
  2589. }
  2590. $data['_status'] = $orderInfo['_status'] ?? [];
  2591. $data['cartInfo'] = $data['cartInfo'] ?? $cartInfo;
  2592. return $data;
  2593. }
  2594. /**
  2595. * 拆单的发货订单数量
  2596. * @param int $id
  2597. * @param $order
  2598. * @return int
  2599. * @throws \think\db\exception\DataNotFoundException
  2600. * @throws \think\db\exception\DbException
  2601. * @throws \think\db\exception\ModelNotFoundException
  2602. */
  2603. public function getDeliverNum(int $id, $order): int
  2604. {
  2605. if (!$order) {
  2606. $order = $this->get($id);
  2607. }
  2608. $ids = $id;
  2609. $pid = (int)$order['pid'];
  2610. if ($pid > 0) {
  2611. $ids = $this->Value([['pid', '=', $pid], ['status', '=', 1]], 'GROUP_CONCAT(id)');
  2612. if (!empty($ids)) {
  2613. $ids = array_map('intval', array_filter(explode(',', $ids)));
  2614. }
  2615. }
  2616. return $this->getCount(['id' => $ids, 'status' => 1]);
  2617. }
  2618. /**
  2619. * 获取确认订单页面是否展示快递配送和到店自提
  2620. * @param $uid
  2621. * @param $cartIds
  2622. * @param $new
  2623. * @return array
  2624. * @throws \Psr\SimpleCache\InvalidArgumentException
  2625. */
  2626. public function checkShipping($uid, $cartIds, $new)
  2627. {
  2628. if ($new) {
  2629. $cartIds = explode(',', $cartIds);
  2630. $cartInfo = [];
  2631. $redis = CacheService::redisHandler();
  2632. foreach ($cartIds as $key) {
  2633. $info = $redis->get($key);
  2634. if ($info) {
  2635. $cartInfo[] = $info;
  2636. }
  2637. }
  2638. } else {
  2639. /** @var StoreCartServices $cartServices */
  2640. $cartServices = app()->make(StoreCartServices::class);
  2641. $cartInfo = $cartServices->getCartList(['uid' => $uid, 'status' => 1, 'id' => $cartIds], 0, 0, ['productInfo', 'attrInfo']);
  2642. }
  2643. if (!$cartInfo) {
  2644. throw new ValidateException('获取购物车信息失败');
  2645. }
  2646. $arr = [];
  2647. $store_id = [];
  2648. //delivery_type :1、快递,2、到店自提,3、门店配送
  2649. foreach ($cartInfo as $item) {
  2650. $delivery_type = is_string($item['productInfo']['delivery_type']) ? explode(',', $item['productInfo']['delivery_type']) : $item['productInfo']['delivery_type'];
  2651. if (in_array(1, $delivery_type)) {//支持平台配送 验证平台该商品
  2652. $productInfo = $item['productInfo'] ?? [];
  2653. if ($productInfo && isset($productInfo['type']) && $productInfo['type'] == 1 && isset($productInfo['pid']) && $productInfo['pid']) {
  2654. /** @var StoreProductServices $productServices */
  2655. $productServices = app()->make(StoreProductServices::class);
  2656. $platInfo = $productServices->getCacheProductInfo((int)$productInfo['pid']);
  2657. if (!$platInfo || $platInfo['stock'] <= 0) {
  2658. unset($delivery_type[array_search('1', $delivery_type)]);
  2659. }
  2660. }
  2661. }
  2662. $arr = array_merge($arr, $delivery_type);
  2663. if (isset($item['productInfo']['type']) && isset($item['productInfo']['relation_id']) && $item['productInfo']['type'] == 1 && $item['productInfo']['relation_id']) {
  2664. $store_id[] = $item['productInfo']['relation_id'];
  2665. }
  2666. }
  2667. $count = count($arr);
  2668. if (!$count) {
  2669. $arr = [1, 2, 3];
  2670. }
  2671. // 门店总开关
  2672. if (!sys_config('store_func_status', 1)) {
  2673. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2674. if (in_array(3, $arr)) unset($arr[array_search(3, $arr)]);
  2675. } elseif (sys_config('store_self_mention', 1)) {
  2676. //判断有没有满足自提的店铺
  2677. $where['id'] = $store_id;
  2678. $where['is_store'] = 1;
  2679. $where['is_show'] = 1;
  2680. $where['is_del'] = 0;
  2681. /** @var SystemStoreServices $SystemStoreServe */
  2682. $SystemStoreServe = app()->make(SystemStoreServices::class);
  2683. $store_list = $SystemStoreServe->count($where);
  2684. if (!$store_list) {
  2685. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2686. }
  2687. } else {
  2688. if (in_array(2, $arr)) unset($arr[array_search(2, $arr)]);
  2689. }
  2690. $arr = array_merge(array_unique($arr));
  2691. return ['type' => $arr];
  2692. }
  2693. /**
  2694. * @param int $pid
  2695. * @param int $order_id
  2696. * @return bool
  2697. * @throws \think\db\exception\DbException
  2698. */
  2699. public function checkSubOrderNotSend(int $pid, int $order_id)
  2700. {
  2701. $order_count = $this->dao->getSubOrderNotSend($pid, $order_id);
  2702. if ($order_count > 0) {
  2703. return false;
  2704. } else {
  2705. return true;
  2706. }
  2707. }
  2708. /**
  2709. * @param int $pid
  2710. * @param int $order_id
  2711. * @return bool
  2712. * @throws \think\db\exception\DbException
  2713. */
  2714. public function checkSubOrderNotTake(int $pid, int $order_id)
  2715. {
  2716. $order_count = $this->dao->getSubOrderNotTake($pid, $order_id);
  2717. if ($order_count > 0) {
  2718. return false;
  2719. } else {
  2720. return true;
  2721. }
  2722. }
  2723. /**
  2724. * 地区返佣
  2725. * @param $orderInfo
  2726. * @param $userInfo
  2727. * @return bool
  2728. */
  2729. public function backAreaBrokerage()
  2730. {
  2731. //商城分销功能是否开启 0关闭1开启
  2732. if (!sys_config('brokerage_func_status')) return true;
  2733. if (sys_config('area_award_time') <= 0) return true;
  2734. $last_time = sys_config('area_award_last_time');
  2735. if ($last_time + (3600 * (sys_config('area_award_time'))) > time()) {
  2736. return true;
  2737. }
  2738. //冻结时间
  2739. $broken_time = intval(sys_config('extract_time'));
  2740. $frozen_time = time() + $broken_time * 86400;
  2741. $userServices = app()->make(UserServices::class);
  2742. $storeOrderServices = app()->make(StoreOrderServices::class);
  2743. $res = true;
  2744. // 获取上级推广员信息
  2745. /** @var UserServices $userServices */
  2746. //找有代理的省
  2747. $provinces = $userServices->search()->where('area_admin', 3)->column('area_admin_province');
  2748. $provinces = array_unique($provinces);
  2749. foreach ($provinces as $value) {
  2750. $order_price = $storeOrderServices->search(['pid' => 0])->where('order_province', $value)
  2751. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2752. ->where('send_area_award', 0)
  2753. ->where('paid', 1)
  2754. ->where('is_del', 0)
  2755. ->where('is_system_del', 0)
  2756. ->where('refund_status', 0)
  2757. ->whereIn('status', [2, 3])
  2758. ->field('sum(total_price-cost) as total_price_sum')
  2759. ->find();
  2760. $order_price = $order_price['total_price_sum'] ?? 0;
  2761. if ($order_price <= 0) {
  2762. continue;
  2763. }
  2764. //找省代
  2765. $admins = $userServices->search()->where('area_admin', 3)->where('area_admin_province', $value)->select();
  2766. if (count($admins) > 0) {
  2767. $award = bcdiv(bcmul((string)sys_config('province_award'), (string)$order_price, 2), 100, 2);
  2768. if ($award > 0) {
  2769. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2770. if ($brokeragePrice > 0) {
  2771. foreach ($admins as $v) {
  2772. $spreadPrice = (string)$v['brokerage_price'];
  2773. // 上级推广员返佣之后的金额
  2774. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2775. // 添加佣金记录
  2776. /** @var UserBrokerageServices $userBrokerageServices */
  2777. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2778. $type = 'get_area_award';
  2779. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2780. 'pay_price' => floatval($order_price),
  2781. 'area' => $value . '省级',
  2782. 'number' => floatval($brokeragePrice),
  2783. 'frozen_time' => $frozen_time
  2784. ], $balance, 0);
  2785. // 添加用户佣金
  2786. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2787. $res = $res1 && $res2 && $res;
  2788. }
  2789. }
  2790. }
  2791. }
  2792. }
  2793. $citys = $userServices->search()->where('area_admin', 2)->select();
  2794. $pc = [];
  2795. foreach ($citys as $v) {
  2796. $p = $v['area_admin_province'];
  2797. $c = $v['area_admin_city'];
  2798. if (!in_array(compact('p', 'c'), $pc)) {
  2799. $pc[] = compact('p', 'c');
  2800. }
  2801. }
  2802. foreach ($pc as $value) {
  2803. $order_price = $storeOrderServices->search(['pid' => 0])->where('order_province', $value['p'])->where('order_city', $value['c'])
  2804. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2805. ->where('send_area_award', 0)
  2806. ->where('paid', 1)
  2807. ->where('is_del', 0)
  2808. ->where('is_system_del', 0)
  2809. ->where('refund_status', 0)
  2810. ->whereIn('status', [2, 3])
  2811. ->field('sum(total_price-cost) as total_price_sum')
  2812. ->find();
  2813. $order_price = $order_price['total_price_sum'] ?? 0;
  2814. if ($order_price <= 0) {
  2815. continue;
  2816. }
  2817. //找市代
  2818. $admins = $userServices->search()->where('area_admin', 2)->where('area_admin_province', $value['p'])
  2819. ->where('area_admin_city', $value['c'])->select();
  2820. if (count($admins) > 0) {
  2821. $award = bcdiv(bcmul((string)sys_config('city_award'), (string)$order_price, 2), 100, 2);
  2822. if ($award > 0) {
  2823. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2824. if ($brokeragePrice > 0) {
  2825. foreach ($admins as $v) {
  2826. $spreadPrice = (string)$v['brokerage_price'];
  2827. // 上级推广员返佣之后的金额
  2828. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2829. // 添加佣金记录
  2830. /** @var UserBrokerageServices $userBrokerageServices */
  2831. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2832. $type = 'get_area_brokerage';
  2833. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2834. 'pay_price' => floatval($order_price),
  2835. 'area' => $value['p'] . $value['c'] . '级',
  2836. 'number' => floatval($brokeragePrice),
  2837. 'frozen_time' => $frozen_time
  2838. ], $balance, 0);
  2839. // 添加用户佣金
  2840. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2841. $res = $res1 && $res2 && $res;
  2842. }
  2843. }
  2844. }
  2845. }
  2846. }
  2847. $citys = $userServices->search()->where('area_admin', 1)->select();
  2848. $pcd = [];
  2849. foreach ($citys as $v) {
  2850. $p = $v['area_admin_province'];
  2851. $c = $v['area_admin_city'];
  2852. $d = $v['area_admin_district'];
  2853. if (!in_array(compact('p', 'c', 'd'), $pcd)) {
  2854. $pcd[] = compact('p', 'c', 'd');
  2855. }
  2856. }
  2857. foreach ($pcd as $value) {
  2858. $order_price = $storeOrderServices->search(['pid' => 0])
  2859. ->where('order_province', $value['p'])
  2860. ->where('order_city', $value['c'])
  2861. ->where('order_district', $value['d'])
  2862. ->whereNotIn('type', [1, 2, 3, 5, 8])
  2863. ->where('send_area_award', 0)
  2864. ->where('paid', 1)
  2865. ->where('is_del', 0)
  2866. ->where('is_system_del', 0)
  2867. ->where('refund_status', 0)
  2868. ->whereIn('status', [2, 3])
  2869. ->field('sum(total_price-cost) as total_price_sum')
  2870. ->find();
  2871. $order_price = $order_price['total_price_sum'] ?? 0;
  2872. if ($order_price <= 0) {
  2873. continue;
  2874. }
  2875. //找区代
  2876. $admins = $userServices->search()->where('area_admin', 1)
  2877. ->where('area_admin_province', $value['p'])
  2878. ->where('area_admin_city', $value['c'])
  2879. ->where('area_admin_district', $value['d'])
  2880. ->select();
  2881. if (count($admins) > 0) {
  2882. $award = bcdiv(bcmul((string)sys_config('district_award'), (string)$order_price, 2), 100, 2);
  2883. if ($award > 0) {
  2884. $brokeragePrice = bcdiv($award, (string)count($admins), 2);
  2885. if ($brokeragePrice > 0) {
  2886. foreach ($admins as $v) {
  2887. $spreadPrice = (string)$v['brokerage_price'];
  2888. // 上级推广员返佣之后的金额
  2889. $balance = bcadd($spreadPrice, $brokeragePrice, 2);
  2890. // 添加佣金记录
  2891. /** @var UserBrokerageServices $userBrokerageServices */
  2892. $userBrokerageServices = app()->make(UserBrokerageServices::class);
  2893. $type = 'get_area_brokerage';
  2894. $res1 = $userBrokerageServices->income($type, $v['uid'], [
  2895. 'pay_price' => floatval($order_price),
  2896. 'area' => $value['p'] . $value['c'] . $value['d'] . '级',
  2897. 'number' => floatval($brokeragePrice),
  2898. 'frozen_time' => $frozen_time
  2899. ], $balance, 0);
  2900. // 添加用户佣金
  2901. $res2 = $userServices->bcInc($v['uid'], 'brokerage_price', $brokeragePrice, 'uid');
  2902. $res = $res1 && $res2 && $res;
  2903. }
  2904. }
  2905. }
  2906. }
  2907. }
  2908. return $res
  2909. && $storeOrderServices->search()->where('send_area_award', 0)->update(['send_area_award' => 1])
  2910. && SystemConfig::where('menu_name', 'area_award_last_time')->update(['value' => time()]);
  2911. }
  2912. }