ApproachOrderForm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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\IPay88;
  8. use common\helpers\LoggerTool;
  9. use common\helpers\PayStack;
  10. use common\helpers\user\Balance;
  11. use common\helpers\user\Cash;
  12. use common\helpers\user\Info;
  13. use common\libs\logging\operate\AdminOperate;
  14. use common\models\ApproachDecOrder;
  15. use common\models\ApproachOrder;
  16. use common\models\ApproachOrderGoods;
  17. use common\models\BaUser;
  18. use common\models\DealType;
  19. use common\models\DecLevelLog;
  20. use common\models\DecOrder;
  21. use common\models\Order;
  22. use common\models\OrderGoods;
  23. use common\models\Period;
  24. use common\models\ReceiveAddress;
  25. use common\models\Region;
  26. use common\models\ShopGoods;
  27. use common\models\User;
  28. use common\models\UserNetwork;
  29. use common\models\Instalment;
  30. use Yii;
  31. use yii\base\Exception;
  32. /**
  33. * Login form
  34. */
  35. class ApproachOrderForm extends Model
  36. {
  37. public $sn;
  38. public $expressCompany;
  39. public $orderTrackNo;
  40. public $status;
  41. public $remark;
  42. public $note;
  43. public $type;
  44. public $addressId;
  45. public $payType;
  46. public $goodsId;
  47. public $goodsNum;
  48. public $payPassword;
  49. public $userName;
  50. public $consignee;
  51. public $acceptMobile;
  52. public $province;
  53. public $city;
  54. public $county;
  55. public $lgaName;
  56. public $detailaddress;
  57. public $consigneeIdNo;
  58. public $consigneeRealName;
  59. private $_address;
  60. private $_decAmount;
  61. private $_decPv;
  62. private $_freight;
  63. private $_payAmount;
  64. private $_orderGoods;
  65. private $_remainPv;
  66. private $_realPv;
  67. /**
  68. * @var ApproachOrder
  69. */
  70. private $_model;
  71. public function init() {
  72. parent::init();
  73. $this->adminOperateLogger = new AdminOperate([
  74. 'fetchClass' => ApproachOrder::class,
  75. ]);
  76. }
  77. /**
  78. * @inheritdoc
  79. */
  80. public function rules()
  81. {
  82. return [
  83. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','cityName','detailaddress', 'consigneeIdNo', 'consigneeRealName'], 'trim'],
  84. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province','city','county','detailaddress', 'consigneeIdNo', 'consigneeRealName'], 'required'],
  85. [['status'], 'isStatus'],
  86. [['addressId'], 'isAddress'],
  87. [['payType'], 'isPayType'],
  88. ];
  89. }
  90. public function attributeLabels()
  91. {
  92. return [
  93. 'sn' => '订单号',
  94. 'expressCompany' => '快递公司',
  95. 'orderTrackNo' => '快递单号',
  96. 'status' => '状态',
  97. 'remark' => '备注',
  98. 'type' => '订单类型',
  99. 'addressId' => '收货地址',
  100. 'payType' => '支付方式',
  101. 'goodsId' => '商品ID',
  102. 'goodsNum' => '商品数量',
  103. 'userName' => '复消会员编号',
  104. 'consignee' => '收货人',
  105. 'acceptMobile' => '收货电话',
  106. 'province' => '省',
  107. 'city' => '市',
  108. 'county' => '区',
  109. 'detailaddress' => '收货详细地址',
  110. ];
  111. }
  112. /**
  113. * 指定校验场景
  114. * @return array
  115. */
  116. public function scenarios()
  117. {
  118. $parentScenarios = parent::scenarios();
  119. $customScenarios = [
  120. // 管理员修改订单状态
  121. 'adminStatus' => ['sn', 'status'],
  122. // 校验订单支付
  123. 'verifyPay' => ['sn', 'status', 'note'],
  124. // 会员下单
  125. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'consigneeIdNo', 'consigneeRealName'],
  126. ];
  127. return array_merge($parentScenarios, $customScenarios);
  128. }
  129. /**
  130. * 校验之前
  131. * @return bool
  132. */
  133. public function beforeValidate()
  134. {
  135. $parentValidate = parent::beforeValidate();
  136. if ($this->sn) {
  137. $this->_model = ApproachOrder::findOne(['SN'=>$this->sn]);
  138. LoggerTool::debug($this->_model);
  139. if (!$this->_model){
  140. $this->addError('sn', '订单不存在');
  141. return false;
  142. }
  143. }
  144. // if ($this->sn) {
  145. // $this->_model = ApproachOrder::find()->where('SN=:SN', [':SN' => $this->sn])->one();
  146. // if (!$this->_model){
  147. // $this->addError('sn', '订单不存在. ' . json_encode($this->_model));
  148. // return false;
  149. // }
  150. // }
  151. // if ($this->scenario == 'verifyIPay88'){
  152. // if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  153. // $this->addError('sn', '支付方式错误');
  154. // return false;
  155. // }
  156. // }
  157. return $parentValidate;
  158. }
  159. /**
  160. * 判断收货地址是否存在
  161. * @param $attribute
  162. */
  163. public function isAddress($attribute){
  164. if (!$receiveAddress = ReceiveAddress::find()->where('ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  165. $this->addError($attribute, '收货地址不存在');
  166. } else {
  167. if (!$receiveAddress['ZIP_CODE']){
  168. $this->addError($attribute, '收货地址没有填写邮编');
  169. } else {
  170. $this->_address = $receiveAddress;
  171. }
  172. }
  173. }
  174. /**
  175. * 判断支付方式
  176. * @param $attribute
  177. * @throws Exception
  178. */
  179. public function isPayType($attribute)
  180. {
  181. if ($this->payType != 'online'){
  182. $this->addError('支付方式错误');
  183. }
  184. // 一个订单只能包含一类商品
  185. $goods = ShopGoods::find()->select('ID,CATE_ID')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  186. if (!$goods) {
  187. throw new Exception('商品已下架');
  188. }
  189. $goodsCategoryType = array_unique(array_column($goods, 'CATE_ID'));
  190. if (count($goodsCategoryType) > 1) {
  191. $this->addError($attribute, '订单不能包含多种商品分类');
  192. }
  193. }
  194. /**
  195. * 校验类型
  196. * @param $attribute
  197. */
  198. public function isStatus($attribute){
  199. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  200. $this->addError($attribute, '订单状态类型错误');
  201. return ;
  202. }
  203. }
  204. /**
  205. * 校验iPay88支付,更新订单状态.同步到正式订单.
  206. * @throws Exception
  207. */
  208. public function verifyPayOnline(): ?ApproachOrder
  209. {
  210. if (!$this->validate()) {
  211. LoggerTool::debug([$this->sn, $this->note]);
  212. return null;
  213. }
  214. LoggerTool::info([$this->sn, $this->note]);
  215. // 调用iPay88支付校验
  216. // LoggerTool::info([$this->note['reference'], $this->note]);
  217. // $payload = IPay88::transactionVerify($this->note['reference']);
  218. // LoggerTool::info($payload);
  219. // if ($payload['status'] !== true) {
  220. // throw new Exception(Form::formatErrorsForApi($payload['message']));
  221. // }
  222. // if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  223. // throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  224. // }
  225. $db = \Yii::$app->db;
  226. $transaction = $db->beginTransaction();
  227. try {
  228. // 更新准订单状态为已支付
  229. $this->_model->STATUS = $this->status;
  230. $this->_model->NOTE = json_encode($this->note);
  231. $this->_model->PAY_AT = time();
  232. // $this->_model->PAY_AT = Date::utcToTime($this->note['TranDate']);
  233. if (!$this->_model->save()) {
  234. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  235. }
  236. // 同步准订单到正式订单
  237. Order::insertOne($this->_model->toArray());
  238. // 同步准订单商品到正式订单商品
  239. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  240. OrderGoods::batchInsert($approachOrderGoods);
  241. // 删除中间表
  242. ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  243. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  244. $transaction->commit();
  245. } catch (Exception $e) {
  246. $transaction->rollBack();
  247. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  248. return null;
  249. }
  250. return $this->_model;
  251. }
  252. /**
  253. * BV分期
  254. *
  255. *
  256. */
  257. private function _pvSplit($oPv){
  258. $sysConfig = Cache::getSystemConfig();
  259. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE'];
  260. if ($oPv > $mesureUpCondition) {
  261. $currentPv = $oPv % $mesureUpCondition + $mesureUpCondition;
  262. $remainPv = $oPv - $currentPv;
  263. } else {
  264. $currentPv = $oPv;
  265. $remainPv = 0;
  266. }
  267. return [
  268. 'current' => $currentPv,
  269. 'remain' => $remainPv
  270. ];
  271. }
  272. /**
  273. * 复销
  274. * @throws Exception
  275. * @throws \yii\db\Exception
  276. */
  277. public function add() {
  278. if(!$this->validate()){
  279. return null;
  280. }
  281. $ids = $this->goodsId;
  282. $totalAmount = 0;
  283. $totalPv = 0;
  284. $totalRealPv = 0;
  285. $this->_remainPv = 0;
  286. $cateId = [];
  287. foreach ($this->goodsNum as $k => $v) {
  288. if ($v) {
  289. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  290. if (!$goods) {
  291. throw new Exception('商品已下架');
  292. }
  293. $cateId[] = $goods['CATE_ID'];
  294. if ($goods['STORE_NUMS'] > 0) {
  295. $discount = $goods['SELL_DISCOUNT'];
  296. $realPrice = $goods['SELL_PRICE'] * $discount;
  297. $realPv = $goods['PRICE_PV'] * $discount;
  298. if ($goods['PV_SPLIT'] == 1) { // 当商品为PV分期时
  299. $pvSplit = $this->_pvSplit($realPv);
  300. $currentPv = $pvSplit['current'];
  301. $remainPv = $pvSplit['remain'];
  302. $totalPv += $currentPv * intval($v);
  303. $totalRealPv += $realPv * intval($v);
  304. $this->_remainPv += $remainPv * intval($v);
  305. } else {
  306. $currentPv = $goods['PRICE_PV'];
  307. $totalPv += $realPv * intval($v);
  308. $totalRealPv += $realPv * intval($v);
  309. $remainPv = 0;
  310. $this->_remainPv += 0;
  311. }
  312. $totalAmount += $realPrice * intval($v);
  313. $this->_orderGoods[] = [
  314. 'GOODS_ID' => $goods['ID'],
  315. 'PRICE' => $goods['SELL_PRICE'],
  316. 'PV' => $currentPv,
  317. 'REAL_PRICE' => $realPrice,
  318. 'REAL_PV' => $realPv,
  319. 'REMAIN_PV' => $remainPv,
  320. 'POINT' => $goods['POINT'],
  321. 'BUY_NUMS' => intval($v),
  322. 'SKU_CODE' => $goods['GOODS_NO'],
  323. 'GOODS_TITLE' => $goods['GOODS_NAME']
  324. ];
  325. }
  326. }
  327. }
  328. if (count(array_unique($cateId)) > 1) {
  329. throw new Exception('海内商品、海外商品只能选择一种');
  330. }
  331. $this->_decAmount = $totalAmount;
  332. $this->_decPv = $totalPv;
  333. $this->_realPv = $totalRealPv;
  334. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  335. $this->_payAmount = $this->_decAmount + $this->_freight;
  336. $db = \Yii::$app->db;
  337. $transaction = $db->beginTransaction();
  338. // 支付减库存
  339. foreach ($this->goodsNum as $k => $v) {
  340. if ($v) {
  341. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=> $ids[$k]]);
  342. if (!$goods) {
  343. throw new Exception('商品已下架');
  344. }
  345. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]) {
  346. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  347. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  348. $data->STORE_NUMS = $goods_store_nums;
  349. $data->update();
  350. //下单后库存小于等于0 商品下架
  351. if ($goods_store_nums <= 0) {
  352. $data->STATUS = 0;
  353. $data->UPDATED_AT = Date::nowTime();
  354. $data->update();
  355. }
  356. } else {
  357. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  358. }
  359. }
  360. }
  361. try {
  362. // 写入订单
  363. if (!$orderResult = $this->addOrder()) {
  364. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  365. }
  366. // TODO: 获取iPay88所需参数
  367. // $orderSn = $orderResult->SN;
  368. $transaction->commit();
  369. return $orderResult;
  370. }catch (\Exception $e){
  371. $transaction->rollBack();
  372. $this->addError('add', $e->getMessage());
  373. return null;
  374. }
  375. }
  376. /**
  377. * 复销订单
  378. * @throws Exception
  379. */
  380. public function addOrder()
  381. {
  382. $periodObj = Period::instance();
  383. $nowPeriodNum = $periodObj->getNowPeriodNum();
  384. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  385. $userId = \Yii::$app->user->id;
  386. $userName = Info::getUserNameByUserId($userId);
  387. $userRealName = Info::getUserRealNameByUserId($userId);
  388. $userMobile = Info::getUserMobileByUserId($userId);
  389. $userEmail = Info::getUserEmailByUserId($userId);
  390. // 加入订单信息
  391. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  392. if(!$warehouse){
  393. throw new Exception('地区暂时不支持配送,具体联系客服');
  394. }
  395. $ordNo = $this->_generateSn();
  396. $orderModel = new ApproachOrder();
  397. $orderModel->SN = 'OS' . $ordNo;
  398. $orderModel->DEC_SN = 'DS' . $ordNo;
  399. $orderModel->ORDER_TYPE = $this->type;
  400. $orderModel->USER_ID = $userId;
  401. $orderModel->USER_NAME = $userName;
  402. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  403. $orderModel->PV = $this->_decPv;
  404. $orderModel->PAY_AMOUNT = $this->_payAmount;
  405. $orderModel->PAY_PV = $this->_decPv;
  406. $orderModel->REMAIN_PV = $this->_remainPv;
  407. $orderModel->PAY_AT = 0;
  408. $orderModel->PAY_TYPE = $this->payType;
  409. $orderModel->PERIOD_NUM = $nowPeriodNum;
  410. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  411. $orderModel->FREIGHT = $this->_freight;
  412. $orderModel->PAY_FREIGHT = $this->_freight;
  413. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  414. $orderModel->MOBILE = $this->_address['MOBILE'];
  415. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  416. $orderModel->CITY = $this->_address['CITY'];
  417. $orderModel->COUNTY = $this->_address['COUNTY'];
  418. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  419. $orderModel->FRONT_REMARK = $this->remark;
  420. $orderModel->WAREHOUSE = $warehouse;
  421. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  422. $orderModel->CREATED_AT = Date::nowTime();
  423. $orderModel->CREATE_USER = $userName;
  424. $orderModel->EMAIL = $userEmail ?: $userName.'@elken.net';
  425. $orderModel->CONSIGNEE_ID_NO = $this->consigneeIdNo;
  426. $orderModel->CONSIGNEE_REAL_NAME = $this->consigneeRealName;
  427. $orderModel->ZIP_CODE = $this->_address['ZIP_CODE'];
  428. if(!$orderModel->save()){
  429. $this->addErrors($orderModel->getErrors());
  430. return false;
  431. }
  432. // 加入商品到订单商品表
  433. foreach($this->_orderGoods as $key=>$value) {
  434. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  435. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  436. }
  437. ApproachOrderGoods::batchInsert($this->_orderGoods);
  438. return $orderModel;
  439. }
  440. /**
  441. * 生成流水号
  442. * @return string
  443. */
  444. private function _generateSn() {
  445. return Date::today('Ymd') . $this->_random(10, 1);
  446. }
  447. /**
  448. * 生成随机数
  449. * @param $length
  450. * @param int $numeric
  451. * @return string
  452. */
  453. private function _random($length, $numeric = 0) {
  454. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  455. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  456. $hash = '';
  457. $max = strlen($seed) - 1;
  458. for ($i = 0; $i < $length; $i++) {
  459. $hash .= $seed[mt_rand(0, $max)];
  460. }
  461. return $hash;
  462. }
  463. }