OrderDeleteForm.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Cache;
  4. use common\helpers\Date;
  5. use common\components\Model;
  6. use common\helpers\Form;
  7. use common\helpers\user\Balance;
  8. use common\helpers\user\Cash;
  9. use common\helpers\user\Info;
  10. use common\libs\logging\operate\AdminOperate;
  11. use common\models\DealType;
  12. use common\models\DecOrder;
  13. use common\models\Order;
  14. use common\models\OrderGoods;
  15. use common\models\Period;
  16. use common\models\ReceiveAddress;
  17. use common\models\Region;
  18. use common\models\ShopGoods;
  19. use common\models\User;
  20. use common\models\UserNetwork;
  21. use yii\base\Exception;
  22. /**
  23. * 删除订单
  24. */
  25. class OrderDeleteForm extends Model
  26. {
  27. public $orderSn;
  28. /**
  29. * @var Order
  30. */
  31. private $_model;
  32. /**
  33. * @inheritdoc
  34. */
  35. public function rules()
  36. {
  37. return [
  38. [['orderSn'], 'trim'],
  39. [['orderSn'], 'required'],
  40. [['orderSn'], 'checkOrderType'],
  41. ];
  42. }
  43. public function attributeLabels()
  44. {
  45. return [
  46. 'orderSn' => '订单号',
  47. ];
  48. }
  49. /**
  50. * 指定校验场景
  51. * @return array
  52. */
  53. public function scenarios()
  54. {
  55. $parentScenarios = parent::scenarios();
  56. $customScenarios = [
  57. // // 管理员发货
  58. // 'adminDelivery' => ['sn', 'expressCompany', 'orderTrackNo'],
  59. // // 会员确认收货
  60. // 'userConfirm' => ['sn', 'expressCompany', 'orderTrackNo'],
  61. // // 管理员修改订单状态
  62. // 'adminStatus' => ['sn', 'status'],
  63. // // 管理员修改备注
  64. // 'adminRemark' => ['sn', 'remark'],
  65. // // 会员下单
  66. // 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'remark', 'payPassword'],
  67. // // 帮会员复消下单
  68. // 'reconsumeOrder' => ['type','userName', 'payType','goodsId','goodsNum', 'remark', 'payPassword','consignee','acceptMobile','province','city','county','detailaddress'],
  69. ];
  70. return array_merge($parentScenarios, $customScenarios);
  71. }
  72. public function returnOrder() {
  73. if(!$this->validate()){
  74. return null;
  75. }
  76. $sn = $this->orderSn;
  77. // 获取订单详情
  78. $orderInfo = Order::findUseDbCalc()
  79. ->select('ID,DEC_SN,USER_ID,ORDER_TYPE,IS_DELETE')
  80. ->where("SN=:SN", [':SN' => $sn])
  81. ->asArray()
  82. ->one();
  83. // 如果会员已经是锁定状态了,删除订单的时候,是否还要退还金额
  84. $db = \Yii::$app->db;
  85. $transaction = $db->beginTransaction();
  86. try {
  87. // 如果是注册订单,则删除订单并退还金额,然后再冻结用户
  88. if ($orderInfo['ORDER_TYPE'] == 'ZC') {
  89. // 删除报单
  90. $delDecOrder = DecOrder::updateAll(
  91. ['IS_DEL'=>1, 'DELETED_AT'=>Date::nowTime()],
  92. 'ORDER_SN=:ORDER_SN',
  93. ['ORDER_SN'=>$sn]
  94. );
  95. if (!$delDecOrder) {
  96. $transaction->rollBack();
  97. throw new Exception('删除报单失败,删除订单失败');
  98. }
  99. // 锁定用户
  100. $userModel = User::findOne(['ID' => $orderInfo['USER_ID']]);
  101. $userModel->STATUS = 0;
  102. $userModel->STATUS_AT = Date::nowTime();
  103. if(!$userModel->save(false)) {
  104. $transaction->rollBack();
  105. throw new Exception('锁定会员失败,删除订单失败');
  106. }
  107. }
  108. // 公共的退钱,删除订单操作
  109. $delOrder = Order::updateAll(
  110. ['IS_DELETE'=>1, 'DELETED_AT'=>Date::nowTime()],
  111. 'SN=:SN',
  112. ['SN'=>$sn]
  113. );
  114. if (!$delOrder) {
  115. $transaction->rollBack();
  116. throw new Exception('删除订单失败');
  117. }
  118. // 开始退钱,退积分等
  119. $payType = $orderInfo['PAY_TYPE'];
  120. $transaction->commit();
  121. } catch(Exception $e) {
  122. $transaction->rollBack();
  123. $this->addError('add', $e->getMessage());
  124. return null;
  125. }
  126. }
  127. /**
  128. * 判断支付方式
  129. * @param $attribute
  130. */
  131. public function isPayType($attribute){
  132. if(!array_key_exists($this->payType, ShopGoods::payTypes())){
  133. $this->addError($attribute, '支付方式错误');
  134. return;
  135. }
  136. }
  137. // 判断订单类型
  138. public function checkOrderType($attribute) {
  139. $sn = $this->orderSn;
  140. $orderDetail = Order::findUseDbCalc()
  141. ->select('ID,DEC_SN,USER_ID,ORDER_TYPE,IS_DELETE')
  142. ->where("SN=:SN", [':SN' => $sn])
  143. ->asArray()
  144. ->one();
  145. if (empty($orderDetail)) {
  146. $this->addError($attribute, '未找到订单信息,订单编号为:'.$this->orderSn);
  147. return ;
  148. }
  149. if ($orderDetail['IS_DELETE'] == 1) {
  150. $this->addError($attribute, '订单已被删除,订单编号为'.$this->orderSn);
  151. return ;
  152. }
  153. // 已挂网或者挂网中的业绩期订单,不能进行删除操作
  154. $periodNum = $orderDetail['PERIOD_NUM'];
  155. $periodObj = Period::findOneAsArray(['PERIOD_NUM'=>$periodNum]);
  156. if (empty($periodObj)) {
  157. $this->addError($attribute, '订单对应业绩期不存在,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
  158. return ;
  159. }
  160. if ($periodObj['IS_SENT'] == 1) {
  161. $this->addError($attribute, '订单对应业绩期已挂网,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
  162. return ;
  163. }
  164. if ($periodObj['IS_SENDING'] == 1) {
  165. $this->addError($attribute, '订单对应业绩期正在挂网,订单编号为'.$this->orderSn.' 业绩期为:'.$periodNum);
  166. return ;
  167. }
  168. if ($orderDetail['ORDER_TYPE'] == 'ZC') {
  169. $decDetail = DecOrder::findUseDbCalc()
  170. ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
  171. ->where("ORDER_SN=:ORDER_SN", [':ORDER_SN' => $sn])
  172. ->asArray()
  173. ->one();
  174. if (empty($decDetail)) {
  175. $this->addError($attribute, '未获取到对应报单信息,订单编号为:'.$this->orderSn);
  176. return ;
  177. }
  178. if ($decDetail['IS_DEL'] == 1) {
  179. $this->addError($attribute, '对应报单信息已被删除,订单编号为:'.$this->orderSn);
  180. return ;
  181. }
  182. // 如果是注册订单,则判断是否是升级单,如果是升级单,则不能进行删除
  183. if ($decDetail['DETAIL_TYPE'] == 2) {
  184. $this->addError($attribute, '升级单无法删除,订单编号为:'.$this->orderSn);
  185. return ;
  186. } else {
  187. // 如果是注册单,但是这个用户存在升级单,则也不能进行删除
  188. $hasUpgradeOrder = DecOrder::findUseDbCalc()
  189. ->select('TO_USER_ID,DETAIL_TYPE,UPGRADE_TYPE,IS_DEL')
  190. ->where("TO_USER_ID=:TO_USER_ID AND IS_DEL=0 AND DETAIL_TYPE=2", [':TO_USER_ID' => $decDetail['TO_USER_ID']])
  191. ->asArray()
  192. ->one();
  193. if (!empty($hasUpgradeOrder)) {
  194. $this->addError($attribute, '此注册报单用户,存在升级单,无法删除,订单编号为:'.$this->orderSn);
  195. return ;
  196. }
  197. // 删除注册单,判断是否有复消单,如果存在复消单,需要先删除复消单
  198. $hasFxOrder = Order::findUseDbCalc()
  199. ->select('SN')
  200. ->where("USER_ID=:USER_ID AND IS_DELETE=0 AND ORDER_TYPE='FX'", [':USER_ID' => $decDetail['TO_USER_ID']])
  201. ->asArray()
  202. ->one();
  203. if (!empty($hasFxOrder)) {
  204. $this->addError($attribute, '此注册报单用户,存在复消单,无法删除,订单编号为:'.$this->orderSn);
  205. return ;
  206. }
  207. }
  208. }
  209. return true;
  210. }
  211. /**
  212. * 校验类型
  213. * @param $attribute
  214. */
  215. public function isStatus($attribute){
  216. if(!in_array($this->type, \Yii::$app->params['orderStatus'])){
  217. $this->addError($attribute, '类型错误');
  218. return ;
  219. }
  220. if ($this->scenario == 'adminStatus'){
  221. if ($this->status == $this->_model['STATUS']) {
  222. $this->addError($attribute, '订单状态没有改变');
  223. return ;
  224. }
  225. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  226. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  227. return ;
  228. }
  229. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  230. $this->addError($attribute, '订单已失效不能处理');
  231. return ;
  232. }
  233. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  234. $this->addError($attribute, '订单不能单独处理为物流状态');
  235. return ;
  236. }
  237. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  238. $this->addError($attribute, '订单已失效不能处理');
  239. return ;
  240. }
  241. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  242. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  243. $this->addError($attribute, '订单已完成不能取消');
  244. return ;
  245. }
  246. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  247. $this->addError($attribute, '订单已删除不能取消');
  248. return ;
  249. }
  250. }
  251. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  252. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  253. $this->addError($attribute, '订单已完成不能删除');
  254. return ;
  255. }
  256. }
  257. }
  258. }
  259. /**
  260. * 帮会员复销
  261. * @return bool|null
  262. * @throws Exception
  263. * @throws \yii\db\Exception
  264. */
  265. public function reconsumeAdd(){
  266. if(!$this->validate()){
  267. return null;
  268. }
  269. $ids = $this->goodsId;
  270. $totalAmount = 0;
  271. $totalPv = 0;
  272. $goodsType = ShopGoods::GOODS_TYPE;
  273. foreach ($this->goodsNum as $k => $v) {
  274. if ($v) {
  275. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  276. if($goods['STORE_NUMS']>0){
  277. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  278. $discount = $goodsType[$goods['TYPE']]['discount'];
  279. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  280. $realPv = $goods['PRICE_PV'] * $discount/100;
  281. } else {
  282. $discount = $goods['SELL_DISCOUNT'];
  283. $realPrice = $goods['SELL_PRICE'] * $discount;
  284. $realPv = $goods['PRICE_PV'] * $discount;
  285. }
  286. $totalAmount += $realPrice * intval($v);
  287. $totalPv += $realPv * intval($v);
  288. $this->_orderGoods[] = [
  289. 'GOODS_ID' => $goods['ID'],
  290. 'PRICE' => $goods['SELL_PRICE'],
  291. 'PV' => $goods['PRICE_PV'],
  292. 'REAL_PRICE' => $realPrice,
  293. 'REAL_PV' => $realPv,
  294. 'POINT' => $goods['POINT'],
  295. 'BUY_NUMS' => intval($v),
  296. 'SKU_CODE' => $goods['GOODS_NO'],
  297. 'GOODS_TITLE' => $goods['GOODS_NAME']
  298. ];
  299. }
  300. }
  301. }
  302. $this->_decAmount = $totalAmount;
  303. $this->_decPv = $totalPv;
  304. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  305. $this->_payAmount = $this->_decAmount + $this->_freight;
  306. $db = \Yii::$app->db;
  307. $transaction = $db->beginTransaction();
  308. try {
  309. $loginUserId = \Yii::$app->user->id;
  310. //是否开启伞下会员限制
  311. $isResaleUmbrella = Cache::getSystemConfig()['isResaleUmbrella']['VALUE'];
  312. if($isResaleUmbrella){
  313. $userId = Info::getUserIdByUserName($this->userName);
  314. $userNetwork = UserNetwork::find()->where("USER_ID=:USER_ID AND INSTR(PARENT_UIDS,'{$loginUserId}')>0", ['USER_ID'=>$userId])->count();
  315. if(!$userNetwork){
  316. throw new Exception($this->userName.'不是您的伞下会员,不能为其复消!');
  317. }
  318. }
  319. //判断用户余额是否充足
  320. if($this->payType=='cash') {
  321. if (Cash::getAvailableBalance($loginUserId) < $this->_payAmount) {
  322. throw new Exception('余额不足,无法购买商品');
  323. }
  324. }else{
  325. if ($this->_payAmount > Balance::getBalanceReconsumePoints($loginUserId)) {
  326. throw new Exception('复消积分不足,无法购买商品');
  327. }
  328. }
  329. //写入订单
  330. if (!$orderResult = $this->addUserOrder()) {
  331. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  332. }
  333. $transaction->commit();
  334. }catch (\Exception $e){
  335. $transaction->rollBack();
  336. $this->addError('add', $e->getMessage());
  337. return null;
  338. }
  339. return true;
  340. }
  341. /**
  342. * 帮会员复消的订单
  343. */
  344. public function addUserOrder(){
  345. $periodObj = Period::instance();
  346. $nowPeriodNum = $periodObj->getNowPeriodNum();
  347. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  348. //帮复消会员Id(登陆会员)
  349. $loginUserId = \Yii::$app->user->id;
  350. $loginUserName = Info::getUserNameByUserId($loginUserId);
  351. //订单会员Id
  352. $userId = Info::getUserIdByUserName($this->userName);
  353. // 加入订单信息
  354. $warehouse = Region::getWarehouseByCode($this->province);//仓库
  355. if(!$warehouse){
  356. throw new Exception('地区暂时不支持配送,具体联系客服');
  357. }
  358. $ordNo = $this->_generateSn();
  359. $orderModel = new Order();
  360. $orderModel->SN = 'OS'.$ordNo;
  361. $orderModel->DEC_SN = 'DS'.$ordNo;
  362. $orderModel->ORDER_TYPE = $this->type;
  363. $orderModel->USER_ID = $userId;
  364. $orderModel->USER_NAME = $this->userName;
  365. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  366. $orderModel->PV = $this->_decPv;
  367. $orderModel->PAY_AMOUNT = $this->_payAmount;
  368. $orderModel->PAY_PV = $this->_decPv;
  369. $orderModel->PAY_AT = Date::nowTime();
  370. $orderModel->PAY_TYPE = $this->payType;
  371. $orderModel->PERIOD_NUM = $nowPeriodNum;
  372. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  373. $orderModel->FREIGHT = $this->_freight;
  374. $orderModel->PAY_FREIGHT = $this->_freight;
  375. $orderModel->CONSIGNEE = $this->consignee;
  376. $orderModel->MOBILE = $this->acceptMobile;
  377. $orderModel->PROVINCE = $this->province;
  378. $orderModel->CITY = $this->city;
  379. $orderModel->COUNTY = $this->county;
  380. $orderModel->ADDRESS = $this->detailaddress;
  381. $orderModel->FRONT_REMARK = $this->remark;
  382. $orderModel->WAREHOUSE = $warehouse;
  383. $orderModel->STATUS = 1;
  384. $orderModel->CREATED_AT = Date::nowTime();
  385. $orderModel->CREATE_USER = $loginUserName;
  386. if(!$orderModel->save()){
  387. $this->addErrors($orderModel->getErrors());
  388. return false;
  389. }
  390. // 加入商品到订单商品表
  391. foreach($this->_orderGoods as $key=>$value){
  392. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  393. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  394. }
  395. OrderGoods::batchInsert($this->_orderGoods);
  396. //扣除会员余额/积分
  397. if($this->payType=='cash') {
  398. Cash::changeUserCash($loginUserId, 'CASH', -abs($this->_payAmount), ['REMARK' => '会员复销余额支付']);
  399. }else{
  400. Balance::changeUserBonus($loginUserId,'reconsume_points', -abs($this->_payAmount),['DEAL_TYPE_ID' => DealType::RECONSUME_POINTS_EXCHANGE, 'REMARK' => '会员复销积分兑换']);
  401. }
  402. return $orderModel;
  403. }
  404. /**
  405. * 生成流水号
  406. * @return string
  407. */
  408. private function _generateSn() {
  409. return Date::today('Ymd') . $this->_random(10, 1);
  410. }
  411. /**
  412. * 生成随机数
  413. * @param $length
  414. * @param int $numeric
  415. * @return string
  416. */
  417. private function _random($length, $numeric = 0) {
  418. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  419. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  420. $hash = '';
  421. $max = strlen($seed) - 1;
  422. for ($i = 0; $i < $length; $i++) {
  423. $hash .= $seed[mt_rand(0, $max)];
  424. }
  425. return $hash;
  426. }
  427. }