ApproachOrderForm.php 16 KB

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