ErpInventory.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /**
  3. * 厦门云联储网络科技有限公司
  4. * https://www.baokuaiyun.com
  5. * Copyright (c) 2023 爆块云 All rights reserved.
  6. */
  7. namespace app\models;
  8. use Yii;
  9. use yii\behaviors\TimestampBehavior;
  10. use yii\db\ActiveRecord;
  11. /**
  12. * This is the model class for table "{{%erp_inventory}}".
  13. *
  14. * @property integer $id
  15. * @property string $goods_no
  16. */
  17. class ErpInventory extends \yii\db\ActiveRecord
  18. {
  19. public $sync2Goods = 1;
  20. /**
  21. * @inheritdoc
  22. */
  23. public static function tableName()
  24. {
  25. return '{{%erp_inventory}}';
  26. }
  27. public function behaviors()
  28. {
  29. return [
  30. [
  31. 'class' => TimestampBehavior::class,
  32. ]
  33. ];
  34. }
  35. public function afterSave($insert, $changedAttributes)
  36. {
  37. parent::afterSave($insert, $changedAttributes);
  38. if(!$insert && $changedAttributes['num'] && $this->sync2Goods){
  39. queue_push(new \app\jobs\erp\ErpInventory2GoodsJob([
  40. 'id' => $this->id,
  41. ]), 30, 1);
  42. }
  43. }
  44. public static function num2Goods($id)
  45. {
  46. $ei = ErpInventory::findOne($id);
  47. $numAdd = Goods::numAddStatic($ei->goods_id, explode(',', $ei->attr_ids), $ei->num, 1);
  48. if(!$numAdd){
  49. \Yii::error([__METHOD__, 'erp同步库存到商品失败!', $ei->attributes]);
  50. }
  51. }
  52. public static function logSave ($ei, $num, $type = ErpInventoryLog::LOG_TYPE_ORDER, $order_id = 0, $order_no = '')
  53. {
  54. $t = \Yii::$app->db->beginTransaction();
  55. try {
  56. $model = new ErpInventoryLog();
  57. $model->inventory_id = $ei['id'];
  58. $model->attr_ids = $ei['attr_ids'];
  59. $model->type = $type;
  60. $model->order_id = $order_id;
  61. $model->order_no = $order_no;
  62. $model->before = $ei['num'];
  63. $model->after = $ei['num'] + $num;
  64. $model->num = $num;
  65. if (!$model->save()) {
  66. \Yii::error([__METHOD__, $model->attributes]);
  67. throw new \Exception('日志保存失败!' . array_shift($model->getFirstErrors()));
  68. }
  69. $ei->num = $model->after;
  70. if($type == ErpInventoryLog::LOG_TYPE_PURCHASEOUT && $ei->num < 0){
  71. \Yii::error([__METHOD__, $ei->attributes]);
  72. throw new \Exception('库存保存失败!ID:'. $ei->id .'出库数量大于库存');
  73. }
  74. if (!$ei->save()) {
  75. \Yii::error([__METHOD__, $ei->attributes]);
  76. throw new \Exception('库存保存失败!' . array_shift($ei->getFirstErrors()));
  77. }
  78. $t->commit();
  79. return [
  80. 'code' => 0,
  81. 'msg' => '操作成功!'
  82. ];
  83. } catch (\Exception $e) {
  84. $t->rollBack();
  85. \Yii::error($e);
  86. return [
  87. 'code' => 1,
  88. 'msg' => $e->getMessage()
  89. ];
  90. }
  91. }
  92. }