chenqp vor 1 Jahr
Ursprung
Commit
583bc365a3

+ 13 - 0
app/Http/Controllers/Api/EmployeeController.php

@@ -198,6 +198,19 @@ class EmployeeController extends BaseController
         }
     }
 
+    public function departSetIndex(Request $request)
+    {
+        $service = new EmployeeService();
+        $user = $request->userData->toArray();
+        list($status,$data) = $service->departSetIndex($request->all(),$user);
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
     public function departEdit(Request $request)
     {
         $service = new EmployeeService();

+ 38 - 2
app/Http/Controllers/Api/StatisticsController.php

@@ -7,10 +7,46 @@ use Illuminate\Http\Request;
 
 class StatisticsController extends BaseController
 {
-    public function statisticsXs(Request $request){
+    public function statisticsBt(Request $request){
         $service = new StatisticsService();
         $userData = $request->userData->toArray();
-        list($status,$data) = $service->statisticsXs($request->all(),$userData);
+        list($status,$data) = $service->statisticsBt($request->all(),$userData);
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    public function statisticsArea(Request $request){
+        $service = new StatisticsService();
+        $userData = $request->userData->toArray();
+        list($status,$data) = $service->statisticsArea($request->all(),$userData);
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    public function statisticsAreaDepart(Request $request){
+        $service = new StatisticsService();
+        $userData = $request->userData->toArray();
+        list($status,$data) = $service->statisticsAreaDepart($request->all(),$userData);
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    public function statisticsAreaDepartProduct(Request $request){
+        $service = new StatisticsService();
+        $userData = $request->userData->toArray();
+        list($status,$data) = $service->statisticsAreaDepartProduct($request->all(),$userData);
 
         if($status){
             return $this->json_return(200,'',$data);

+ 19 - 0
app/Model/Depart.php

@@ -16,4 +16,23 @@ class Depart extends Model
     const UPDATED_AT = 'upd_time';
     protected $dateFormat = 'U';
     const IS_UES = 1;//启用
+
+    const area_one = 1;
+    const area_two = 2;
+    const area_three = 3;
+    const area_four = 4;
+    const area_five = 5;
+    const area_six = 6;
+    const area_seven = 7;
+    public static $area = [
+        self::area_one => '华东大区',
+        self::area_two => '华中大区',
+        self::area_three => '华北大区',
+        self::area_four => '华南大区',
+        self::area_five => '东北大区',
+        self::area_six => '西北大区',
+        self::area_seven => '西南大区',
+    ];
+
+
 }

+ 13 - 0
app/Model/DepartIndex.php

@@ -0,0 +1,13 @@
+<?php
+
+namespace App\Model;
+
+use Illuminate\Database\Eloquent\Model;
+
+class DepartIndex extends Model
+{
+    protected $table = "depart_index"; //指定表
+    const CREATED_AT = 'crt_time';
+    const UPDATED_AT = 'upd_time';
+    protected $dateFormat = 'U';
+}

+ 47 - 1
app/Service/EmployeeService.php

@@ -4,6 +4,7 @@ namespace App\Service;
 
 use App\Model\BasicType;
 use App\Model\Depart;
+use App\Model\DepartIndex;
 use App\Model\Employee;
 use App\Model\EmployeeDepartPermission;
 use App\Model\EmployeeFile;
@@ -613,6 +614,34 @@ class EmployeeService extends Service
         return [true, $role];
     }
 
+    public function departSetIndex($data,$user){
+        if(empty($data['data'])) return [false, '指标数据不能为空'];
+
+        $time = time();
+        $insert = [];
+        foreach ($data['data'] as $value){
+            if(empty($value['top_depart_id'])) return [false, '请选择门店'];
+            if(! isset($value['param_one'])) return [false, '请填写销售额'];
+            if(in_array(0.0, floatval($value['param_one']), true)) return [false,'销售额不能为空'];
+            $insert[] = [
+                'top_depart_id' => $value['top_depart_id'],
+                'param_one' => $value['param_one'],
+                'crt_time' => $time,
+            ];
+        }
+
+        if(empty($insert)) return [true, ''];
+
+        //删除指标
+        DepartIndex::where('del_time',0)
+            ->update(['del_time' => $time]);
+
+        //写入指标
+        DepartIndex::insert($insert);
+
+        return [true, ''];
+    }
+
     /**
      * 部门编辑
      * @param $data
@@ -654,6 +683,8 @@ class EmployeeService extends Service
                 $model->basic_type_id = $value['basic_type_id'] ?? 0;
                 $model->rate = $value['rate'] ?? 0;
                 $model->notify_id = $value['notify_id'] ?? 0;
+                $model->area = $value['area'] ?? 0;
+                $model->province = $value['province'] ?? "";
                 $model->save();
                 $depart_id = $model->id;
                 if(empty($depart_id)) {
@@ -769,7 +800,7 @@ class EmployeeService extends Service
      */
     public function departList($data,$user){
         $model = Depart::where('del_time',0)
-            ->select('title','id','code','parent_id','is_main','basic_type_id','rate','notify_id','channel_id')
+            ->select('title','id','code','parent_id','is_main','basic_type_id','rate','notify_id','channel_id','area','province')
             ->orderby('id', 'asc');
 
         if(! empty($data['get_top']) && $data['get_top'] == 1){
@@ -809,11 +840,16 @@ class EmployeeService extends Service
             ->pluck('emp_name','id')
             ->toArray();
 
+        //省
+        $address_map = config('address');
+        $address_map = array_column($address_map,'label','value');
         foreach ($list as $key => $value){
             $list[$key]['basic_type_title'] = $basic[$value['basic_type_id']] ?? '';
             $list[$key]['is_show_basic_type'] = $user['is_all_depart'];
             $list[$key]['notify_name'] = $emp_map[$value['notify_id']] ?? '';
             $list[$key]['channel_name'] = $emp_map[$value['channel_id']] ?? '';
+            $list[$key]['area_name'] = Depart::$area[$value['area']] ?? '';
+            $list[$key]['province_name'] = $address_map[$value['province']] ?? '';
         }
 
         return $list;
@@ -893,7 +929,17 @@ class EmployeeService extends Service
             if($bool) return [false,'总社已存在!'];
         }
 
+        //省
+        $address_map = config('address');
+        $address_map = array_column($address_map,'label','value');
+
         foreach ($data['data'] as $key => $value){
+            if(! empty($value['area'])){
+                $area = array_keys(Depart::$area);
+                if(! in_array($value['area'], $area)) return [false, '门店所属大区不存在'];
+            }
+            if(! empty($value['province']) && ! isset($address_map[$value['province']])) return [false, '门店所属省份不存在'];
+
             if(empty($value['parent_id'])) $data['data'][$key]['parent_id'] = 0;
 
             $data['data'][$key]['upd_time'] = time();

+ 578 - 102
app/Service/StatisticsService.php

@@ -2,8 +2,7 @@
 
 namespace App\Service;
 
-use App\Model\Construction;
-use App\Model\ConstructionProductInfo;
+use App\Model\Depart;
 use App\Model\InOutRecord;
 use App\Model\InvoiceOrder;
 use App\Model\InvoiceOrderInfo;
@@ -19,114 +18,323 @@ use Illuminate\Support\Facades\DB;
 
 class StatisticsService extends Service
 {
-    public function statisticsXs($data,$user){
+    //销售统计饼图 根据合同类型区分(例如线上合同、线下合同)
+    public function statisticsBt($data,$user){
+        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择销售订单时间区间'];
 
+        $model = SalesOrder::Clear($user,$data);
+        $model = $model->where('del_time',0)
+            ->select('model_type',DB::raw("sum(contract_fee) as total"))
+            ->groupBy('model_type');
+
+        if(! empty($data['crt_time'][0]) && ! empty($data['crt_time'][1])) {
+            $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
+            $model->where('crt_time','>=',$return[0]);
+            $model->where('crt_time','<=',$return[1]);
+        }
+
+        $list = $model->get()->toArray();
+        $list = $this->fillStatisticsBt($list);
+
+        return [true, $list];
     }
 
-    public function inoutrecord(){
-        $in_data = InvoiceOrder::where('del_time',0)
-            ->select('id','sales_order_id')
-            ->get()->toArray();
+    public function fillStatisticsBt($data){
+        if(empty($data)) return $data;
 
-        $map = [];
-        $s_p = SalesOrderProductInfo::whereIn('sales_order_id',array_column($in_data,'sales_order_id'))
+        foreach ($data as $key => $value){
+            $data[$key]['model_type_title'] = SalesOrder::$model_type_title[$value['model_type']] ?? "";
+        }
+
+        return $data;
+    }
+
+    //大区 订货统计
+    public function statisticsArea($data,$user){
+        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];
+        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
+
+        //大区
+        $area = Depart::$area;
+        $area_map = [];
+        foreach ($area as $key => $value){
+            $area_map[] = [
+                'key' => $key,
+                'title' => $value,
+                'total' => 0
+            ];
+        }
+        //分社所属大区
+        $depart_map = Depart::where('parent_id',0)
             ->where('del_time',0)
-            ->select('sales_order_id','product_id','final_amount','price')
+            ->pluck('area','id')
+            ->toArray();
+
+        //向总社采购的钱
+        $purchase_map = [];
+        $purchase = PurchaseOrder::where('del_time',0)
+            ->where('order_type',[PurchaseOrder::Order_type_three,PurchaseOrder::Order_type_four])
+            ->where('crt_time','>=',$return[0])
+            ->where('crt_time','<=',$return[1])
+            ->select('top_depart_id','purchase_total')
             ->get()->toArray();
-        foreach ($s_p as $value){
-            $map[$value['sales_order_id']][] = [
-                'product_id' => $value['product_id'],
-                'final_amount' => $value['final_amount'],
-                'price' => $value['price'],
-            ];
+        foreach ($purchase as $value){
+            $area = $depart_map[$value['top_depart_id']] ?? 0;
+            if(! $area) continue;
+            if(isset($purchase_map[$area])){
+                $total = bcadd($purchase_map[$area], $value['purchase_total'],2);
+                $purchase_map[$area] = $total;
+            }else{
+                $purchase_map[$area] = $value['purchase_total'];
+            }
         }
 
-        DB::beginTransaction();
-        try {
-            foreach ($in_data as $value){
-                $tmp = $map[$value['sales_order_id']] ?? [];
-                if(empty($tmp)) continue;
-                foreach ($tmp as $val){
-                    InvoiceOrderInfo::where('del_time',0)
-                        ->where('invoice_id', $value['id'])
-                        ->where('product_id', $val['product_id'])
-                        ->update([
-                            'final_amount' => $val['final_amount'],
-                            'price' => $val['price'],
-                        ]);
-                }
+        //退货的差异
+        $returnExchange_map = [];
+        $returnExchange = ReturnExchangeOrder::where('del_time',0)
+            ->where('type',ReturnExchangeOrder::Order_type2)
+            ->where('crt_time','>=',$return[0])
+            ->where('crt_time','<=',$return[1])
+            ->where('crt_time','<=',$return[1])
+            ->select('top_depart_id','difference_amount')
+            ->get()->toArray();
+        foreach ($returnExchange as $value){
+            $area = $depart_map[$value['top_depart_id']] ?? 0;
+            if(! $area) continue;
+            if(isset($returnExchange_map[$area])){
+                $total = bcadd($returnExchange_map[$area], $value['difference_amount'],2);
+                $returnExchange_map[$area] = $total;
+            }else{
+                $returnExchange_map[$area] = $value['difference_amount'];
+            }
+        }
 
+        foreach ($area_map as $key => $value){
+            $purchase_tmp = $purchase_map[$value['key']] ?? 0;
+            $return_tmp = $returnExchange_map[$value['key']] ?? 0;
+            $area_map[$key]['total'] = bcsub($purchase_tmp, $return_tmp,2);
+        }
+
+        return [true, $area_map];
+    }
+
+    // 大区下的门店  订货统计
+    public function statisticsAreaDepart($data,$user){
+        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];
+        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
+        if(empty($data['area']) || ! isset(Depart::$area[$data['area']])) return [false, '该大区不存在'];
+
+        $depart = Depart::where('parent_id',0)
+            ->where('del_time',0)
+            ->where('area',$data['area'])
+            ->select('id','title')
+            ->get()
+            ->toArray();
+        if(empty($depart)) return [false, '该大区下不存在门店'];
+
+        //向总社采购的钱
+        $purchase_map = [];
+        $purchase = PurchaseOrder::where('del_time',0)
+            ->whereIn('top_depart_id',array_column($depart,'id'))
+            ->where('order_type',[PurchaseOrder::Order_type_three,PurchaseOrder::Order_type_four])
+            ->where('crt_time','>=',$return[0])
+            ->where('crt_time','<=',$return[1])
+            ->select('top_depart_id','purchase_total')
+            ->get()->toArray();
+        foreach ($purchase as $value){
+            if(isset($purchase_map[$value['top_depart_id']])){
+                $total = bcadd($purchase_map[$value['top_depart_id']], $value['purchase_total'],2);
+                $purchase_map[$value['top_depart_id']] = $total;
+            }else{
+                $purchase_map[$value['top_depart_id']] = $value['purchase_total'];
             }
-        }catch (\Throwable $exception){
-            DB::rollBack();
-            dd($exception->getMessage());
         }
 
-        DB::commit();
-        dd(1);
+        //退货的差异
+        $returnExchange_map = [];
+        $returnExchange = ReturnExchangeOrder::where('del_time',0)
+            ->whereIn('top_depart_id',array_column($depart,'id'))
+            ->where('type',ReturnExchangeOrder::Order_type2)
+            ->where('crt_time','>=',$return[0])
+            ->where('crt_time','<=',$return[1])
+            ->where('crt_time','<=',$return[1])
+            ->select('top_depart_id','difference_amount')
+            ->get()->toArray();
+        foreach ($returnExchange as $value){
+            if(isset($returnExchange_map[$value['top_depart_id']])){
+                $total = bcadd($returnExchange_map[$value['top_depart_id']], $value['difference_amount'],2);
+                $returnExchange_map[$value['top_depart_id']] = $total;
+            }else{
+                $returnExchange_map[$value['top_depart_id']] = $value['difference_amount'];
+            }
+        }
 
+        foreach ($depart as $key => $value){
+            $purchase_tmp = $purchase_map[$value['id']] ?? 0;
+            $return_tmp = $returnExchange_map[$value['id']] ?? 0;
+            $depart[$key]['total'] = bcsub($purchase_tmp, $return_tmp,2);
+        }
+
+        return [true, $depart];
     }
 
-    public function inoutrecord2(){
-        DB::beginTransaction();
-        try {
-            DB::table('in_out_record')
-                ->where('price',0)
-                ->whereIn('order_type', array_values(ReturnExchangeOrder::$prefix))
-                ->select('id','order_number','product_id')
-                ->orderBy('id','asc')
-                ->chunk(200,function ($data) {;
-                    $data = Collect($data)->map(function ($object) {
-                        return (array)$object;
-                    })->toArray();
+    // 大区下的门店 某个门店 关于产品以及分类的统计  订货统计
+    public function statisticsAreaDepartProduct($data,$user){
+        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];
+        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
+        if(empty($data['top_depart_id'])) return [false, '请选择门店'];
 
-                    $map = ReturnExchangeOrder::where('del_time',0)
-                        ->whereIn('order_number',array_column($data,'order_number'))
-                        ->pluck('id','order_number')
-                        ->toArray();
-                    $result = ReturnExchangeOrderProductInfo::where('del_time',0)
-                        ->whereIn('return_exchange_id',array_values($map))
-                        ->select('return_exchange_id','return_exchange_price','product_id')
-                        ->get()->toArray();
-                    $result_map = [];
-                    foreach ($result as $v){
-                        $result_map[$v['return_exchange_id']][$v['product_id']] = [
-                            'product_id' => $v['product_id'],
-                            'price' => $v['return_exchange_price'],
-                        ];
-                    }
+        //时间 =》 钱
+        $purchase_map1 = $this->getTime($return);
+        //产品 =》 数量
+        $purchase_category_map = $purchase_map = [];
+        $purchase = PurchaseOrder::where('del_time',0)
+            ->where('top_depart_id',$data['top_depart_id'])
+            ->where('order_type',[PurchaseOrder::Order_type_three,PurchaseOrder::Order_type_four])
+            ->where('crt_time','>=',$return[0])
+            ->where('crt_time','<=',$return[1])
+            ->select('id','crt_time')
+            ->get()->toArray();
+        $purchase_for_time = array_column($purchase,'crt_time','id');
+        $purchase_product = PurchaseOrderInfo::where("del_time",0)
+            ->whereIn('purchase_order_id',array_column($purchase,'id'))
+            ->select('purchase_order_id','product_id','number','price','final_amount','sports_bag_id')
+            ->get()->toArray();
 
-                    foreach ($data as $value){
-                        $tmp_id = $map[$value['order_number']] ?? 0;
-                        if($tmp_id < 0) continue;
-                        $tmp = $result_map[$tmp_id][$value['product_id']] ?? [];
-                        if(empty($tmp)) continue;
+        //退换货
+        $returnExchange_map = $this->returnExchange($data,$return);
+        //产品
+        $product_list = Product::whereIn('id',array_unique(array_merge_recursive(array_column($purchase_product,'product_id'),array_keys($returnExchange_map,'product_id'))))
+            ->select('id','product_category','title')
+            ->get()->toArray();
+        $product_list_map = array_column($product_list,null,'id');
 
-                        InOutRecord::where('id',$value['id'])->update([
-                            'price' => $tmp['price']
-                        ]);
-                    }
-            });
+        $category_return = ProductCategory::where('del_time',0)
+            ->where('parent_id',0)
+            ->pluck('title','id')
+            ->toArray();
+        foreach ($purchase_product as $value){
+            if($value['sports_bag_id'] > 0){
+                $money = $value['final_amount'];
+            }elseif($value['final_amount'] > 0){
+                $money = $value['final_amount'];
+            }else{
+                $money = bcmul($value['price'],$value['number'],2);
+            }
+            $crt_time = $purchase_for_time[$value['purchase_order_id']];
+            $crt_time = date("Y-m-d",$crt_time);
 
-            DB::commit();
-        }catch (\Throwable $exception){
-            DB::rollBack();
-            dd($exception->getMessage());
+            //产品信息
+            $product_tmp = $product_list_map[$value['product_id']] ?? [];
+
+            //钱
+            if(isset($purchase_map1[$crt_time])){
+                $purchase_map1[$crt_time]['total'] = bcadd($purchase_map1[$crt_time]['total'],$money,2);
+            }
+
+            //-------根据产品
+            //数量
+            if(isset($purchase_map[$value['product_id']])){
+                $tmp_number = bcadd($purchase_map[$value['product_id']]['number'], $value['number'],2);
+                $purchase_map[$value['product_id']]['number'] = $tmp_number;
+            }else{
+                $purchase_map[$value['product_id']] = [
+                    'title' => $product_tmp['title'],
+                    'number' => $value['number']
+                ];
+            }
+            //-------根据产品
+
+            //-------根据产品大类
+            //数量
+            $category_tmp = json_decode($product_tmp['product_category']);
+            $category_tmp = $category_tmp[0];
+
+            if(isset($purchase_category_map[$category_tmp])){
+                $tmp_number = bcadd($purchase_map[$value['product_id']]['number'], $value['number'],2);
+                $purchase_category_map[$category_tmp]['number'] = $tmp_number;
+            }else{
+                $purchase_category_map[$category_tmp] = [
+                    'number' => $value['number'],
+                    'title' => $category_return[$category_tmp] ?? ""
+                ];
+            }
         }
-        dd(1);
+
+        return [true, ['money' => array_values($purchase_map1), 'product_num' => array_values($purchase_map), 'category_num' => array_values($purchase_category_map)]];
+    }
+
+    public function getTime($data){
+        $startTimestamp = $data[0]; // 起始时间戳
+        $endTimestamp = $data[1];   // 结束时间戳
+
+        // 创建 DateTime 对象
+        $startDate = new \DateTime();
+        $endDate = new \DateTime();
+
+        $startDate->setTimestamp($startTimestamp);
+        $endDate->setTimestamp($endTimestamp);
+
+        // 创建 DatePeriod 对象
+        $interval = new \DateInterval('P1D'); // 每天的间隔
+        $dateRange = new \DatePeriod($startDate, $interval, $endDate);
+
+        // 遍历日期范围并输出每个日期
+        $return = [];
+        foreach ($dateRange as $date) {
+            $day = $date->format('Y-m-d');
+            $return[$day] = [
+                'day' => $day,
+                'total' => 0
+            ];
+        }
+        return $return;
+    }
+
+    public function returnExchange($data,$return){ return [];
+        $returnExchange_map = [];
+        $returnExchange = ReturnExchangeOrder::where('del_time',0)
+            ->where('top_depart_id',$data['top_depart_id'])
+            ->where('type',ReturnExchangeOrder::Order_type2)
+            ->where('crt_time','>=',$return[0])
+            ->where('crt_time','<=',$return[1])
+            ->select('id')
+            ->get()->toArray();
+        $returnExchange_product = ReturnExchangeOrderProductInfo::where("del_time",0)
+            ->whereIn('return_exchange_id',array_column($returnExchange,'id'))
+            ->select('product_id','number','return_exchange_price as price')
+            ->get()->toArray();
+        foreach ($returnExchange_product as $value){
+            $money = bcmul($value['price'],$value['number'],2);
+
+            if(isset($returnExchange_map[$value['product_id']])){
+                $tmp_money = bcadd($returnExchange_map[$value['product_id']]['total'], $money,2);
+                $tmp_number = bcadd($returnExchange_map[$value['product_id']]['number'], $value['number'],2);
+                $returnExchange_map[$value['product_id']] = [
+                    'number' => $tmp_number,
+                    'total' => $tmp_money
+                ];
+            }else{
+                $returnExchange_map[$value['product_id']] = [
+                    'number' => $value['number'],
+                    'total' => $money
+                ];
+            }
+        }
+
+        return $returnExchange_map;
     }
 
     public function statisticsJc($data,$user){
         if(empty($data['top_depart_id'])) return [false, '请选择门店'];
-        $model = Product::ProductClear($user,$data);
+        $model = Product::ProductClear2($user,$data);
         $model = $model->where('del_time',0)
             ->select('title','id','code','depart_id','top_depart_id','product_attribute')
             ->orderby('product_attribute', 'desc')
             ->orderby('id', 'desc');
 
+        if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
         if(! empty($data['title'])) $model->where('title', 'LIKE', '%'.$data['title'].'%');
-        if(isset($data['state'])) $model->where('state', $data['state']);
-        if(isset($data['is_use'])) $model->where('is_use', $data['is_use']);
         if(isset($data['product_attribute'])) $model->where('product_attribute', $data['product_attribute']);
         if(! empty($data['product_category_id'])) $model->where('product_category_id', $data['product_category_id']);
         if(! empty($data['product_category'])) {
@@ -136,7 +344,6 @@ class StatisticsService extends Service
                 ->get()->toArray();
             $model->whereIn('product_category_id',array_unique(array_column($product_category,'id')));
         }
-        if(! empty($data['code'])) $model->where('code', 'LIKE', '%'.$data['code'].'%');
 
         $list = $this->limit($model,'',$data);
         $list = $this->fillData($list,$user,$data);
@@ -148,23 +355,63 @@ class StatisticsService extends Service
         if(empty($data['data'])) return $data;
 
         //产品
-        $product = array_column($data,'id');
+        $product = array_column($data['data'],'id');
         //本月入库 本月出库
         list($in, $out) = $this->getThisMonthData($product,$user,$search);
-        //上月结存
-        $lastJc = $this->getLastMonthBalance($product,$user,$search);
+        //上月结存 汇总这个月之前的出入
+        list($last_in,$last_out) = $this->getLastMonthBalance($product,$user,$search);
 
         foreach ($data['data'] as $key => $value){
-            $data['data'][$key]['in_number'] = $in[$value['id']] ?? 0;
-            $data['data'][$key]['out_number'] = $out[$value['id']] ?? 0;
-            $data['data'][$key]['last_jc_number'] = $lastJc[$value['id']] ?? 0;
-            $data['data'][$key]['last_jc_number'] = $lastJc[$value['id']] ?? 0;
+            $last_in_tmp = $last_in[$value['id']] ?? [];
+            $last_in_money = $last_in_tmp['total'] ?? 0;//本月之前入的金额
+            $last_in_number = $last_in_tmp['number'] ?? 0;//本月之前入的数量
+            $last_out_tmp = $last_out[$value['id']] ?? [];
+            $last_out_money = $last_out_tmp['total'] ?? 0;//本月之前出的金额
+            $last_out_number = $last_out_tmp['number'] ?? 0;//本月之前出的数量
+
+            //上月结存
+            $last_jc_money = bcsub($last_in_money,$last_out_money,2);//结存金额
+            $last_jc_number = bcsub($last_in_number,$last_out_number,2);//结存数量
+            $last_jc_price = floatval($last_jc_number) ? bcdiv($last_jc_money,$last_jc_number,2) : 0;//结存单价
+            $data['data'][$key]['last_jc_money'] = $last_jc_money;
+            $data['data'][$key]['last_jc_number'] = $last_jc_number;
+            $data['data'][$key]['last_jc_price'] = $last_jc_price;
+
+            //本月入库
+            $this_in_tmp = $in[$value['id']] ?? [];
+            $this_in_money = $this_in_tmp['total'] ?? 0;//本月入的金额
+            $this_in_number = $this_in_tmp['number'] ?? 0;//本月入的数量
+            $this_in_price = floatval($this_in_number) ? bcdiv($this_in_money,$this_in_number,2) : 0;//本月入单价
+            $data['data'][$key]['this_in_money'] = $this_in_money;
+            $data['data'][$key]['this_in_number'] = $this_in_number;
+            $data['data'][$key]['this_in_price'] = $this_in_price;
+
+            //本月出库
+            $this_out_tmp = $out[$value['id']] ?? [];
+            $this_out_money = $this_out_tmp['total'] ?? 0;//本月出的金额
+            $this_out_number = $this_out_tmp['number'] ?? 0;//本月出的数量
+            //单价= (上月结存金额+本月入库金额) /上月结存数量+本月入库数量
+            $amount = bcadd($last_jc_money, $this_in_money,2);
+            $number = bcadd($last_jc_number, $this_in_number,2);
+            $this_out_price = floatval($number) ? bcdiv($amount,$number,2) : 0;//本月出单价
+            $data['data'][$key]['this_out_money'] = $this_out_money;
+            $data['data'][$key]['this_out_number'] = $this_out_number;
+            $data['data'][$key]['this_out_price'] = $this_out_price;
+
+            //本月结存
+            //本月结存 数量/金额=本月入库+上月结存-本月出库
+            $this_jc_money = bcsub(bcadd($this_in_money,$last_jc_money,2),$this_out_money);
+            $this_jc_number = bcsub(bcadd($this_in_number,$last_jc_number,2),$this_out_number);
+            $this_jc_price = floatval($this_jc_number) ? bcdiv($this_jc_money,$this_jc_number,2) : 0;//本月结存单价
+            $data['data'][$key]['this_jc_money'] = $this_jc_money;
+            $data['data'][$key]['this_jc_number'] = $this_jc_number;
+            $data['data'][$key]['this_jc_price'] = $this_jc_price;
         }
 
         return $data;
     }
 
-    //本月入库 出库
+    //本月入库 出库(库存流水)
     public function getThisMonthData($product = [], $user = [], $search = []){
         $in = $out = [];
         $startStamp = strtotime(date("Y-m-01 00:00:00"));
@@ -176,21 +423,36 @@ class StatisticsService extends Service
             ->where('crt_time','>=',$startStamp)
             ->where('crt_time','<=',$endStamp)
             ->whereIn('product_id',$product)
-            ->select('product_id','number')
+            ->select('product_id','number','price')
             ->get()->toArray();
 
         foreach ($list as $value){
             if($value['number'] >= 0){
+                $tmp_total = bcmul($value['number'], $value['price'], 2);
                 if(isset($in[$value['product_id']])){
-                    $in[$value['product_id']] += $value['number'];
+                    $number = bcadd($in[$value['product_id']]['number'], $value['number'],0);
+                    $total = bcadd($in[$value['product_id']]['total'], $tmp_total,2);
+                    $in[$value['product_id']]['number'] = $number;
+                    $in[$value['product_id']]['total'] = $total;
                 }else{
-                    $in[$value['product_id']] = $value['number'];
+                    $in[$value['product_id']] = [
+                        'number' => $value['number'],
+                        'total' => $tmp_total,
+                    ];
                 }
             }else{
+                $number = abs($value['number']);
+                $tmp_total = bcmul($number, $value['price'], 2);
                 if(isset($out[$value['product_id']])){
-                    $out[$value['product_id']] += abs($value['number']);
+                    $number = bcadd($out[$value['product_id']]['number'], $number,0);
+                    $total = bcadd($out[$value['product_id']]['total'], $tmp_total,2);
+                    $out[$value['product_id']]['number'] = $number;
+                    $out[$value['product_id']]['total'] = $total;
                 }else{
-                    $out[$value['product_id']] = abs($value['number']);
+                    $out[$value['product_id']] = [
+                        'number' => $number,
+                        'total' => $tmp_total,
+                    ];
                 }
             }
         }
@@ -198,7 +460,7 @@ class StatisticsService extends Service
         return [$in, $out];
     }
 
-    //上月结存
+    //上月结存(汇总这个月之前的出入)(库存流水)
     public function getLastMonthBalance($product = [], $user = [], $search = []){
         $return = [];
         $startStamp = strtotime(date("Y-m-01 00:00:00"));
@@ -206,21 +468,44 @@ class StatisticsService extends Service
         $list = $model->where('del_time',0)
             ->where('crt_time','<',$startStamp)
             ->whereIn('product_id',$product)
-            ->select('product_id','number')
+            ->select('product_id','number','price')
             ->get()->toArray();
 
         foreach ($list as $value){
-            if(isset($return[$value['product_id']])){
-                $return[$value['product_id']] += $value['number'];
+            if($value['number'] >= 0){
+                $tmp_total = bcmul($value['number'], $value['price'], 2);
+                if(isset($in[$value['product_id']])){
+                    $number = bcadd($in[$value['product_id']]['number'], $value['number'],0);
+                    $total = bcadd($in[$value['product_id']]['total'], $tmp_total,2);
+                    $in[$value['product_id']]['number'] = $number;
+                    $in[$value['product_id']]['total'] = $total;
+                }else{
+                    $in[$value['product_id']] = [
+                        'number' => $value['number'],
+                        'total' => $tmp_total,
+                    ];
+                }
             }else{
-                $return[$value['product_id']] = $value['number'];
+                $number = abs($value['number']);
+                $tmp_total = bcmul($number, $value['price'], 2);
+                if(isset($out[$value['product_id']])){
+                    $number = bcadd($out[$value['product_id']]['number'], $number,0);
+                    $total = bcadd($out[$value['product_id']]['total'], $tmp_total,2);
+                    $out[$value['product_id']]['number'] = $number;
+                    $out[$value['product_id']]['total'] = $total;
+                }else{
+                    $out[$value['product_id']] = [
+                        'number' => $number,
+                        'total' => $tmp_total,
+                    ];
+                }
             }
         }
 
-        return $return;
+        return [$in, $out];
     }
 
-    //本月入库
+    //本月入库(单据)暂时没用
     public function getThisMonthIn1($product = [], $user = [], $search = []){
         $return = [];
         $startStamp = strtotime(date("Y-m-01 00:00:00"));
@@ -307,7 +592,198 @@ class StatisticsService extends Service
         return $purchase_product_array;
     }
 
-    public function getThisMonthOut($product = [], $user = [], $search = []){
 
+    //--------------------------脚本
+    public function inoutrecord(){return;
+        $in_data = InvoiceOrder::where('del_time',0)
+            ->select('id','sales_order_id')
+            ->get()->toArray();
+
+        $map = [];
+        $s_p = SalesOrderProductInfo::whereIn('sales_order_id',array_column($in_data,'sales_order_id'))
+            ->where('del_time',0)
+            ->select('sales_order_id','product_id','final_amount','price')
+            ->get()->toArray();
+        foreach ($s_p as $value){
+            $map[$value['sales_order_id']][] = [
+                'product_id' => $value['product_id'],
+                'final_amount' => $value['final_amount'],
+                'price' => $value['price'],
+            ];
+        }
+
+        DB::beginTransaction();
+        try {
+            foreach ($in_data as $value){
+                $tmp = $map[$value['sales_order_id']] ?? [];
+                if(empty($tmp)) continue;
+                foreach ($tmp as $val){
+                    InvoiceOrderInfo::where('del_time',0)
+                        ->where('invoice_id', $value['id'])
+                        ->where('product_id', $val['product_id'])
+                        ->update([
+                            'final_amount' => $val['final_amount'],
+                            'price' => $val['price'],
+                        ]);
+                }
+
+            }
+        }catch (\Throwable $exception){
+            DB::rollBack();
+            dd($exception->getMessage());
+        }
+
+        DB::commit();
+        dd(1);
+
+    }
+
+    public function inoutrecord2(){return;
+        DB::beginTransaction();
+        try {
+            DB::table('in_out_record')
+                ->where('price',0)
+                ->whereIn('order_type', array_values(ReturnExchangeOrder::$prefix))
+                ->select('id','order_number','product_id')
+                ->orderBy('id','asc')
+                ->chunk(200,function ($data) {;
+                    $data = Collect($data)->map(function ($object) {
+                        return (array)$object;
+                    })->toArray();
+
+                    $map = ReturnExchangeOrder::where('del_time',0)
+                        ->whereIn('order_number',array_column($data,'order_number'))
+                        ->pluck('id','order_number')
+                        ->toArray();
+                    $result = ReturnExchangeOrderProductInfo::where('del_time',0)
+                        ->whereIn('return_exchange_id',array_values($map))
+                        ->select('return_exchange_id','return_exchange_price','product_id')
+                        ->get()->toArray();
+                    $result_map = [];
+                    foreach ($result as $v){
+                        $result_map[$v['return_exchange_id']][$v['product_id']] = [
+                            'product_id' => $v['product_id'],
+                            'price' => $v['return_exchange_price'],
+                        ];
+                    }
+
+                    foreach ($data as $value){
+                        $tmp_id = $map[$value['order_number']] ?? 0;
+                        if($tmp_id < 0) continue;
+                        $tmp = $result_map[$tmp_id][$value['product_id']] ?? [];
+                        if(empty($tmp)) continue;
+
+                        InOutRecord::where('id',$value['id'])->update([
+                            'price' => $tmp['price']
+                        ]);
+                    }
+                });
+
+            DB::commit();
+        }catch (\Throwable $exception){
+            DB::rollBack();
+            dd($exception->getMessage());
+        }
+        dd(1);
+    }
+
+    public function statisticsAreaDepartProduct222($data,$user){
+        if(empty($data['crt_time'][0]) || empty($data['crt_time'][1])) return [false, '请选择时间区间'];
+        $return = $this->changeDateToTimeStampAboutRange($data['crt_time']);
+        if(empty($data['top_depart_id'])) return [false, '请选择门店'];
+
+        //向总社采购的钱
+        $purchase_map = [];
+        $purchase = PurchaseOrder::where('del_time',0)
+            ->where('top_depart_id',$data['top_depart_id'])
+            ->where('order_type',[PurchaseOrder::Order_type_three,PurchaseOrder::Order_type_four])
+            ->where('crt_time','>=',$return[0])
+            ->where('crt_time','<=',$return[1])
+            ->select('id')
+            ->get()->toArray();
+        $purchase_product = PurchaseOrderInfo::where("del_time",0)
+            ->whereIn('purchase_order_id',array_column($purchase,'id'))
+            ->select('product_id','number','price','final_amount','sports_bag_id')
+            ->get()->toArray();
+        foreach ($purchase_product as $value){
+            if($value['sports_bag_id'] > 0){
+                $money = $value['final_amount'];
+            }elseif($value['final_amount'] > 0){
+                $money = $value['final_amount'];
+            }else{
+                $money = bcmul($value['price'],$value['number'],2);
+            }
+
+            if(isset($purchase_map[$value['product_id']])){
+                $tmp_money = bcadd($purchase_map[$value['product_id']]['total'], $money,2);
+                $tmp_number = bcadd($purchase_map[$value['product_id']]['number'], $value['number'],2);
+                $purchase_map[$value['product_id']] = [
+                    'number' => $tmp_number,
+                    'total' => $tmp_money
+                ];
+            }else{
+                $purchase_map[$value['product_id']] = [
+                    'number' => $value['number'],
+                    'total' => $money
+                ];
+            }
+        }
+
+        //退货的差异
+        $returnExchange_map = $this->returnExchange($data,$return);
+
+        //产品
+        $product_list = Product::whereIn('id',array_unique(array_merge_recursive(array_column($purchase_product,'product_id'),array_keys($returnExchange_map,'product_id'))))
+            ->select('id','product_category','title')
+            ->get()->toArray();
+        $product_list_map = array_column($product_list,null,'id');
+
+        $category = $category_sum = [];
+        foreach ($purchase_map as $key => $value){
+//            if(isset($returnExchange_map[$key])){
+//                $tmp = $returnExchange_map[$key];
+//                $number = bcsub($value['number'], $tmp['number'],2);
+//                $total = bcsub($value['total'], $tmp['total'],2);
+//                $purchase_map[$key] = [
+//                    'number' => $number,
+//                    'total' => $total,
+//                ];
+//            }
+            $product_tmp = $product_list_map[$key] ?? [];
+            $purchase_map[$key]['title'] = $product_tmp['title'];
+            $category_tmp = json_decode($product_tmp['product_category']);
+            $category_tmp = $category_tmp[0];
+            if(! in_array($category_tmp,$category)) $category[] = $category_tmp;
+
+            if(isset($category_sum[$category_tmp])){
+                $tmp_number = bcadd($category_sum[$category_tmp]['number'], $purchase_map[$key]['number'],2);
+                $tmp_total = bcadd($category_sum[$category_tmp]['total'], $purchase_map[$key]['total'],2);
+                $category_sum[$category_tmp] = [
+                    'number' => $tmp_number,
+                    'total' => $tmp_total,
+                ];
+            }else{
+                $category_sum[$category_tmp] = [
+                    'number' =>  $purchase_map[$key]['number'],
+                    'total' => $purchase_map[$key]['total'],
+                ];
+            }
+        }
+
+        //根据产品大类 $category_sum
+        $category_return = ProductCategory::whereIn('id',$category)
+            ->select('id','title')
+            ->get()->toArray();
+        foreach ($category_return as $key => $value){
+            $tmp = $category_sum[$value['id']] ?? [];
+            $category_return[$key]['number'] = $tmp['number'];
+            $category_return[$key]['total'] = $tmp['total'];
+        }
+
+        //根据产品 $purchase_map
+        dd($purchase_map);
+
+
+        return [true, ''];
     }
 }

+ 5 - 1
routes/api.php

@@ -75,6 +75,7 @@ Route::group(['middleware'=> ['checkLogin']],function ($route){
     $route->any('departEdit', 'Api\EmployeeController@departEdit');
     $route->any('departDel', 'Api\EmployeeController@departDel');
     $route->any('departList', 'Api\EmployeeController@departList');
+    $route->any('departSetIndex', 'Api\EmployeeController@departSetIndex');
 
     $route->any('roleAdd', 'Api\EmployeeController@roleAdd');
     $route->any('roleEdit', 'Api\EmployeeController@roleEdit');
@@ -276,8 +277,11 @@ Route::group(['middleware'=> ['checkLogin']],function ($route){
     $route->any('getMySetting', 'Api\ProductInventoryController@getMySetting');
 
     //统计
-    $route->any('statisticsXs', 'Api\StatisticsController@statisticsXs');
+    $route->any('statisticsBt', 'Api\StatisticsController@statisticsBt');
     $route->any('statisticsJc', 'Api\StatisticsController@statisticsJc');
+    $route->any('statisticsArea', 'Api\StatisticsController@statisticsArea');
+    $route->any('statisticsAreaDepart', 'Api\StatisticsController@statisticsAreaDepart');
+    $route->any('statisticsAreaDepartProduct', 'Api\StatisticsController@statisticsAreaDepartProduct');
 
     //设置开关
     $route->any('productInventorySet', 'Api\ProductInventoryController@productInventorySet');