ApproachOrderForm.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  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. if (!ApproachOrder::findOneAsArray('SN = :SN', [':SN' => $this->sn])){
  139. $this->addError('sn', '订单不存在');
  140. return false;
  141. }
  142. }
  143. // if ($this->sn) {
  144. // $this->_model = ApproachOrder::find()->where('SN=:SN', [':SN' => $this->sn])->one();
  145. // if (!$this->_model){
  146. // $this->addError('sn', '订单不存在. ' . json_encode($this->_model));
  147. // return false;
  148. // }
  149. // }
  150. // if ($this->scenario == 'verifyIPay88'){
  151. // if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  152. // $this->addError('sn', '支付方式错误');
  153. // return false;
  154. // }
  155. // }
  156. return $parentValidate;
  157. }
  158. /**
  159. * 判断收货地址是否存在
  160. * @param $attribute
  161. */
  162. public function isAddress($attribute){
  163. if (!$receiveAddress = ReceiveAddress::find()->where('ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  164. $this->addError($attribute, '收货地址不存在');
  165. } else {
  166. if (!$receiveAddress['ZIP_CODE']){
  167. $this->addError($attribute, '收货地址没有填写邮编');
  168. } else {
  169. $this->_address = $receiveAddress;
  170. }
  171. }
  172. }
  173. /**
  174. * 判断支付方式
  175. * @param $attribute
  176. * @throws Exception
  177. */
  178. public function isPayType($attribute)
  179. {
  180. if ($this->payType != 'online'){
  181. $this->addError('支付方式错误');
  182. }
  183. // 一个订单只能包含一类商品
  184. $goods = ShopGoods::find()->select('ID,CATE_ID')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  185. if (!$goods) {
  186. throw new Exception('商品已下架');
  187. }
  188. $goodsCategoryType = array_unique(array_column($goods, 'CATE_ID'));
  189. if (count($goodsCategoryType) > 1) {
  190. $this->addError($attribute, '订单不能包含多种商品分类');
  191. }
  192. }
  193. /**
  194. * 校验类型
  195. * @param $attribute
  196. */
  197. public function isStatus($attribute){
  198. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  199. $this->addError($attribute, '订单状态类型错误');
  200. return ;
  201. }
  202. }
  203. /**
  204. * 校验iPay88支付,更新订单状态.同步到正式订单.
  205. * @throws Exception
  206. */
  207. public function verifyPayOnline(): ?ApproachOrder
  208. {
  209. if (!$this->validate()) {
  210. return null;
  211. }
  212. LoggerTool::info([$this->sn, $this->note]);
  213. // 调用iPay88支付校验
  214. // LoggerTool::info([$this->note['reference'], $this->note]);
  215. // $payload = IPay88::transactionVerify($this->note['reference']);
  216. // LoggerTool::info($payload);
  217. // if ($payload['status'] !== true) {
  218. // throw new Exception(Form::formatErrorsForApi($payload['message']));
  219. // }
  220. // if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  221. // throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  222. // }
  223. $db = \Yii::$app->db;
  224. $transaction = $db->beginTransaction();
  225. try {
  226. // 更新准订单状态为已支付
  227. $this->_model->STATUS = $this->status;
  228. $this->_model->NOTE = json_encode($this->note);
  229. $this->_model->PAY_AT = time();
  230. // $this->_model->PAY_AT = Date::utcToTime($this->note['TranDate']);
  231. if (!$this->_model->save()) {
  232. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  233. }
  234. // 同步准订单到正式订单
  235. Order::insertOne($this->_model->toArray());
  236. // 同步准订单商品到正式订单商品
  237. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  238. OrderGoods::batchInsert($approachOrderGoods);
  239. // 删除中间表
  240. ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  241. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  242. $transaction->commit();
  243. } catch (Exception $e) {
  244. $transaction->rollBack();
  245. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  246. return null;
  247. }
  248. return $this->_model;
  249. }
  250. /**
  251. * BV分期
  252. *
  253. *
  254. */
  255. private function _pvSplit($oPv){
  256. $sysConfig = Cache::getSystemConfig();
  257. $mesureUpCondition = $sysConfig['monthPcsPvFxCondition']['VALUE'];
  258. if ($oPv > $mesureUpCondition) {
  259. $currentPv = $oPv % $mesureUpCondition + $mesureUpCondition;
  260. $remainPv = $oPv - $currentPv;
  261. } else {
  262. $currentPv = $oPv;
  263. $remainPv = 0;
  264. }
  265. return [
  266. 'current' => $currentPv,
  267. 'remain' => $remainPv
  268. ];
  269. }
  270. /**
  271. * 复销
  272. * @throws Exception
  273. * @throws \yii\db\Exception
  274. */
  275. public function add() {
  276. if(!$this->validate()){
  277. return null;
  278. }
  279. $ids = $this->goodsId;
  280. $totalAmount = 0;
  281. $totalPv = 0;
  282. $totalRealPv = 0;
  283. $this->_remainPv = 0;
  284. $cateId = [];
  285. foreach ($this->goodsNum as $k => $v) {
  286. if ($v) {
  287. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  288. if (!$goods) {
  289. throw new Exception('商品已下架');
  290. }
  291. $cateId[] = $goods['CATE_ID'];
  292. if ($goods['STORE_NUMS'] > 0) {
  293. $discount = $goods['SELL_DISCOUNT'];
  294. $realPrice = $goods['SELL_PRICE'] * $discount;
  295. $realPv = $goods['PRICE_PV'] * $discount;
  296. if ($goods['PV_SPLIT'] == 1) { // 当商品为PV分期时
  297. $pvSplit = $this->_pvSplit($realPv);
  298. $currentPv = $pvSplit['current'];
  299. $remainPv = $pvSplit['remain'];
  300. $totalPv += $currentPv * intval($v);
  301. $totalRealPv += $realPv * intval($v);
  302. $this->_remainPv += $remainPv * intval($v);
  303. } else {
  304. $currentPv = $goods['PRICE_PV'];
  305. $totalPv += $realPv * intval($v);
  306. $totalRealPv += $realPv * intval($v);
  307. $remainPv = 0;
  308. $this->_remainPv += 0;
  309. }
  310. $totalAmount += $realPrice * intval($v);
  311. $this->_orderGoods[] = [
  312. 'GOODS_ID' => $goods['ID'],
  313. 'PRICE' => $goods['SELL_PRICE'],
  314. 'PV' => $currentPv,
  315. 'REAL_PRICE' => $realPrice,
  316. 'REAL_PV' => $realPv,
  317. 'REMAIN_PV' => $remainPv,
  318. 'POINT' => $goods['POINT'],
  319. 'BUY_NUMS' => intval($v),
  320. 'SKU_CODE' => $goods['GOODS_NO'],
  321. 'GOODS_TITLE' => $goods['GOODS_NAME']
  322. ];
  323. }
  324. }
  325. }
  326. if (count(array_unique($cateId)) > 1) {
  327. throw new Exception('海内商品、海外商品只能选择一种');
  328. }
  329. $this->_decAmount = $totalAmount;
  330. $this->_decPv = $totalPv;
  331. $this->_realPv = $totalRealPv;
  332. $this->_freight = ($totalAmount>=300) ? 0 : 15;
  333. $this->_payAmount = $this->_decAmount + $this->_freight;
  334. $db = \Yii::$app->db;
  335. $transaction = $db->beginTransaction();
  336. // 支付减库存
  337. foreach ($this->goodsNum as $k => $v) {
  338. if ($v) {
  339. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID'=> $ids[$k]]);
  340. if (!$goods) {
  341. throw new Exception('商品已下架');
  342. }
  343. if ($goods['STORE_NUMS'] >= $this->goodsNum[$k]) {
  344. $data = ShopGoods::find()->where(['ID' => $ids[$k]])->one();
  345. $goods_store_nums = $data->STORE_NUMS - $this->goodsNum[$k];
  346. $data->STORE_NUMS = $goods_store_nums;
  347. $data->update();
  348. //下单后库存小于等于0 商品下架
  349. if ($goods_store_nums <= 0) {
  350. $data->STATUS = 0;
  351. $data->UPDATED_AT = Date::nowTime();
  352. $data->update();
  353. }
  354. } else {
  355. throw new Exception($goods['GOODS_NAME'].'库存不足,无法购买商品');
  356. }
  357. }
  358. }
  359. try {
  360. // 写入订单
  361. if (!$orderResult = $this->addOrder()) {
  362. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  363. }
  364. // TODO: 获取iPay88所需参数
  365. // $orderSn = $orderResult->SN;
  366. $transaction->commit();
  367. return $orderResult;
  368. }catch (\Exception $e){
  369. $transaction->rollBack();
  370. $this->addError('add', $e->getMessage());
  371. return null;
  372. }
  373. }
  374. /**
  375. * 复销订单
  376. * @throws Exception
  377. */
  378. public function addOrder()
  379. {
  380. $periodObj = Period::instance();
  381. $nowPeriodNum = $periodObj->getNowPeriodNum();
  382. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  383. $userId = \Yii::$app->user->id;
  384. $userName = Info::getUserNameByUserId($userId);
  385. $userRealName = Info::getUserRealNameByUserId($userId);
  386. $userMobile = Info::getUserMobileByUserId($userId);
  387. $userEmail = Info::getUserEmailByUserId($userId);
  388. // 加入订单信息
  389. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  390. if(!$warehouse){
  391. throw new Exception('地区暂时不支持配送,具体联系客服');
  392. }
  393. $ordNo = $this->_generateSn();
  394. $orderModel = new ApproachOrder();
  395. $orderModel->SN = 'OS' . $ordNo;
  396. $orderModel->DEC_SN = 'DS' . $ordNo;
  397. $orderModel->ORDER_TYPE = $this->type;
  398. $orderModel->USER_ID = $userId;
  399. $orderModel->USER_NAME = $userName;
  400. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  401. $orderModel->PV = $this->_decPv;
  402. $orderModel->PAY_AMOUNT = $this->_payAmount;
  403. $orderModel->PAY_PV = $this->_decPv;
  404. $orderModel->REMAIN_PV = $this->_remainPv;
  405. $orderModel->PAY_AT = 0;
  406. $orderModel->PAY_TYPE = $this->payType;
  407. $orderModel->PERIOD_NUM = $nowPeriodNum;
  408. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  409. $orderModel->FREIGHT = $this->_freight;
  410. $orderModel->PAY_FREIGHT = $this->_freight;
  411. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  412. $orderModel->MOBILE = $this->_address['MOBILE'];
  413. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  414. $orderModel->CITY = $this->_address['CITY'];
  415. $orderModel->COUNTY = $this->_address['COUNTY'];
  416. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  417. $orderModel->FRONT_REMARK = $this->remark;
  418. $orderModel->WAREHOUSE = $warehouse;
  419. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  420. $orderModel->CREATED_AT = Date::nowTime();
  421. $orderModel->CREATE_USER = $userName;
  422. $orderModel->EMAIL = $userEmail ?: $userName.'@elken.net';
  423. $orderModel->CONSIGNEE_ID_NO = $this->consigneeIdNo;
  424. $orderModel->CONSIGNEE_REAL_NAME = $this->consigneeRealName;
  425. $orderModel->ZIP_CODE = $this->_address['ZIP_CODE'];
  426. if(!$orderModel->save()){
  427. $this->addErrors($orderModel->getErrors());
  428. return false;
  429. }
  430. // 加入商品到订单商品表
  431. foreach($this->_orderGoods as $key=>$value) {
  432. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  433. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  434. }
  435. ApproachOrderGoods::batchInsert($this->_orderGoods);
  436. return $orderModel;
  437. }
  438. /**
  439. * 生成流水号
  440. * @return string
  441. */
  442. private function _generateSn() {
  443. return Date::today('Ymd') . $this->_random(10, 1);
  444. }
  445. /**
  446. * 生成随机数
  447. * @param $length
  448. * @param int $numeric
  449. * @return string
  450. */
  451. private function _random($length, $numeric = 0) {
  452. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  453. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  454. $hash = '';
  455. $max = strlen($seed) - 1;
  456. for ($i = 0; $i < $length; $i++) {
  457. $hash .= $seed[mt_rand(0, $max)];
  458. }
  459. return $hash;
  460. }
  461. }