OrderEvent.php 140 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\events;
  8. use app\constants\OptionSetting;
  9. use app\models\AgentGoodsBindGoods;
  10. use app\models\AgentGoodsInstallLog;
  11. use app\models\Cash;
  12. use app\models\ReportInfo;
  13. use app\models\ReportPool;
  14. use app\models\ReportPoolLevel;
  15. use app\models\ReportSetting;
  16. use app\models\SaaSLeaguePriceLog;
  17. use app\models\PtActivity;
  18. use app\models\PtActivityOrder;
  19. use app\models\PtActivityOrderDetail;
  20. use app\models\SaasUserPriceLog;
  21. use app\models\AccountLog;
  22. use app\models\Admin;
  23. use app\models\Coupon;
  24. use app\models\DeliveryInfo;
  25. use app\models\Goods;
  26. use app\models\Level;
  27. use app\models\LocalDeliveryCourier;
  28. use app\models\LocalDeliveryLog;
  29. use app\models\Md;
  30. use app\models\MdProfit;
  31. use app\models\MerchantInfo;
  32. use app\models\Option;
  33. use app\models\Order;
  34. use app\models\OrderDetail;
  35. use app\models\OrderRefund;
  36. use app\models\ReOrder;
  37. use app\models\SaasUser;
  38. use app\models\Salesman;
  39. use app\models\SeckillActivityGoods;
  40. use app\models\SeckillActivityOrderLog;
  41. use app\models\Share;
  42. use app\models\ShareHolder;
  43. use app\models\ShareLevel;
  44. use app\models\ShareLevelLog;
  45. use app\models\SharingReceiver;
  46. use app\models\Shop;
  47. use app\models\ShopShare;
  48. use app\models\Store;
  49. use app\models\StoreCash;
  50. use app\models\StoreShareMoney;
  51. use app\models\Supplier;
  52. use app\models\TeamGrades;
  53. use app\models\User;
  54. use app\models\UserBindLog;
  55. use app\models\UserCoupon;
  56. use app\models\UserShareLog;
  57. use app\models\UserShareMoney;
  58. use app\models\VideoGoodsShare;
  59. use app\models\VideoShopOrderExt;
  60. use app\models\WechatConfig;
  61. use app\models\Worker;
  62. use app\models\WorkerLevel;
  63. use app\models\WorkerOrderExt;
  64. use app\modules\admin\models\pt\PtActivityOrderForm;
  65. use app\plugins\adopt\models\AdoptCostOrder;
  66. use app\plugins\adopt\models\AdoptOrderInfo;
  67. use app\plugins\adopt\models\AdoptSetting;
  68. use app\plugins\food\models\FoodOrder;
  69. use app\utils\Alipay\AlipayProfit;
  70. use app\utils\Notice\NoticeSend;
  71. use app\utils\Share\BonusPool;
  72. use app\utils\Wechat\Wechat;
  73. use app\utils\Wechat\WechatMini;
  74. use app\utils\Wechat\WechatShare;
  75. use app\utils\WechatMerchant\Merchant;
  76. use app\utils\yunst\src\OrderYunst;
  77. use EasyWeChat\Factory;
  78. use yii\helpers\Json;
  79. use yii\base\Event;
  80. use yii\db\Expression;
  81. use app\utils\Adapay\Adapay;
  82. /**
  83. * 事件类
  84. * Class TestEvent
  85. * @package app\events
  86. */
  87. class OrderEvent extends Event
  88. {
  89. public $store_id = 1;
  90. public function onLoad() {
  91. }
  92. public function orderGrossProfit() {
  93. try{
  94. $list = Order::find()->where(['is_gross_profit' => 0])->limit(10)->asArray()->all();
  95. $form = new \app\modules\admin\models\CostProfitListForm();
  96. $form->commonData($list);
  97. foreach ($list as $item) {
  98. Order::updateAll(['is_gross_profit' => 1, 'gross_profit' => $item['profit']], ['id' => $item['id']]);
  99. }
  100. } catch (\Exception $ex) {
  101. \Yii::error($ex);
  102. }
  103. }
  104. public function shareLevel($store_id) {
  105. try {
  106. // 1 parent_id = u
  107. // 2 parent_id = a a parent_id = u
  108. // 3 parent_id = b c parent_id = d d parent_id = u
  109. $share_level = ShareLevel::find()->where(['store_id' => $store_id, 'is_delete' => ShareLevel::SHARE_NOT_DELETE, 'status' => ShareLevel::STATUS_ON, 'is_auto_upgrade' => ShareLevel::AUTO_UPGRADE])
  110. ->orderBy('level ASC')->asArray()->all();
  111. foreach ($share_level as $level) {
  112. $user_arr = Share::find()->where(['store_id' => $store_id, 'status' => Share::SHARE_AUDIT_PASS, 'is_delete' => Share::SHARE_NOT_DELETE])
  113. ->andWhere(['<', 'level', $level['level']])->select('id, user_id, level')->asArray()->all();
  114. $level['type'] = intval($level['type']);
  115. foreach ($user_arr as $item) {
  116. $open = false;
  117. $type = 0;
  118. $value = 0;
  119. //团队人数
  120. if ($level['type'] === ShareLevel::TYPE_MEMBER) {
  121. $user_count = User::find()->where(['parent_id' => $item['user_id'], 'is_delete' => User::USER_NOT_DELETE, 'store_id' => $store_id, 'is_distributor' => 1])
  122. ->select('id')->count() ?? 0;
  123. if (intval($level['value']) <= $user_count) {
  124. $open = true;
  125. $type = ShareLevel::TYPE_MEMBER;
  126. $value = $user_count;
  127. }
  128. }
  129. //累计佣金
  130. if ($level['type'] === ShareLevel::TYPE_COMMISSION) {
  131. $user_share_money = UserShareMoney::find()->where(['type' => 0, 'is_delete' => 0, 'user_id' => $item['user_id'], 'store_id' => $store_id])
  132. ->select('money')->sum('money') ?? 0;
  133. if (intval($level['value']) <= $user_share_money) {
  134. $open = true;
  135. $type = ShareLevel::TYPE_COMMISSION;
  136. $value = $user_share_money;
  137. }
  138. }
  139. //累计提现佣金
  140. if ($level['type'] === ShareLevel::TYPE_SEND_COMMISSION) {
  141. $user_share_money_ = UserShareMoney::find()->where(['type' => 1, 'is_delete' => 0, 'user_id' => $item['user_id'], 'store_id' => $store_id])
  142. ->select('money')->sum('money') ?? 0;
  143. if (intval($level['value']) <= $user_share_money_) {
  144. $open = true;
  145. $type = ShareLevel::TYPE_SEND_COMMISSION;
  146. $value = $user_share_money_;
  147. }
  148. }
  149. //累计消费金额
  150. if ($level['type'] === ShareLevel::TYPE_AMOUNT) {
  151. $user_pay_price = Order::find()->where(['is_pay' => 1, 'is_delete' => 0, 'user_id' => $item['user_id'], 'store_id' => $store_id])
  152. ->andWhere(['trade_status' => [Order::ORDER_FLOW_NO_SEND, Order::ORDER_FLOW_SEND, Order::ORDER_FLOW_CONFIRM]])
  153. ->select('pay_price')->sum('pay_price') ?? 0;
  154. if (intval($level['value']) <= $user_pay_price) {
  155. $open = true;
  156. $type = ShareLevel::TYPE_AMOUNT;
  157. $value = $user_pay_price;
  158. }
  159. }
  160. if ($open) {
  161. $share = Share::findOne($item['id']);
  162. $share->level = $level['level'];
  163. if ($share->save()) {
  164. $log = new ShareLevelLog();
  165. $log->level = $level['level'];
  166. $log->old_level = $item['level'];
  167. $log->type = $type;
  168. $log->value = $value;
  169. $log->store_id = $store_id;
  170. $log->user_id = $item['user_id'];
  171. $log->save();
  172. }
  173. }
  174. }
  175. }
  176. return [
  177. 'code' => 0,
  178. 'msg' => '处理完成'
  179. ];
  180. } catch (\Exception $e) {
  181. return [
  182. 'code' => 1,
  183. 'msg' => $e->getMessage()
  184. ];
  185. }
  186. }
  187. public function storeWxOrderShipping() {
  188. try{
  189. $form = new \app\modules\admin\models\WechatThirdForm(['store_id' => $this->store_id]);
  190. $form->storeWxOrderShipping($this->store_id);
  191. } catch (\Exception $ex) {
  192. // \Yii::error($ex);
  193. }
  194. }
  195. public function otherThird() {
  196. // 处理商户进件状态
  197. $this->handleMerchant();
  198. $this->handleMerchant(1);
  199. }
  200. /**
  201. * 执行奖金池自动发放
  202. * @return void
  203. */
  204. public function reportPool() {
  205. //自动检查奖金池是否需要新增
  206. $this->autoCheckPool();
  207. // 处理奖金池自动发放
  208. $this->autoReportPool();
  209. }
  210. public function bonusPool() {
  211. }
  212. public function autoReportPool()
  213. {
  214. $ReportPoolArray = ReportPool::find()->where(['store_id'=>$this->store_id])
  215. ->andWhere(['is_send'=>0])
  216. ->andWhere(['!=','reward_amount',0])
  217. ->andWhere(['<=', 'end_time',time()])
  218. // ->andWhere(['<=', 'start_time',time()])
  219. ->orderBy('id asc')
  220. ->asArray()
  221. ->all();
  222. if(empty($ReportPoolArray)){
  223. return;
  224. }
  225. \Yii::error('---------------------- REPORT POOL BEHAVIOR START------------------' . $this->store_id . '--' . count($ReportPoolArray));
  226. if (!empty($ReportPoolArray)) {
  227. foreach ($ReportPoolArray as $ReportPoolItem) {
  228. $report_info_num = ReportInfo::find()->where(['store_id' => $ReportPoolItem['store_id'], 'pool_id'=> $ReportPoolItem['id'], 'status' => 1])->one();
  229. if (!$report_info_num){
  230. debug_log('奖金池没有报单,奖金池id:' . $ReportPoolItem['id']);
  231. continue;
  232. }
  233. //发放奖励到每个level中
  234. //查看所有奖励记录的积分
  235. $report_bonus_sum = ReportPoolLevel::find()
  236. ->where(['store_id' => $ReportPoolItem['store_id'], 'pool_id' => $ReportPoolItem['id']])
  237. ->sum('money');
  238. $report_level_list = ReportPoolLevel::find()
  239. ->where(['store_id' => $ReportPoolItem['store_id'], 'pool_id' => $ReportPoolItem['id']])
  240. ->asArray()
  241. ->all();
  242. foreach ($report_level_list as $key => $report_level_item){
  243. // 总积分/奖励金额 * 个人奖励积分
  244. //奖励金额计算
  245. $reward_amount = $report_bonus_sum / $ReportPoolItem['reward_amount'] * $report_level_item['money'];
  246. //发放奖励到用户表当中记录
  247. $user = User::findOne($report_level_item['user_id']);
  248. $user->updateCounters(['global_money_total' => $reward_amount, 'global_money' => $reward_amount]);
  249. $report_level_info = ReportPoolLevel::findOne($report_level_item['id']);
  250. $report_level_info->is_send = 1;
  251. $report_level_info->dividend_money = $reward_amount;
  252. $report_level_info->send_time = time();
  253. if (!$report_level_info->save()){
  254. debug_log('分发用户id:'.$report_level_info->id.'奖金池id:'.$ReportPoolItem['id']);
  255. }
  256. }
  257. //奖金池也设置已完成
  258. ReportPool::updateAll(['is_send'=>1,'send_time'=>time()],['id' => $ReportPoolItem['id']]);
  259. //报单列表更新已完成
  260. ReportInfo::updateAll(['is_send'=>1,'send_time'=>time()],['pool_id' => $ReportPoolItem['id']]);
  261. }
  262. }
  263. \Yii::error('---------------------- REPORT POOL BEHAVIOR END------------------');
  264. return false;
  265. }
  266. /**
  267. * 检查奖金池是否需要新增
  268. * @return void
  269. */
  270. public function autoCheckPool()
  271. {
  272. $list = ReportPool::find()->where(['store_id'=>$this->store_id])
  273. ->andWhere(['>=', 'end_time',time()])
  274. ->andWhere(['<=', 'start_time',time()])
  275. ->andWhere(['is_send'=>0])
  276. ->orderBy('id asc')
  277. ->asArray()
  278. ->one();
  279. if(!$list){
  280. $report_setting = ReportSetting::findOne(['store_id' => $this->store_id]);
  281. if (!$report_setting->dividend_day){
  282. debug_log('未设置奖金池分红周期');
  283. return;
  284. }
  285. //如果奖金池不存在就新增奖池
  286. $pool_info = new ReportPool();
  287. $pool_info->store_id = $this->store_id;
  288. $pool_info->start_time = time();
  289. $pool_info->end_time = time() + $report_setting->dividend_day * 24 * 60 * 60;
  290. $pool_info->created_at = time();
  291. $pool_info_copy = ReportPool::find()->where(['store_id'=>$this->store_id])
  292. ->orderBy('id desc')
  293. ->one();
  294. if ($pool_info_copy){
  295. $pool_info->number = $pool_info_copy->number+1;
  296. }else{
  297. $pool_info->number =1;
  298. }
  299. if (!$pool_info->save()){
  300. debug_log('奖金池新增失败');
  301. }
  302. }
  303. }
  304. public function handleMerchant($is_yunst = 0) {
  305. $list = MerchantInfo::find()->where(['!=', 'state', Merchant::APPLYMENT_STATE_FINISHED])
  306. ->andWhere(['!=', 'state', Merchant::APPLYMENT_STATE_CANCELED])
  307. ->andWhere(['>', 'status', 0])
  308. ->andWhere(['bind_store_id' => $this->store_id, 'is_yunst' => $is_yunst, 'is_delete' => 0])->asArray()->all();
  309. if(empty($list)){
  310. return;
  311. }
  312. \Yii::error('---------------------- HANDLE MERCHANT BEHAVIOR START------------------' . $this->store_id . '--' . count($list));
  313. if (!empty($list)) {
  314. try {
  315. if ($is_yunst) {
  316. $merchant = new \app\utils\yunst\src\Merchant();//通联支付
  317. } else {
  318. $merchant = new Merchant();
  319. }
  320. } catch (\Exception $e) {
  321. \Yii::error(['---------------------- HANDLE MERCHANT BEHAVIOR CONFIG ERROR------------------', $e->getMessage()]);
  322. return;
  323. }
  324. foreach ($list as $value) {
  325. if ($is_yunst) {
  326. $res = $merchant->queryMerchantStatus($value['applyment_id']);//通联支付
  327. } else {
  328. $res = $merchant->queryApplyment($value['applyment_id'], $value['business_code']);
  329. if (isset($res['code']) && isset($res['msg'])) {
  330. \Yii::warning(['<=================> 未获取到申请单信息', $res, $value['business_code']]);
  331. continue;
  332. }
  333. }
  334. \Yii::warning(['<=================> 获取到申请单信息', $res, $value['business_code']]);
  335. $merchant_info = MerchantInfo::findOne($value['id']);
  336. //通联支付 start
  337. if ($is_yunst) {
  338. $merchant_info->state = (string)$res['data']['auditstatus'];
  339. if ($res['data']['auditstatus'] == '00'){
  340. $status = 0;
  341. }elseif ($res['data']['auditstatus'] == '01'){
  342. $status = 1;
  343. }elseif ($res['data']['auditstatus'] == '02'){
  344. $status =3;
  345. } elseif ($res['data']['auditstatus'] == '03'){
  346. $status =2;
  347. } elseif ($res['data']['auditstatus'] == '04'){
  348. $status =2;
  349. }
  350. $merchant_info->status = $status;
  351. //通联支付end
  352. } else {
  353. $merchant_info->state = (string)$res['applyment_state'];
  354. $merchant_info->status = Merchant::$valid_state_status[$res['applyment_state']];
  355. if ($res['applyment_state'] === 'APPLYMENT_STATE_CANCELED') {//已撤销
  356. $merchant_info->refuse_desc = "申请单已被撤销,请重新申请";
  357. }
  358. }
  359. $merchant_info->sign_url = "";
  360. $merchant_info->refuse_desc = "";
  361. //通联支付 start
  362. if ($is_yunst) {
  363. if ($res['data']['auditstatus'] == '03' || $res['data']['auditstatus'] == '04' ) {//已撤销
  364. $merchant_info->refuse_desc = $res['subMsg'];
  365. }
  366. //通联支付 end
  367. } else {
  368. if (!empty($res['sign_url']) && in_array($res['applyment_state'], ["APPLYMENT_STATE_TO_BE_SIGNED", "APPLYMENT_STATE_TO_BE_CONFIRMED"])) {
  369. $merchant_info->status = 1;
  370. $merchant_info->sign_url = json_encode([
  371. 'applyment_state_msg' => $res['applyment_state_msg'],
  372. 'sign_url' => $res['sign_url']
  373. ]);
  374. }
  375. //待用户验证
  376. if ($res['applyment_state'] == Merchant::APPLYMENT_STATE_REJECTED) {
  377. if($res['audit_detail']){
  378. $refuse_desc = [];
  379. foreach ($res['audit_detail'] as $idetail) {
  380. $refuse_desc[] = $idetail['field_name'] . ':' . $idetail['reject_reason'];
  381. }
  382. $merchant_info->refuse_desc .= implode(';;;', $refuse_desc);
  383. }
  384. }
  385. $merchant_info->sub_mch_id = $res['sub_mchid'];
  386. }
  387. //通联支付 start
  388. if ($is_yunst) {
  389. if ($res['data']['auditstatus'] == '02') {
  390. $merchant_info->sub_mch_id = $res['data']['merid'];
  391. $store_info = Store::findOne(['id' => $merchant_info->store_id]);
  392. $store_info->cusid = $res['data']['merid'];
  393. $store_info->save();
  394. }
  395. }
  396. //通联支付 end
  397. if ($merchant_info->save()) {
  398. //如果已经完成并且又商户号则开始替换商城配置信息
  399. if ($res['sub_mchid'] && $res['applyment_state'] == Merchant::APPLYMENT_STATE_FINISHED) {
  400. $WechatConfig = WechatConfig::find()->where(['store_id' => $merchant_info->bind_store_id])->one();
  401. if(empty($WechatConfig)){
  402. $WechatConfig = new WechatConfig;
  403. $WechatConfig->store_id = $merchant_info->bind_store_id;
  404. $WechatConfig->created_at = time();
  405. $WechatConfig->updated_at = time();
  406. $WechatConfig->app_id = '0';
  407. $WechatConfig->app_secret = '0';
  408. }
  409. $WechatConfig->mch_id = $res['sub_mchid'];
  410. $res = $WechatConfig->save();
  411. } elseif (empty($res['sub_mchid']) && $res['applyment_state'] == Merchant::APPLYMENT_STATE_FINISHED) {
  412. $merchant_info->status = 2;
  413. $merchant_info->state = Merchant::APPLYMENT_STATE_REJECTED;
  414. $merchant_info->refuse_desc = Json::encode([
  415. 'field' => "subject_type",
  416. 'reject_reason' => "进件已完结,请重新提交资料信息"
  417. ]);
  418. }
  419. // \Yii::warning(['<=================> 更新申请单信息失败', $value['business_code'], $res]);
  420. }
  421. }
  422. }
  423. \Yii::error('---------------------- HANDLE MERCHANT BEHAVIOR END------------------');
  424. return false;
  425. }
  426. /**
  427. * 门店收益计算
  428. */
  429. public function handleMdProfit($order_id) {
  430. $md_profit = MdProfit::findOne(['order_id' => $order_id, 'is_send' => 0]);
  431. if ($md_profit) {
  432. $md = Md::findOne($md_profit->md_id);
  433. $md->updateCounters(['total_profit' => $md_profit->total_profit, 'cash_profit' => $md_profit->total_profit]);
  434. $md_profit->is_send = 1;
  435. $md_profit->save();
  436. }
  437. }
  438. /**
  439. * 处理过期优惠券
  440. */
  441. public function handleCoupon() {
  442. // \Yii::warning('---- COUPON BEHAVIOR START ----');
  443. $coupon_list = UserCoupon::find()->alias('uc')->where([
  444. 'uc.is_use' => 0,
  445. 'uc.is_delete' => 0,
  446. 'uc.is_expire' => 0,
  447. 'uc.store_id' => $this->store_id
  448. ])->leftJoin(['c' => Coupon::tableName()], 'c.id=uc.coupon_id')->select('uc.id, uc.begin_time, uc.end_time, c.expire_type')->asArray()->all();
  449. if (empty($coupon_list)) {
  450. // \Yii::warning('无可操作优惠券数据');
  451. return;
  452. }
  453. foreach ($coupon_list as $value) {
  454. if ($value['expire_type'] == 1 ) {
  455. if ($value['end_time'] < 1) {
  456. continue;
  457. } else {
  458. if (time() > $value['end_time']) {
  459. UserCoupon::updateAll(['is_expire' => 1, 'updated_at' => time()], [
  460. 'id' => $value['id'],
  461. ]);
  462. continue;
  463. }
  464. }
  465. }
  466. if ($value['expire_type'] == 2) {
  467. if (time() > strtotime(date('Y-m-d 23:59:59', $value['end_time']))) {
  468. UserCoupon::updateAll(['is_expire' => 1, 'updated_at' => time()], [
  469. 'id' => $value['id'],
  470. ]);
  471. continue;
  472. }
  473. }
  474. }
  475. // \Yii::warning('---- COUPON BEHAVIOR END ----');
  476. }
  477. /**
  478. * 订单自动收货 (废弃)
  479. */
  480. private function orderConfirm()
  481. {
  482. $time = time();
  483. $delivery_time = (Option::get(OptionSetting::STORE_DELIVERY_TIME, $this->store_id, 0)['value']);
  484. if ($delivery_time !== null) {
  485. $delivery_time = $time - ((int)$delivery_time * 86400);
  486. //不处理视频号小店订单
  487. $field_order_id = VideoShopOrderExt::find()->where(['store_id' => $this->store_id, 'is_delete' => 0])->select('order_id')->column();
  488. $order_confirm = Order::find()->where([
  489. 'is_delete' => 0, 'trade_status' => Order::ORDER_FLOW_SEND, 'store_id' => $this->store_id
  490. ])->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CONFIRM])->andWhere(['<=', 'send_time', $delivery_time])->andWhere(['NOT IN', 'id', $field_order_id])->all();
  491. foreach ($order_confirm as $k => $v) {
  492. /**
  493. * @var Order $v
  494. */
  495. //如果是代理配送 且上门安装,用户没有对商品确认收货则不可确认收货
  496. $order_detail = OrderDetail::findAll(['order_id' => $v->id]);
  497. $is_can_confirm = true;
  498. foreach ($order_detail as $detail) {
  499. $is_can_confirm_sub = ((bool)AgentGoodsInstallLog::findOne(['order_detail_id' => $detail->id, 'status' => [0, 1], 'is_need_install' => 1, 'order_type' => AgentGoodsInstallLog::ORDER_TYPE_NORMAL]));
  500. if ($is_can_confirm_sub) {
  501. $is_can_confirm = false;
  502. }
  503. }
  504. //如果是同城配送平台自配方式,判断骑手是否送达,如果未送达则不可以确认收货
  505. $delivery_info = DeliveryInfo::findOne(['order_no' => $v->order_no]);
  506. if ($delivery_info) {
  507. if($delivery_info->local_status != DeliveryInfo::LOCAL_STATUS_CONFIRM) {
  508. $is_can_confirm = false;
  509. }
  510. }
  511. if ($is_can_confirm) {
  512. Order::updateAll(['trade_status' => Order::ORDER_FLOW_CONFIRM, 'confirm_time' => time()], ['id' => $v->id]);
  513. if ($v->pay_type == 2) {
  514. $v->is_pay = 1;
  515. $v->save();
  516. }
  517. $t = \Yii::$app->db->beginTransaction();
  518. if($delivery_info->local_status == DeliveryInfo::LOCAL_STATUS_CONFIRM) {
  519. /* 骑手完成订单后发放收入 */
  520. $courier = LocalDeliveryCourier::findOne(['id' => $delivery_info->rider_id, 'is_delete' => 0, 'state' => 2]);
  521. //同城配送设置相关
  522. $store_id = 0;
  523. if (intval($delivery_info->is_store_delivery_type)) {
  524. $store_id = $courier->store_id;
  525. }
  526. $values = Option::find()->where([
  527. 'store_id' => $store_id,
  528. 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING
  529. ])->select('value')->one();
  530. $local_setting = json_decode($values->value, true);
  531. if (!empty($courier)) {
  532. if ($store_id > 0) {
  533. $local_setting['default_cost']['value'] = -1;
  534. }
  535. $amount = (float)$local_setting['default_cost']['value'] == -1 ? $delivery_info->fee : (float)$local_setting['default_cost']['value'];
  536. $log = LocalDeliveryLog::saveLog($courier->saas_user_id, $amount, 1, 1, $v->id, "骑手配送收入:" . $amount . "元");
  537. if (!$log) {//发放骑手佣金报错
  538. \Yii::warning('---- ORDER CONFIRM 订单完成发放骑手收入失败,order_id='.$v->id.' ----');
  539. $t->rollBack(); //事务回滚
  540. continue;
  541. }
  542. }
  543. }
  544. $t->commit();
  545. }
  546. }
  547. }
  548. }
  549. /**
  550. * 处理过了售后期且没有售后的订单
  551. */
  552. public function orderSend($type = 0, $order_id = [], $store_id = 0, $after_sale_time = 0, $is_handle_video_order = 0)
  553. {
  554. $time = time();
  555. if ($type) {
  556. $sale_time = $time - ((int)$after_sale_time * 86400);
  557. $where = [
  558. 'and',
  559. ['o.store_id' => $store_id],
  560. ['o.id' => $order_id],
  561. ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.is_sale' => 0],
  562. ['<=', 'o.confirm_time', $sale_time],
  563. ];
  564. $this->store_id = $store_id;
  565. } else {
  566. $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value'];
  567. $sale_time = $time - ((int)$after_sale_time * 86400);
  568. $where = [
  569. 'and',
  570. ['o.store_id' => $this->store_id],
  571. ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.is_sale' => 0],
  572. ['<=', 'o.confirm_time', $sale_time],
  573. ];
  574. }
  575. //不处理视频号小店订单
  576. $field_order_id = [];
  577. if ($is_handle_video_order) {
  578. $field_order_id = VideoShopOrderExt::find()->where(['store_id' => $this->store_id, 'is_delete' => 0])->select('order_id')->column();
  579. }
  580. $order_list = Order::find()->alias('o')
  581. ->where($where)->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL])->andWhere(['NOT IN', 'o.id', $field_order_id])
  582. ->leftJoin(OrderRefund::tableName() . ' r', "r.order_id = o.id and r.is_delete = 0")
  583. ->select(['o.*'])->groupBy('o.id')
  584. ->andWhere([
  585. 'or',
  586. 'isnull(r.id)',
  587. ['r.type' => 2],
  588. ['in', 'r.status', [2, 3]]
  589. ])->offset(0)->limit(50)->asArray()->all();
  590. $store_info = Store::findOne($this->store_id);
  591. $order_id_arr = [];
  592. try {
  593. $order_id_arr = $this->profitSharing($sale_time, $this->store_id);
  594. } catch (\Exception $e) {
  595. \Yii::warning('---- COUPON BEHAVIOR END分账失败 ----' . $e->getMessage());
  596. }
  597. foreach ($order_list as $index => $value) {
  598. if (in_array($value['id'], $order_id_arr ?? [])) {
  599. continue;
  600. }
  601. try {
  602. //检测微信是否收货
  603. Wechat::init($this->store_id);
  604. $app = Wechat::$wechat_mini;
  605. $form = new \app\modules\admin\models\WechatThirdForm(['store_id' => $this->store_id]);
  606. $order_ = Order::find()->where(['id' => $value['id']])->asArray()->one();
  607. if($form->wxOrderStateIsConfirm($app, $order_)){
  608. //如果没有添加成功分账接收人就完结分账
  609. $share_receiver = SharingReceiver::findOne(['store_id' => $this->store_id, 'order_no' => $value['order_no']]);
  610. if (!$share_receiver) {
  611. $res = WechatShare::complete($value['transaction_id'], $value['id'], false, '分账完结', $this->store_id, $value['is_platform'] );
  612. debug_log('分账完结_', 'wechatShare.log');
  613. debug_log($res, 'wechatShare.log');
  614. }
  615. }
  616. } catch (\Exception $e) {
  617. debug_log($e->getMessage(), 'wechatShare.log');
  618. }
  619. Order::updateAll(['is_sale' => 1, 'updated_at' => time()], ['id' => $value['id']]);
  620. \app\models\ActivityRebateOrderNLog::priceInfoOrderId($value['id']);
  621. BonusPool::generalUserConsume($value['user_id'], $value['store_id']);
  622. BonusPool::sendTwoPlusOneTeamLevelShare($value['id']);
  623. BonusPool::sendArea($value['id']);
  624. BonusPool::userAuto2ShareHolder($value['id']);
  625. BonusPool::userSelfBuyGoods2ShareHolder($value['id']);
  626. $this->share_money($value['id']);
  627. $this->share_holder_money($value['id']);
  628. $this->give_integral($value['id']);
  629. $this->shop_share($value['id']);
  630. $this->league_price($value['id']);
  631. // 门店收益
  632. if ($value['md_id'] > 0) {
  633. $this->handleMdProfit($value['id']);
  634. }
  635. BonusPool::sendRange($value['id']);
  636. // 奖金池补充奖金
  637. BonusPool::poolPush($value['id']);
  638. $this->sendVideoGoodsProfit($value['id']);
  639. //代理发放佣金
  640. $this->agencyPrice($value['id']);
  641. //产品代理发放佣金
  642. $this->sendGoodsAgentMoney($value['id']);
  643. try {
  644. // 处理供应链平台商户号收款店铺结算
  645. if ($value['is_use_platform_mch'] == 1 && $value['pay_type'] == 1) {
  646. $profit = $value['pay_price'] * $store_info->transfer_profit / 100;
  647. $price = $value['pay_price'] - $profit;
  648. Store::addMoney($store_info, $price, '用户下单', $value['id'], $value['user_id']);
  649. }
  650. } catch (\Exception $e) {
  651. // Todo
  652. }
  653. try {
  654. //服务人员分佣
  655. $workerProfitSend = \app\modules\admin\models\worker\WorkerForm::workerProfitSend($value['id']);
  656. debug_log(['服务人员分佣', $value['id'], $workerProfitSend], __CLASS__ . '.log');
  657. } catch (\Exception $e) {
  658. \Yii::error($e);
  659. }
  660. }
  661. }
  662. //分账 订单分账失败重新分账
  663. public function profitSharing($sale_time, $store_id)
  664. {
  665. $order_id_arr = [];
  666. try {
  667. $SharingReceiver = SharingReceiver::find()->where(['is_pay' => SharingReceiver::PAY_WAIT])->andWhere(['store_id' => $store_id])->groupBy('order_no')->asArray()->all();
  668. foreach ($SharingReceiver as $item) {
  669. $orderNoHead = substr($item['order_no'], 0, 2);
  670. $model = Order::find();
  671. $where = [];
  672. switch ($orderNoHead) {
  673. case 'ML':
  674. case 'AL':
  675. //商盟会员购物订单
  676. $model = Order::find();
  677. $where = ['AND', [
  678. 'order_no' => $item['order_no'],
  679. 'is_delete' => 0,
  680. 'trade_status' => Order::ORDER_FLOW_CONFIRM
  681. ], ['<=', 'confirm_time', $sale_time + 60]];
  682. break;
  683. case 'SC':
  684. //当面付订单
  685. $model = \app\plugins\scanCodePay\models\Order::find();
  686. $where = [
  687. 'order_no' => $item['order_no'],
  688. 'is_delete' => 0,
  689. 'is_pay' => 1
  690. ];
  691. break;
  692. }
  693. $order = $model->where($where)->one();
  694. if ($item['execute_type'] == SharingReceiver::EXECUTE_TYPE_NORMAL) {
  695. // 微信
  696. try {
  697. $order_id_arr = $this->wechatProfitSharing($order);
  698. } catch (\Exception $e) {
  699. \Yii::warning('---- COUPON BEHAVIOR END微信分账失败 ----');
  700. }
  701. }
  702. if ($item['execute_type'] == SharingReceiver::EXECUTE_TYPE_ALIPAY) {
  703. // 支付宝
  704. try {
  705. $this->alipayProfitSharing($order);
  706. } catch (\Exception $e) {
  707. \Yii::warning('---- COUPON BEHAVIOR END支付宝分账失败 ----' . $e->getMessage());
  708. }
  709. }
  710. }
  711. } catch (\Exception $e) {
  712. \Yii::warning('---- COUPON BEHAVIOR END ----');
  713. }
  714. return $order_id_arr;
  715. }
  716. private function saasUserPriceLog($order, $SharingReceivers = [], $expend = false, $log = '') {
  717. try {
  718. $log_type = SaasUserPriceLog::LOG_TYPE_INCOME;
  719. $remark = '';
  720. if($expend){
  721. $log_type = SaasUserPriceLog::LOG_TYPE_EXPEND;
  722. $remark = '-分账成功';
  723. }
  724. $log && $remark = $log;
  725. foreach ($SharingReceivers as $item) {
  726. \Yii::warning(['---- saasUserPriceLog Err11 ----', $item]);
  727. if(in_array($item['type'], [SharingReceiver::RECEIVE_MERCHANT_ID])){
  728. continue;
  729. }
  730. $desc = $item['remark'] . $remark;
  731. $saas_id = $item['saas_id'];
  732. if(!$saas_id){
  733. if(!$order->is_platform){
  734. $saas_id = $item['user_id'];
  735. }else{
  736. $userInfo = User::findOne($item['user_id']);
  737. if(!empty($userInfo)){
  738. $saas = SaasUser::findOne(['mobile' => $userInfo->binding]);
  739. $saas_id = $saas->id;
  740. }
  741. }
  742. }
  743. \Yii::warning(['---- saasUserPriceLog Err22 ----', $saas_id, $item['amount'], $item['from'], $log_type, $order->order_no, $desc]);
  744. SaasUserPriceLog::saveLog($saas_id, $item['amount'], $item['from'], $log_type, $order->order_no, $desc);
  745. }
  746. } catch (\Exception $e) {
  747. \Yii::warning('---- saasUserPriceLog Err ----' . __LINE__);
  748. }
  749. }
  750. /**
  751. * 积分发放
  752. */
  753. private function give_integral($id)
  754. {
  755. $give = Order::findOne($id);
  756. if ($give['give_integral'] != 0) {
  757. return;
  758. }
  759. $integral = OrderDetail::find()
  760. ->andWhere(['order_id' => $give['id'], 'is_delete' => 0])
  761. ->select([
  762. 'sum(integral)',
  763. ])->scalar();
  764. if (!$integral) {
  765. return;
  766. }
  767. $giveUser = User::findOne(['id' => $give['user_id']]);
  768. $give->give_integral = 1;
  769. $give->save();
  770. AccountLog::saveLog($giveUser->id, $integral, AccountLog::TYPE_INTEGRAL,
  771. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  772. $give->id, '订单'.$give->order_no.'赠送积分');
  773. }
  774. // 团长佣金结算
  775. private function shop_share($id,$type=0)
  776. {
  777. if ($id) {
  778. $shopShare = ShopShare::findOne([
  779. 'order_id' => $id,
  780. 'type' => $type
  781. ]);
  782. if ($shopShare->shop_id && $shopShare->status == 0) {
  783. $shop = Shop::findOne($shopShare->shop_id);
  784. if ($shop && $shop->user_id) {
  785. $form = User::findOne(['id' => $shop->user_id]);
  786. $form->updateCounters(['tuan_price' => $shopShare->amount]);
  787. $shopShare->status = 1;
  788. $shopShare->save();
  789. }
  790. }
  791. }
  792. }
  793. /**
  794. * 分销订单佣金结算
  795. * @param Order $order
  796. */
  797. private function sendOrderProfit($order, $expire_day = 0) {
  798. if (!$order->share_order_profit) {
  799. \Yii::warning('订单佣金可分发值为0');
  800. return;
  801. }
  802. $user_share = UserShareLog::find()->where(['user_id' => $order->user_id])->orderBy('created_at desc')->limit(1)->asArray()->one();
  803. \Yii::warning($user_share);
  804. if (empty($user_share)) {
  805. \Yii::warning('订单佣金未找到分享关系');
  806. return;
  807. }
  808. if ($expire_day > 0) {
  809. if ($order->pay_time - $user_share['created_at'] > $expire_day * 24 * 3600) {
  810. \Yii::warning('订单佣金分享关系已过期');
  811. return;
  812. }
  813. }
  814. $user = User::findOne($user_share['parent_id']);
  815. if (!$user) {
  816. \Yii::warning('订单佣金未找到分享关系用户');
  817. return;
  818. }
  819. if ($order->share_send_type == 2) {
  820. AccountLog::saveLog($user_share['parent_id'], $order->share_order_profit, AccountLog::TYPE_INTEGRAL,
  821. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  822. $order->id, "商城订单佣金赠送积分, 订单号:{$order->order_no}");
  823. } else if ($order->share_send_type == 3) {
  824. AccountLog::saveLog($user_share['parent_id'], $order->share_order_profit, AccountLog::TYPE_BALANCE,
  825. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  826. $order->id, "商城订单佣金赠送余额, 订单号:{$order->order_no}");
  827. } else {
  828. $user->updateCounters(['total_price' => doubleval($order->share_order_profit), 'price' => doubleval($order->share_order_profit)]);
  829. $order->updateCounters(['share_price' => doubleval($order->share_order_profit)]);
  830. UserShareMoney::set($order->share_order_profit, $user->id, $order->id, 0, 5, $order->store_id, 0);
  831. }
  832. }
  833. private function league_price($id){
  834. $order = Order::findOne($id);
  835. $store = Store::findOne($this->store_id);
  836. $user = User::findOne($order->user_id);
  837. $saas_user = SaasUser::findOne(['mobile' => $user->binding]);
  838. if($order->send_price > 0){ // && $store->league_price > 0
  839. //给用户发放联盟券
  840. $send_price = $order->send_price;
  841. if($saas_user){
  842. $before = $saas_user->league_price;
  843. $saas_user->updateCounters(['league_price' => floatval($send_price)]);
  844. //给用户增加赠送的联盟券
  845. SaaSLeaguePriceLog::setLeaguePriceLog(
  846. $order->store_id,
  847. $saas_user->id,
  848. $send_price,
  849. $before,
  850. SaaSLeaguePriceLog::TYPE_ORDER_REBATE,
  851. SaaSLeaguePriceLog::SEND_TYPE,
  852. SaaSLeaguePriceLog::ROLE_USER,
  853. $order->id
  854. );
  855. }
  856. //给商家扣减 (用户赠送的联盟券钱从商家从扣减)
  857. $before = $store->league_price;
  858. $store->updateCounters(['league_price' => -floatval($send_price)]);
  859. //给商家扣减 (用户赠送的联盟券钱从商家从扣减)
  860. SaaSLeaguePriceLog::setLeaguePriceLog(
  861. $order->store_id,
  862. $saas_user->id,
  863. $send_price,
  864. $before,
  865. SaaSLeaguePriceLog::TYPE_ORDER_REBATE,
  866. SaaSLeaguePriceLog::TAKE_TYPE,
  867. SaaSLeaguePriceLog::ROLE_STORE,
  868. $order->id
  869. );
  870. }
  871. if($order->take_price > 0){
  872. //给商家增加 (用户抵扣钱从赠送给商家)
  873. $before = $store->league_price;
  874. //给商家返券
  875. $store->updateCounters(['league_price' => floatval($order->take_price)]);
  876. SaaSLeaguePriceLog::setLeaguePriceLog(
  877. $order->store_id,
  878. $saas_user->id,
  879. $order->take_price,
  880. $before,
  881. SaaSLeaguePriceLog::TYPE_ORDER_REBATE,
  882. SaaSLeaguePriceLog::SEND_TYPE,
  883. SaaSLeaguePriceLog::ROLE_STORE,
  884. $order->id
  885. );
  886. }
  887. }
  888. // 分销订单佣金结算
  889. private function share_money($id)
  890. {
  891. $order = Order::findOne($id);
  892. if (!$order) {
  893. return;
  894. }
  895. if ($order->is_price != 0) {
  896. return;
  897. }
  898. //排除商盟订单
  899. if($order->user_id == 0) {
  900. return;
  901. }
  902. $setting = Option::get('share_money_setting', $this->store_id);
  903. $setting = $setting ? Json::decode($setting['value']) : [];
  904. if (!$setting) {
  905. \Yii::warning('订单佣金发送:未开启分销设置1');
  906. return;
  907. }
  908. //临时关系佣金发放
  909. if (!empty($order->limit_id) && !empty($order->limit_price)) {
  910. \Yii::error("临时绑定关系发放佣金", '临时绑定关系发放佣金');
  911. //临时绑定关系发放佣金
  912. $bind_log = UserBindLog::findOne($order->limit_id);
  913. $user = User::findOne($bind_log->parent_id);
  914. $user->updateCounters(['total_price' => $order->limit_price, 'price' => $order->limit_price]);
  915. UserShareMoney::set($order->limit_price, $user->id, $order->id, 0, 6, $order->store_id, 0);
  916. $order->is_send_limit = 1;
  917. $order->updateCounters(['share_price' => doubleval($order->limit_price)]);
  918. $res = $order->save();
  919. if (!$res) {
  920. \Yii::error("订单保存失败");
  921. };
  922. } else {
  923. \Yii::error("订单中临时关系佣金为空");
  924. }
  925. $share_setting = Option::get('share_basic_setting', $this->store_id);
  926. $share_setting = $share_setting ? Json::decode($share_setting['value']) : [];
  927. // 分销商自购返利
  928. $order->share_price = 0;
  929. $user = User::findOne(['id' => $order->user_id]);
  930. if ($order->rebate > 0) {
  931. if ($order->share_send_type == 2) {
  932. AccountLog::saveLog($order->user_id, $order->rebate, AccountLog::TYPE_INTEGRAL,
  933. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  934. $order->id, "商城订单自购返利赠送积分, 订单号:{$order->order_no}");
  935. } else if ($order->share_send_type == 3) {
  936. AccountLog::saveLog($order->user_id, $order->rebate, AccountLog::TYPE_BALANCE,
  937. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  938. $order->id, "商城订单自购返利赠送余额, 订单号:{$order->order_no}");
  939. } else {
  940. $user->updateCounters(['total_price' => doubleval($order->rebate), 'price' => doubleval($order->rebate)]);
  941. $order->updateCounters(['share_price' => doubleval($order->rebate)]);
  942. UserShareMoney::set($order->rebate, $user->id, $order->id, 0, 4, $order->store_id, 0);
  943. }
  944. $order->is_price = 1;
  945. }
  946. // 一级佣金发放
  947. if ($share_setting['level']['value'] >= 1) {
  948. $user_1 = User::findOne($order->old_parent_id);
  949. if (!$user_1) {
  950. $order->save();
  951. return;
  952. }
  953. if ($order->share_send_type == 2 && $order->first_price > 0) {
  954. AccountLog::saveLog($user_1->id, $order->first_price, AccountLog::TYPE_INTEGRAL,
  955. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  956. $order->id, "商城订单分销赠送积分, 订单号:{$order->order_no}");
  957. } else if ($order->share_send_type == 3 && $order->first_price > 0) {
  958. AccountLog::saveLog($user_1->id, $order->first_price, AccountLog::TYPE_BALANCE,
  959. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  960. $order->id, "商城订单分销赠送余额, 订单号:{$order->order_no}");
  961. } else {
  962. $user_1->updateCounters(['total_price' => $order->first_price, 'price' => $order->first_price]);
  963. UserShareMoney::set($order->first_price, $user_1->id, $order->id, 0, 1, $order->store_id, 0);
  964. $order->updateCounters(['share_price' => doubleval($order->first_price)]);
  965. }
  966. $order->is_price = 1;
  967. }
  968. // 二级佣金发放
  969. if ($share_setting['level']['value'] >= 2) {
  970. $user_2 = User::findOne($order->old_parent_id_1);
  971. if ($user_2) {
  972. if ($order->share_send_type == 2 && $order->second_price > 0) {
  973. AccountLog::saveLog($user_2->id, $order->second_price, AccountLog::TYPE_INTEGRAL,
  974. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  975. $order->id, "商城订单分销赠送积分, 订单号:{$order->order_no}");
  976. } else if ($order->share_send_type == 3 && $order->second_price > 0) {
  977. AccountLog::saveLog($user_2->id, $order->second_price, AccountLog::TYPE_BALANCE,
  978. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  979. $order->id, "商城订单分销赠送余额, 订单号:{$order->order_no}");
  980. } else {
  981. $user_2->updateCounters(['total_price' => $order->second_price, 'price' => $order->second_price]);
  982. UserShareMoney::set($order->second_price, $user_2->id, $order->id, 0, 2, $order->store_id, 0);
  983. $order->updateCounters(['share_price' => doubleval($order->second_price)]);
  984. }
  985. }
  986. }
  987. // 三级佣金发放
  988. if ($share_setting['level']['value'] >= 3 && $order->rebate == 0) {
  989. $user_3 = User::findOne($order->old_parent_id_2);
  990. if ($user_3) {
  991. if ($order->share_send_type == 2 && $order->third_price > 0) {
  992. AccountLog::saveLog($user_3->id, $order->third_price, AccountLog::TYPE_INTEGRAL,
  993. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  994. $order->id, "商城订单分销赠送积分, 订单号:{$order->order_no}");
  995. } else if ($order->share_send_type == 3 && $order->third_price > 0) {
  996. AccountLog::saveLog($user_3->id, $order->third_price, AccountLog::TYPE_BALANCE,
  997. AccountLog::LOG_TYPE_INCOME, AccountLog::TYPE_PLATFORM_ORDER,
  998. $order->id, "商城订单分销赠送余额, 订单号({$order->order_no})");
  999. } else {
  1000. $user_3->updateCounters(['total_price' => $order->third_price, 'price' => $order->third_price]);
  1001. UserShareMoney::set($order->third_price, $user_3->id, $order->id, 0, 3, $order->store_id, 0);
  1002. $order->updateCounters(['share_price' => doubleval($order->third_price)]);
  1003. }
  1004. }
  1005. }
  1006. $order->save();
  1007. return;
  1008. }
  1009. // 等级分佣结算
  1010. private function share_holder_money($id)
  1011. {
  1012. $order = Order::findOne($id);
  1013. if (!$order) {
  1014. return;
  1015. }
  1016. if ($order->holder_is_price != 0) {
  1017. return;
  1018. }
  1019. //商盟订单没有股东分红
  1020. if($order->user_id == 0){
  1021. return;
  1022. }
  1023. // 一级佣金发放
  1024. if ($order->holder_first_price > 0) {
  1025. $user_1 = User::findOne($order->parent_id);
  1026. $user_1->updateCounters(['total_price' => $order->holder_first_price, 'price' => $order->holder_first_price]);
  1027. UserShareMoney::set($order->holder_first_price, $user_1->id, $order->id, 2, 1, $this->store_id, 0);
  1028. $order->holder_is_price = 1;
  1029. $order->updateCounters(['share_price' => doubleval($order->holder_first_price)]);
  1030. }
  1031. // 二级佣金发放
  1032. if ($order->holder_second_price > 0) {
  1033. $user_2 = User::findOne($order->parent_id_1);
  1034. $user_2->updateCounters(['total_price' => $order->holder_second_price, 'price' => $order->holder_second_price]);
  1035. UserShareMoney::set($order->holder_second_price, $user_2->id, $order->id, 2, 2, $this->store_id, 0);
  1036. $order->updateCounters(['share_price' => doubleval($order->holder_second_price)]);
  1037. }
  1038. // 三级佣金发放
  1039. if ($order->holder_third_price > 0) {
  1040. $user_3 = User::findOne($order->parent_id_2);
  1041. $user_3->updateCounters(['total_price' => $order->holder_third_price, 'price' => $order->holder_third_price]);
  1042. UserShareMoney::set($order->holder_third_price, $user_3->id, $order->id, 2, 3, $this->store_id, 0);
  1043. $order->updateCounters(['share_price' => doubleval($order->holder_third_price)]);
  1044. }
  1045. // 旧关系发放
  1046. // 一级佣金发放
  1047. if ($order->old_holder_first_price > 0) {
  1048. $user_1 = User::findOne($order->old_parent_id);
  1049. $user_1->updateCounters(['total_price' => $order->old_holder_first_price, 'price' => $order->old_holder_first_price]);
  1050. UserShareMoney::set($order->old_holder_first_price, $user_1->id, $order->id, 2, 1, $this->store_id, 0);
  1051. $order->updateCounters(['share_price' => doubleval($order->old_holder_first_price)]);
  1052. }
  1053. // 二级佣金发放
  1054. if ($order->old_holder_second_price > 0) {
  1055. $user_2 = User::findOne($order->old_parent_id_1);
  1056. $user_2->updateCounters(['total_price' => $order->old_holder_second_price, 'price' => $order->old_holder_second_price]);
  1057. UserShareMoney::set($order->old_holder_second_price, $user_2->id, $order->id, 2, 2, $this->store_id, 0);
  1058. $order->updateCounters(['share_price' => doubleval($order->old_holder_second_price)]);
  1059. }
  1060. // 三级佣金发放
  1061. if ($order->old_holder_third_price > 0) {
  1062. $user_3 = User::findOne($order->old_parent_id_2);
  1063. $user_3->updateCounters(['total_price' => $order->old_holder_third_price, 'price' => $order->old_holder_third_price]);
  1064. UserShareMoney::set($order->old_holder_third_price, $user_3->id, $order->id, 2, 3, $this->store_id, 0);
  1065. $order->updateCounters(['share_price' => doubleval($order->old_holder_third_price)]);
  1066. }
  1067. $order->save();
  1068. }
  1069. private function money($parent_id, $money)
  1070. {
  1071. if ($parent_id == 0) {
  1072. return ['code' => 1, 'parent_id' => 0];
  1073. }
  1074. $parent = User::findOne(['id' => $parent_id]);
  1075. if (!$parent) {
  1076. return ['code' => 1, 'parent_id' => 0];
  1077. }
  1078. $parent->updateCounters(['total_price' => $money, 'price' => $money]);
  1079. return [
  1080. 'code' => 0,
  1081. 'parent_id' => $parent->parent_id,
  1082. ];
  1083. }
  1084. /**
  1085. * 分账
  1086. * @param Order | \app\plugins\scanCodePay\models\Order | ReOrder | FoodOrder $order
  1087. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  1088. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  1089. * @throws \GuzzleHttp\Exception\GuzzleException
  1090. */
  1091. public function wechatProfitSharing($order) {
  1092. if (!\Yii::$app->isSaas()) {
  1093. return;
  1094. }
  1095. if (!$order) {
  1096. \Yii::error('<=======================> 微信分账订单不存在');
  1097. return;
  1098. }
  1099. if(in_array($order->pay_type, [Order::PAY_TYPE_ADAPAY_WX, Order::PAY_TYPE_ADAPAY_ALIPAY]) && $this->is_yunst==0){
  1100. return $this->adapayProfitSharing($order);
  1101. }
  1102. if(in_array($order->pay_type, [Order::PAY_TYPE_YUNST_WECHAT_PAY, Order::PAY_TYPE_YUNST_ALI_PAY])){
  1103. //通联支付分账
  1104. return $this->yunstProfitSharing($order);
  1105. }
  1106. // 此方法目前为多次分账,故分账结束后,剩余金额需要主动完结分账去触发解冻资金
  1107. $order_id = $order->order_no;
  1108. $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id,
  1109. 'transaction_id' => $order->transaction_id, 'is_pay' => SharingReceiver::PAY_WAIT, 'execute_type' => SharingReceiver::EXECUTE_TYPE_NORMAL])
  1110. ->asArray()->all();
  1111. $profitOrderId = 0;
  1112. $receivers_share_ok = SharingReceiver::find()->where(['store_id' => $order->store_id,
  1113. 'transaction_id' => $order->transaction_id, 'is_pay' => SharingReceiver::PAY_SUCCESS, 'execute_type' => SharingReceiver::EXECUTE_TYPE_NORMAL])
  1114. ->orderBy('id DESC')->asArray()->one();
  1115. $receivers_share_ok && $profitOrderId = $receivers_share_ok['order_id'];
  1116. $cacheKey = 'wechatProfitSharing11:' . $order->transaction_id;
  1117. if(\Yii::$app->cache->get($cacheKey)){
  1118. \Yii::error('<=======================> 微信分账进程已存在');
  1119. return;
  1120. }
  1121. \Yii::$app->cache->set($cacheKey, 1, 160);
  1122. $order_id_arr = [];
  1123. foreach($receivers_share as $receivers_share1){
  1124. sleep(1);
  1125. //检测微信是否收货
  1126. Wechat::init($this->store_id);
  1127. $app = WechatMini::getWechatConfig($this->store_id);
  1128. if (!$app) {
  1129. array_push($order_id_arr, $order->id);
  1130. continue;
  1131. }
  1132. $form = new \app\modules\admin\models\WechatThirdForm(['store_id' => $this->store_id]);
  1133. $order_ = Order::find()->where(['id' => $order->id])->asArray()->one();
  1134. $orderNoHead = substr($receivers_share1['order_no'], 0, 2);
  1135. $model = Order::find();
  1136. $where = [];
  1137. switch ($orderNoHead) {
  1138. case 'ML':
  1139. case 'AL':
  1140. //商盟会员购物订单
  1141. $model = Order::find();
  1142. $where = [
  1143. 'order_no' => $receivers_share1['order_no'],
  1144. 'is_delete' => 0,
  1145. 'trade_status' => Order::ORDER_FLOW_CONFIRM
  1146. ];
  1147. break;
  1148. case 'SC':
  1149. //当面付订单
  1150. $model = \app\plugins\scanCodePay\models\Order::find();
  1151. $where = [
  1152. 'order_no' => $receivers_share1['order_no'],
  1153. 'is_delete' => 0,
  1154. 'is_pay' => 1
  1155. ];
  1156. break;
  1157. }
  1158. $order_ = $model->where($where)->asArray()->one();
  1159. $res = $form->wxOrderStateIsConfirm($app, $order_);
  1160. if(!$res){
  1161. array_push($order_id_arr, $order->id);
  1162. continue;
  1163. }
  1164. $profitOrderId || $profitOrderId = $order->order_no;
  1165. $res = WechatShare::share($order->transaction_id, $profitOrderId, [$receivers_share1], false, false, $order->store_id, $order->is_platform, $order);
  1166. \Yii::error(['wechatProfitSharingwechatProfitSharing11:', $res]);
  1167. if ($res['code'] > 0) {
  1168. $faildDes = !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg'];
  1169. $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')');
  1170. $receivers_share_platform = [[
  1171. 'type' => SharingReceiver::RECEIVE_MERCHANT_ID,
  1172. 'account' => Option::get('sp_mch_id', 0, 'saas')['value'],
  1173. 'amount' => $receivers_share1['amount'],
  1174. 'name' => Option::get('sp_name', 0, 'saas')['value'],
  1175. ]];
  1176. //分到平台
  1177. if($receivers_share1['type'] == 2){
  1178. SharingReceiver::updateAll([
  1179. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'],
  1180. 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]);
  1181. continue;
  1182. }
  1183. sleep(1);
  1184. $res = WechatShare::share($order->transaction_id, $profitOrderId, $receivers_share_platform, false, false, $order->store_id, $order->is_platform, $order);
  1185. \Yii::error(['分到平台wechatProfitSharingwechatProfitSharing11:', $res]);
  1186. if ($res['code'] > 0) {
  1187. SharingReceiver::updateAll([
  1188. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1189. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'],
  1190. 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]);
  1191. $this->saasUserPriceLog($order, [$receivers_share1]);
  1192. $this->saasUserPriceLog($order, [$receivers_share1], true, '-分账失败');
  1193. }else{
  1194. SharingReceiver::updateAll([
  1195. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1196. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]);
  1197. $this->saasUserPriceLog($order, [$receivers_share1]);
  1198. $profitOrderId = $res['res']['order_id'];
  1199. }
  1200. } else {
  1201. $order_id = $res['res']['order_id'];
  1202. SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]);
  1203. $this->saasUserPriceLog($order, [$receivers_share1]);
  1204. $this->saasUserPriceLog($order, [$receivers_share1], true);
  1205. $profitOrderId = $res['res']['order_id'];
  1206. }
  1207. }
  1208. // 单次分账结束后,剩余金额自动解冻返给商户, 无需主动触发分账完结接口,多次分账时需要最终触发分账完结,最终解冻给商户
  1209. // 分账完结
  1210. $res = WechatShare::complete($order->transaction_id, $order_id, false, '分账完结', $order->store_id, $order->is_platform );
  1211. return $order_id_arr;
  1212. \Yii::error(['<=======================> 订单号:' . $order->order_no . '-分账完结结果:', $res]);
  1213. }
  1214. /**
  1215. * 自动提现
  1216. * @return void
  1217. */
  1218. public function autoCash($order_id)
  1219. {
  1220. $sharing_info = SharingReceiver::find()->where(['order_id' => $order_id, 'is_pay' => SharingReceiver::PAY_SUCCESS])->one();
  1221. if ($sharing_info){
  1222. $order_info = \app\plugins\scanCodePay\models\Order::find()->where(['id' => $sharing_info->order_id])->one();
  1223. if ($order_info){
  1224. $store_price = $sharing_info->amount;
  1225. $mch_price = ($order_info->pay_price - $sharing_info->amount);
  1226. //平台提现
  1227. $cash = new StoreCash();
  1228. $cash->order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH);
  1229. $cash->is_delete = 0;
  1230. $cash->status = 0;
  1231. $cash->price = $store_price;
  1232. $cash->created_at = time();
  1233. $cash->store_id = -1;
  1234. $cash->type =6;//通联提现
  1235. $cash->name = '平台提现';
  1236. $cash->mobile = '';
  1237. $cash->pay_time = 0;
  1238. $cash->service_charge = 0;
  1239. $cash->cash_type = 0;
  1240. if ($cash->save()) {
  1241. //调用通联自动提现接口
  1242. $oldConf = Option::get(OptionSetting::SAAS_YUNST_SETTING, 0, 'saas')['value'];
  1243. if ($oldConf) {
  1244. $oldConf = json_decode($oldConf, true);
  1245. if (!empty($oldConf)) {
  1246. $customer_number = $oldConf['customer_number'];
  1247. $orderYunst = new OrderYunst();
  1248. // $res = $orderYunst->queryAcctInfo('66065100000219T');
  1249. $res = $orderYunst->queryAcctInfo($customer_number);
  1250. debug_log($res);
  1251. $amount = 0;
  1252. if ($res['subCode'] == 'SUCCESS'){
  1253. $amount = $res['data']['amount'];//真的
  1254. }
  1255. if ($store_price > $amount) {
  1256. debug_log('平台提现金额大于通联账户余额');
  1257. }
  1258. $orderYunst = new OrderYunst();
  1259. $data['bizOrderNo'] = $cash->order_no;
  1260. $data['bizUserId'] = $customer_number;//代理商号
  1261. $data['amount'] = intval($cash->price * 100);
  1262. $data['notifyUrl'] = \Yii::$app->request->hostInfo;
  1263. $data['remark'] = "";
  1264. $data['authWay'] = "3";
  1265. $res_cash = $orderYunst->servicerWithdraw($data);
  1266. debug_log($res_cash);
  1267. if ($res_cash['subCode'] != 'SUCCESS'){
  1268. debug_log('平台提现失败');
  1269. debug_log($res_cash['subMsg']);
  1270. $cash_info2 = StoreCash::findOne($cash->id);
  1271. $order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH);
  1272. $cash_info2->order_no = $order_no;
  1273. $cash_info2->save();
  1274. }else{
  1275. $cash_info = StoreCash::findOne($cash->id);
  1276. $cash_info->status = 2;
  1277. $cash_info->pay_time = time();
  1278. $cash_info->save();
  1279. debug_log('平台提现成功');
  1280. }
  1281. }
  1282. }
  1283. }
  1284. //商户提现
  1285. $cash_mch = new StoreCash();
  1286. $cash_mch->order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH);
  1287. $cash_mch->is_delete = 0;
  1288. $cash_mch->status = 0;
  1289. $cash_mch->price = $mch_price;
  1290. $cash_mch->created_at = time();
  1291. $cash_mch->store_id = $sharing_info->store_id;
  1292. $cash_mch->type =6;//通联提现
  1293. $cash_mch->name = '商户提现';
  1294. $cash_mch->mobile = '';
  1295. $cash_mch->pay_time = 0;
  1296. $cash_mch->service_charge = 0;
  1297. $cash_mch->cash_type = 0;
  1298. if ($cash_mch->save()) {
  1299. //调用通联自动提现接口
  1300. $store = \app\models\Store::findOne($sharing_info->store_id);
  1301. $orderYunst = new OrderYunst();
  1302. $res2 = $orderYunst->queryAcctInfo($store->store_number);
  1303. debug_log($res2);
  1304. $amount2 = 0;
  1305. if ($res2['subCode'] == 'SUCCESS'){
  1306. $amount2 = $res2['data']['amount'];//真的
  1307. }
  1308. if ($mch_price > $amount2) {
  1309. debug_log('平台提现金额大于通联账户余额');
  1310. }
  1311. $orderYunst = new OrderYunst();
  1312. $data['bizOrderNo'] = $cash_mch->order_no;
  1313. $store = Store::findOne(['id' => $cash_mch->store_id]);
  1314. $data['bizUserId'] = $store->store_number;
  1315. $data['amount'] = intval($cash_mch->price * 100);
  1316. $data['notifyUrl'] = \Yii::$app->request->hostInfo;
  1317. $data['remark'] = "";
  1318. $data['authWay'] = "3";
  1319. $res_cash2 = $orderYunst->servicerWithdraw($data);
  1320. debug_log($res_cash2);
  1321. if ($res_cash2['subCode'] != 'SUCCESS'){
  1322. debug_log('商户提现失败');
  1323. debug_log($res_cash2['subMsg']);
  1324. $cash_info2 = StoreCash::findOne($cash_mch->id);
  1325. $order_no = \app\utils\OrderNo::getOrderNo(\app\utils\OrderNo::ORDER_CASH);
  1326. $cash_info2->order_no = $order_no;
  1327. $cash_info2->save();
  1328. }else{
  1329. $cash_info2 = StoreCash::findOne($cash_mch->id);
  1330. $cash_info2->status = 2;
  1331. $cash_info2->pay_time = time();
  1332. $cash_info2->save();
  1333. debug_log('商户提现成功');
  1334. }
  1335. }
  1336. }else{
  1337. debug_log('订单不存在,提现失败');
  1338. }
  1339. }else{
  1340. debug_log('分账不存在,提现失败');
  1341. }
  1342. }
  1343. public function adapayProfitSharing($order) {
  1344. $order_id = $order->order_no;
  1345. $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id,
  1346. 'order_no' => $order->order_no, 'is_pay' => SharingReceiver::PAY_WAIT])
  1347. ->asArray()->all();
  1348. $profitOrderId = 0;
  1349. $cacheKey = 'adapayProfitSharing11:' . $order->adapay_payment_id;
  1350. if(\Yii::$app->cache->get($cacheKey)){
  1351. \Yii::error('<=======================> adapay分账进程已存在');
  1352. return;
  1353. }
  1354. \Yii::$app->cache->set($cacheKey, 1, 160);
  1355. foreach($receivers_share as $receivers_share1){
  1356. sleep(1);
  1357. $res = Adapay::share($order, $receivers_share1);
  1358. \Yii::error(['adapayProfitSharingadapayProfitSharing11:', $res]);
  1359. if ($res['code'] > 0) {
  1360. $faildDes = $res['msg'];
  1361. $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')');
  1362. //分到平台
  1363. if($receivers_share1['type'] == 2){
  1364. SharingReceiver::updateAll([
  1365. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'],
  1366. 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]);
  1367. continue;
  1368. }
  1369. sleep(1);
  1370. $res = Adapay::shareToSaas($order, $receivers_share1);
  1371. \Yii::error(['分到平台adapayProfitSharingadapayProfitSharing11:', $res]);
  1372. if ($res['code'] > 0) {
  1373. SharingReceiver::updateAll([
  1374. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1375. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'],
  1376. 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]);
  1377. $this->saasUserPriceLog($order, [$receivers_share1]);
  1378. $this->saasUserPriceLog($order, [$receivers_share1], true, '-分账失败');
  1379. }else{
  1380. SharingReceiver::updateAll([
  1381. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1382. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]);
  1383. $this->saasUserPriceLog($order, [$receivers_share1]);
  1384. }
  1385. } else {
  1386. $order_id = $res['res']['order_id'];
  1387. SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]);
  1388. $this->saasUserPriceLog($order, [$receivers_share1]);
  1389. $this->saasUserPriceLog($order, [$receivers_share1], true);
  1390. }
  1391. }
  1392. // 分账完结
  1393. \Yii::error(['<=======================> 订单号:' . $order->order_no . '-分账完结结果:']);
  1394. }
  1395. /**
  1396. * 通联分账
  1397. * @param $order
  1398. * @return void
  1399. */
  1400. public function yunstProfitSharing($order) {
  1401. $order_id = $order->order_no;
  1402. /**
  1403. * 查询待分账的记录
  1404. */
  1405. $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id,
  1406. 'order_no' => $order->order_no])
  1407. // ->andWhere(['in','is_pay',[SharingReceiver::PAY_WAIT,SharingReceiver::PAY_FAIL]])
  1408. ->andWhere(['is_pay'=>SharingReceiver::PAY_WAIT])
  1409. ->asArray()->all();
  1410. debug_log('开始分账le');
  1411. debug_log($receivers_share);
  1412. $profitOrderId = 0;
  1413. // $cacheKey = 'yunstProfitSharing:' . $order->adapay_payment_id;
  1414. // if(\Yii::$app->cache->get($cacheKey)){
  1415. // \Yii::error('<=======================> yunst分账进程已存在');
  1416. // return;
  1417. // }
  1418. //
  1419. // \Yii::$app->cache->set($cacheKey, 1, 160);
  1420. foreach($receivers_share as $receivers_share1){
  1421. sleep(1);
  1422. //开始分账
  1423. debug_log('开始分账1');
  1424. debug_log($receivers_share1);
  1425. //这里重新方法调用orderYunst来实现分账
  1426. $res = OrderYunst::share($order, $receivers_share1);
  1427. \Yii::error(['adapayProfitSharingadapayProfitSharing11:', $res]);
  1428. //通联分账
  1429. if ($res['code'] > 0) {
  1430. debug_log('分账失败了');
  1431. debug_log($res);
  1432. $faildDes = $res['msg'];
  1433. $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')');
  1434. //分到平台
  1435. if($receivers_share1['type'] == 2){
  1436. debug_log('到这里了吧hahahah');
  1437. debug_log($res['res']);
  1438. debug_log($res['msg']);
  1439. debug_log($res['res']['yunst_order_no']);
  1440. debug_log($res['res']['err_code']);
  1441. debug_log($res['res']['err_code_des']);
  1442. SharingReceiver::updateAll([
  1443. 'updated_at' => time(),
  1444. 'yunst_order_no'=>$res['res']['yunst_order_no'],
  1445. 'is_pay' => SharingReceiver::PAY_FAIL,
  1446. 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'],
  1447. 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]);
  1448. continue;
  1449. }
  1450. sleep(1);
  1451. //如果分账到账户失败再重试
  1452. $res = OrderYunst::shareToSaas($order, $receivers_share1);
  1453. \Yii::error(['分到平台yunstProfitSharingadapayProfitSharing11:', $res]);
  1454. if ($res['code'] > 0) {
  1455. SharingReceiver::updateAll([
  1456. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1457. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => !empty($res['res']['err_code']) ? $res['res']['err_code'] : $res['msg'],
  1458. 'err_code_des' => !empty($res['res']['err_code_des']) ? $res['res']['err_code_des'] : $res['msg']], ['id' => $receivers_share1['id']]);
  1459. $this->saasUserPriceLog($order, [$receivers_share1]);
  1460. $this->saasUserPriceLog($order, [$receivers_share1], true, '-分账失败');
  1461. }else{
  1462. SharingReceiver::updateAll([
  1463. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1464. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]);
  1465. $this->saasUserPriceLog($order, [$receivers_share1]);
  1466. //如果是分账成功自动提现
  1467. $this->autoCash($order_id);
  1468. }
  1469. } else {
  1470. debug_log('分账成功了');
  1471. debug_log($res);
  1472. $order_id = $res['res']['order_id'];
  1473. SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS, 'order_id' => $res['res']['order_id']], ['id' => $receivers_share1['id']]);
  1474. $this->saasUserPriceLog($order, [$receivers_share1]);
  1475. $this->saasUserPriceLog($order, [$receivers_share1], true);
  1476. //如果是分账成功自动提现
  1477. $this->autoCash($order_id);
  1478. }
  1479. }
  1480. // 分账完结
  1481. \Yii::error(['<=======================> 订单号:' . $order->order_no . '-分账完结结果:']);
  1482. }
  1483. public function adapayShareToSelf() {
  1484. $time = time();
  1485. $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value'];
  1486. $sale_time = $time - (((int)$after_sale_time + 1) * 86400);
  1487. $where = [
  1488. 'and',
  1489. ['o.store_id' => $this->store_id],
  1490. ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.is_sale' => 1, 'o.adapay_share_finish' => 0],
  1491. ['<=', 'o.confirm_time', $sale_time],
  1492. ['<>', 'o.adapay_payment_id', ''],
  1493. ];
  1494. $query = Order::find()->alias('o')
  1495. ->where($where)->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL])
  1496. ->offset(0)->limit(50);
  1497. $order_list = $query->all();
  1498. foreach ($order_list as $index => $order) {
  1499. $share = Adapay::shareToSelf($order);
  1500. if($share['code'] == 0){
  1501. Order::updateAll(['adapay_share_finish' => 1], ['id' => $order['id']]);
  1502. }
  1503. }
  1504. $this->adapayShareToSelfScanCodePayOrder();
  1505. $this->adapayShareToSelfReOrder();
  1506. }
  1507. public function adapayShareToSelfScanCodePayOrder() {
  1508. $time = time();
  1509. $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value'];
  1510. $sale_time = $time - (((int)$after_sale_time + 1) * 1);
  1511. $where = [
  1512. 'and',
  1513. ['o.store_id' => $this->store_id],
  1514. ['o.is_delete' => 0, 'o.trade_status' => Order::ORDER_FLOW_CONFIRM, 'o.adapay_share_finish' => 0],
  1515. ['<=', 'o.pay_time', $sale_time],
  1516. ['<>', 'o.adapay_payment_id', ''],
  1517. ];
  1518. $query = \app\plugins\scanCodePay\models\Order::find()->alias('o')
  1519. ->where($where)->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL])
  1520. ->offset(0)->limit(50);
  1521. $order_list = $query->all();
  1522. foreach ($order_list as $index => $order) {
  1523. $share = Adapay::shareToSelf($order);
  1524. if($share['code'] == 0){
  1525. \app\plugins\scanCodePay\models\Order::updateAll(['adapay_share_finish' => 1], ['id' => $order['id']]);
  1526. }
  1527. }
  1528. }
  1529. public function adapayShareToSelfReOrder() {
  1530. $time = time();
  1531. $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value'];
  1532. $sale_time = $time - (((int)$after_sale_time + 1) * 1);
  1533. $where = [
  1534. 'and',
  1535. ['o.store_id' => $this->store_id],
  1536. ['o.is_delete' => 0, 'o.adapay_share_finish' => 0],
  1537. ['<=', 'o.pay_time', $sale_time],
  1538. ['<>', 'o.adapay_payment_id', ''],
  1539. ];
  1540. $query = ReOrder::find()->alias('o')
  1541. ->where($where)
  1542. ->offset(0)->limit(50);
  1543. $order_list = $query->all();
  1544. foreach ($order_list as $index => $order) {
  1545. $share = Adapay::shareToSelf($order);
  1546. if($share['code'] == 0){
  1547. ReOrder::updateAll(['adapay_share_finish' => 1], ['id' => $order['id']]);
  1548. }
  1549. }
  1550. }
  1551. /**
  1552. * 支付宝分账
  1553. * @param Order | \app\plugins\scanCodePay\models\Order | ReOrder | FoodOrder $order
  1554. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  1555. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  1556. * @throws \GuzzleHttp\Exception\GuzzleException
  1557. */
  1558. public function alipayProfitSharing($order) {
  1559. if (!$order) {
  1560. \Yii::error('<=======================> 支付宝分账订单不存在');
  1561. return;
  1562. }
  1563. $receivers_share = SharingReceiver::find()->where(['store_id' => $order->store_id, 'is_pay' => SharingReceiver::PAY_WAIT, 'order_no' => $order->order_no, 'execute_type' => SharingReceiver::EXECUTE_TYPE_ALIPAY])
  1564. ->asArray()->all();
  1565. if (empty($receivers_share)) {
  1566. \Yii::error('<=======================> 订单号:' . $order->order_no . '分账接收人为空');
  1567. return;
  1568. }
  1569. \Yii::warning($receivers_share);
  1570. $cacheKey = 'alipayProfitSharing11:' . $order->order_no;
  1571. if(\Yii::$app->cache->get($cacheKey)){
  1572. \Yii::error('<=======================> 支付宝分账进程已存在');
  1573. return;
  1574. }
  1575. \Yii::$app->cache->set($cacheKey, 1, 160);
  1576. foreach ($receivers_share as $receiver) {
  1577. sleep(1);
  1578. $res_arr = [];
  1579. $res_arr[] = [
  1580. 'royalty_type' => 'transfer',
  1581. 'trans_in_type' => 'userId',
  1582. 'amount' => $receiver['amount'],
  1583. 'trans_in' => $receiver['account'],
  1584. 'desc' => $receiver['description']
  1585. ];
  1586. $storeInfo = Store::find()->where(['id'=>$order->store_id,'is_delete'=>0])->asArray()->one();
  1587. // if ($storeInfo['business_model'] != 1) {
  1588. // $res = AlipayUnion::settle($order->order_no, $order->alipay_trade_no, $res_arr, $order->store_id,'true');
  1589. // } else {
  1590. $is_app = false;
  1591. if ($order->order_origin === Order::ORDER_SOURCE_APP) {
  1592. $is_app = true;
  1593. }
  1594. $res = AlipayProfit::settle($order->order_no, $order->alipay_trade_no, $res_arr, $order->store_id,'true', $is_app);
  1595. // }
  1596. \Yii::error(['<=======================> 订单号:' . $order->order_no . ', 分销请求分账结果:', $res]);
  1597. if ($res['code'] > 0) {
  1598. $faildDes = $res['res']['sub_msg'];
  1599. $faildDes && $faildDes = addslashes('(失败:' . $faildDes . ')');
  1600. $receivers_share_platform = [];
  1601. $amount = $receiver['amount'];
  1602. $receivers_share_platform[] = [
  1603. 'royalty_type' => 'transfer',
  1604. 'trans_in_type' => 'userId',
  1605. 'amount' => $amount,
  1606. 'trans_in' => Option::get('alipay_user_id', 0, 'saas')['value'],
  1607. 'desc' => '分账到平台',
  1608. ];
  1609. //分到平台
  1610. if($receiver['type'] == 2){
  1611. SharingReceiver::updateAll([
  1612. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => $res['res']['code'],
  1613. 'err_code_des' => $res['res']['sub_msg']], ['id' => $receiver['id']]);
  1614. continue;
  1615. }
  1616. sleep(1);
  1617. // if ($storeInfo['business_model'] != 1) {
  1618. // $res = AlipayUnion::settle($order->order_no, $order->alipay_trade_no, $receivers_share_platform, $order->store_id,'true');
  1619. // } else {
  1620. $is_app = false;
  1621. if ($order->order_origin === Order::ORDER_SOURCE_APP) {
  1622. $is_app = true;
  1623. }
  1624. $res = AlipayProfit::settle($order->order_no, $order->alipay_trade_no, $receivers_share_platform, $order->store_id,'true', $is_app);
  1625. // }
  1626. \Yii::error(['分到平台wechatProfitSharingwechatProfitSharing11:', $res]);
  1627. if ($res['code'] > 0) {
  1628. SharingReceiver::updateAll([
  1629. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1630. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_FAIL, 'err_code' => $res['res']['code'],
  1631. 'err_code_des' => $res['res']['sub_msg']], ['id' => $receiver['id']]);
  1632. $this->saasUserPriceLog($order, [$receiver]);
  1633. $this->saasUserPriceLog($order, [$receiver], true, '-分账失败');
  1634. }else{
  1635. SharingReceiver::updateAll([
  1636. 'description' => new Expression('CONCAT(description, "' . $faildDes . '-分账失败,转到服务商")'),
  1637. 'updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS], ['id' => $receiver['id']]);
  1638. $this->saasUserPriceLog($order, [$receiver]);
  1639. }
  1640. return;
  1641. }
  1642. SharingReceiver::updateAll(['updated_at' => time(), 'is_pay' => SharingReceiver::PAY_SUCCESS], ['id' => $receiver['id']]);
  1643. $this->saasUserPriceLog($order, $receivers_share);
  1644. $this->saasUserPriceLog($order, $receivers_share, true);
  1645. }
  1646. }
  1647. /**
  1648. * 自动取消预约订单
  1649. */
  1650. public function orderBook() {
  1651. $orders = Order::find()->where(['is_delete' => 0, 'is_pay' => 0, 'store_id' => $this->store_id])
  1652. ->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL])
  1653. ->andWhere(['in', 'order_type', [1, 2]])->all();
  1654. /* @var Order[] $orders */
  1655. if (!empty($orders)) {
  1656. foreach ($orders as $order) {
  1657. if (time() - $order->created_at > 15 * 30) {
  1658. $order->trade_status = Order::ORDER_FLOW_CANCEL;
  1659. $order->updated_at = time();
  1660. $order->save();
  1661. }
  1662. }
  1663. }
  1664. }
  1665. public function workerLevel() {
  1666. try {
  1667. $worker_list = Worker::find()->where(['store_id' => $this->store_id, 'status' => Worker::STATUS_VALID])->select('id, level')->asArray()->all();
  1668. foreach ($worker_list as $item) {
  1669. $order_ext_price_num = WorkerOrderExt::find()->alias('woe')
  1670. ->leftJoin(['o' => Order::tableName()], 'o.id = woe.order_id')
  1671. ->where(['woe.worker_id' => $item['id'], 'woe.status_ext' => 100])
  1672. ->andWhere(['o.is_delete' => 0, 'o.is_sale' => 1])
  1673. ->select('o.total_price, o.order_type_ext')->asArray()->all();
  1674. $order_num = 0;
  1675. $order_price = 0;
  1676. foreach ($order_ext_price_num as $order_item) {
  1677. if (in_array($order_item['order_type_ext'], [0, Order::ORDER_TYPE_EXT_WORKER_FIRST_PAY])) {
  1678. ++$order_num;
  1679. }
  1680. $order_price += $order_item['total_price'];
  1681. }
  1682. $worker_level = WorkerLevel::find()->where(['store_id' => $this->store_id, 'status' => 1, 'is_delete' => 0])
  1683. ->andWhere(['AND', ['<=', 'order_money', $order_price],['<=', 'order_count', $order_price], ['>', 'level', $item['level']]])
  1684. ->orderBy('level DESC')
  1685. ->asArray()->one();
  1686. if ($worker_level) {
  1687. $current_level = $worker_level['level'];
  1688. if ($current_level) {
  1689. $worker = Worker::findOne($item['id']);
  1690. $worker->level = $current_level;
  1691. $worker->save();
  1692. }
  1693. }
  1694. }
  1695. } catch (\Exception $e) {
  1696. debug_log($e->getMessage(), 'worker.log');
  1697. }
  1698. }
  1699. public function level() {
  1700. $time = time();
  1701. $after_sale_time = Option::get(OptionSetting::STORE_AFTER_SALE_TIME, $this->store_id, 0)['value'];
  1702. $sale_time = $time - ((int)$after_sale_time * 86400);
  1703. //查出所有有订单的会员
  1704. $userIds = Order::find()->alias('o')->select(['o.user_id', 'sum(o.pay_price) order_money'])
  1705. ->where(['o.is_delete' => 0, 'o.store_id' => $this->store_id, 'o.trade_status' => 3])
  1706. ->andWhere(['<=', 'o.confirm_time', $sale_time])
  1707. ->andWhere(['>','o.user_id',0]) //新增user_id=0是商盟订单
  1708. ->leftJoin(['r' => OrderRefund::find()->where(['is_delete' => 0, 'store_id' => $this->store_id])->select('*')], "r.order_id=o.id")
  1709. ->andWhere([
  1710. 'or',
  1711. 'isnull(r.id)',
  1712. ['r.type' => 2],
  1713. ['in', 'r.status', [2, 3]]
  1714. ])
  1715. ->groupBy('o.user_id');
  1716. $cacheKey = __METHOD__;
  1717. if(cache()->get($cacheKey)){
  1718. $sale_time2 = $sale_time - 3 * 86400;
  1719. $uids = (clone $userIds)->andWhere(['>=', 'o.confirm_time', $sale_time2])->all();
  1720. if(empty($uids)){
  1721. return;
  1722. }
  1723. $uidArr = array_column($uids, 'user_id');
  1724. $userIds->andWhere(['o.user_id' => $uidArr]);
  1725. }
  1726. cache()->set($cacheKey, 1, 86400);
  1727. //查如上会员的当前等级金额
  1728. $userList = User::find()
  1729. ->alias('u')
  1730. ->select(['u.*', 'uids.order_money'])
  1731. ->innerJoin(['uids' => $userIds], 'uids.user_id = u.id')
  1732. ->andWhere('uids.order_money is not null')
  1733. ->asArray()->all();
  1734. //查会员等级
  1735. $levelList = Level::find()
  1736. ->where(['store_id' => $this->store_id, 'is_delete' => 0, 'status' => 1])
  1737. ->orderBy(['money' => SORT_DESC, 'id' => SORT_DESC])
  1738. ->asArray()->all();
  1739. //调整会员等级
  1740. foreach ($userList as $user) {
  1741. foreach ($levelList as $level) {
  1742. if ($user['order_money'] >= $level['money']) {
  1743. if ($user['level'] < $level['level']) {
  1744. $user_info = User::findOne($user['id']);
  1745. $user_info->level = $level['level'];
  1746. if ($user_info->save()) {
  1747. \Yii::error(['会员自动升级==============>', $user_info->id]);
  1748. }
  1749. }
  1750. break;
  1751. }
  1752. }
  1753. }
  1754. }
  1755. /**
  1756. * 认养成熟超时自动设置农场代采
  1757. */
  1758. public function AdoptOrderMature() {
  1759. $time = time();
  1760. $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]);
  1761. $mature_overtime = $AdoptSetting->mature_overtime;
  1762. $mature_time = $time - ($mature_overtime * 86400);
  1763. $order_info = AdoptOrderInfo::find()->where([
  1764. 'is_delete' => 0, 'pick_method'=> AdoptOrderInfo::ORDER_FLOW_NO_PICK,
  1765. 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE, 'store_id' => $this->store_id,
  1766. ])->andWhere(['<=', 'mature_time', $mature_time])->all();
  1767. foreach ($order_info as $k => $v) {
  1768. $v->pick_method = AdoptOrderInfo::ORDER_FLOW_OTHER_PICK;
  1769. $v->pick_time = $v->mature_time + ($mature_overtime * 86400);
  1770. $v->pick_treatment_method = AdoptOrderInfo::ORDER_FLOW_PICK_STORAGE;
  1771. $v->pick_treatment_method_time = time();
  1772. $v->save();
  1773. }
  1774. }
  1775. /**
  1776. * 认养入库超时自动设置保管
  1777. */
  1778. public function AdoptOrderStorage() {
  1779. $time = time();
  1780. $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]);
  1781. $storage_overtime = $AdoptSetting->storage_overtime;
  1782. $storage_time = $time - ($storage_overtime * 86400);
  1783. $order_info = AdoptOrderInfo::find()
  1784. ->where([
  1785. 'is_delete' => 0,
  1786. 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE,
  1787. 'is_storage' => AdoptOrderInfo::ORDER_FLOW_STORAGE,
  1788. 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_WAIT_PRESERVE,
  1789. 'store_id' => $this->store_id,
  1790. ])
  1791. ->andWhere(['!=', 'pick_method', AdoptOrderInfo::ORDER_FLOW_NO_PICK])
  1792. ->andWhere(['<=', 'storage_time', $storage_time])->all();
  1793. foreach ($order_info as $k => $v) {
  1794. $v->is_preserve = AdoptOrderInfo::ORDER_FLOW_PRESERVE;
  1795. $v->preserve_time = $v->storage_time + ($storage_overtime * 86400);
  1796. $v->save();
  1797. }
  1798. }
  1799. /**
  1800. * 认养免费保管结束开始计费
  1801. */
  1802. public function AdoptOrderBillingStart() {
  1803. $time = time();
  1804. $AdoptSetting = AdoptSetting::findOne(['store_id' => $this->store_id,]);
  1805. $free_preserve_time = $AdoptSetting->free_preserve_time;
  1806. $preserve_time = $time - ($free_preserve_time * 86400);
  1807. $order_info = AdoptOrderInfo::find()->where([
  1808. 'is_delete' => 0, 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_PRESERVE,
  1809. 'store_id' => $this->store_id,
  1810. ])->andWhere(['<=', 'preserve_time', $preserve_time])->all();
  1811. foreach ($order_info as $k => $v) {
  1812. $v->billing_start_time = $v->preserve_time + ($free_preserve_time * 86400);
  1813. $v->save();
  1814. }
  1815. }
  1816. /**
  1817. * 认养成熟超时提示信息 (提示成熟超时要自动代采入库)
  1818. */
  1819. public function AdoptOrderMatureTips(){
  1820. $time = time();
  1821. $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]);
  1822. $mature_overtime_tips = $AdoptSetting->mature_overtime_tips;
  1823. $mature_time = $time - ($mature_overtime_tips * 86400);
  1824. $mature_overtime = $AdoptSetting->mature_overtime;
  1825. $order_info = AdoptOrderInfo::find()
  1826. ->where([
  1827. 'is_delete' => 0, 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE,
  1828. 'pick_method'=> AdoptOrderInfo::ORDER_FLOW_NO_PICK, 'store_id' => $this->store_id,])
  1829. ->andWhere(['<=', 'mature_time', $mature_time])->andWhere(['is_sms_mature'=>0])->all();
  1830. if ($order_info){
  1831. foreach ($order_info as $k => $v) {
  1832. $order_relevance = Order::findOne(['id'=>$v->order_id]);
  1833. $v->is_sms_mature = 1;
  1834. $v->save();
  1835. //查看已成熟几天。几天后系统自动设置
  1836. $day1 = ceil(time() - $v->mature_time);
  1837. $day2 = $mature_overtime -$day1;
  1838. NoticeSend::Adopt($this->user_id, $v->mobile, $order_relevance->order_no, $v->name, 1,$day1,$day2);
  1839. }
  1840. }
  1841. }
  1842. /**
  1843. * 认养入库超时提示信息 (提示入库过期要自动保管)
  1844. */
  1845. public function AdoptOrderStorageTips(){
  1846. $time = time();
  1847. $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]);
  1848. $storage_overtime_tips = $AdoptSetting->storage_overtime_tips;
  1849. $storage_time = $time - ($storage_overtime_tips * 86400);
  1850. $storage_overtime = $AdoptSetting->mature_overtime;
  1851. $order_info = AdoptOrderInfo::find()
  1852. ->where([
  1853. 'is_delete' => 0,
  1854. 'is_mature' => AdoptOrderInfo::ORDER_FLOW_MATURE,
  1855. 'is_storage' => AdoptOrderInfo::ORDER_FLOW_STORAGE,
  1856. 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_WAIT_PRESERVE,
  1857. 'store_id' => $this->store_id,
  1858. ])
  1859. ->andWhere(['!=', 'pick_method', AdoptOrderInfo::ORDER_FLOW_NO_PICK])
  1860. ->andWhere(['<=', 'storage_time', $storage_time])->andWhere(['is_sms_storage'=>0])->all();
  1861. if ($order_info){
  1862. foreach ($order_info as $k => $v) {
  1863. $order_relevance = Order::findOne(['id'=>$v->order_id]);
  1864. $v->is_sms_storage = 1;
  1865. $v->save();
  1866. //查看已成熟几天。几天后系统自动设置
  1867. $day1 = ceil(time() - $v->storage_time);
  1868. $day2 = $storage_overtime -$day1;
  1869. NoticeSend::Adopt($this->user_id, $v->mobile, $order_relevance->order_no, $v->name, 2,$day1,$day2);
  1870. }
  1871. }
  1872. }
  1873. /**
  1874. * 认养免费保管提示信息 (提示从开始保管时间算免费保管超时)
  1875. */
  1876. public function AdoptOrderBillingTips(){
  1877. $time = time();
  1878. $AdoptSetting = AdoptSetting::findOne([ 'store_id' => $this->store_id,]);
  1879. $preserve_time_tips = $AdoptSetting->free_preserve_time_tips;
  1880. $preserve_time = $time - ($preserve_time_tips * 86400);
  1881. $preserve = $AdoptSetting->free_preserve_time;
  1882. $order_info = AdoptOrderInfo::find()->where([
  1883. 'is_delete' => 0, 'is_preserve' => AdoptOrderInfo::ORDER_FLOW_PRESERVE,
  1884. 'store_id' => $this->store_id,
  1885. ])->andWhere(['<=', 'preserve_time', $preserve_time])->andWhere(['is_sms_preserve'=>0])->all();
  1886. if ($order_info){
  1887. foreach ($order_info as $k => $v) {
  1888. $order_relevance = Order::findOne(['id'=>$v->order_id]);
  1889. $v->is_sms_preserve = 1;
  1890. $v->save();
  1891. //查看已成熟几天。几天后系统自动设置
  1892. $day1 = ceil(time() - $v->preserve_time);
  1893. $day2 = $preserve -$day1;
  1894. NoticeSend::Adopt($this->user_id, $v->mobile, $order_relevance->order_no, $v->name, 3,$day1,$day2);
  1895. }
  1896. }
  1897. }
  1898. /**
  1899. * 认养配送订单自动收货
  1900. */
  1901. private function adoptCostOrderConfirm()
  1902. {
  1903. $time = time();
  1904. $delivery_time = Option::get(OptionSetting::STORE_DELIVERY_TIME, $this->store_id)['value'];
  1905. $delivery_time = $time - ((int)$delivery_time * 86400);
  1906. $order_confirm = AdoptCostOrder::find()->where([
  1907. 'is_delete' => 0, 'trade_status' => AdoptCostOrder::ORDER_FLOW_SEND, 'store_id' => $this->store_id,
  1908. ])->andWhere(['<>', 'trade_status', AdoptCostOrder::ORDER_FLOW_CONFIRM])->andWhere(['<=', 'send_time', $delivery_time])->all();
  1909. foreach ($order_confirm as $k => $v) {
  1910. /**
  1911. * @var Order $v
  1912. */
  1913. $adopt_order_info = AdoptOrderInfo::find()->alias('aoi')
  1914. ->where([
  1915. 'aoi.order_id' => $v->order_id,
  1916. 'aoi.store_id' => $this->store_id,
  1917. 'aoi.harvest_weight' => 0
  1918. ])->one();
  1919. if ($adopt_order_info->harvest_weight == 0) {
  1920. $adopt_order = Order::find()->alias('o')
  1921. ->where([
  1922. 'o.id' => $v->order_id,
  1923. 'o.store_id' => $this->store_id,
  1924. 'o.order_type' => 5,
  1925. ])->one();
  1926. $adopt_order->trade_status = Order::ORDER_FLOW_CONFIRM;
  1927. $adopt_order->save();
  1928. $goods = Goods::findOne(OrderDetail::findOne(['order_id' => $v->order_id])->goods_id);
  1929. NoticeSend::AdoptOrderStateChange($adopt_order->user_id, $adopt_order_info->mobile, $adopt_order->order_no, $goods->name, 13);
  1930. }
  1931. AdoptCostOrder::updateAll(['trade_status' => Order::ORDER_FLOW_CONFIRM, 'confirm_time' => time()], ['id' => $v->id]);
  1932. if ($v->pay_type == 2) {
  1933. $v->is_pay = 1;
  1934. $v->save();
  1935. }
  1936. }
  1937. }
  1938. /**
  1939. * 自动取消认养配送订单
  1940. */
  1941. public function adoptCostOrderCancel() {
  1942. $time = time();
  1943. $over_time = Option::get(OptionSetting::STORE_DELIVERY_TIME, $this->store_id)['value'];
  1944. if (!$over_time) {
  1945. $over_time = 1;
  1946. }
  1947. $over_day = $time - ($over_time * 86400);
  1948. $orders = AdoptCostOrder::find()->where(['is_delete' => 0, 'is_pay' => 0, 'store_id' => $this->store_id,])
  1949. ->andWhere(['<>', 'trade_status', Order::ORDER_FLOW_CANCEL])
  1950. ->andWhere(['<=', 'created_at', $over_day])->andWhere(['!=', 'pay_type', 2])
  1951. ->all();
  1952. /* @var AdoptCostOrder[] $orders */
  1953. if (!empty($orders)) {
  1954. foreach ($orders as $order) {
  1955. $t = \Yii::$app->db->beginTransaction();
  1956. if ($order->order_type == 1) {
  1957. $adopt_order = AdoptOrderInfo::find()->where(['order_id' => $order->order_id, 'is_delete' => 0, 'store_id' => $this->store_id,])->one();
  1958. $adopt_order->updateCounters(['harvest_weight' => $order->weight]);
  1959. }
  1960. $order->trade_status = Order::ORDER_FLOW_CANCEL;
  1961. $order->updated_at = time();
  1962. if (!$order->save()) {
  1963. $t->rollBack();
  1964. continue;
  1965. }
  1966. $t->commit();
  1967. }
  1968. }
  1969. }
  1970. /**
  1971. * 抖品发放佣金
  1972. */
  1973. public function sendVideoGoodsProfit($id)
  1974. {
  1975. try {
  1976. $video_share = VideoGoodsShare::find()->where(['order_id' => $id, 'is_pay' => 1, 'is_send' => 0])->all();
  1977. foreach ($video_share as $item) {
  1978. $item->is_send = 1;
  1979. $item->send_time = time();
  1980. if ($item->save()) {
  1981. $user = User::findOne($item->author_user_id);
  1982. $user->total_price = ((float)$user->total_price + (float)$item->proportion);
  1983. $user->price = ((float)$user->price + (float)$item->proportion);
  1984. if ($user->save()) {
  1985. $UserShareMoney = new UserShareMoney();
  1986. $UserShareMoney->store_id = $item->store_id;
  1987. $UserShareMoney->order_id = $item->order_id;
  1988. $UserShareMoney->user_id = $item->author_user_id;
  1989. $UserShareMoney->type = 0;
  1990. $UserShareMoney->source = 1;
  1991. $UserShareMoney->money = $item->proportion;
  1992. $UserShareMoney->created_at = time();
  1993. $UserShareMoney->order_type = 0;
  1994. $UserShareMoney->is_delete = 0;
  1995. $UserShareMoney->version = cyy_version();
  1996. $UserShareMoney->save();
  1997. }
  1998. }
  1999. }
  2000. } catch (\Exception $e) {
  2001. \Yii::error($e->getMessage());
  2002. }
  2003. }
  2004. /**
  2005. * 成为股东自动成为分销商
  2006. * @param $user_id integer 用户id
  2007. */
  2008. private function shareHolderAutoBecomeShare()
  2009. {
  2010. $share_holder_list = ShareHolder::find()->alias('sh')
  2011. ->where(['sh.is_delete' => 0, 'sh.status' => 1])
  2012. ->leftJoin(['s' => Share::tableName()], 'sh.user_id=s.user_id')
  2013. ->andWhere('s.id is null')
  2014. ->select('sh.*')
  2015. ->asArray()->all();
  2016. foreach ($share_holder_list as $k => $v) {
  2017. $user_id = $v['user_id'];
  2018. $store_id = $v['store_id'];
  2019. $share = Share::findOne(['user_id' => $user_id, 'is_delete' => 0, 'store_id' => $store_id]);
  2020. if ($share && $share->status == 1) {
  2021. continue;
  2022. }
  2023. if (!$share || $share->status == 2) {
  2024. $share = new Share();
  2025. $share->user_id = $user_id;
  2026. $share->mobile = '';
  2027. $share->name = '';
  2028. $share->is_delete = 0;
  2029. $share->store_id = $store_id;
  2030. }
  2031. $share->status = 1;
  2032. $share->created_at = time();
  2033. $share->save();
  2034. $user = User::findOne($user_id);
  2035. $user->time = time();
  2036. $user->is_distributor = 1;
  2037. $user->save();
  2038. }
  2039. }
  2040. /**
  2041. * 用户自动成为分销商
  2042. * @param $user_id integer 用户id
  2043. */
  2044. private function userAutoBecomeShare()
  2045. {
  2046. $store_id = $this->store_id;
  2047. $share_basic_setting = Option::get(OptionSetting::SHARE_BASIC_SETTING, $store_id, OptionSetting::SHARE_GROUP_NAME, '')['value'];
  2048. $share_basic_setting = json_decode($share_basic_setting, true);
  2049. //
  2050. $share_basic_setting['share_condition']['value'] = $share_basic_setting['share_condition']['value'] ?? 2;
  2051. $share_basic_setting['auto_share_val']['value'] = $share_basic_setting['auto_share_val']['value'] ?? 0;
  2052. // if (!empty($share_basic_setting['share_condition']) && !empty($share_basic_setting['auto_share_val'])) {
  2053. //判断无需审核且消费0元成为分销商条件
  2054. if (intval($share_basic_setting['share_condition']['value']) === 2 && floatval($share_basic_setting['auto_share_val']['value']) <= 0) {
  2055. //筛出已经成为分销商的用户
  2056. $filter_user_id = Share::find()->where(['is_delete' => 0, 'store_id' => $store_id, 'status' => 1])->select('user_id')
  2057. ->column();
  2058. //筛出已经被删除的分销商
  2059. $filter_delete_user_id = Share::find()->where(['is_delete' => 1, 'store_id' => $store_id, 'status' => 1])->select('user_id')
  2060. ->column();
  2061. $filter_user_id = array_merge($filter_user_id, $filter_delete_user_id);
  2062. //查询用户
  2063. $user_query = User::find()->where(['store_id' => $store_id, 'is_delete' => 0]);
  2064. if (!empty($filter_user_id)) {
  2065. $user_query->andWhere(['NOT IN', 'id', $filter_user_id]);
  2066. }
  2067. $user_list = $user_query->select('id')->column();
  2068. foreach ($user_list as $item) {
  2069. $share = Share::findOne(['user_id' => $item->id, 'is_delete' => 0, 'store_id' => $store_id]);
  2070. if (!$share) {
  2071. $share = new Share();
  2072. $share->mobile = '';
  2073. $share->name = '';
  2074. $share->is_delete = 0;
  2075. $share->user_id = $item;
  2076. $share->created_at = time();
  2077. }
  2078. $share->status = 1;
  2079. $share->store_id = $store_id;
  2080. if ($share->save()) {
  2081. $user = User::findOne($item);
  2082. $user->time = time();
  2083. $user->is_distributor = 1;
  2084. $user->save();
  2085. }
  2086. }
  2087. }
  2088. // }
  2089. }
  2090. public function seckillActivityOrder($store_id)
  2091. {
  2092. try {
  2093. $activity_order_log = SeckillActivityOrderLog::find()->alias('sao')->where(['AND', [
  2094. '<', 'sao.created_at', (time() - (60 * 15))
  2095. ], [
  2096. 'sao.is_delete' => 0,
  2097. 'sao.store_id' => $store_id,
  2098. ]])->andWhere([
  2099. 'OR', [
  2100. 'o.trade_status' => 1
  2101. ],
  2102. [
  2103. 'o.is_pay' => 0,
  2104. ]
  2105. ])->leftJoin(['o' => Order::tableName()], 'sao.order_id = o.id')->select('sao.id, sao.is_delete, sao.activity_goods_id, sao.activity_id, sao.num, sao.goods_id')->all();
  2106. foreach ($activity_order_log as $item) {
  2107. $goods = SeckillActivityGoods::findOne(['is_delete' => 0, 'goods_id' => $item->goods_id, 'activity_id' => $item->activity_id]);
  2108. if ($goods) {
  2109. $goods->sale_num -= $item->num;
  2110. if (!$goods->save()) {
  2111. throw new \Exception(json_encode($goods->errors));
  2112. }
  2113. }
  2114. $item->is_delete = 1;
  2115. if (!$item->save()) {
  2116. throw new \Exception(json_encode($item->errors));
  2117. }
  2118. }
  2119. } catch (\Exception $e) {
  2120. \Yii::error("秒杀逻辑处理" . $e->getMessage());
  2121. // return [
  2122. // 'code' => 1,
  2123. // 'msg' => $e->getMessage()
  2124. // ];
  2125. }
  2126. }
  2127. //拼团
  2128. public function ptActivityOrder($store_id)
  2129. {
  2130. try {
  2131. //判断团长下单的人
  2132. $pt_order_all = PtActivityOrder::find()->alias('o')
  2133. ->where(['o.store_id' => $store_id, 'o.is_pay' => 1, 'o.trade_status' => 0, 'is_pt_finish' => 0])
  2134. ->leftJoin(['od' => PtActivityOrderDetail::tableName()], 'o.id = od.order_id')
  2135. ->andWhere(['o.pt_number' => 0])->select('o.id, od.activity_id, o.pay_time')->asArray()->all();
  2136. foreach ($pt_order_all as $pt_order) {
  2137. $activity = PtActivity::findOne($pt_order['activity_id']);
  2138. $split_time = ($activity->split_time * 60 * 60);
  2139. //已经过期,需要失败处理
  2140. if ((time() - $split_time > $pt_order['pay_time']) || $activity->end_time < time()) {
  2141. $pt_order_ = PtActivityOrder::find()->where(['is_pay' => 1])
  2142. ->andWhere(['OR', ['id' => $pt_order['id']], ['pt_number' => $pt_order['id']]])
  2143. ->select('id')->asArray()->all();
  2144. foreach ($pt_order_ as $item) {
  2145. $order = PtActivityOrder::findOne($item['id']);
  2146. if ($order->head_integral > 0 && intval($order->head_integral_status) === 1) {
  2147. $res = AccountLog::saveLog($order->user_id, floatval($order->head_integral), AccountLog::TYPE_INTEGRAL, AccountLog::LOG_TYPE_INCOME, 3, $order->id, "商城拼团失败,退还开团支付积分,订单号为:{$order->order_no}。");
  2148. if (!$res) {
  2149. debug_log('开团积分退款失败' . json_encode($res), 'ptOrderLog.log');
  2150. }
  2151. $order->head_integral_status = 2;
  2152. }
  2153. $order->is_pt_finish = 2;
  2154. $order->save();
  2155. }
  2156. $form = new PtActivityOrderForm();
  2157. $result = $form->loserHandle($pt_order['id']);
  2158. if ($result['code'] !== 0) {
  2159. throw new \Exception($result['msg']);
  2160. }
  2161. }
  2162. }
  2163. } catch (\Exception $e) {
  2164. \Yii::error("拼团逻辑处理" . $e->getMessage());
  2165. // return [
  2166. // 'code' => 1,
  2167. // 'msg' => $e->getMessage()
  2168. // ];
  2169. }
  2170. }
  2171. private function agencyPrice($order_id){
  2172. try {
  2173. $order = Order::findOne($order_id);
  2174. $option = Option::get('agency_price_config', 0, 'saas', [])['value'];
  2175. debug_log('agency_price_config' . $option);
  2176. if ($option) {
  2177. $option = json_decode($option, true);
  2178. }
  2179. $province_percent = $option['province_percent'] ?? 0;
  2180. $city_percent = $option['city_percent'] ?? 0;
  2181. $district_percent = $option['district_percent'] ?? 0;
  2182. $bdoption = Option::get('bd_agency_price_config', 0, 'saas', [])['value'];
  2183. debug_log('bd_agency_price_config' . $bdoption);
  2184. if ($bdoption) {
  2185. $bdoption = json_decode($bdoption, true);
  2186. }
  2187. $bd_agent_percent = $bdoption['bd_agent_percent'] ?? 0;
  2188. //获取代理商ID
  2189. $store = Store::findOne($order->store_id);
  2190. $admin_list = Admin::find()->where(['province_id' => $store->province_id, 'is_delete' => 0, 'type' => 'admin'])->asArray()->all();
  2191. $user = User::findOne($order->user_id);
  2192. $saasUser = SaasUser::findOne(['mobile' => $user->binding]);
  2193. $saas_user_name = '-';
  2194. if ($saasUser) {
  2195. $saas_user_name = $saasUser->name;
  2196. }
  2197. //推广代理
  2198. if($store->salesman_id){
  2199. $salesman = Salesman::findOne($store->salesman_id);
  2200. $bd = Admin::find()->where(['type' => Admin::ADMIN_TYPE_BD_AGENT, 'id' => $salesman['admin_id']])->asArray()->one();
  2201. if($bd){
  2202. $admin_list[] = $bd;
  2203. }
  2204. }
  2205. foreach ($admin_list as $item) {
  2206. $ag_rebate = 0;
  2207. $rate = 0;
  2208. $desc = '';
  2209. $type = StoreShareMoney::TYPE_AREA_AGENT;
  2210. if($item['type'] == Admin::ADMIN_TYPE_BD_AGENT){
  2211. $ag_rebate = $order->ag_rebate * ($bd_agent_percent / 100);
  2212. $ag_rebate = sprintf("%.2f", $ag_rebate);
  2213. $rate = $bd_agent_percent;
  2214. $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元推广代佣金';
  2215. $type = StoreShareMoney::TYPE_BD_AGENT;
  2216. }
  2217. //省
  2218. if ((int)$item['area_level'] === 3) {
  2219. $ag_rebate = $order->ag_rebate * ($province_percent / 100);
  2220. $ag_rebate = sprintf("%.2f", $ag_rebate);
  2221. $rate = $province_percent;
  2222. $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元省代佣金';
  2223. }
  2224. //市
  2225. if ((int)$item['area_level'] === 2 && (int)$item['city_id'] === (int)$store->city_id) {
  2226. $ag_rebate = $order->ag_rebate * ($city_percent / 100);
  2227. $ag_rebate = sprintf("%.2f", $ag_rebate);
  2228. $rate = $city_percent;
  2229. $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元市代佣金';
  2230. }
  2231. //区
  2232. if ((int)$item['area_level'] === 1 && (int)$item['city_id'] === (int)$store->city_id && (int)$item['district_id'] === (int)$store->district_id) {
  2233. $ag_rebate = $order->ag_rebate * ($district_percent / 100);
  2234. $ag_rebate = sprintf("%.2f", $ag_rebate);
  2235. $rate = $district_percent;
  2236. $desc = '用户' . $saas_user_name . '下单,订单' . $order->order_no . ',发放 ' . $ag_rebate . '元区代佣金';
  2237. }
  2238. if ($ag_rebate <= 0) {
  2239. continue;
  2240. }
  2241. //给用户增加佣金
  2242. $SaasUser = SaasUser::findOne($item['saas_user_id']);
  2243. $SaasUser->share_profit = ($SaasUser->share_profit * 1) + ($ag_rebate * 1);
  2244. $res = $SaasUser->save();
  2245. //增加记录
  2246. if ($res) {
  2247. $form = new StoreShareMoney();
  2248. $form->user_id = $SaasUser->id;
  2249. $form->store_id = $store->id;
  2250. $form->profit = $rate;
  2251. $form->total_price = $order->total_price;
  2252. $form->desc = $desc;
  2253. $form->order_id = $order_id;
  2254. $form->created_at = time();
  2255. $form->type = $type;//
  2256. $form->status = StoreShareMoney::STATUS_STORE_ORDER;
  2257. $form->commission = $ag_rebate;
  2258. $form->is_send = 1;
  2259. $res = $form->save();
  2260. if (!$res) {
  2261. debug_log($form->errors);
  2262. }
  2263. }
  2264. }
  2265. } catch (\Exception $e) {
  2266. \Yii::error($e->getMessage());
  2267. }
  2268. }
  2269. private function sendGoodsAgentMoney($order_id){
  2270. $t = \Yii::$app->db->beginTransaction();
  2271. try {
  2272. $order = Order::findOne($order_id);
  2273. $option = Option::get('goods_agent_price_config', 0, 'saas', [])['value'];
  2274. $option = json_decode($option, true);
  2275. $goods_agent_percent = $option['goods_agent_percent'] ?? 0;
  2276. $goods_agent_install_percent = $option['goods_agent_install_percent'] ?? 0;
  2277. //订单中是否包含产品代理绑定的产品
  2278. $order_detail = OrderDetail::find()->alias('od')
  2279. ->leftJoin(['g' => Goods::tableName()], 'od.goods_id = g.id')->where(['od.order_id' => $order->id])
  2280. ->select('od.id, g.cloud_goods_id, od.total_price, g.cloud_supplier_id, g.name')->asArray()->all();
  2281. foreach ($order_detail as $value) {
  2282. //计算产品代理佣金
  2283. $supplier_rate = 0;
  2284. if (!empty($value['cloud_supplier_id'])) {
  2285. $supplier = Supplier::findOne(['cloud_supplier_id' => $value['cloud_supplier_id']]);
  2286. $supplier_rate = $supplier->rate;
  2287. }
  2288. if (!empty($value['cloud_goods_id'])) {
  2289. //抓取云仓佣金
  2290. $cloud_url = "/goods/getGoodsInfo";
  2291. $cloud_data = [];
  2292. $cloud_data['goods_id'] = $value['cloud_goods_id'];
  2293. $domain = (new OptionSetting)->getCloudDomainName();
  2294. $cloud_info = cloud_post($domain . $cloud_url, $cloud_data);
  2295. $cloud_info = json_decode($cloud_info, true);
  2296. if($cloud_info['code'] != 0){
  2297. throw new \Exception($cloud_info['msg']);
  2298. }else{
  2299. $goods = $cloud_info['data']['goods'];
  2300. $agent_profit_default = (int)$goods['agent_profit_default'];
  2301. if (!$agent_profit_default) {
  2302. $goods_agent_percent = $goods['agent_percent'];
  2303. $goods_agent_install_percent = $goods['agent_install_percent'];
  2304. }
  2305. }
  2306. $agent_goods_bind_goods = AgentGoodsBindGoods::find()->where(['cloud_goods_id' => $value['cloud_goods_id'], 'is_delete' => 0, 'status' => 1])
  2307. ->select('goods_agent_admin_id, cloud_supplier_id')->asArray()->all();
  2308. if (!empty($agent_goods_bind_goods)) {
  2309. $goods_agent_admin_id = array_column($agent_goods_bind_goods, 'goods_agent_admin_id');
  2310. $where = [
  2311. 'id' => $goods_agent_admin_id,
  2312. 'province_id' => $order->province_id
  2313. ];
  2314. $admin = Admin::findOne(array_merge($where, [
  2315. 'area_level' => 1,
  2316. 'city_id' => $order->city_id,
  2317. 'district_id' => $order->district_id
  2318. ]));
  2319. if (empty($admin)) {
  2320. $admin = Admin::findOne(array_merge($where, [
  2321. 'area_level' => 2,
  2322. 'city_id' => $order->city_id
  2323. ]));
  2324. if (empty($admin)) {
  2325. $admin = Admin::findOne(array_merge($where, [
  2326. 'area_level' => 3
  2327. ]));
  2328. }
  2329. }
  2330. if (!empty($admin)) {
  2331. $agent_rebate = $value['total_price'] * ($supplier_rate / 100) * ($goods_agent_percent / 100);
  2332. //给用户增加佣金
  2333. $SaasUser = SaasUser::findOne($admin->saas_user_id);
  2334. $SaasUser->share_profit = ($SaasUser->share_profit * 1) + ($agent_rebate * 1);
  2335. if (!$SaasUser->save()) {
  2336. throw new \Exception(json_encode($SaasUser->errors));
  2337. }
  2338. $StoreShareMoney = new StoreShareMoney();
  2339. $StoreShareMoney->user_id = $SaasUser->id;
  2340. $StoreShareMoney->store_id = $order->store_id;
  2341. $StoreShareMoney->profit = $goods_agent_percent;
  2342. $StoreShareMoney->total_price = $value['total_price'];
  2343. $StoreShareMoney->desc = '产品代理佣金发放,代理商品' . $value['name'];
  2344. $StoreShareMoney->order_id = $order_id;
  2345. $StoreShareMoney->created_at = time();
  2346. $StoreShareMoney->status = StoreShareMoney::STATUS_STORE_ORDER;
  2347. $StoreShareMoney->type = StoreShareMoney::TYPE_GOODS_AGENT;
  2348. $StoreShareMoney->commission = $agent_rebate;
  2349. $StoreShareMoney->is_send = 1;
  2350. if (!$StoreShareMoney->save()) {
  2351. throw new \Exception(json_encode($StoreShareMoney->errors));
  2352. }
  2353. }
  2354. }
  2355. }
  2356. //计算上门安装佣金
  2357. $install_log = AgentGoodsInstallLog::findOne(['order_detail_id' => $value['id'], 'status' => 2, 'is_need_install' => 1, 'order_type' => AgentGoodsInstallLog::ORDER_TYPE_NORMAL]);
  2358. if (!empty($install_log)) {
  2359. $admin = Admin::findOne($install_log->goods_agent_admin_id);
  2360. if (!empty($admin)) {
  2361. $agent_rebate = $value['total_price'] * ($supplier_rate / 100) * ($goods_agent_install_percent / 100);
  2362. //给用户增加佣金
  2363. $SaasUser = SaasUser::findOne($admin->saas_user_id);
  2364. $SaasUser->share_profit = ($SaasUser->share_profit * 1) + ($agent_rebate * 1);
  2365. if (!$SaasUser->save()) {
  2366. throw new \Exception(json_encode($SaasUser->errors));
  2367. }
  2368. $StoreShareMoney = new StoreShareMoney();
  2369. $StoreShareMoney->user_id = $SaasUser->id;
  2370. $StoreShareMoney->store_id = $order->store_id;
  2371. $StoreShareMoney->profit = $goods_agent_install_percent;
  2372. $StoreShareMoney->total_price = $value['total_price'];
  2373. $StoreShareMoney->desc = '产品代理上门安装佣金发放,安装商品' . $value['name'];
  2374. $StoreShareMoney->order_id = $order_id;
  2375. $StoreShareMoney->created_at = time();
  2376. $StoreShareMoney->status = StoreShareMoney::STATUS_STORE_ORDER;
  2377. $StoreShareMoney->type = StoreShareMoney::TYPE_GOODS_AGENT;
  2378. $StoreShareMoney->commission = $agent_rebate;
  2379. $StoreShareMoney->is_send = 1;
  2380. if (!$StoreShareMoney->save()) {
  2381. throw new \Exception(json_encode($StoreShareMoney->errors));
  2382. }
  2383. }
  2384. }
  2385. }
  2386. $t->commit();
  2387. } catch (\Exception $e) {
  2388. $t->rollBack();
  2389. \Yii::error($e->getMessage());
  2390. }
  2391. }
  2392. /**
  2393. * 同城配送订单处理
  2394. */
  2395. private function localDeliveryOrder()
  2396. {
  2397. \Yii::warning(['---- Order Event BEGIN 自动派单发放开始 localDeliveryOrder ----']);
  2398. $time = time();
  2399. $values = Option::find()->where([
  2400. 'store_id' => 0,
  2401. 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING
  2402. ])->select('value')->one();
  2403. if ($values) {
  2404. $local_setting = json_decode($values->value, true);
  2405. } else {
  2406. $local_setting = null;
  2407. }
  2408. if ($local_setting['send_type']['value'] != 'auto') { //未开启自动派单
  2409. \Yii::warning(['---- Order Event BEGIN 平台未开启自动派单 localDeliveryOrder ----']);
  2410. return false;
  2411. }
  2412. $default_time = $local_setting['default_time']['value']; //默认预计送达所消耗的时间,例:30分钟
  2413. //待分配骑手的订单
  2414. $list = Order::find()->alias('o')
  2415. ->leftJoin(['di' => DeliveryInfo::tableName()], 'o.order_no = di.order_no')
  2416. ->where(['o.order_type' => Order::ORDER_TYPE_STORE, 'di.is_local' => 1])
  2417. ->andWhere([
  2418. 'o.trade_status' => Order::ORDER_FLOW_NO_SEND,
  2419. 'o.is_delete' => Order::IS_DELETE_FALSE,
  2420. 'di.local_status' => DeliveryInfo::LOCAL_STATUS_NO_SEND,
  2421. 'di.rider_id' => 0,
  2422. ])
  2423. ->andWhere([
  2424. 'or',
  2425. ['o.is_pay' => Order::IS_PAY_TRUE],
  2426. ['o.pay_type' => Order::PAY_TYPE_COD]
  2427. ])
  2428. ->andWhere([
  2429. 'or',
  2430. ['<=', 'o.delivery_time', bcadd($time, bcmul($default_time, 60, 0), 0)],
  2431. ['o.delivery_time' => 0]
  2432. ])
  2433. ->select('o.*')
  2434. ->all();
  2435. foreach ($list as $order) {
  2436. $this->autoSendDeliveryOrder($order);
  2437. }
  2438. }
  2439. /**
  2440. * 模块名:autoSendDeliveryOrder
  2441. * 代码描述:平台自配的同城订单自动派单
  2442. * 作者:WPing丶
  2443. * 请求方式:GET
  2444. * 创建时间:2023/07/04 16:39:37
  2445. * @param object order
  2446. */
  2447. private function autoSendDeliveryOrder($order)
  2448. {
  2449. \Yii::warning(['---- Order Event BEGIN 平台自动派单开始,order_id='.$order->id.' ----']);
  2450. if ($order->is_delivery != 1) { //非同城订单
  2451. \Yii::warning(['---- Order Event BEGIN 非同城订单,order_id='.$order->id.' ----']);
  2452. return false;
  2453. }
  2454. $values = Option::find()->where([
  2455. 'store_id' => 0,
  2456. 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING
  2457. ])->select('value')->one();
  2458. if ($values) {
  2459. $local_setting = json_decode($values->value, true);
  2460. } else {
  2461. $local_setting = null;
  2462. }
  2463. $default_time = $local_setting['default_time']['value'];
  2464. if ((time() + ($default_time * 60)) < $order->delivery_time) { //期望送达时间提前30分钟分配订单
  2465. \Yii::warning(['---- Order Event BEGIN 当前订单时间小于期望送达时间,order_id='.$order->id.' ----']);
  2466. return false;
  2467. }
  2468. $delivery_info = DeliveryInfo::findOne(['order_no' => $order->order_no]);
  2469. if ($delivery_info->is_local == DeliveryInfo::IS_LOCAL_NO) { //非平台自配
  2470. \Yii::warning(['---- Order Event BEGIN 当前订单非平台自配订单,order_id='.$order->id.' ----']);
  2471. return false;
  2472. }
  2473. $option = Option::find()->where(['store_id' => 0, 'group' => OptionSetting::LOCAL_DELIVERY_GROUP_NAME, 'name' => OptionSetting::LOCAL_DELIVERY_SETTING])->select('value')->one();
  2474. if ($option) {
  2475. $setting = json_decode($option->value, true);
  2476. } else {
  2477. $setting = null;
  2478. }
  2479. if ($setting['send_type']['value'] != 'auto') { //未开启自动派单
  2480. \Yii::warning(['---- Order Event BEGIN 平台未开启自动派单,order_id='.$order->id.' ----']);
  2481. return false;
  2482. }
  2483. //获取可配送此订单的配送员列表
  2484. $query = LocalDeliveryCourier::find()
  2485. ->where([
  2486. 'is_delete' => 0,
  2487. 'state' => 2,
  2488. 'status' => 1
  2489. ]);
  2490. /* 2023年7月6日20:17:11 */
  2491. //配送员筛选条件:配送订单自动推送给负责本村的配送员
  2492. $province_id = $order->province_id ? $order->province_id : 0;
  2493. $city_id = $order->city_id ? $order->city_id : 0;
  2494. $district_id = $order->district_id ? $order->district_id : 0;
  2495. $town_id = $order->town_id ? $order->town_id : 0;
  2496. $village_id = $order->village_id ? $order->village_id : 0;
  2497. $area = '[{"province_id":"' . $province_id . '","city_id":"' . $city_id . '","district_id":"' . $district_id . '","town_id":"' . $town_id . '","village_id":"' . $village_id . '"}]';
  2498. $query->andWhere(['area' => $area]);
  2499. /* end */
  2500. //默认都为店铺模式
  2501. //if ($setting['delivery_type']['value'] == "store") { //店铺模式:开启该模式只有店铺的“专属配送员”或者“平台配送员”才可以配送此订单
  2502. $query->andWhere([
  2503. 'or',
  2504. ['store_id' => $order->store_id],
  2505. ['type' => 1]
  2506. ]);
  2507. //}
  2508. $courier_list = $query->asArray()->all();
  2509. $courier_list_new = [];
  2510. foreach ($courier_list as $courier) {
  2511. //获取当前配送员正在配送的订单数量
  2512. $now_order_num = DeliveryInfo::find()
  2513. ->alias('di')
  2514. ->leftJoin(['o' => Order::tableName()], 'o.order_no = di.order_no')
  2515. ->where(['di.rider_id' => $courier['id'], 'di.is_local' => 1, 'o.is_pay' => 1])
  2516. ->andWhere([
  2517. 'or',
  2518. ['o.trade_status' => 0],
  2519. ['o.trade_status' => 1]
  2520. ])->count();
  2521. if ($courier['max_num'] == 0 || $now_order_num < $courier['max_num']) { //排除掉订单满载的配送员
  2522. $work_time = json_decode($courier['work_time'],true);
  2523. $begin_time = strtotime(date('Y-m-d ').$work_time[0]['begin_time']);
  2524. $end_time = strtotime(date('Y-m-d ').$work_time[0]['end_time']);
  2525. if (time() >= $begin_time && time() <= $end_time ) {//排除不在上岗时间的配送员
  2526. $courier_list_new[] = $courier;
  2527. }
  2528. }
  2529. }
  2530. if (count($courier_list_new) == 0) { //没有满足条件的配送员
  2531. \Yii::warning(['---- Order Event BEGIN 平台没有满足条件的配送员,order_id='.$order->id.' ----']);
  2532. return false;
  2533. }
  2534. //随机选择一名天选打工人给他分配订单(目前是随机,后期再优化)
  2535. $t = \Yii::$app->db->beginTransaction(); //开始事务
  2536. $randomKey = array_rand($courier_list_new);
  2537. $chosen_worker = $courier_list_new[$randomKey];
  2538. $delivery_info->rider_id = $chosen_worker['id'];
  2539. $delivery_info->rider_name = $chosen_worker['real_name'];
  2540. $delivery_info->rider_mobile = $chosen_worker['mobile'];
  2541. $delivery_info->local_status = DeliveryInfo::LOCAL_STATUS_WAITING;
  2542. $delivery_info->rush_time = time();
  2543. if (!$delivery_info->save()) {
  2544. \Yii::warning(['---- Order Event BEGIN 存delivery_info表失败,order_id='.$order->id.' ----']);
  2545. $t->rollBack(); //事务回滚
  2546. return false;
  2547. }
  2548. $order->send_time = time();
  2549. $order->trade_status = 2;
  2550. if (!$order->save()) {
  2551. \Yii::warning(['---- Order Event BEGIN 存order表失败,order_id='.$order->id.' ----']);
  2552. $t->rollBack(); //事务回滚
  2553. return false;
  2554. }
  2555. \Yii::warning(['---- Order Event END 自动派单成功,order_id='.$order->id.' ----']);
  2556. $t->commit(); //事务执行
  2557. }
  2558. //会员到期
  2559. public function userLevelExpiresHandle() {
  2560. try {
  2561. //获取已经到期的用户且排除永久日期的用户
  2562. $time = time();
  2563. $user_list = User::find()->where(['is_delete' => User::USER_NOT_DELETE])
  2564. ->andWhere(['AND', ['<', 'user_level_expires', $time], ['>', 'user_level_expires', 0]])
  2565. ->asArray()->all();
  2566. foreach ($user_list as $user_item) {
  2567. $user_level_expires_ext = json_decode($user_item['user_level_expires_ext'], true);
  2568. //排序
  2569. $last_names = array_column($user_level_expires_ext, 'level');
  2570. array_multisort($last_names, SORT_DESC, $user_level_expires_ext);
  2571. //去除已经过期的
  2572. if ($user_level_expires_ext) {
  2573. foreach ($user_level_expires_ext as $user_level_index => $user_level_item) {
  2574. // 去除已经过期的
  2575. if ($user_level_item['expires_in'] > 0 && $user_level_item['expires_in'] <= time()) {
  2576. unset($user_level_expires_ext[$user_level_index]);
  2577. }
  2578. }
  2579. }
  2580. $user_level_expires_ext = array_values($user_level_expires_ext);
  2581. $user = User::findOne($user_item['id']);
  2582. //
  2583. $user_level_expires = $user->user_level_expires;
  2584. $user_level = -1;
  2585. if (isset($user_level_expires_ext[0]['expires_in'])) {
  2586. $user_level_expires = $user_level_expires_ext[0]['expires_in'];
  2587. $user_level = $user_level_expires_ext[0]['level'];
  2588. }
  2589. $user->user_level_expires_ext = json_encode($user_level_expires_ext, JSON_UNESCAPED_UNICODE);
  2590. $user->user_level_expires = $user_level_expires;
  2591. $user->level = $user_level;
  2592. $user->save();
  2593. }
  2594. $team_grades_list = TeamGrades::find()->where(['is_delete' => User::USER_NOT_DELETE])
  2595. ->andWhere(['AND', ['<', 'level_expires', $time], ['>', 'level_expires', 0]])
  2596. ->asArray()->all();
  2597. foreach ($team_grades_list as $team_grades_item) {
  2598. $level_expires_ext = json_decode($team_grades_item['level_expires_ext'], true);
  2599. //排序
  2600. $last_names = array_column($level_expires_ext, 'level');
  2601. array_multisort($last_names, SORT_DESC, $level_expires_ext);
  2602. //去除已经过期的
  2603. if ($level_expires_ext) {
  2604. foreach ($level_expires_ext as $user_level_index => $user_level_item) {
  2605. // 去除已经过期的
  2606. if ($user_level_item['expires_in'] > 0 && $user_level_item['expires_in'] <= time()) {
  2607. unset($level_expires_ext[$user_level_index]);
  2608. }
  2609. }
  2610. }
  2611. $level_expires_ext = array_values($level_expires_ext);
  2612. $teamGrades = TeamGrades::findOne($team_grades_item['id']);
  2613. //
  2614. $level_expires = 0;
  2615. $team_grades_level = -1;
  2616. if (isset($level_expires_ext[0]['expires_in'])) {
  2617. $level_expires = $level_expires_ext[0]['expires_in'];
  2618. $team_grades_level = $level_expires_ext[0]['level'];
  2619. }
  2620. $teamGrades->level_expires_ext = json_encode($level_expires_ext, JSON_UNESCAPED_UNICODE);
  2621. $teamGrades->level_expires = $level_expires;
  2622. $teamGrades->team_grades_level = $team_grades_level;
  2623. $teamGrades->save();
  2624. }
  2625. } catch (\Exception $e) {
  2626. }
  2627. }
  2628. public function getWechatConfig($store_id) {
  2629. // TODO: 小程序为例
  2630. // 获取微信配置进行初始化
  2631. $wechat_config = WechatConfig::findOne(['store_id' => $store_id, 'type' => 1]);
  2632. if (\Yii::$app->prod_is_dandianpu()) {
  2633. $platform_mch_appid = Option::get('one_store_wechat_appid', 0, 'saas')['value'];
  2634. $platform_mch_key = Option::get('one_store_wechat_secret', 0, 'saas')['value'];
  2635. $wechat_config = (object)[
  2636. 'app_id' => $platform_mch_appid,
  2637. 'app_secret' => $platform_mch_key
  2638. ];
  2639. //没有进件走平台账号
  2640. if($store_id > 0){
  2641. $hasIncoming = \app\models\Store::hasIncoming($store_id);
  2642. if(!$hasIncoming){
  2643. $mch_id = Option::get('one_store_mch_id', 0, 'saas', '')['value'];
  2644. $pay_key = Option::get('one_store_pay_key', 0, 'saas', '')['value'];
  2645. $apiclient_cert = Option::get('one_store_apiclient_cert', 0, 'saas', '')['value'];
  2646. $apiclient_key = Option::get('one_store_apiclient_key', 0, 'saas', '')['value'];
  2647. $wechat_config->mch_id = $mch_id;
  2648. $wechat_config->pay_key = $pay_key;
  2649. $wechat_config->cert_pem = $apiclient_cert;
  2650. $wechat_config->key_pem = $apiclient_key;
  2651. }
  2652. }
  2653. } else {
  2654. //如果是商盟 获取商盟小程序配置信息
  2655. if($store_id == -1){
  2656. $keys = [
  2657. 'platform_appid',
  2658. 'platform_mch_id',
  2659. 'platform_key',
  2660. 'platform_apiclient_cert',
  2661. 'platform_apiclient_key',
  2662. 'platform_pay_key',
  2663. ];
  2664. $data = Option::get($keys, 0, 'saas');
  2665. if (empty($data)) {
  2666. $data = [
  2667. 'platform_appid' => '',
  2668. 'platform_mch_id' => '',
  2669. 'platform_key' => ' ',
  2670. 'platform_apiclient_cert' => '',
  2671. 'platform_apiclient_key' => '',
  2672. 'platform_pay_key'=> '',
  2673. ];
  2674. } else {
  2675. $arr = [];
  2676. foreach ($data as $value) {
  2677. $index = array_search($value['name'], $keys);
  2678. unset($keys[$index]);
  2679. $arr[$value['name']] = $value['value'];
  2680. }
  2681. foreach ($keys as $key) {
  2682. $arr[$key] = '';
  2683. }
  2684. $data = $arr;
  2685. }
  2686. $wechat_config =new WechatConfig();
  2687. $wechat_config->app_id = $data['platform_appid'];
  2688. $wechat_config->app_secret = $data['platform_key'];
  2689. $wechat_config->mch_id = $data['platform_mch_id'];
  2690. $wechat_config->pay_key = $data['platform_pay_key'];
  2691. $wechat_config->cert_pem = $data['platform_apiclient_cert'];
  2692. $wechat_config->key_pem = $data['platform_apiclient_key'];
  2693. }
  2694. }
  2695. // 证书
  2696. if (!is_dir(\Yii::$app->runtimePath . '/pem')) {
  2697. mkdir(\Yii::$app->runtimePath . '/pem');
  2698. file_put_contents(\Yii::$app->runtimePath . '/pem/index.html', '');
  2699. }
  2700. $cert_pem_file = null;
  2701. if (isset($wechat_config->cert_pem) && $wechat_config->cert_pem) {
  2702. $cert_pem_file = \Yii::$app->runtimePath . '/pem/' . md5($wechat_config->cert_pem);
  2703. if (!file_exists($cert_pem_file)) {
  2704. file_put_contents($cert_pem_file, $wechat_config->cert_pem);
  2705. }
  2706. }
  2707. $key_pem_file = null;
  2708. if (isset($wechat_config->key_pem) && $wechat_config->key_pem) {
  2709. $key_pem_file = \Yii::$app->runtimePath . '/pem/' . md5($wechat_config->key_pem);
  2710. if (!file_exists($key_pem_file)) {
  2711. file_put_contents($key_pem_file, $wechat_config->key_pem);
  2712. }
  2713. }
  2714. $config = [
  2715. 'app_id' => $wechat_config->app_id,
  2716. 'secret' => $wechat_config->app_secret,
  2717. 'key' => $wechat_config->pay_key ?? '',
  2718. 'mch_id' => $wechat_config->mch_id ?? '',
  2719. 'cert_path' => $cert_pem_file,
  2720. 'key_path' => $key_pem_file,
  2721. 'response_type' => 'array'
  2722. ];
  2723. return Factory::payment($config);
  2724. }
  2725. //获取微信转账状态
  2726. public function getWechatCashStatus($store_id) {
  2727. $cash_list = Cash::find()->where(
  2728. [
  2729. 'store_id' => $store_id,
  2730. 'is_delete' => 0,
  2731. 'status' => Cash::STATUS_GIVEN,
  2732. 'pay_type' => Cash::PAY_TYPE_WX,
  2733. 'wx_cash_status' => [
  2734. -1,
  2735. Cash::WX_CASH_STATUS_INIT,
  2736. Cash::WX_CASH_STATUS_WAIT_PAY,
  2737. Cash::WX_CASH_STATUS_PROCESSING
  2738. ], 'wx_cash_type' => Cash::WX_CASH_TYPE_OLD
  2739. ])->asArray()->all();
  2740. $wechat = $this->getWechatConfig($store_id);
  2741. $Wxv3 = (new \app\utils\WechatMerchant\WxV3($wechat));
  2742. foreach ($cash_list as $item) {
  2743. $this->handleWechatCashFail($Wxv3, $store_id, $item['order_no']);
  2744. }
  2745. }
  2746. public static function handleWechatCashFail($Wxv3, $store_id, $order_no) {
  2747. $cash = Cash::findOne(['order_no' => $order_no, 'is_delete' => 0, 'wx_cash_status' => [
  2748. -1,
  2749. Cash::WX_CASH_STATUS_INIT,
  2750. Cash::WX_CASH_STATUS_WAIT_PAY,
  2751. Cash::WX_CASH_STATUS_PROCESSING
  2752. ], 'wx_cash_type' => Cash::WX_CASH_TYPE_OLD]);
  2753. if ($cash) {
  2754. $result = $Wxv3->getBatchDetail($store_id, ['out_batch_no' => $order_no]);
  2755. if (!$result['code']) {
  2756. $cash->wx_cash_status = Cash::WX_CASH_STATUS_ARR[$result['data']['detail_status']];
  2757. $cash->wx_cash_error = "";
  2758. if (intval($cash->wx_cash_status) === Cash::WX_CASH_STATUS_FAIL) {
  2759. $cash->wx_cash_error = Cash::WX_CASH_FAIL_REASON[$result['data']['fail_reason']];
  2760. $cash->status = Cash::STATUS_REFUSE;
  2761. cash::cashRefuse($cash->id);
  2762. }
  2763. if ($cash->save()) {
  2764. $user = User::findOne(['id' => $cash->user_id]);
  2765. debug_log([
  2766. 'type' => '提现驳回成功',
  2767. 'result' => $result
  2768. ], 'wechat_cash_status.log');
  2769. NoticeSend::CashFail($cash->user_id, $user->binding, $cash->price, '提现被驳回', '提现被驳回', $store_id);
  2770. } else {
  2771. debug_log([
  2772. 'type' => '提现驳回失败',
  2773. 'error' => json_encode($cash->errors, JSON_UNESCAPED_UNICODE)
  2774. ], 'wechat_cash_status.log');
  2775. }
  2776. }
  2777. }
  2778. }
  2779. }