]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
ERP-85 Реализовать обмен данных с 1С Бухгалтерия
authormarina <m.zozirova@gmail.com>
Fri, 23 Aug 2024 09:48:41 +0000 (12:48 +0300)
committermarina <m.zozirova@gmail.com>
Fri, 23 Aug 2024 09:48:41 +0000 (12:48 +0300)
erp24/api2/controllers/DataBuhController.php
erp24/controllers/ApiController.php
erp24/migrations/m240822_055751_alter_motivation_buh_table.php [new file with mode: 0644]
erp24/records/MotivationBuh.php [new file with mode: 0644]
erp24/records/MotivationBuhValue.php [new file with mode: 0644]
erp24/records/StoreGuidBuh.php [new file with mode: 0644]
erp24/services/MotivationServiceBuh.php [new file with mode: 0644]
erp24/views/api/store-guid-buh.php [new file with mode: 0644]

index a759f4dfbdbf5c490f585c2d61866238bca1a6d1..3686b90c55c40b2d8c723509cf18459574deb226 100644 (file)
@@ -8,12 +8,14 @@ use Yii;
 use yii\helpers\Json;
 use yii_app\records\ApiCronBuh;
 use yii_app\records\Firms;
+use yii_app\services\MotivationServiceBuh;
 
 class DataBuhController extends BaseController
 {
     const OUT_DIR =
 //        DIR . "/../json";
         "/var/www/erp24/api2/json_buh";
+
 //          "/var/www/www-root/data/www/api.bazacvetov24.ru/data/json";
 
     public function actionRequest($inn)
@@ -67,6 +69,9 @@ class DataBuhController extends BaseController
     }
 
 
+    /**
+     * @throws Exception
+     */
     public function actionUpload()
     {
         set_time_limit(600);
@@ -105,7 +110,7 @@ class DataBuhController extends BaseController
             file_put_contents(self::OUT_DIR . '/error_buh_upload.txt', PHP_EOL . 'result empty', FILE_APPEND);
         }
 
-        return $this->asJson(['request_id' => $requestId,'response' => true]);
+        return $this->asJson(['request_id' => $requestId, 'response' => true]);
     }
 
 }
\ No newline at end of file
index bf3a829c9cc3b6167946a8915a5d0db80e2ba90d..e1cf22065cd687575b6a2a9f18e119f5eb018a4f 100644 (file)
@@ -2,8 +2,10 @@
 
 namespace app\controllers;
 
+use yii_app\records\StoreGuidBuh;
 use kartik\select2\Select2;
 use Yii;
+use yii\data\ActiveDataProvider;
 use yii\data\ArrayDataProvider;
 use yii\helpers\ArrayHelper;
 use yii\helpers\Html;
@@ -305,7 +307,8 @@ class ApiController extends Controller
         }
     }
 
-    public function actionPoiskItems($q) {
+    public function actionPoiskItems($q)
+    {
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
         $out = ['results' => ['id' => '', 'text' => '']];
 
@@ -426,4 +429,27 @@ class ApiController extends Controller
             return $data;
         }
     }
+
+    public function actionStoreGuidBuh()
+    {
+
+        $model = new StoreGuidBuh();
+
+        $request = Yii::$app->request->post();
+        if ($request) {
+            $model->load($request);
+            if ($model->save())
+               $this->redirect(Yii::$app->request->referrer);
+        }
+
+        $dataProvider = new ActiveDataProvider([
+            'query' => StoreGuidBuh::find(),
+            'pagination' => false,
+        ]);
+
+        return $this->render('store-guid-buh', [
+            'dataProvider' => $dataProvider,
+            'model' => $model
+        ]);
+    }
 }
\ No newline at end of file
diff --git a/erp24/migrations/m240822_055751_alter_motivation_buh_table.php b/erp24/migrations/m240822_055751_alter_motivation_buh_table.php
new file mode 100644 (file)
index 0000000..9494f50
--- /dev/null
@@ -0,0 +1,46 @@
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Class m240822_055751_alter_motivation_buh_table
+ */
+class m240822_055751_alter_motivation_buh_table extends Migration
+{
+    /**
+     * {@inheritdoc}
+     */
+    public function safeUp()
+    {
+        $this->alterColumn('motivation_buh', 'inn', $this->bigInteger()->comment('ИНН'));
+        $this->addColumn('motivation_buh', 'created_by', $this->integer());
+        $this->addColumn('motivation_buh', 'updated_by', $this->integer());
+        $this->dropColumn('store_guid_buh', 'created_admin_id');
+        $this->dropColumn('store_guid_buh', 'updated_admin_id');
+        $this->addColumn('store_guid_buh', 'created_by', $this->integer());
+        $this->addColumn('store_guid_buh', 'updated_by', $this->integer());
+        $this->addColumn('motivation_buh_value', 'created_by', $this->integer());
+        $this->addColumn('motivation_buh_value', 'updated_by', $this->integer());
+        $this->addColumn('motivation_buh_value', 'created_at', $this->timestamp());
+        $this->addColumn('motivation_buh_value', 'updated_at', $this->timestamp());
+
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function safeDown()
+    {
+        $this->alterColumn('motivation_buh', 'inn', $this->integer()->comment('ИНН'));
+        $this->dropColumn('motivation_buh', 'created_by');
+        $this->dropColumn('motivation_buh', 'updated_by');
+        $this->dropColumn('store_guid_buh', 'created_by');
+        $this->dropColumn('store_guid_buh', 'updated_by');
+        $this->addColumn('store_guid_buh', 'created_admin_id', $this->integer());
+        $this->addColumn('store_guid_buh', 'updated_admin_id', $this->integer());
+        $this->dropColumn('motivation_buh_value', 'created_by');
+        $this->dropColumn('motivation_buh_value', 'updated_by');
+        $this->dropColumn('motivation_buh_value', 'created_at');
+        $this->dropColumn('motivation_buh_value', 'updated_at');
+    }
+}
diff --git a/erp24/records/MotivationBuh.php b/erp24/records/MotivationBuh.php
new file mode 100644 (file)
index 0000000..c4830e4
--- /dev/null
@@ -0,0 +1,75 @@
+<?php
+
+namespace yii_app\records;
+
+use yii\behaviors\BlameableBehavior;
+use yii\behaviors\TimestampBehavior;
+use yii\db\Expression;
+
+/**
+ * This is the model class for table "motivation_buh".
+ *
+ * @property int $id
+ * @property int $inn ИНН фирмы источника данных
+ * @property int $year Год
+ * @property int $month Месяц
+ * @property string $updated_at Дата изменения записи
+ * @property string $created_at Дата создания записи
+ */
+class MotivationBuh extends \yii\db\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return 'motivation_buh';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['inn', 'year', 'month'], 'required'],
+            [['inn', 'year', 'month'], 'default', 'value' => null],
+            [['inn', 'year', 'month'], 'integer'],
+        ];
+
+    }
+
+
+    public function behaviors()
+    {
+        return [
+            [
+                'class' => TimestampBehavior::class,
+                'createdAtAttribute' => 'created_at',
+                'updatedAtAttribute' => 'updated_at',
+                'value' => new Expression('NOW()'),
+            ],
+            [
+                'class' => BlameableBehavior::class,
+                'createdByAttribute' => 'created_by',
+                'updatedByAttribute' => 'updated_by',
+            ],
+        ];
+    }
+
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'id' => 'ID',
+            'inn' => 'Inn',
+            'year' => 'Year',
+            'month' => 'Month',
+            'updated_at' => 'Updated At',
+            'created_at' => 'Created At',
+        ];
+    }
+}
diff --git a/erp24/records/MotivationBuhValue.php b/erp24/records/MotivationBuhValue.php
new file mode 100644 (file)
index 0000000..0637961
--- /dev/null
@@ -0,0 +1,81 @@
+<?php
+
+namespace yii_app\records;
+
+use yii\behaviors\BlameableBehavior;
+use yii\behaviors\TimestampBehavior;
+use yii\db\Expression;
+
+/**
+ * This is the model class for table "motivation_buh_value".
+ *
+ * @property int $id
+ * @property int $motivation_buh_id id motivation buh
+ * @property int $store_id ID магазина
+ * @property int $motivation_group_id group id motivation
+ * @property int $value_id value id
+ * @property string $value_type тип значения
+ * @property int|null $value_int value int
+ * @property float|null $value_float value float
+ * @property string|null $value_string value string
+ */
+class MotivationBuhValue extends \yii\db\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return 'motivation_buh_value';
+    }
+
+    public function behaviors()
+    {
+        return [
+            [
+                'class' => TimestampBehavior::class,
+                'createdAtAttribute' => 'created_at',
+                'updatedAtAttribute' => 'updated_at',
+                'value' => new Expression('NOW()'),
+            ],
+            [
+                'class' => BlameableBehavior::class,
+                'createdByAttribute' => 'created_by',
+                'updatedByAttribute' => 'updated_by',
+            ],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['motivation_buh_id', 'store_id', 'motivation_group_id', 'value_id', 'value_type'], 'required'],
+            [['motivation_buh_id', 'store_id', 'motivation_group_id', 'value_id', 'value_int'], 'default', 'value' => null],
+            [['motivation_buh_id', 'store_id', 'motivation_group_id', 'value_id', 'value_int'], 'integer'],
+            [['value_float'], 'number'],
+            [['value_type'], 'string', 'max' => 10],
+            [['value_string'], 'string', 'max' => 255],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'id' => 'ID',
+            'motivation_buh_id' => 'Motivation Buh ID',
+            'store_id' => 'Store ID',
+            'motivation_group_id' => 'Motivation Group ID',
+            'value_id' => 'Value ID',
+            'value_type' => 'Value Type',
+            'value_int' => 'Value Int',
+            'value_float' => 'Value Float',
+            'value_string' => 'Value String',
+        ];
+    }
+}
diff --git a/erp24/records/StoreGuidBuh.php b/erp24/records/StoreGuidBuh.php
new file mode 100644 (file)
index 0000000..399246b
--- /dev/null
@@ -0,0 +1,92 @@
+<?php
+
+namespace yii_app\records;
+
+use yii\behaviors\BlameableBehavior;
+use yii\behaviors\TimestampBehavior;
+use yii\db\Expression;
+use yii_app\records\Admin;
+use yii_app\records\CityStore;
+
+/**
+ * This is the model class for table "store_guid_buh".
+ *
+ * @property int $id
+ * @property int $store_id store id
+ * @property string $store_guid store guid
+ * @property int|null $updated_by updated by
+ * @property int $created_by created by
+ * @property string|null $updated_at Дата изменения записи
+ * @property string $created_at Дата создания записи
+ */
+class StoreGuidBuh extends \yii\db\ActiveRecord
+{
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return 'store_guid_buh';
+    }
+
+    public function behaviors()
+    {
+        return [
+            [
+                'class' => TimestampBehavior::class,
+                'createdAtAttribute' => 'created_at',
+                'updatedAtAttribute' => 'updated_at',
+                'value' => new Expression('NOW()'),
+            ],
+            [
+                'class' => BlameableBehavior::class,
+                'createdByAttribute' => 'created_by',
+                'updatedByAttribute' => 'updated_by',
+            ],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['store_id', 'store_guid'], 'required'],
+            [['store_id', 'store_guid'], 'unique', 'targetAttribute' => ['store_id', 'store_guid']],
+            [['updated_at', 'created_at'], 'safe'],
+            [['store_guid'], 'string', 'max' => 255],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'id' => 'ID',
+            'store_id' => 'Store ID',
+            'store_guid' => 'Store Guid',
+            'updated_by' => 'Updated By',
+            'created_by' => 'Created By',
+            'updated_at' => 'Updated At',
+            'created_at' => 'Created At',
+        ];
+    }
+
+    public function getStore()
+    {
+        return $this->hasOne(CityStore::class, ['id' => 'store_id']);
+    }
+
+    public function getCreated()
+    {
+        return $this->hasOne(Admin::class, ['id' => 'created_by']);
+    }
+
+    public function getUpdated()
+    {
+        return $this->hasOne(Admin::class, ['id' => 'updated_by']);
+    }
+}
diff --git a/erp24/services/MotivationServiceBuh.php b/erp24/services/MotivationServiceBuh.php
new file mode 100644 (file)
index 0000000..a7944e5
--- /dev/null
@@ -0,0 +1,150 @@
+<?php
+
+namespace yii_app\services;
+
+use yii_app\records\MotivationBuh;
+use yii_app\records\MotivationBuhValue;
+use yii_app\records\StoreGuidBuh;
+use yii\db\Exception;
+use yii\helpers\Json;
+use yii_app\records\CityStore;
+use yii_app\records\MotivationCostsItem;
+use yii_app\records\MotivationValueGroup;
+
+class MotivationServiceBuh
+{
+    /**
+     * @throws Exception
+     */
+    public static function uploadBuhData($data)
+    {
+        $data = Json::decode($data);
+        $year = date('Y', strtotime($data['start_time']));
+        $month = date('m', strtotime($data['start_time']));
+        $inn = preg_replace('/^.*_/', '', $data['request_id']);
+        $weeks = self::getWeeksOfMonthForRange($data['start_time'], $data['end_time']);
+        $totalDays = ceil((strtotime($data['end_time']) - strtotime($data['start_time'])) / 86400);
+
+        if (!$weeks)
+            throw new \Exception('Указан некорректный период!');
+
+        if (!empty($data['cost_items'])) {
+            foreach ($data['cost_items'] as $stores) {
+                foreach ($stores as $storeData) {
+                    $storeBuh = StoreGuidBuh::find()
+                        ->andWhere(['store_guid' => $storeData['store_guid']])
+                        ->one();
+
+                    if (isset($storeBuh)) {
+                        $store = CityStore::getCityStoreById($storeBuh->store_id, true);
+
+                        foreach ($storeData['items'] as $items) {
+                            foreach ($items as $item) {
+
+                                foreach ($weeks as $week) {
+                                    $daysInWeek = in_array($week, [1, 2, 3, 4]) ? 7 : $totalDays - 28;
+
+                                    $value = MotivationCostsItem::findOne(['name' => $item['name']]);
+                                    if (!$value) {
+                                        LogService::apiErrorLog(json_encode(["error_id" => 3, "error" => $item['name']], JSON_UNESCAPED_UNICODE));
+                                    }
+
+                                    $sumForWeek = ($item['summ'] / $totalDays) * $daysInWeek;
+
+
+                                    $motivationBuh = MotivationBuh::findOne([
+                                        'year' => $year,
+                                        'month' => $month,
+                                        'inn' => $inn
+                                    ]);
+                                    if (!$motivationBuh) {
+                                        $motivationBuh = new MotivationBuh();
+                                        $motivationBuh->setAttributes([
+                                            'year' => $year,
+                                            'month' => $month,
+                                            'inn' => $inn
+                                        ]);
+                                        $motivationBuh->save();
+
+                                    }
+
+                                    $motivationBuhValue = MotivationBuhValue::findOne([
+                                        'motivation_buh_id' => $motivationBuh->id,
+                                        'store_id' => $store['id'],
+                                        'motivation_group_id' => $week,
+                                        'value_id' => $value->id,
+                                        'value_type' => MotivationCostsItem::DATA_TYPE_FLOAT,
+                                    ]);
+
+                                    $motivationValueGroup = MotivationValueGroup::findOne(['alias' => 'week' . $week]);
+
+                                    if ($motivationBuhValue) {
+                                        $motivationBuhValue->setAttribute('value_float', $sumForWeek);
+                                    } else {
+                                        $motivationBuhValue = new MotivationBuhValue();
+                                        $motivationBuhValue->setAttributes([
+                                            'motivation_buh_id' => $motivationBuh->id,
+                                            'store_id' => $store['id'],
+                                            'motivation_group_id' => $motivationValueGroup->id,
+                                            'value_id' => $value->id,
+                                            'value_type' => MotivationCostsItem::DATA_TYPE_FLOAT,
+                                            'value_float' => $sumForWeek
+                                        ]);
+                                    }
+                                    if ($motivationBuhValue->validate()) {
+                                        $motivationBuhValue->save();
+                                    } else {
+                                        LogService::apiErrorLog(json_encode(["error_id" => 3, "error" => $motivationBuhValue->getErrors()], JSON_UNESCAPED_UNICODE));
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+
+    }
+
+    private static function getWeeksOfMonthForRange($startTime, $endTime)
+    {
+        $startDateTime = new \DateTime($startTime);
+        $endDateTime = new \DateTime($endTime);
+
+        if ((date('m', strtotime($startTime))) != date('m', strtotime($endTime)) || (date('Y', strtotime($startTime))) != date('Y', strtotime($endTime)))
+            return null;
+
+        if (in_array(date('d', strtotime($startTime)), [1, 8, 22, 29]) && in_array(date('d', strtotime($endTime)), [7, 14, 21, 28, 30, 31]))
+            return null;
+
+        if ($startDateTime > $endDateTime) {
+            list($startDateTime, $endDateTime) = [$endDateTime, $startDateTime];
+        }
+
+        $weeks = [];
+        $daysInMonth = cal_days_in_month(CAL_GREGORIAN, (int)$startDateTime->format('m'), (int)$startDateTime->format('Y'));
+
+        while ($startDateTime <= $endDateTime) {
+            $week = (int)ceil($startDateTime->format('j') / 7);
+
+            if (!in_array($week, $weeks)) {
+                if ($week == 5) {
+                    $daysLeftInMonth = $daysInMonth - $startDateTime->format('j') + 1;
+                    $intervalDays = $endDateTime->diff($startDateTime)->days + 1;
+
+                    if ($intervalDays == $daysLeftInMonth) {
+                        $weeks[] = $week;
+                    }
+                } else {
+                    $weeks[] = $week;
+                }
+            }
+            $startDateTime->modify('+1 day');
+        }
+
+        return $weeks;
+    }
+
+}
+
diff --git a/erp24/views/api/store-guid-buh.php b/erp24/views/api/store-guid-buh.php
new file mode 100644 (file)
index 0000000..56b6038
--- /dev/null
@@ -0,0 +1,85 @@
+<?php
+
+use kartik\form\ActiveForm;
+use yii\grid\GridView;
+use yii\helpers\Html;
+use yii_app\records\CityStore;
+
+/** @var yii\web\View $this */
+/** @var yii_app\models\StoreGuidBuhSearch $searchModel */
+/** @var yii\data\ActiveDataProvider $dataProvider */
+
+$this->title = 'Интеграция с 1С Бухгалтерия';
+$this->params['breadcrumbs'][] = $this->title;
+?>
+<div class="p-8">
+<div class="store-guid-buh">
+
+    <div class="store-guid-buh-form">
+
+        <?php $form = ActiveForm::begin(); ?>
+
+        <?= $form->field($model, 'store_id')->dropDownList(\yii\helpers\ArrayHelper::map(CityStore::findAll(['visible' => 1]), 'id', 'name'))->label('Магазин') ?>
+
+        <?= $form->field($model, 'store_guid')->textInput(['maxlength' => true])->label('Guid в 1С Бухгалетрия') ?>
+
+        <div class="form-group">
+            <?= Html::submitButton('Создать', ['class' => 'btn btn-success']) ?>
+        </div>
+
+        <?php ActiveForm::end(); ?>
+
+    </div>
+
+
+    <?= GridView::widget([
+        'dataProvider' => $dataProvider,
+        'columns' => [
+            'id',
+            [
+                    'label' => 'Магазиин',
+                'attribute' => 'store_id',
+                'value' => function ($model) {
+                    return $model->store->name;
+                }
+            ],
+            [
+                'label' => 'Guid в 1С Бухгалетрия',
+                'attribute' => 'store_guid',
+
+            ],
+            [
+                'label' => 'Создатель',
+                'attribute' => 'created_by',
+                'value' => function ($model) {
+                    return $model->created->name;
+                }
+            ],
+
+            [
+                'label' => 'Время создания',
+                'attribute' => 'created_at',
+                'value' => function ($model) {
+                    return date('d-m-Y H:i:s', strtotime($model->created_at));
+                }
+            ],
+            [
+                'label' => 'Последнее изменение',
+                'attribute' => 'created_by',
+                'value' => function ($model) {
+                    return $model->updated->name;
+                }
+            ],
+            [
+                'label' => 'Время последнего изменения',
+                'attribute' => 'updated_at',
+                'value' => function ($model) {
+                    return date('d-m-Y H:i:s', strtotime($model->updated_at));
+                }
+            ],
+        ],
+    ]); ?>
+
+
+</div>
+</div>