ApproachOrderForm.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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\LoggerTool;
  8. use common\helpers\PayStack;
  9. use common\helpers\user\Balance;
  10. use common\helpers\user\Cash;
  11. use common\helpers\user\Info;
  12. use common\libs\logging\operate\AdminOperate;
  13. use common\models\ApproachDecOrder;
  14. use common\models\ApproachOrder;
  15. use common\models\ApproachOrderGoods;
  16. use common\models\BaUser;
  17. use common\models\DealType;
  18. use common\models\DecLevelLog;
  19. use common\models\DecOrder;
  20. use common\models\Order;
  21. use common\models\OrderGoods;
  22. use common\models\Period;
  23. use common\models\ReceiveAddress;
  24. use common\models\Region;
  25. use common\models\ShopGoods;
  26. use common\models\User;
  27. use common\models\UserNetwork;
  28. use yii\base\Exception;
  29. /**
  30. * Login form
  31. */
  32. class ApproachOrderForm extends Model
  33. {
  34. public $sn;
  35. public $expressCompany;
  36. public $orderTrackNo;
  37. public $status;
  38. public $remark;
  39. public $note;
  40. public $type;
  41. public $addressId;
  42. public $payType;
  43. public $goodsId;
  44. public $goodsNum;
  45. public $payPassword;
  46. public $email;
  47. public $userName;
  48. public $consignee;
  49. public $acceptMobile;
  50. public $province;
  51. public $city;
  52. public $county;
  53. public $lgaName;
  54. public $cityName;
  55. public $detailaddress;
  56. private $_address;
  57. private $_decAmount;
  58. private $_decPv;
  59. private $_freight;
  60. private $_payAmount;
  61. private $_orderGoods;
  62. private $_standardAmount;
  63. private $_decAmountStandard;
  64. /**
  65. * @var ApproachOrder
  66. */
  67. private $_model;
  68. public function init() {
  69. parent::init();
  70. $this->adminOperateLogger = new AdminOperate([
  71. 'fetchClass' => ApproachOrder::class,
  72. ]);
  73. }
  74. /**
  75. * @inheritdoc
  76. */
  77. public function rules()
  78. {
  79. return [
  80. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'lgaName','cityName','detailaddress','email'], 'trim'],
  81. [['sn', 'expressCompany', 'orderTrackNo', 'status', 'remark','type','addressId','payType','goodsId','goodsNum', 'payPassword','userName','consignee','acceptMobile','province',/*'city','county',*/'detailaddress'/*,'email'*/], 'required'],
  82. [['status'], 'isStatus'],
  83. [['addressId'], 'isAddress'],
  84. [['payType'], 'isPayType'],
  85. [['payPassword'], 'validatePassword'],
  86. ];
  87. }
  88. public function attributeLabels()
  89. {
  90. return [
  91. 'sn' => 'Order code',//订单号
  92. 'expressCompany' => 'ExpressCompany',//快递公司
  93. 'orderTrackNo' => 'courier number',//快递单号
  94. 'status' => 'status',//状态
  95. 'remark' => 'remark',//备注
  96. 'type' => 'order type',//订单类型
  97. 'addressId' => 'addressId',//收货地址
  98. 'payType' => 'payType',//支付方式
  99. 'goodsId' => 'Product ID',
  100. 'goodsNum' => 'Product quantity',//
  101. 'userName' => '复消会员编号',//复消会员编号
  102. 'consignee' => '收货人',//收货人
  103. 'acceptMobile' => '收货电话',//收货电话
  104. 'province' => '省',
  105. 'city' => '市',
  106. 'county' => '区',
  107. 'lgaName' => 'lga name',
  108. 'cityName' => 'City Name',
  109. 'detailaddress' => '收货详细地址',
  110. 'email' => 'Email',
  111. ];
  112. }
  113. /**
  114. * 指定校验场景
  115. * @return array
  116. */
  117. public function scenarios()
  118. {
  119. $parentScenarios = parent::scenarios();
  120. $customScenarios = [
  121. // 管理员修改订单状态
  122. 'adminStatus' => ['sn', 'status'],
  123. // 校验订单支付
  124. 'verifyPayStack' => ['sn', 'note', 'status'],
  125. // 会员下单
  126. 'userOrder' => ['type','addressId', 'payType','goodsId','goodsNum', 'note', 'payPassword'],
  127. ];
  128. return array_merge($parentScenarios, $customScenarios);
  129. }
  130. /**
  131. * 校验之前
  132. * @return bool
  133. */
  134. public function beforeValidate()
  135. {
  136. $parentValidate = parent::beforeValidate();
  137. if ($this->sn) {
  138. $this->_model = ApproachOrder::findOne(['SN' => $this->sn]);
  139. if (!$this->_model){
  140. $this->addError('sn', '订单不存在');
  141. return false;
  142. }
  143. }
  144. if ($this->scenario == 'verifyPayStack'){
  145. if ($this->_model->STATUS != \Yii::$app->params['orderStatus']['notPaid']['value']) {
  146. $this->addError('sn', '订单支付状态错误');
  147. return false;
  148. }
  149. }
  150. return $parentValidate;
  151. }
  152. /**
  153. * 判断收货地址是否存在
  154. * @param $attribute
  155. */
  156. public function isAddress($attribute){
  157. if (!$receiveAddress = ReceiveAddress::find()->where(' ID=:ID', [':ID' => $this->addressId])->asArray()->one()) {
  158. $this->addError($attribute, '收货地址不存在');
  159. } else {
  160. $this->_address = $receiveAddress;
  161. }
  162. }
  163. /**
  164. * 校验支付密码
  165. * @param $attribute
  166. * @param $params
  167. */
  168. public function validatePassword($attribute, $params) {
  169. if (!User::validatePayPassword(\Yii::$app->user->id, $this->payPassword)) {
  170. $this->addError($attribute, '支付密码不正确');
  171. }
  172. }
  173. /**
  174. * 判断支付方式
  175. * @param $attribute
  176. */
  177. public function isPayType($attribute)
  178. {
  179. if ($this->payType != 'pay_stack'){
  180. $this->addError($attribute, '只允许PayStack方式支付');
  181. return;
  182. }
  183. // 一个订单只能包含一类商品
  184. $goods = ShopGoods::find()->select('ID,CATEGORY_TYPE')->where(['in', 'ID', $this->goodsId])->andWhere(['STATUS' => 1])->asArray()->all();
  185. $goodsCategoryType = array_unique(array_column($goods, 'CATEGORY_TYPE'));
  186. if (count($goodsCategoryType) != 1) {
  187. $this->addError($attribute, 'Order cannot contain multiple product categories');//订单不能包含多种商品分类
  188. return;
  189. }
  190. // 购买方式
  191. $sellTypeLabelMap = array_column(ShopGoods::SALE_TYPE, NULL, 'label');
  192. if (!array_key_exists($this->payType, $sellTypeLabelMap)) {
  193. $this->addError($attribute, '不支持PayStack方式支付');
  194. return;
  195. }
  196. // 所选支付方式必须是商品分类支持的类型
  197. $categoryType = array_column(ShopGoods::CATEGORY_TYPE, NULL, 'id');
  198. // 商品类型
  199. $currCategoryType = $goodsCategoryType[0];
  200. if (!array_key_exists($currCategoryType, $categoryType)) {
  201. $this->addError($attribute, '商品分类错误');
  202. return;
  203. }
  204. $sellType = $categoryType[$currCategoryType]['sell_type'] ?? [];
  205. if (!$sellType || !in_array($this->payType, array_column($sellType, 'label'))) {
  206. $this->addError($attribute, '支付方式错误3');
  207. }
  208. }
  209. /**
  210. * 校验类型
  211. * @param $attribute
  212. */
  213. public function isStatus($attribute){
  214. if($this->type && !in_array($this->type, \Yii::$app->params['orderStatus'])){
  215. $this->addError($attribute, '订单状态类型错误');
  216. return ;
  217. }
  218. if ($this->scenario == 'adminStatus'){
  219. if ($this->status == $this->_model['STATUS']) {
  220. $this->addError($attribute, '订单状态没有改变');
  221. return ;
  222. }
  223. if($this->status == \Yii::$app->params['orderStatus']['notPaid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['delivery']) {
  224. $this->addError($attribute, '订单已经进入物流状态不能改为未支付');
  225. return ;
  226. }
  227. elseif($this->status == \Yii::$app->params['orderStatus']['paid'] && $this->_model['STATUS'] >= \Yii::$app->params['orderStatus']['cancel']) {
  228. $this->addError($attribute, '订单已失效不能处理');
  229. return ;
  230. }
  231. elseif($this->status == \Yii::$app->params['orderStatus']['delivery']) {
  232. $this->addError($attribute, '订单不能单独处理为物流状态');
  233. return ;
  234. }
  235. elseif($this->status == \Yii::$app->params['orderStatus']['complete'] && $this->_model['STATUS'] > \Yii::$app->params['orderStatus']['cancel']) {
  236. $this->addError($attribute, '订单已失效不能处理');
  237. return ;
  238. }
  239. elseif($this->status == \Yii::$app->params['orderStatus']['cancel']) {
  240. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  241. $this->addError($attribute, '订单已完成不能取消');
  242. return ;
  243. }
  244. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['del']) {
  245. $this->addError($attribute, '订单已删除不能取消');
  246. return ;
  247. }
  248. }
  249. elseif($this->status == \Yii::$app->params['orderStatus']['del']) {
  250. if($this->_model['STATUS'] == \Yii::$app->params['orderStatus']['complete']) {
  251. $this->addError($attribute, '订单已完成不能删除');
  252. return ;
  253. }
  254. }
  255. }
  256. }
  257. /**
  258. * 校验PayStack支付,更新订单状态.同步到正式订单.
  259. * @throws Exception
  260. */
  261. public function verifyPayStack(): ?ApproachOrder
  262. {
  263. if (!$this->validate()) {
  264. return null;
  265. }
  266. // 调用PayStack支付校验
  267. LoggerTool::info([$this->note['reference'], $this->note]);
  268. $payload = PayStack::transactionVerify($this->note['reference']);
  269. LoggerTool::info($payload);
  270. if ($payload['status'] !== true) {
  271. throw new Exception(Form::formatErrorsForApi($payload['message']));
  272. }
  273. if ($payload['data']['amount'] != $this->_model->PAY_AMOUNT * 100) {
  274. throw new Exception(Form::formatErrorsForApi('支付金额与订单金额不符'));
  275. }
  276. // 订单类型:userOrder(会员订单)、userUpgrade(会员升级)、userDec(会员报单)
  277. $orderType = $this->note['metadata']['custom_fields'][1]['value'] ?? false;
  278. $db = \Yii::$app->db;
  279. $transaction = $db->beginTransaction();
  280. try {
  281. // 更新准订单状态为已支付
  282. $this->_model->STATUS = $this->status;
  283. $this->_model->NOTE = json_encode($this->note);
  284. $this->_model->PAY_AT = Date::utcToTime($this->note['paid_at']);
  285. $this->_model->EMAIL = $this->note['email'];
  286. if (!$this->_model->save()) {
  287. throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
  288. }
  289. // 更新订单商品的支付Email
  290. ApproachOrderGoods::updateAll(['EMAIL' => $this->note['email']], 'ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  291. // 同步准订单到正式订单
  292. Order::insertOne($this->_model->toArray());
  293. // 同步准订单商品到正式订单商品
  294. $approachOrderGoods = ApproachOrderGoods::findAllAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  295. foreach ($approachOrderGoods as &$approachOrderGood) {
  296. $approachOrderGood['EMAIL'] = $this->email;
  297. }
  298. OrderGoods::batchInsert($approachOrderGoods);
  299. // 会员报单、BA升级
  300. if (in_array($orderType, ['userDec', 'baUpgrade', 'userUpgrade'])) {
  301. // 同步报单
  302. $approachDecOrder = ApproachDecOrder::findOneAsArray('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  303. if ($approachDecOrder) {
  304. unset($approachDecOrder['STATUS']);
  305. // 同步报单
  306. DecOrder::insertOne($approachDecOrder);
  307. // 修改会员锁定状态
  308. if (in_array($orderType, ['userDec', 'baUpgrade'])) {
  309. if (!User::updateAll(['STATUS' => 1], 'ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']])) {
  310. throw new Exception(Form::formatErrorsForApi('change user status error'));
  311. }
  312. }
  313. // 修改BA会员升级状态
  314. if ($orderType === 'baUpgrade') {
  315. // 查询BA会员名
  316. $userInfo = User::findOneAsArray('ID=:USER_ID', [':USER_ID' => $approachDecOrder['TO_USER_ID']]);
  317. if (!BaUser::updateAll(['WHETHER_UPGRADE' => 1, 'BA_UPGRADE_AT' => time()], 'USER_NAME=:USER_NAME', [':USER_NAME' => $userInfo['USER_NAME']])) {
  318. throw new Exception(Form::formatErrorsForApi('Brand Ambassador upgrade error!'));
  319. }
  320. }
  321. // 正式会员-升级单
  322. if ($orderType === 'userUpgrade') {
  323. // 会员升级 报单类型:2会员升级单
  324. if ($approachDecOrder['DETAIL_TYPE'] == 2) {
  325. // 为被升级人进行升级操作
  326. $decLevelLog = new DecLevelLog();
  327. $decLog = [
  328. 'userId' => $approachDecOrder['TO_USER_ID'],//会员ID
  329. 'fromId' => $approachDecOrder['ORI_LV'], // 变动前的级别
  330. 'levelId' => $approachDecOrder['UPGRADE_LV'],// 变动后的级别
  331. 'actionId' => $approachDecOrder['USER_ID'],
  332. 'remark' => $approachDecOrder['REMARK'],
  333. 'lvPv' => $this->_model->PV,
  334. ];
  335. $modifyDecLv = $decLevelLog->frontendChange($decLog);
  336. if (empty($modifyDecLv)) {
  337. $transaction->rollBack();
  338. throw new Exception("Failed to upgrade for member");//为会员升级失败
  339. }
  340. }
  341. }
  342. // 删除中间表
  343. ApproachDecOrder::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  344. }
  345. }
  346. // 删除中间表
  347. ApproachOrder::deleteAll('SN = :SN', [':SN' => $this->sn]);
  348. ApproachOrderGoods::deleteAll('ORDER_SN = :ORDER_SN', [':ORDER_SN' => $this->sn]);
  349. $transaction->commit();
  350. } catch (Exception $e) {
  351. $transaction->rollBack();
  352. $this->addError('edit', $e->getFile() . ' ' . $e->getMessage());
  353. return null;
  354. }
  355. return $this->_model;
  356. }
  357. /**
  358. * 复销
  359. * @throws Exception
  360. * @throws \yii\db\Exception
  361. */
  362. public function add(){
  363. if(!$this->validate()){
  364. return null;
  365. }
  366. $ids = $this->goodsId;
  367. $totalAmount = 0;
  368. $totalPv = 0;
  369. $totalAmountStandard = 0;
  370. $goodsType = ShopGoods::GOODS_TYPE;
  371. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0); // 汇率
  372. foreach ($this->goodsNum as $k => $v) {
  373. if ($v) {
  374. $goods = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1',[':ID'=> $ids[$k]]);
  375. if($goods['STORE_NUMS']>0){
  376. if ($goods['TYPE'] == 1 || $goods['TYPE'] == 2) {
  377. $discount = $goodsType[$goods['TYPE']]['discount'];
  378. $realPrice = $goods['SELL_PRICE'] * $discount/100;
  379. $realPv = $goods['PRICE_PV'] * $discount/100;
  380. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount/100;
  381. } else {
  382. $discount = $goods['SELL_DISCOUNT'];
  383. $realPrice = $goods['SELL_PRICE'] * $discount;
  384. $realPv = $goods['PRICE_PV'] * $discount;
  385. $realPriceStandard = $goods['SELL_PRICE_STANDARD'] * $discount;
  386. }
  387. $totalAmount += $realPrice * intval($v);
  388. $totalPv += $realPv * intval($v);
  389. $totalAmountStandard += $realPriceStandard * intval($v);
  390. $this->_orderGoods[] = [
  391. 'GOODS_ID' => $goods['ID'],
  392. 'PRICE' => $goods['SELL_PRICE'],
  393. 'PV' => $goods['PRICE_PV'],
  394. 'REAL_PRICE' => $realPrice,
  395. 'REAL_PV' => $realPv,
  396. 'POINT' => $goods['POINT'],
  397. 'BUY_NUMS' => intval($v),
  398. 'TAX_RATE' => $goods['TAX_RATE'],
  399. 'SKU_CODE' => $goods['GOODS_NO'],
  400. 'GOODS_TITLE' => $goods['GOODS_NAME'],
  401. 'CATEGORY_TYPE' => $goods['CATEGORY_TYPE'],
  402. 'PAY_TYPE' => $this->payType,
  403. 'EMAIL' => $this->email,
  404. 'STANDARD_PRICE' => $goods['SELL_PRICE_STANDARD'],
  405. 'REAL_STANDARD_PRICE' => $realPriceStandard,
  406. 'EXCHANGE_RATE' => $exchangeRate,
  407. ];
  408. }
  409. }
  410. }
  411. // 汇率
  412. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  413. // 运费.奈拉
  414. $freight = floatval(Cache::getSystemConfig()['freight']['VALUE'] ?? 0);
  415. // 普通商品免运费阈值.奈拉
  416. $freeShipping = floatval(Cache::getSystemConfig()['freeShipping']['VALUE'] ?? 0);
  417. $this->_decAmount = $totalAmount;
  418. $this->_decPv = $totalPv;
  419. $this->_freight = ($totalAmount >= $freeShipping) ? 0 : $freight;
  420. if($this->_address['PROVINCE']==1){
  421. $this->_freight = 0;
  422. }
  423. $this->_payAmount = $this->_decAmount + $this->_freight;
  424. $this->_decAmountStandard = $totalAmountStandard;
  425. $this->_standardAmount = $this->_decAmountStandard + $this->_freight;
  426. $db = \Yii::$app->db;
  427. $transaction = $db->beginTransaction();
  428. try {
  429. //写入订单
  430. if (!$orderResult = $this->addOrder()) {
  431. throw new Exception(Form::formatErrorsForApi($orderResult->getErrors()));
  432. }
  433. $transaction->commit();
  434. return $orderResult;
  435. }catch (\Exception $e){
  436. $transaction->rollBack();
  437. $this->addError('add', $e->getMessage());
  438. return null;
  439. }
  440. }
  441. /**
  442. * 复销订单
  443. * @throws Exception
  444. */
  445. public function addOrder()
  446. {
  447. $periodObj = Period::instance();
  448. $nowPeriodNum = $periodObj->getNowPeriodNum();
  449. $nowCalcMonth = $periodObj->getYearMonth($nowPeriodNum);
  450. $userId = \Yii::$app->user->id;
  451. $userName = Info::getUserNameByUserId($userId);
  452. $userRealName = Info::getUserRealNameByUserId($userId);
  453. $userMobile = Info::getUserMobileByUserId($userId);
  454. $userEmail = Info::getUserEmailByUserId($userId);
  455. $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);
  456. // 加入订单信息
  457. if ($this->_address['PROVINCE'] != 1) {
  458. $warehouse = Region::getWarehouseByCode($this->_address['PROVINCE']);//仓库
  459. if (!$warehouse) {
  460. // throw new Exception('地区2暂时不支持配送,具体联系客服');
  461. }
  462. }else{
  463. $warehouse = '01';
  464. }
  465. $_hasPV = $this->_decPv;
  466. $ordNo = $this->_generateSn();
  467. $orderModel = new ApproachOrder();
  468. $orderModel->SN = 'OS' . $ordNo;
  469. $orderModel->DEC_SN = 'DS' . $ordNo;
  470. $orderModel->ORDER_TYPE = $this->type;
  471. $orderModel->USER_ID = $userId;
  472. $orderModel->USER_NAME = $userName;
  473. $orderModel->ORDER_AMOUNT = $this->_decAmount;
  474. $orderModel->PV = $_hasPV;
  475. $orderModel->PAY_AMOUNT = $this->_payAmount;
  476. $orderModel->PAY_PV = $_hasPV; // 兑换积分不能算业绩
  477. $orderModel->PAY_AT = 0;
  478. $orderModel->PAY_TYPE = $this->payType;
  479. $orderModel->PERIOD_NUM = $nowPeriodNum;
  480. $orderModel->P_CALC_MONTH = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  481. $orderModel->FREIGHT = $this->_freight;
  482. $orderModel->PAY_FREIGHT = $this->_freight;
  483. $orderModel->CONSIGNEE = $this->_address['CONSIGNEE'];
  484. $orderModel->MOBILE = $this->_address['MOBILE'];
  485. $orderModel->PROVINCE = $this->_address['PROVINCE'];
  486. // $orderModel->CITY = $this->_address['CITY'];
  487. // $orderModel->COUNTY = $this->_address['COUNTY'];
  488. $orderModel->LGA_NAME = $this->_address['LGA_NAME'];
  489. $orderModel->CITY_NAME = $this->_address['CITY_NAME'];
  490. $orderModel->ADDRESS = $this->_address['ADDRESS'];
  491. $orderModel->FRONT_REMARK = $this->remark;
  492. $orderModel->WAREHOUSE = $warehouse;
  493. $orderModel->STATUS = \Yii::$app->params['orderStatus']['notPaid']['value'];
  494. $orderModel->CREATED_AT = Date::nowTime();
  495. $orderModel->CREATE_USER = $userName;
  496. $orderModel->EMAIL = $userEmail?$userEmail:$userName.'@elken.net';
  497. $orderModel->ORDER_AMOUNT_STANDARD = $this->_decAmountStandard;
  498. $orderModel->PAY_AMOUNT_STANDARD = $this->_standardAmount;
  499. $orderModel->EXCHANGE_RATE = $exchangeRate;
  500. if($this->_address['PROVINCE']==1){
  501. $orderModel->EXPRESS_TYPE = 1;
  502. $orderModel->CONSIGNEE = $userRealName;
  503. $orderModel->MOBILE = $userMobile;
  504. $orderModel->PROVINCE = 1;
  505. $orderModel->CITY = 1;
  506. $orderModel->COUNTY = 1;
  507. $orderModel->ADDRESS = '';
  508. }
  509. if(!$orderModel->save()){
  510. $this->addErrors($orderModel->getErrors());
  511. return false;
  512. }
  513. // 加入商品到订单商品表
  514. foreach($this->_orderGoods as $key=>$value) {
  515. $this->_orderGoods[$key]['ORDER_SN'] = $orderModel->SN;
  516. $this->_orderGoods[$key]['P_CALC_MONTH'] = Date::ociToDate($nowCalcMonth, Date::OCI_TIME_FORMAT_SHORT_MONTH);
  517. }
  518. ApproachOrderGoods::batchInsert($this->_orderGoods);
  519. // TODO: 记录流水
  520. return $orderModel;
  521. }
  522. /**
  523. * 生成流水号
  524. * @return string
  525. */
  526. private function _generateSn() {
  527. return Date::today('Ymd') . $this->_random(10, 1);
  528. }
  529. /**
  530. * 生成随机数
  531. * @param $length
  532. * @param int $numeric
  533. * @return string
  534. */
  535. private function _random($length, $numeric = 0) {
  536. $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
  537. $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
  538. $hash = '';
  539. $max = strlen($seed) - 1;
  540. for ($i = 0; $i < $length; $i++) {
  541. $hash .= $seed[mt_rand(0, $max)];
  542. }
  543. return $hash;
  544. }
  545. }