]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
add report show weeks
authorAlexander Smirnov <fredeom@mail.ru>
Sun, 28 Apr 2024 17:22:37 +0000 (20:22 +0300)
committerAlexander Smirnov <fredeom@mail.ru>
Sun, 28 Apr 2024 17:22:37 +0000 (20:22 +0300)
erp24/api3/core/services/ReportService.php
erp24/api3/modules/v1/controllers/ReportController.php
erp24/api3/modules/v1/requests/report/ReportWeeksInput.php [new file with mode: 0644]

index 70a636492021b9cc7e0c6918f8670620f951bd7e..d833a397818fc8c1d80f19853dfdb94a5227191f 100644 (file)
@@ -25,6 +25,17 @@ class ReportService
     public function show($data) {
         $currentDate = $data->date_start;
         $reports = [];
+
+        $employees = Sales::find()->select(["COUNT(*) as cnt", "admin_id"])
+            ->where([
+                'between',
+                'date',
+                date("Y-m-d 00:00:00", strtotime($data->date_start)),
+                date("Y-m-d 23:59:59", strtotime($data->date_end))])
+            ->andWhere(['store_id' => $data->stores])
+            ->groupBy(['admin_id'])->asArray()->all();
+        $employeeCount = count($employees);
+
         while ($currentDate <= $data->date_end) {
             $report = [
                 "date" => $currentDate,
@@ -127,10 +138,10 @@ class ReportService
                 ->asArray()->all();
 
             $sales = Sales::find()->alias('s')->select(["COUNT(*) as cnt",
-                "sum(IF(operation='Продажа',s.summ,IF(operation='Возврат',-s.summ,0))) as total",
-                "sum(IF(IfNull(s.phone,-1)=-1,0,1)) as bonusUserCount",
-                "sum(IF(IfNull(s.phone,-1)!=-1 AND (IfNull(u.sale_cnt, -1) = -1 OR u.sale_cnt < 2), 1, 0)) as newBonusUserCount",
-                "sum(IF(IfNull(s.phone,-1)!=-1 AND u.sale_cnt > 1, 1, 0)) as repeatBonusUserCount",
+                "sum(CASE WHEN operation='Продажа' THEN s.summ ELSE (CASE WHEN operation='Возврат' THEN -s.summ ELSE 0 END) END) as total",
+                "sum(CASE WHEN s.phone is null THEN 0 ELSE 1 END) as bonusUserCount",
+                "sum(CASE WHEN (s.phone IS NOT NULL) AND ((u.sale_cnt IS NULL) OR u.sale_cnt < 2) THEN 1 ELSE 0 END) as newBonusUserCount",
+                "sum(CASE WHEN (s.phone IS NOT NULL) AND u.sale_cnt > 1 THEN 1 ELSE 0 END) as repeatBonusUserCount",
                 "s.store_id",
                 "s.admin_id"])
                 ->leftJoin('users u', 'u.phone = s.phone AND u.phone IN (\''
@@ -144,6 +155,17 @@ class ReportService
                 $salesMapArr[$sale['store_id']][] = $sale;
             }
 
+            $salesReturn = Sales::find()->alias('s')->select(["COUNT(*) as cnt", "sum(s.summ) as total", "s.store_id", "s.admin_id"])
+                ->where(['operation' => Sales::OPERATION_RETURN])
+                ->andWhere(['between', 's.date', $date_start, $date_end])
+                ->andWhere(['s.store_id' => $data->stores])
+                ->groupBy(['s.store_id', 's.admin_id'])->asArray()->all();
+
+            $salesReturnMapArr = [];
+            foreach ($salesReturn as $sale) {
+                $salesReturnMapArr[$sale['store_id']][] = $sale;
+            }
+
             $writeOffsMonth = WriteOffs::find()->select(['sum(summ) as total', 'store_id'])
                 ->where(['between', 'date', date("Y-m-01", strtotime($currentDate)), $date_end])
                 ->andWhere(['type' => WriteOffsErp::WRITE_OFFS_TYPE_BRAK])
@@ -187,7 +209,7 @@ class ReportService
                     ->asArray()->all();
 
                 $salesMatrix = Sales::find()->alias('s')->select([
-                    "sum(IF(operation='Продажа',p.summ,IF(operation='Возврат',-p.summ,0))) as total",
+                    "sum(CASE WHEN operation='Продажа' THEN p.summ ELSE (CASE WHEN operation='Возврат' THEN -p.summ ELSE 0 END) END) as total",
                     's.store_id', 's.admin_id'])
                     ->leftJoin('sales_products p', 'p.check_id = s.id')
                     ->where(['between', 's.date', $date_start, $date_end])
@@ -211,6 +233,8 @@ class ReportService
             $storeVisitorsQuantityTotal = 0;
             $storeSaleQuantityTotal = 0;
             $storeSaleTotalTotal = 0;
+            $storeSaleReturnQuantityTotal = 0;
+            $storeSaleReturnTotalTotal = 0;
             $storeSaleBonusCountTotal = 0;
             $storeSaleNewBonusCountTotal = 0;
             $storeSaleRepeatBonusCountTotal = 0;
@@ -227,9 +251,12 @@ class ReportService
             foreach ($stores as $store) {
                 /** @var CityStore $store */
                 $storeSaleArr = $salesMapArr[$store->id] ?? [];
+                $storeSaleReturnArr = $salesReturnMapArr[$store->id] ?? [];
                 $storeVisitorsQuantity = (int)($storeVisitorsByStore[$store->id] ?? 0);
                 $storeSaleQuantity = 0;
                 $storeSaleTotal = 0;
+                $storeSaleReturnQuantity = 0;
+                $storeSaleReturnTotal = 0;
                 $storeSaleBonusCount = 0;
                 $storeSaleNewBonusCount = 0;
                 $storeSaleRepeatBonusCount = 0;
@@ -242,19 +269,29 @@ class ReportService
                     $storeSaleNewBonusCount += (int)$storeSale['newBonusUserCount'];
                     $storeSaleRepeatBonusCount += (int)$storeSale['repeatBonusUserCount'];
                 }
+                $storeSaleReturnByAdminId = [];
+                foreach ($storeSaleReturnArr as $storeSale) {
+                    $storeSaleReturnByAdminId[$storeSale['admin_id']] = $storeSale;
+                    $storeSaleReturnQuantity += (int)$storeSale['cnt'];
+                    $storeSaleReturnTotal += (int)$storeSale['total'];
+                }
 
                 $storeVisitorsQuantityTotal += $storeVisitorsQuantity;
                 $storeSaleQuantityTotal += $storeSaleQuantity;
                 $storeSaleTotalTotal += $storeSaleTotal;
+                $storeSaleReturnQuantityTotal += $storeSaleReturnQuantity;
+                $storeSaleReturnTotalTotal += $storeSaleReturnTotal;
                 $storeSaleBonusCountTotal += $storeSaleBonusCount;
                 $storeSaleNewBonusCountTotal += $storeSaleNewBonusCount;
                 $storeSaleRepeatBonusCountTotal += $storeSaleRepeatBonusCount;
 
                 if (isset($adminNames[$store->id])) {
                     foreach ($adminNames[$store->id] as &$adminRecord) {
-                        $adminRecord["sale_quantity"] = (int)($storeSaleByAdminId[$adminRecord['id']]['cnt'] ?? 0);
                         $adminRecord["sale_total"] = (int)($storeSaleByAdminId[$adminRecord['id']]['total'] ?? 0);
+                        $adminRecord["sale_quantity"] = (int)($storeSaleByAdminId[$adminRecord['id']]['cnt'] ?? 0);
                         $adminRecord["sale_avg"] = $adminRecord["sale_quantity"] > 0 ? floor($adminRecord["sale_total"] / $adminRecord["sale_quantity"]) : 0;
+                        $adminRecord["sale_return_quantity"] = (int)($storeSaleReturnByAdminId[$adminRecord['id']]['cnt'] ?? 0);
+                        $adminRecord["sale_return_total"] = (int)($storeSaleReturnByAdminId[$adminRecord['id']]['total'] ?? 0);
                         $adminRecord["bonus_user_count"] = (int)($storeSaleByAdminId[$adminRecord['id']]['bonusUserCount'] ?? 0);
                         $adminRecord["bonus_user_per_sale_percent"] = $adminRecord["sale_quantity"] > 0 ? floor($adminRecord["bonus_user_count"] / $adminRecord["sale_quantity"] * 100) : 0;
                         $adminRecord["bonus_new_user_count"] = (int)($storeSaleByAdminId[$adminRecord['id']]['newBonusUserCount'] ?? 0);
@@ -313,6 +350,8 @@ class ReportService
                     "sale_quantity" => $storeSaleQuantity,
                     "sale_total" => $storeSaleTotal,
                     "sale_avg" => $storeSaleQuantity > 0 ? floor($storeSaleTotal / $storeSaleQuantity) : 0,
+                    "sale_return_quantity" => $storeSaleReturnQuantity,
+                    "sale_return_total" => $storeSaleReturnTotal,
                     "bonus_user_count" => $storeSaleBonusCount,
                     "bonus_user_per_sale_percent" => $storeSaleQuantity > 0 ? floor($storeSaleBonusCount / $storeSaleQuantity * 100) : 0,
                     "bonus_new_user_count" => $storeSaleNewBonusCount,
@@ -331,19 +370,26 @@ class ReportService
             }
 
             $report['total'] = [
-                "visitors_quantity" => $storeVisitorsQuantityTotal,
-                "sale_quantity" => $storeSaleQuantityTotal,
                 "sale_total" => $storeSaleTotalTotal,
+                "sale_quantity" => $storeSaleQuantityTotal,
                 "sale_avg" => $storeSaleQuantityTotal > 0 ? floor($storeSaleTotalTotal / $storeSaleQuantityTotal) : 0,
-                "bonus_user_count" => $storeSaleBonusCountTotal,
-                "bonus_user_per_sale_percent" => $storeSaleQuantityTotal > 0 ? floor($storeSaleBonusCountTotal / $storeSaleQuantityTotal * 100) : 0,
-                "bonus_new_user_count" => $storeSaleNewBonusCountTotal,
-                "bonus_repeat_user_count" => $storeSaleRepeatBonusCountTotal,
-                "total_write_offs_per_date_percent" => $storeSaleTotalTotal > 0 ? floor($totalWriteOffsPerDateTotal / $storeSaleTotalTotal * 100) : 0,
                 "total_write_offs_per_date" => $totalWriteOffsPerDateTotal,
+                "total_write_offs_per_date_percent" => $storeSaleTotalTotal > 0 ? floor($totalWriteOffsPerDateTotal / $storeSaleTotalTotal * 100) : 0,
                 "total_write_offs_per_month" => $totalWriteOffsPerMonthTotal,
+                "total_write_offs_per_month_percent" => $storeSaleTotalTotal > 0 ? floor($totalWriteOffsPerMonthTotal / $storeSaleTotalTotal * 100) : 0,
                 "total_payroll_days" => $totalPayrollDaysTotal,
+                "total_payroll_days_percent" => $storeSaleTotalTotal > 0 ? floor($totalPayrollDaysTotal / $storeSaleTotalTotal * 100) : 0,
                 "total_payroll_month" => $totalPayrollMonthTotal,
+                "total_payroll_month_percent" => $storeSaleTotalTotal > 0 ? floor($totalPayrollMonthTotal / $storeSaleTotalTotal * 100) : 0,
+                "employee_sale_avg" => $employeeCount > 0 ? floor($storeSaleTotalTotal / $employeeCount) : 0,
+                "visitors_quantity" => $storeVisitorsQuantityTotal,
+                "conversion" => $storeSaleQuantityTotal > 0 ? floor($storeVisitorsQuantityTotal / $storeSaleQuantityTotal * 100) : 0,
+                "bonus_user_count" => $storeSaleBonusCountTotal,
+                "bonus_user_per_sale_percent" => $storeSaleQuantityTotal > 0 ? floor($storeSaleBonusCountTotal / $storeSaleQuantityTotal * 100) : 0,
+                "bonus_new_user_count" => $storeSaleNewBonusCountTotal,
+                "bonus_repeat_user_count" => $storeSaleRepeatBonusCountTotal,
+                "sale_return_quantity" => $storeSaleReturnQuantityTotal,
+                "sale_return_total" => $storeSaleReturnTotalTotal,
                 "total_matrix_per_day" => $totalMatrixPerDayTotal,
                 "total_wrap_per_day" => $totalWrapPerDayTotal,
                 "total_services_per_day" => $totalServicePerDayTotal,
@@ -356,4 +402,377 @@ class ReportService
 
         return $reports;
     }
+
+    /**
+     * @throws \yii\base\Exception
+     * @throws Exception
+     */
+    public function showWeeks($data) {
+        set_time_limit(600);
+
+        $reports = [];
+
+        $cityStoreNames = ArrayHelper::map(CityStore::find()->all(), 'id', 'name');
+
+        $eitStores = ExportImportTable::find()->where(['export_val' => $data->stores])
+            ->select(['entity_id', 'export_val'])
+            ->where(['export_id' => 1, 'entity' => 'city_store'])
+            ->indexBy(['entity_id'])
+            ->asArray()->all();
+
+        $store_guids = [];
+        foreach ($data->stores as $store_id) {
+            $store_guids[$store_id] = $eitStores[$store_id]['export_val'];
+        }
+
+        $cond = ['or'];
+        foreach ($data->date as $ind => $dateStartEnd) {
+            $cond[]= ['between', 'date',
+                date("Y-m-d 00:00:00", strtotime($dateStartEnd[0])),
+                date("Y-m-d 23:59:59", strtotime($dateStartEnd[1]))];
+        }
+        $employeesTotal = Sales::find()->select(["COUNT(*) as cnt", "admin_id"]) // , "DATA_FORMAT(date, '%Y-%m-%d') as day"
+            ->where(['store_id' => $data->stores])
+            ->andWhere($cond)
+            ->groupBy(['admin_id'])->asArray()->all();
+        $employeeCountTotal = count($employeesTotal);
+
+        foreach ($data->date as $ind => $dateStartEnd) {
+            $currentDate = $dateStartEnd[0];
+
+            $employeeCount = [];
+            foreach ($data->stores as $store_id) {
+                $employees = Sales::find()->select(["COUNT(*) as cnt", "admin_id"])
+                    ->where(['between', 'date',
+                        date("Y-m-d 00:00:00", strtotime($dateStartEnd[0])),
+                        date("Y-m-d 23:59:59", strtotime($dateStartEnd[1]))])
+                    ->andWhere(['store_id' => $store_id])
+                    ->groupBy(['admin_id'])->asArray()->all();
+                $employeeCount[$store_id] = count($employees);
+            }
+
+            $storeVisitorsQuantityTotal = [];
+            $storeSaleQuantityTotal = [];
+            $storeSaleTotalTotal = [];
+            $storeSaleReturnQuantityTotal = [];
+            $storeSaleReturnTotalTotal = [];
+            $storeSaleBonusCountTotal = [];
+            $storeSaleNewBonusCountTotal = [];
+            $storeSaleRepeatBonusCountTotal = [];
+            $totalWriteOffsPerDateTotal = [];
+            $totalWriteOffsPerMonthTotal = [];
+            $totalPayrollDaysTotal = [];
+            $totalPayrollMonthTotal = [];
+            $totalMatrixPerDayTotal = [];
+            $totalWrapPerDayTotal = [];
+            $totalServicePerDayTotal = [];
+            $totalPottedPerDayTotal = [];
+
+            $adminPayrollDaysMonth = AdminPayrollDays::find()->select(["FLOOR(SUM(day_payroll)) as total", 'store_id'])
+                ->where([
+                    'between', 'date',
+                    date("Y-m-01 00:00:00", strtotime($dateStartEnd[0])),
+                    date("Y-m-d 23:59:59", strtotime($dateStartEnd[1]))])
+                ->andWhere(['store_id' => $data->stores])
+                ->groupBy(['store_id'])
+                ->indexBy('store_id')
+                ->asArray()->all();
+
+            $writeOffsMonth = WriteOffs::find()->select(['sum(summ) as total', 'store_id'])
+                ->where([
+                    'between', 'date',
+                    date("Y-m-01 00:00:00", strtotime($dateStartEnd[0])),
+                    date("Y-m-d 23:59:59", strtotime($dateStartEnd[1]))])
+                ->andWhere(['type' => WriteOffsErp::WRITE_OFFS_TYPE_BRAK])
+                ->andWhere(['store_id' => array_values($store_guids)])
+                ->groupBy(['store_id'])
+                ->indexBy('store_id')
+                ->asArray()->all();
+
+            $salesMonth = Sales::find()->alias('s')->select([
+                    "sum(CASE WHEN operation='Продажа' THEN s.summ ELSE (CASE WHEN operation='Возврат' THEN -s.summ ELSE 0 END) END) as total",
+                    'store_id_1c',
+                ])
+                ->where([
+                    'between', 'date',
+                    date("Y-m-01 00:00:00", strtotime($dateStartEnd[0])),
+                    date("Y-m-d 23:59:59", strtotime($dateStartEnd[1]))])
+                ->andWhere(['s.store_id' => $data->stores])
+                ->groupBy(['store_id_1c'])
+                ->indexBy('store_id_1c')
+                ->asArray()->all();
+
+            while ($currentDate <= $dateStartEnd[1]) {
+
+                $adminPayrollDays = AdminPayrollDays::find()->select(["FLOOR(SUM(day_payroll)) as total", 'store_id'])
+                    ->where(['date' => $currentDate])
+                    ->andWhere(['store_id' => $data->stores])
+                    ->groupBy(['store_id'])
+                    ->indexBy('store_id')
+                    ->asArray()->all();
+
+                $date_start = $data->shift_type == 2 ?
+                    date("Y-m-d 20:00:00", strtotime($currentDate)) :
+                    date("Y-m-d 08:00:00", strtotime($currentDate));
+                $date_end = $data->shift_type == 1 ?
+                    date("Y-m-d 20:00:00", strtotime($currentDate)) :
+                    date("Y-m-d 08:00:00", strtotime("+1 day", strtotime($currentDate)));
+
+//                return [$adminPayrollDaysMonth, $adminPayrollDays];
+                $storeVisitorsQuery = StoreVisitors::find()
+                    ->select([
+                        'counter' => new \yii\db\Expression("SUM(counter)"),
+                        'store_id'
+                    ]);
+
+                if ($data->shift_type == 1) {
+                    $storeVisitorsQuery->andWhere(['>=', 'date_hour', 8])->andWhere(['<=', 'date_hour', 20])
+                        ->andWhere(['date' => date("Y-m-d", strtotime($currentDate))]);
+                }
+                if ($data->shift_type == 2) {
+                    $storeVisitorsQuery->andWhere([
+                        'or',
+                        [
+                            'and',
+                            ['>=', 'date_hour', 20],
+                            ['<=', 'date_hour', 23],
+                            ['date' => date("Y-m-d", strtotime($currentDate))]
+                        ],
+                        [
+                            'and',
+                            ['>=', 'date_hour', 0],
+                            ['<=', 'date_hour', 7],
+                            ['date' => date("Y-m-d", strtotime("+1 day", strtotime($currentDate)))]
+                        ],
+                    ]);
+                }
+                if ($data->shift_type == 0) {
+                    $storeVisitorsQuery->andWhere([
+                        'or',
+                        [
+                            'and',
+                            ['>=', 'date_hour', 8],
+                            ['<=', 'date_hour', 23],
+                            ['date' => date("Y-m-d", strtotime($currentDate))]
+                        ],
+                        [
+                            'and',
+                            ['>=', 'date_hour', 0],
+                            ['<=', 'date_hour', 7],
+                            ['date' => date("Y-m-d", strtotime("+1 day", strtotime($currentDate)))]
+                        ],
+                    ]);
+                }
+
+                $storeVisitors = $storeVisitorsQuery->andWhere(['store_id' => $data->stores])
+                    ->groupBy(['store_id'])
+                    ->indexBy('store_id')->asArray()->all();
+//                return [$storeVisitors];
+
+                $salesPhones = Sales::find()->select(["DISTINCT(phone)"])
+                    ->where(['between', 'date', $date_start, $date_end])
+                    ->andWhere(['IS NOT', 'phone', new Expression('NULL')])
+                    ->andWhere(['store_id' => $data->stores])
+                    ->asArray()->all();
+
+//                return [$salesPhones];
+
+                $sales = Sales::find()->alias('s')->select(["COUNT(*) as cnt",
+                    "sum(CASE WHEN operation='Продажа' THEN s.summ ELSE (CASE WHEN operation='Возврат' THEN -s.summ ELSE 0 END) END) as total",
+                    "sum(CASE WHEN s.phone is null THEN 0 ELSE 1 END) as bonusUserCount",
+                    "sum(CASE WHEN (s.phone IS NOT NULL) AND ((u.sale_cnt IS NULL) OR u.sale_cnt < 2) THEN 1 ELSE 0 END) as newBonusUserCount",
+                    "sum(CASE WHEN (s.phone IS NOT NULL) AND u.sale_cnt > 1 THEN 1 ELSE 0 END) as repeatBonusUserCount",
+                    'store_id_1c',
+                    ])
+                    ->leftJoin('users u', 'u.phone = s.phone::varchar(20) AND u.phone IN (\''
+                        . implode('\',\'', ArrayHelper::getColumn($salesPhones, 'phone')) .'\')')
+                    ->where(['between', 's.date', $date_start, $date_end])
+                    ->andWhere(['s.store_id' => $data->stores])
+                    ->groupBy(['store_id_1c'])
+                    ->indexBy('store_id_1c')
+                    ->asArray()->all();
+
+//                return [$sales];
+
+                $salesReturn = Sales::find()->alias('s')->select(["COUNT(*) as cnt", "sum(s.summ) as total", "store_id_1c"])
+                    ->where(['operation' => Sales::OPERATION_RETURN])
+                    ->andWhere(['between', 's.date', $date_start, $date_end])
+                    ->andWhere(['s.store_id' => $data->stores])
+                    ->groupBy(['store_id_1c'])
+                    ->indexBy('store_id_1c')
+                    ->asArray()->all();
+
+//                return [$salesReturn];
+
+                $writeOffs = WriteOffs::find()->select(['sum(summ) as total', 'store_id'])
+                    ->where(['between', 'date', $date_start, $date_end])
+                    ->andWhere(['type' => WriteOffsErp::WRITE_OFFS_TYPE_BRAK])
+                    ->andWhere(['store_id' => array_values($store_guids)])
+                    ->groupBy(['store_id'])
+                    ->indexBy('store_id')
+                    ->asArray()->all();
+
+//                return [$writeOffsMonth, $writeOffs];
+
+                $specificSales = [];
+                foreach (['matrix', 'wrap', 'services', 'potted'] as $productTip) {
+                    $productsClass = ProductsClass::find()->select(['category_id', 'tip'])
+                        ->where(['tip' => $productTip])
+                        ->indexBy('category_id')
+                        ->asArray()->all();
+
+                    $products1c = Products1c::find()->select(['id', 'parent_id', 'name'])
+                        ->where(['parent_id' => array_keys($productsClass), 'tip' => 'products'])
+                        ->indexBy(['id'])
+                        ->asArray()->all();
+
+                    $salesMatrix = Sales::find()->alias('s')->select([
+                        "sum(CASE WHEN operation='Продажа' THEN p.summ ELSE (CASE WHEN operation='Возврат' THEN -p.summ ELSE 0 END) END) as total",
+                        'store_id'
+                        ])                        ->leftJoin('sales_products p', 'p.check_id = s.id')
+                        ->where(['between', 's.date', $date_start, $date_end])
+                        ->andWhere(['operation' => Sales::OPERATION_SALE])
+                        ->andWhere(['p.product_id' => array_keys($products1c)])
+                        ->andWhere(['store_id' => $data->stores])
+                        ->groupBy(['store_id'])
+                        ->indexBy('store_id')
+                        ->asArray()->all();
+
+                    $specificSales[$productTip] = $salesMatrix;
+                }
+
+//                return [$specificSales];
+
+                $storeVisitorsQuantity = [];
+                $storeSaleQuantity = [];
+                $storeSaleTotal = [];
+                $storeSaleReturnQuantity = [];
+                $storeSaleReturnTotal = [];
+                $storeSaleBonusCount = [];
+                $storeSaleNewBonusCount = [];
+                $storeSaleRepeatBonusCount = [];
+                foreach ($data->stores as $store_id) {
+                    $storeVisitorsQuantity[$store_id] = (int)($storeVisitors[$store_id]['counter'] ?? 0);
+                    $storeSaleQuantity[$store_id] = (int)($sales[$eitStores[$store_id]['export_val']]['cnt'] ?? 0);
+                    $storeSaleTotal[$store_id] = (int)($sales[$eitStores[$store_id]['export_val']]['total'] ?? 0);
+                    $storeSaleReturnQuantity[$store_id] = (int)($salesReturn[$eitStores[$store_id]['export_val']]['cnt'] ?? 0);
+                    $storeSaleReturnTotal[$store_id] = (int)($salesReturn[$eitStores[$store_id]['export_val']]['total'] ?? 0);
+                    $storeSaleBonusCount[$store_id] = (int)($sales[$eitStores[$store_id]['export_val']]['bonusUserCount'] ?? 0);
+                    $storeSaleNewBonusCount[$store_id] = (int)($sales[$eitStores[$store_id]['export_val']]['newBonusUserCount'] ?? 0);
+                    $storeSaleRepeatBonusCount[$store_id] = (int)($sales[$eitStores[$store_id]['export_val']]['repeatBonusUserCount'] ?? 0);
+
+                    $storeVisitorsQuantityTotal[$store_id] = ($storeVisitorsQuantityTotal[$store_id] ?? 0) + $storeVisitorsQuantity[$store_id];
+                    $storeSaleQuantityTotal[$store_id] = ($storeSaleQuantityTotal[$store_id] ?? 0) + $storeSaleQuantity[$store_id];
+                    $storeSaleTotalTotal[$store_id] = ($storeSaleTotalTotal[$store_id] ?? 0) + $storeSaleTotal[$store_id];
+                    $storeSaleReturnQuantityTotal[$store_id] = ($storeSaleReturnQuantityTotal[$store_id] ?? 0) + $storeSaleReturnQuantity[$store_id];
+                    $storeSaleReturnTotalTotal[$store_id] = ($storeSaleReturnTotalTotal[$store_id] ?? 0) + $storeSaleReturnTotal[$store_id];
+                    $storeSaleBonusCountTotal[$store_id] = ($storeSaleBonusCountTotal[$store_id] ?? 0) + $storeSaleBonusCount[$store_id];
+                    $storeSaleNewBonusCountTotal[$store_id] = ($storeSaleNewBonusCountTotal[$store_id] ?? 0) + $storeSaleNewBonusCount[$store_id];
+                    $storeSaleRepeatBonusCountTotal[$store_id] = ($storeSaleRepeatBonusCountTotal[$store_id] ?? 0) + $storeSaleRepeatBonusCount[$store_id];
+
+                    $totalWriteOffsPerDateTotal[$store_id] = ($totalWriteOffsPerDateTotal[$store_id] ?? 0) + (int)($writeOffs[$store_guids[$store_id]]["total"] ?? 0);
+                    $totalPayrollDaysTotal[$store_id] = ($totalPayrollDaysTotal[$store_id] ?? 0) + (int)($adminPayrollDays[$store_id]['total'] ?? 0);
+
+                    $totalSpecificPerDay = [];
+                    foreach (['matrix', 'wrap', 'services', 'potted'] as $spec) {
+                        $totalSpecificPerDay[$store_id][$spec] = 0;
+                        foreach ($specificSales[$spec][$store_id] ?? [] as $specificSale) {
+                            $totalSpecificPerDay[$store_id][$spec] += (float)($specificSale ?? 0);
+                        }
+                    }
+                    $totalMatrixPerDay[$store_id] = $totalSpecificPerDay[$store_id]['matrix'];
+                    $totalWrapPerDay[$store_id] = $totalSpecificPerDay[$store_id]['wrap'];
+                    $totalServicePerDay[$store_id] = $totalSpecificPerDay[$store_id]['services'];
+                    $totalPottedPerDay[$store_id] = $totalSpecificPerDay[$store_id]['potted'];
+
+                    $totalMatrixPerDayTotal[$store_id] = ($totalMatrixPerDayTotal[$store_id] ?? 0) + $totalMatrixPerDay[$store_id];
+                    $totalWrapPerDayTotal[$store_id] = ($totalWrapPerDayTotal[$store_id] ?? 0) + $totalWrapPerDay[$store_id];
+                    $totalServicePerDayTotal[$store_id] = ($totalServicePerDayTotal[$store_id] ?? 0) + $totalServicePerDay[$store_id];
+                    $totalPottedPerDayTotal[$store_id] = ($totalPottedPerDayTotal[$store_id] ?? 0) + $totalPottedPerDay[$store_id];
+                }
+
+                $currentDate = date("Y-m-d", strtotime("+1 day", strtotime($currentDate)));
+            }
+
+            $stores = [];
+            $total = [];
+
+            foreach ($data->stores as $store_id) {
+                $store = [
+                    "sale_month_total" => ($salesMonth[$store_guids[$store_id]]["total"] ?? 0),
+                    "sale_total" => $storeSaleTotalTotal[$store_id] ?? 0,
+                    "sale_quantity" => $storeSaleQuantityTotal[$store_id] ?? 0,
+                    "sale_avg" => $storeSaleQuantityTotal[$store_id] ?? 0 > 0 ? floor($storeSaleTotalTotal[$store_id] / $storeSaleQuantityTotal[$store_id]) : 0,
+                    "total_write_offs_per_date" => $totalWriteOffsPerDateTotal[$store_id] ?? 0,
+                    "total_write_offs_per_date_percent" => $storeSaleTotalTotal[$store_id] ?? 0 > 0 ? floor($totalWriteOffsPerDateTotal[$store_id] / $storeSaleTotalTotal[$store_id] * 100) : 0,
+                    "total_write_offs_per_month" => (int)($writeOffsMonth[$store_guids[$store_id]]["total"] ?? 0),//$totalWriteOffsPerMonthTotal[$store_id] ?? 0,
+//                    "total_write_offs_per_month_percent" => $storeSaleTotalTotal[$store_id] ?? 0 > 0 ? floor((int)($writeOffsMonth[$store_guids[$store_id]]["total"] ?? 0) / $storeSaleTotalTotal[$store_id] * 100) : 0,
+                    "total_write_offs_per_month_percent" => ($salesMonth[$store_guids[$store_id]]["total"] ?? 0) > 0 ? floor((int)($writeOffsMonth[$store_guids[$store_id]]["total"] ?? 0) / ($salesMonth[$store_guids[$store_id]]["total"] ?? 0) * 100) : 0,
+                    "total_payroll_days" => $totalPayrollDaysTotal[$store_id] ?? 0,
+                    "total_payroll_days_percent" => $storeSaleTotalTotal[$store_id] ?? 0 > 0 ? floor($totalPayrollDaysTotal[$store_id] / $storeSaleTotalTotal[$store_id] * 100) : 0,
+                    "total_payroll_month" => (int)($adminPayrollDaysMonth[$store_id]['total'] ?? 0),//$totalPayrollMonthTotal[$store_id] ?? 0,
+//                    "total_payroll_month_percent" => $storeSaleTotalTotal[$store_id] ?? 0 > 0 ? floor(($adminPayrollDaysMonth[$store_id]['total'] ?? 0) / $storeSaleTotalTotal[$store_id] * 100) : 0,
+                    "total_payroll_month_percent" => ($salesMonth[$store_guids[$store_id]]["total"] ?? 0) > 0 ? floor(($adminPayrollDaysMonth[$store_id]['total'] ?? 0) / ($salesMonth[$store_guids[$store_id]]["total"] ?? 0) * 100) : 0,
+                    "employee_sale_avg" => $employeeCount[$store_id] ?? 0 > 0 ? floor($storeSaleTotalTotal[$store_id] / $employeeCount[$store_id]) : 0,
+                    "visitors_quantity" => $storeVisitorsQuantityTotal[$store_id] ?? 0,
+                    "conversion" => $storeSaleQuantityTotal[$store_id] ?? 0 > 0 ? floor($storeVisitorsQuantityTotal[$store_id] / $storeSaleQuantityTotal[$store_id] * 100) : 0,
+                    "bonus_user_count" => $storeSaleBonusCountTotal[$store_id] ?? 0,
+                    "bonus_user_per_sale_percent" => $storeSaleQuantityTotal[$store_id] ?? 0 > 0 ? floor($storeSaleBonusCountTotal[$store_id] / $storeSaleQuantityTotal[$store_id] * 100) : 0,
+                    "bonus_new_user_count" => $storeSaleNewBonusCountTotal[$store_id] ?? 0,
+                    "bonus_repeat_user_count" => $storeSaleRepeatBonusCountTotal[$store_id] ?? 0,
+                    "sale_return_quantity" => $storeSaleReturnQuantityTotal[$store_id] ?? 0,
+                    "sale_return_total" => $storeSaleReturnTotalTotal[$store_id] ?? 0,
+                    "total_matrix_per_day" => $totalMatrixPerDayTotal[$store_id] ?? 0,
+                    "total_wrap_per_day" => $totalWrapPerDayTotal[$store_id] ?? 0,
+                    "total_services_per_day" => $totalServicePerDayTotal[$store_id] ?? 0,
+                    "total_potted_per_day" => $totalPottedPerDayTotal[$store_id] ?? 0,
+                ];
+                $stores []= ['id' => $store_id, 'guid' => $eitStores[$store_id]['export_val'],
+                    'name' => $cityStoreNames[$store_id], 'data' => $store];
+
+                $total["sale_month_total"] = ($total["sale_month_total"] ?? 0) + ($salesMonth[$store_guids[$store_id]]["total"] ?? 0);
+                $total["sale_total"] = ($total["sale_total"] ?? 0) + ($storeSaleTotalTotal[$store_id] ?? 0);
+                $total["sale_quantity"] = ($total["sale_quantity"] ?? 0) + ($storeSaleQuantityTotal[$store_id] ?? 0);
+                $total["sale_avg"] = 0;
+                $total["total_write_offs_per_date"] = ($total["total_write_offs_per_date"] ?? 0) + ($totalWriteOffsPerDateTotal[$store_id] ?? 0);
+                $total["total_write_offs_per_date_percent"] = 0;
+                $total["total_write_offs_per_month"] = ($total["total_write_offs_per_month"] ?? 0) + (int)($writeOffsMonth[$store_guids[$store_id]]["total"] ?? 0); //($totalWriteOffsPerMonthTotal[$store_id] ?? 0);
+                $total["total_write_offs_per_month_percent"] = 0;
+                $total["total_payroll_days"] = ($total["total_payroll_days"] ?? 0) + ($totalPayrollDaysTotal[$store_id] ?? 0);
+                $total["total_payroll_days_percent"] = 0;
+                $total["total_payroll_month"] = ($total["total_payroll_month"] ?? 0) + (int)($adminPayrollDaysMonth[$store_id]['total'] ?? 0);//($totalPayrollMonthTotal[$store_id] ?? 0);
+                $total["total_payroll_month_percent"] = 0;
+                $total["employee_sale_avg"] = 0;
+                $total["visitors_quantity"] = ($total["visitors_quantity"] ?? 0) + ($storeVisitorsQuantityTotal[$store_id] ?? 0);
+                $total["conversion"] = 0;
+                $total["bonus_user_count"] = ($total["bonus_user_count"] ?? 0) + ($storeSaleBonusCountTotal[$store_id] ?? 0);
+                $total["bonus_user_per_sale_percent"] = 0;
+                $total["bonus_new_user_count"] = ($total["bonus_new_user_count"] ?? 0) + ($storeSaleNewBonusCountTotal[$store_id] ?? 0);
+                $total["bonus_repeat_user_count"] = ($total["bonus_repeat_user_count"] ?? 0) + ($storeSaleRepeatBonusCountTotal[$store_id] ?? 0);
+                $total["sale_return_quantity"] = ($total["sale_return_quantity"] ?? 0) + ($storeSaleReturnQuantityTotal[$store_id] ?? 0);
+                $total["sale_return_total"] = ($total["sale_return_total"] ?? 0) + ($storeSaleReturnTotalTotal[$store_id] ?? 0);
+                $total["total_matrix_per_day"] = ($total["total_matrix_per_day"] ?? 0) + ($totalMatrixPerDayTotal[$store_id] ?? 0);
+                $total["total_wrap_per_day"] = ($total["total_wrap_per_day"] ?? 0) + ($totalWrapPerDayTotal[$store_id] ?? 0);
+                $total["total_services_per_day"] = ($total["total_services_per_day"] ?? 0) + ($totalServicePerDayTotal[$store_id] ?? 0);
+                $total["total_potted_per_day"] = ($total["total_potted_per_day"] ?? 0) + ($totalPottedPerDayTotal[$store_id] ?? 0);
+            }
+            $total["sale_avg"] = $total["sale_quantity"] > 0 ? floor($total["sale_total"] / $total["sale_quantity"]) : 0;
+            $total["total_write_offs_per_date_percent"] = $total["sale_total"] > 0 ? floor($total["total_write_offs_per_date"] / $total["sale_total"] * 100) : 0;
+            $total["total_write_offs_per_month_percent"] = $total["sale_month_total"] > 0 ? floor($total["total_write_offs_per_month"] / $total["sale_month_total"] * 100) : 0;
+            $total["total_payroll_days_percent"] = $total["sale_total"] > 0 ? floor($total["total_payroll_days"] / $total["sale_total"] * 100) : 0;
+            $total["total_payroll_month_percent"] = $total["sale_month_total"] > 0 ? floor($total["total_payroll_month"] / $total["sale_month_total"] * 100) : 0;
+            $total["employee_sale_avg"] = $employeeCountTotal > 0 ? floor($total["sale_total"] / $employeeCountTotal) : 0;
+            $total["conversion"] = $total["visitors_quantity"] > 0 ? floor($total["sale_quantity"] / $total["visitors_quantity"] * 100) : 0;;
+            $total["bonus_user_per_sale_percent"] = $total["sale_quantity"] > 0 ? floor($total["bonus_user_count"] / $total["sale_quantity"] * 100) : 0;
+
+            $report = [
+                "date_from" => $dateStartEnd[0],
+                "date_to" => $dateStartEnd[1],
+                "stores" => $stores,
+                "total" => $total,
+            ];
+            $reports []= $report;
+        }
+        return $reports;
+    }
 }
\ No newline at end of file
index ca77e70afd9720d651ad2ee1dd8016ec6df3f942..c3b8bf2b05a4b6dd7cca5549922cfa78e7603582 100644 (file)
@@ -6,6 +6,7 @@ use yii\helpers\Json;
 use yii_app\api3\core\services\ReportService;
 use yii_app\api3\core\traits\ServiceTrait;
 use yii_app\api3\modules\v1\requests\report\ReportInput;
+use yii_app\api3\modules\v1\requests\report\ReportWeeksInput;
 use yii_app\records\ApiLogs;
 
 /**
@@ -16,7 +17,7 @@ class ReportController extends \yii_app\api3\controllers\NoActiveController
     use ServiceTrait;
 
     public function actionShow() {
-        // localhost:8888/v1/report/Show
+        // localhost:8888/v1/report/show
         // {
         //   "stores": [1,2,3],
         //   "date_start": "2024-02-15",
@@ -46,4 +47,40 @@ class ReportController extends \yii_app\api3\controllers\NoActiveController
 
         return $result;
     }
+
+    public function actionShowWeeks() {
+        // localhost:8888/v1/report/show-weeks
+        // {
+        //   "stores": [1,2,3],
+        //   "date" : [
+        //       ["2024-02-08", "2024-02-14"],
+        //       ["2024-02-15", "2024-02-21"],
+        //       ["2024-02-22", "2024-02-28"],
+        //       ["2024-02-29", "2024-03-06"],
+        //   ],
+        //   "shift_type": 1 // 1 - дневная, 2 - ночная, 0 - дневная и ночная смена вместе
+        // }
+        $params = \Yii::$app->request->post();
+
+        $model = new ReportWeeksInput;
+        $data = $this->validate($model, $params);
+
+        $result = $this->reportService->showWeeks($data);
+
+        $apiLogs = new ApiLogs;
+        $apiLogs->url = \Yii::$app->request->url;
+        $apiLogs->request_id = "";
+        $apiLogs->date = date('Y-m-d H:i:s');
+        $apiLogs->content = Json::encode($data);
+        $apiLogs->hash_content = "";
+        $apiLogs->result = Json::encode($result);
+        $apiLogs->status = 0;
+        $apiLogs->store_id = "report_show_weeks";
+        $apiLogs->seller_id = "";
+        $apiLogs->phone = "";
+        $apiLogs->ip = "127.0.0.1";
+        $apiLogs->save();
+
+        return $result;
+    }
 }
\ No newline at end of file
diff --git a/erp24/api3/modules/v1/requests/report/ReportWeeksInput.php b/erp24/api3/modules/v1/requests/report/ReportWeeksInput.php
new file mode 100644 (file)
index 0000000..eba3d9b
--- /dev/null
@@ -0,0 +1,22 @@
+<?php
+
+namespace yii_app\api3\modules\v1\requests\report;
+
+use yii\base\Model;
+
+class ReportWeeksInput extends Model
+{
+    public $stores;
+    public $date;
+    public $shift_type;
+
+    public function rules(): array
+    {
+        return [
+            [['stores', 'date', 'shift_type'], 'required'],
+            ['stores', 'each', 'rule' => ['integer']],
+            //[['date_start', 'date_end'], 'datetime', 'format' => 'yyyy-M-d'],
+            ['shift_type', 'in', 'range' => [0, 1, 2]]
+        ];
+    }
+}
\ No newline at end of file