Jelajahi Sumber

Merge remote-tracking branch 'origin/fyy' into fyy

root 2 tahun lalu
induk
melakukan
b045a90c4c

+ 16 - 0
app/Http/Controllers/Api/CloudDataController.php

@@ -0,0 +1,16 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Jobs\CloudDataJob;
+use App\Jobs\ProcessDataJob;
+use App\Service\CloudDataService;
+use Illuminate\Http\Request;
+
+//有人云
+class CloudDataController extends BaseController
+{
+    public function getCloudData(Request $request){
+        CloudDataJob::dispatch([])->onQueue('cloud_has_man');
+    }
+}

+ 4 - 6
app/Http/Controllers/Api/FyyOrderController.php

@@ -17,7 +17,6 @@ class FyyOrderController extends BaseController
         $array = [
             'sqlserver_host' => $data['host'] ?? '',
             'sqlserver_port' => $data['port'] ?? 0,
-            'sqlserver_database' => $data['database'] ?? '',
             'sqlserver_zt' => $data['zt'] ?? '',
             'sqlserver_account' => $data['account'] ?? '',
             'sqlserver_password' => $data['password'] ?? '',
@@ -80,7 +79,6 @@ class FyyOrderController extends BaseController
         }
     }
 
-
     public function orderList(Request $request)
     {
         $service = new FyyOrderService();
@@ -94,7 +92,6 @@ class FyyOrderController extends BaseController
         }
     }
 
-
     public function orderDetail(Request $request)
     {
         $service = new FyyOrderService();
@@ -110,8 +107,8 @@ class FyyOrderController extends BaseController
 
     public function fyyRefreshOnHandQuantity(Request $request){
         $service = new FyyOrderService();
-        $user = $request->get('auth');
-        list($status,$data) = $service->fyyRefreshOnHandQuantity($request->all());
+        $userData = $request->userData->toArray();
+        list($status,$data) = $service->fyyRefreshOnHandQuantity($request->all(),$userData);
 
         if($status){
             return $this->json_return(200,'',$data);
@@ -134,7 +131,8 @@ class FyyOrderController extends BaseController
 
     public function getShipmentOrder(Request $request){
         $service = new FyyOrderService();
-        list($status,$data) = $service->getShipmentOrder($request->all());
+        $userData = $request->userData->toArray();
+        list($status,$data) = $service->getShipmentOrder($request->all(),$userData);
 
         if($status){
             return $this->json_return(200,'',$data);

+ 16 - 2
app/Http/Controllers/Api/LoginController.php

@@ -5,6 +5,7 @@ use App\Service\EmployeeService;
 use App\Service\TokenService;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Redis;
 
 //登录
 class LoginController extends BaseController
@@ -25,8 +26,8 @@ class LoginController extends BaseController
         list($bool, $return) = $result;
         if(! $bool) return $this->json_return(201,'',$return);
 
-        //日志
-        $res = Log::channel('login')->info("登录成功", $return);
+        //账套信息
+        $this->setSqlServer($request->all(), $return['id']);
 
         //生成token
         $jwtToken = TokenService::getToken($return['id']);
@@ -43,10 +44,23 @@ class LoginController extends BaseController
         list($bool, $return) = $result;
         if(! $bool) return $this->json_return(201,'',$return);
 
+        //账套信息
+        $this->setSqlServer($request->all(), $return['id']);
+
         //生成token
         $jwtToken = TokenService::getToken($return['id']);
         $jwtToken = self::MOBILE . $jwtToken;
 
         return $this->json_return(200,'', ['token' => $jwtToken]);
     }
+
+    //设置账套缓存
+    private function setSqlServer($data,$user_id){
+        $array = [
+            'sqlserver_zt' => $data['sqlserver_zt'] ?? '',
+        ];
+        $key = 'fyy_sql_server' . $user_id;
+        Redis::set($key,json_encode($array));
+        Redis::expire($key, 86400);
+    }
 }

+ 93 - 0
app/Http/Controllers/Api/ReportFormsController.php

@@ -0,0 +1,93 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Service\ReportFormsService;
+use Illuminate\Http\Request;
+
+class ReportFormsController extends BaseController
+{
+    //生产进度
+    public function productionReport(Request $request){
+        $service = new ReportFormsService();
+        list($status,$data) = $service->productionReport($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    //班组
+    public function teamReport(Request $request){
+        $service = new ReportFormsService();
+        list($status,$data) = $service->teamReport($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    //班组 详情
+    public function teamReportDetail(Request $request){
+        $service = new ReportFormsService();
+        list($status,$data) = $service->teamReportDetail($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    //不良品
+    public function badGoodsReport(Request $request){
+        $service = new ReportFormsService();
+        list($status,$data) = $service->badGoodsReport($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    //不良品 详情
+    public function badGoodsReportDetail(Request $request){
+        $service = new ReportFormsService();
+        list($status,$data) = $service->badGoodsReportDetail($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    //不良品原因
+    public function badGoodsReasonReport(Request $request){
+        $service = new ReportFormsService();
+        list($status,$data) = $service->badGoodsReasonReport($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+
+    //不良品原因详情
+    public function badGoodsReasonReportDetail(Request $request){
+        $service = new ReportFormsService();
+        list($status,$data) = $service->badGoodsReasonReportDetail($request->all());
+
+        if($status){
+            return $this->json_return(200,'',$data);
+        }else{
+            return $this->json_return(201,$data);
+        }
+    }
+}

+ 328 - 0
app/Http/Controllers/Api/ScreenController.php

@@ -0,0 +1,328 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Model\Box;
+use App\Model\BoxDetail;
+use App\Model\DispatchSub;
+use App\Model\OrdersProductProcess;
+use App\Model\Process;
+use App\Model\SaleOrdersProduct;
+use Carbon\Carbon;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
+
+class ScreenController extends BaseController
+{
+    //产值数据全览
+    public function output_value(Request $request){
+        $currentYear = Carbon::now()->year;
+        $lastYear = $currentYear - 1;
+        $currentMonth = Carbon::now()->month;
+
+        $totalValueAllTime = SaleOrdersProduct::where('del_time',0)->sum('finished_num');
+        $totalValueLastYear = SaleOrdersProduct::where('del_time',0)->whereRaw("YEAR(FROM_UNIXTIME(crt_time)) = $lastYear")->sum('finished_num');
+        $totalValueCurrentYearMonth = SaleOrdersProduct::where('del_time',0)->whereRaw("YEAR(FROM_UNIXTIME(crt_time)) = $currentYear AND MONTH(FROM_UNIXTIME(crt_time)) = $currentMonth")->sum('finished_num');
+
+        return $this->json_return(200,'',['total_time'=>$totalValueAllTime, 'total_last_year'=>$totalValueLastYear, 'total_current_month'=>$totalValueCurrentYearMonth]);
+    }
+
+    //项目进度
+    public function order_process1(Request $request) {
+        $result = SaleOrdersProduct::where('del_time',0)
+            ->select(DB::raw('sum(order_quantity) as total'), DB::raw('sum(finished_num) as finished_num'),'out_order_no as Code','customer_name as CustomerName')
+            ->groupBy('out_order_no')
+            ->get()->toArray();
+        if(! empty($result)){
+            foreach ($result as $key => $value){
+                $result[$key]['rate'] = intval($value['finished_num'] / $value['total']);
+                unset($result[$key]['total']);
+                unset($result[$key]['finished_num']);
+            }
+        }
+
+        return $this->json_return(200,'',$result);
+    }
+
+    //历史项目 在手项目
+    public function project_region(Request $request){
+        $all = SaleOrdersProduct::where('del_time',0)
+            ->whereColumn('order_quantity','=','finished_num')
+            ->select('out_order_no')
+            ->groupBy('out_order_no')
+            ->get()
+            ->toArray();
+        $all = array_column($all,'out_order_no');
+
+        $not_all = SaleOrdersProduct::where('del_time',0)
+            ->whereColumn('order_quantity','<>','finished_num')
+            ->select('out_order_no')
+            ->groupBy('out_order_no')
+            ->get()
+            ->toArray();
+        $not_all = array_column($not_all,'out_order_no');
+        $all = array_diff($all, $not_all);
+
+        $arr = [
+            "all_num" => count($all),
+            "num" => count($not_all),
+        ];
+        return $this->json_return(200,'',$arr);
+    }
+
+    //本月质量
+    public function output_value_month1(Request $request){
+        date_default_timezone_set("PRC");
+        $date = date('Ymd',time());
+
+        $startDate = strtotime(date('Y-m-01 00:00:00', time()));
+        $endDate = strtotime(date('Y-m-t 23:59:59', time()));
+        //工序-----------------------------
+        $model = new OrdersProductProcess(['channel' => $date]);//当前季度的数据
+        $data = $model->where('del_time',0)
+            ->where('status',4)
+            ->select('crt_time')
+            ->where('crt_time','>=',$startDate)
+            ->where('crt_time','<=',$endDate)
+            ->get()->toArray();
+
+        $return = [];
+        if(! empty($data)){
+            foreach ($data as $value){
+                $crt_time = date('Y-m-d',$value['crt_time']);
+                if(isset($return[$crt_time])){
+                    $return[$crt_time]['num'] += 1;
+                }else{
+                    $return[$crt_time] = [
+                        'num' => 1,
+                        'value' => $crt_time
+                    ];
+                }
+            }
+        }
+        $return = array_values($return);
+        return $this->json_return(200,'',$return);
+    }
+
+    //产量趋势图
+    public function output_value_efficiency(Request $request){
+        date_default_timezone_set("PRC");
+        // 获取当前时间戳
+        $currentTimestamp = time();
+        // 输出过去两周的起止时间(包括当前日期)
+        $timestamp = strtotime("-13 days", $currentTimestamp);
+        $startOfDay = strtotime(date('Y-m-d 00:00:00', $timestamp));
+        $endOfDay = strtotime(date('Y-m-d 23:59:59', $currentTimestamp));
+
+        $box = Box::where('del_time',0)
+            ->where('crt_time','>=',$startOfDay)
+            ->where('crt_time','<=',$endOfDay)
+            ->select('crt_time','top_order_no','order_no')
+            ->orderBy('crt_time','desc')
+            ->get()->toArray();
+        $result = [];
+        if(! empty($box)){
+            foreach ($box as $value){
+                $model = new BoxDetail(['channel' => $value['top_order_no']]);
+                $map = $model->where('del_time',0)
+                    ->where('order_no',$value['order_no'])
+                    ->select('order_no',DB::raw('sum(num) as num'))
+                    ->groupBy('order_no')
+                    ->pluck('num','order_no')
+                    ->toArray();
+                $output = $map[$value['order_no']] ?? 0;
+                $times = date('Y-m-d',$value['crt_time']);
+                if(isset($result[$times])){
+                    $result[$times]['output'] += $output;
+                }else{
+                    $result[$times] = [
+                        'crt_time' => $times,
+                        'output' => $output
+                    ];
+                }
+            }
+        }
+        $result = array_values($result);
+        return $this->json_return(200,'',$result);
+    }
+
+    //工序负荷全览
+    public function capacity(Request $request){
+        date_default_timezone_set("PRC");
+        $date = date('Ymd',time());
+
+        //工序-----------------------------
+        $model = new OrdersProductProcess(['channel' => $date]);//当前季度的数据
+        $data = $model->where('del_time',0)
+            ->where('status',2)
+            ->select('finished_time')
+            ->get()->toArray();
+
+        $return = [];
+        if(! empty($data)){
+            foreach ($data as $value){
+                $finished_time = date('Ymd',$value['finished_time']);
+                if(isset($return[$finished_time])){
+                    $return[$finished_time] += 1;
+                }else{
+                    $return[$finished_time] = 1;
+                }
+            }
+        }
+        $maxValue = empty($return) ? 0 : max($return);
+        $today = $return[$date] ?? 0;
+        $rate = $maxValue ? intval($today/$maxValue) : 0;
+        //工序-----------------------------
+
+        //包装-----------------------------
+        $model = new BoxDetail(['channel' => $date]);//当前季度的数据
+        $data = $model->where('del_time',0)
+            ->select('crt_time','num')
+            ->get()->toArray();
+
+        $return = [];
+        if(! empty($data)){
+            foreach ($data as $value){
+                $crt_time = date('Ymd',$value['crt_time']);
+                if(isset($return[$crt_time])){
+                    $return[$crt_time] += $value['num'];
+                }else{
+                    $return[$crt_time] = $value['num'];
+                }
+            }
+        }
+        $maxValue = empty($return) ? 0 : max($return);
+        $today = $return[$date] ?? 0;
+        $rate2 = $maxValue ? intval($today/$maxValue) : 0;
+        //包装-----------------------------
+
+        $arr = [
+            [
+                [
+                    "title"=> "压贴",
+                    "rate"=> $rate
+                ],
+                [
+                    "title"=> "包装",
+                    "rate"=> $rate2
+                ]
+            ],
+        ];
+        return $this->json_return(200,'',['data' => $arr]);
+
+    }
+
+    //设备信息 暂时不做
+    public function product_num(Request $request){
+        $arr = [
+            [
+                "machine_day_num"=> "4903.69",
+                "machine_month_num"=> "139.64",
+                "machine_week_num"=> "47.21",
+                "break_day_num"=> "0",
+                "break_month_num"=> "10",
+                "break_week_num"=> "3",
+                "start_time"=> date("Y-m-d H:i:s",time()),
+                "day_num"=> "766",
+                "week_num"=> "4598",
+                "month_num"=> "14489",
+                "rate"=> "72"
+            ],
+            [
+                "machine_day_num"=> "469591.19",
+                "machine_month_num"=> "107.03",
+                "machine_week_num"=> "35.23",
+                "break_day_num"=> 0,
+                "break_month_num"=> "210",
+                "break_week_num"=> "18",
+                "start_time"=> date("Y-m-d H:i:s",time()),
+                "day_num"=> 0,
+                "week_num"=> "2353",
+                "month_num"=> "6255",
+                "rate"=> 0
+            ],
+            [
+                "machine_day_num"=> "0",
+                "machine_month_num"=> "14.02",
+                "machine_week_num"=> "6.88",
+                "break_day_num"=> "0",
+                "break_month_num"=> "0",
+                "break_week_num"=> "0",
+                "start_time"=> date("Y-m-d H:i:s",time()),
+                "day_num"=> "0",
+                "week_num"=> "494",
+                "month_num"=> "3058",
+                "rate"=> "0"
+            ],
+            [
+                "machine_day_num"=> "4903.77",
+                "machine_month_num"=> "149.14",
+                "machine_week_num"=> "56.72",
+                "break_day_num"=> "0",
+                "break_month_num"=> "0",
+                "break_week_num"=> "0",
+                "start_time"=> date("Y-m-d H:i:s",time()),
+                "day_num"=> "626",
+                "week_num"=> "4460",
+                "month_num"=> "13034",
+                "rate"=> "48"
+            ]
+        ];
+        return $this->json_return(200,'',$arr);
+    }
+
+    //在制工单
+    public function work_order(Request $request){
+        date_default_timezone_set("PRC");
+        // 获取当前时间戳
+        $currentTimestamp = time();
+        $timestamp = strtotime("-3 months", $currentTimestamp);
+        $startOfDay = strtotime(date('Y-m-d 00:00:00', $timestamp));
+        $endOfDay = strtotime(date('Y-m-d 23:59:59', $currentTimestamp));
+
+        $result = DispatchSub::where('del_time',0)
+            ->where('crt_time',">=", $startOfDay)
+            ->where('crt_time',"<=", $endOfDay)
+            ->whereColumn('dispatch_quantity','>','finished_num')
+            ->select('dispatch_no as order_no','process_id','product_title','dispatch_quantity as product_num','finished_num as finish_num')
+            ->get()->toArray();
+        if(! empty($result)){
+            $process_id = array_unique(array_column($result,'process_id'));
+            $processMap = Process::whereIn('id',$process_id)
+                ->pluck('title','id')
+                ->toArray();
+            foreach ($result as $key => $value){
+                $result[$key]['procedure'] = $processMap[$value['process_id']] ?? '';
+            }
+        }
+
+        return $this->json_return(200,'',$result);
+    }
+
+    //待加工
+    public function nu_work_order(Request $request){
+        date_default_timezone_set("PRC");
+
+        $date = date('Ymd',time());
+
+        //工序-----------------------------
+        $model = new OrdersProductProcess(['channel' => $date]);//当前季度的数据
+        $result = $model->where('del_time',0)
+            ->where('status',0)
+            ->select('production_no as order_no','product_title','process_id',DB::raw('count(id) as product_num'))
+            ->groupBy('order_product_id')
+            ->get()->toArray();
+
+        if(! empty($result)){
+            $process_id = array_unique(array_column($result,'process_id'));
+            $processMap = Process::whereIn('id',$process_id)
+                ->pluck('title','id')
+                ->toArray();
+            foreach ($result as $key => $value){
+                $result[$key]['procedure'] = $processMap[$value['process_id']] ?? '';
+            }
+        }
+
+        return $this->json_return(200,'',$result);
+    }
+}

+ 52 - 0
app/Jobs/CloudDataJob.php

@@ -0,0 +1,52 @@
+<?php
+
+namespace App\Jobs;
+
+use App\Service\CloudDataService;
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+use Symfony\Component\Console\Output\ConsoleOutput;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class CloudDataJob implements ShouldQueue
+{
+    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
+
+    protected $data;
+
+    /**
+     * Create a new job instance.
+     *
+     * @return void
+     */
+    public function __construct($data)
+    {
+        $this->data = $data;
+    }
+
+    /**
+     * Execute the job.
+     *
+     * @return void
+     */
+    public function handle()
+    {
+        $this->settle();
+
+        //输出信息 测试
+        $this->echoMessage(new ConsoleOutput());
+    }
+
+    private function settle(){
+        $service = new CloudDataService();
+        $service->cloudData();
+    }
+
+    protected function echoMessage(OutputInterface $output)
+    {
+        $output->writeln($this->data);
+    }
+}

+ 4 - 4
app/Jobs/ProcessDataJob.php

@@ -104,7 +104,7 @@ class ProcessDataJob implements ShouldQueue
     private function U8Rdrecord10Save(){
         $service = new FinishedOrderService();
         //标记
-        list($status,$msg) = $service->addInJob($this->data['result'],$this->data['data']);
+        list($status,$msg) = $service->addInJob($this->data['result'],$this->data['data'],$this->user);
         return [$status,$msg];
     }
 
@@ -112,7 +112,7 @@ class ProcessDataJob implements ShouldQueue
     private function U8Rdrecord10SaveMobile(){
         $service = new FinishedOrderService();
         //标记
-        list($status,$msg) = $service->addMobileInJob($this->data['result'],$this->data['data'],$this->data['quantity_count']);
+        list($status,$msg) = $service->addMobileInJob($this->data['result'],$this->data['data'],$this->data['quantity_count'],$this->user);
         return [$status,$msg];
     }
 
@@ -141,7 +141,7 @@ class ProcessDataJob implements ShouldQueue
     //销售单出库
     private function U8Rdrecord32Save(){
         $service = new FyyOrderService();
-        list($status,$msg) = $service->addInJob($this->data['result'],$this->data['data']);
+        list($status,$msg) = $service->addInJob($this->data['result'],$this->data['data'],$this->user);
         return [$status,$msg];
     }
 
@@ -167,7 +167,7 @@ class ProcessDataJob implements ShouldQueue
         //队列名
         $job = $this->jobs[$this->type];
 
-        if ($failureCount < 2) {
+        if ($failureCount < 1) {
             // 将任务重新放回队列
             self::dispatch($this->data,$this->user,$this->type)->onQueue($job)->delay(now()->addSeconds(2));
         } else {

+ 14 - 0
app/Model/SystemL.php

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

+ 129 - 0
app/Service/CloudDataService.php

@@ -0,0 +1,129 @@
+<?php
+
+namespace App\Service;
+
+use App\Model\SystemL;
+use Illuminate\Support\Facades\Redis;
+
+class CloudDataService extends Service
+{
+    //密钥
+    private $token_key = '';
+    //appSecret
+    private $app_secret = 'ziou5spsyi9c947rasqajhwoejee1oq3';
+    //appKey
+    private $app_key = '7k8iwOdL';
+    //设备id
+    private $device = [
+        "01401422100800008703",
+        "01401422100800000103",
+        "01401422100800008976",
+        "01401422100800000342"
+    ];
+
+    public function cloudData(){
+        $this->getAllDevice();
+    }
+
+    //获取token
+    public function getToken(){
+        $token = Redis::get($this->token_key);
+        if(! empty($token)) return $token;
+
+        //接口地址
+        $url = 'https://openapi.mp.usr.cn/usrCloud/user/getAuthToken';
+        //参数
+        $app_message = [
+            'appSecret' => $this->app_secret,
+            'appKey' => $this->app_key,
+        ];
+        //发送请求
+        $result = $this->curlOpen($url,['header'=>['Content-Type:application/json'],'post'=>json_encode($app_message)]);
+
+        if(empty($result)) die('err');
+        $res = json_decode($result,true);
+
+        //设置token缓存
+        $token = $res['data']['X-Access-Token'];
+        Redis::setex($this->token_key,(3600*1.5),$token);
+        return $token;
+    }
+
+    //获取数据
+    public function getAllDevice(){
+        $url = 'https://openapi.mp.usr.cn/usrCloud/datadic/getDataPointInfoByDevice';
+        $res = $this->xlCurl($url,['deviceIds' => $this->device]);
+
+//        $getUrl = $this->xlCurl('https://openapi.mp.usr.cn/usrCloud/vn/ucloudSdk/getHistoryServerAddress',[]);
+//        if(isset(json_decode($getUrl,true)['data']['historyServerAddr']))  $getUrl = json_decode($getUrl,true)['data']['historyServerAddr'];
+//        else $getUrl = 'https://history.usr.cn:7002';
+
+        $getUrl = 'https://history.usr.cn:7002';
+        $list = json_decode($res,true);
+
+        date_default_timezone_set("PRC");
+
+        $now = strtotime(date('Y-m-d')) * 1000;
+        $start = $now;
+
+        //目前设置的今天的开始时间戳 for循环一次
+        for ($i = $start; $i <= $now; $i = $i + 86400 * 1000){
+            $end = $i + 86400 * 1000;
+            SystemL::where('push_time','>=',$i)->where('push_time','<',$end)->delete();
+
+            foreach ($list['data'] as $v){
+                $deviceNo = $v['deviceId'];
+                foreach ($v['slaves'] as $vv){
+                    $slaveName = $vv['slaveName'];
+                    foreach ($vv['iotDataDescription'] as $vvv){
+                        $name = $vvv['name'];
+                        $id = $vvv['id'];
+                        $url = $getUrl.'/history/datapoint';
+                        $res =  $this->xlCurl($url,[
+                            'pageNo' => 1,
+                            'start' => $i,
+                            'end' => $end,
+                            'pageSize' => 1000,
+                            'devDatapoints' => [[
+                                'deviceNo' => $deviceNo,
+                                'slaveIndex' => 1,
+                                'itemId' => 1,
+                                'dataPointId' => $id,
+                            ]],
+                        ]);
+//                        file_put_contents('record_one.txt',$res,8);
+//                        dump($res);
+                        $res = json_decode($res,true);
+                        $insert = [];
+                        if(! empty($res['data']['list'])){
+                            foreach ($res['data']['list'] as $rv){
+                                foreach ($rv['list'] as $rvv){
+                                    $insert[] =  [
+                                        'device_name' => $rv['deviceName'],
+                                        'time' => $rvv['time'],
+                                        'value' => $rvv['value'],
+                                        'data_point_name' => $rv['dataPointName'],
+                                        'device_no' => $deviceNo,
+                                        'data_point_id' => $id,
+                                        'push_time' => $rvv['time'],
+                                        'slave_name' => $slaveName,
+                                    ];
+                                }
+                            }
+                            //dd($insert);
+                            //写入数据
+                            SystemL::insert($insert);
+                        }
+                        sleep(10);
+                    }
+                }
+            }
+        }
+    }
+
+    //发送请求
+    public function xlCurl($url,$data){
+        $token = $this->getToken();
+        return $this->curlOpen($url,['header'=>['Content-Type:application/json','X-Access-Token:'.$token,],'post'=>json_encode($data)]);
+    }
+}

+ 6 - 18
app/Service/DeleteOrderService.php

@@ -59,7 +59,7 @@ class DeleteOrderService extends Service
                 ->select('order_no')
                 ->whereIn('id',$id);
             $order_no = DB::table('sale_orders_product')
-                ->select('order_no','del_time')
+                ->select('sale_orders_product.order_no','sale_orders_product.del_time')
                 ->joinSub($subquery, 'sub', function ($join) {
                     $join->on('sale_orders_product.order_no', '=', 'sub.order_no');
                 })->get()->toArray();
@@ -67,6 +67,7 @@ class DeleteOrderService extends Service
             if(! empty($order_no)){
                 $tmp = [];
                 foreach ($order_no as $value){
+                    $value = (array)$value;
                     if($value['del_time'] == 0){
                         $tmp[] = $value['order_no'];
                     }else{
@@ -116,6 +117,7 @@ class DeleteOrderService extends Service
             if(! empty($order_no)){
                 $tmp = [];
                 foreach ($order_no as $value){
+                    $value = (array)$value;
                     if($value['del_time'] == 0){
                         $tmp[] = $value['production_no'];
                     }else{
@@ -150,7 +152,7 @@ class DeleteOrderService extends Service
             }
 
             //销售订单里的已生产数量
-            (new ProductionOrderService())->writeProductionQuantity(array_column($message,'sale_orders_product_id'));
+            (new ProductionOrderService())->writeProductionQuantityDEL(array_column($message,'sale_orders_product_id'));
 
             DB::commit();
         }catch (\Throwable $e){
@@ -182,7 +184,7 @@ class DeleteOrderService extends Service
                 ->select('dispatch_no')
                 ->whereIn('id',$id);
             $order_no = DB::table('dispatch_sub')
-                ->select('dispatch_no','del_time')
+                ->select('dispatch_sub.dispatch_no','dispatch_sub.del_time')
                 ->joinSub($subquery, 'sub', function ($join) {
                     $join->on('dispatch_sub.dispatch_no', '=', 'sub.dispatch_no');
                 })->get()->toArray();
@@ -190,6 +192,7 @@ class DeleteOrderService extends Service
             if(! empty($order_no)){
                 $tmp = [];
                 foreach ($order_no as $value){
+                    $value = (array)$value;
                     if($value['del_time'] == 0){
                         $tmp[] = $value['dispatch_no'];
                     }else{
@@ -251,7 +254,6 @@ class DeleteOrderService extends Service
 
             date_default_timezone_set('PRC');
 
-            $insertSqlServer = [];
             foreach ($result as $key => $value){
                 SaleOrdersProduct::where('id',$value['sale_orders_product_id'])->decrement('finished_num', $value['finished_num']);
 
@@ -277,7 +279,6 @@ class DeleteOrderService extends Service
                     ]);
 
                 $result[$key]['quantity'] = $value['finished_num'];
-                $insertSqlServer[] = $result[$key];
             }
 
             DispatchSub::whereIn('id',$id)->update([
@@ -285,9 +286,6 @@ class DeleteOrderService extends Service
                 'waste_num' => 0
             ]);
 
-            //入库单红字生成
-            $this->insertSqlServer($insertSqlServer);
-
             DB::commit();
         }catch (\Throwable $e){
             DB::rollBack();
@@ -296,14 +294,4 @@ class DeleteOrderService extends Service
 
         return [true,''];
     }
-
-    //产成品入库
-    public function insertSqlServer($array){
-        if(empty($array)) return [true,''];
-
-        $sqlServerModel = new FyySqlServerService();
-        list($status,$msg) = $sqlServerModel->U8Rdrecord10Save($array,1);
-
-        return [$status,$msg];
-    }
 }

+ 102 - 50
app/Service/DispatchService.php

@@ -9,6 +9,7 @@ use App\Model\Employee;
 use App\Model\EmployeeTeamPermission;
 use App\Model\Equipment;
 use App\Model\FinishedOrderSub;
+use App\Model\Orders;
 use App\Model\OrdersProduct;
 use App\Model\OrdersProductProcess;
 use App\Model\Process;
@@ -47,56 +48,19 @@ class DispatchService extends Service
         list($status,$msg) = $this->orderRule($data);
         if(!$status) return [$status,$msg];
 
-        $dispatch_no = $this->setOrderNO();
         try{
             DB::beginTransaction();
 
-            //主表
-            Dispatch::insert(['dispatch_no' => $dispatch_no,'crt_time' => time()]);
-
-            //生产数据的源数据
-            $result = $msg;
-
-            date_default_timezone_set("PRC");
-            $time_tmp = date("Ymd", $data['out_order_no_time'][0]);
-            $process_model = new OrdersProductProcess(['channel' => $time_tmp]);
-
-            $time = time();
-            $equipment_id = is_array($data['equipment_id']) ? $data['equipment_id'] : [$data['equipment_id']];
-            $equipment_id = array_filter($equipment_id);
-            $team_id = is_array($data['team_id']) ? $data['team_id'] : [$data['team_id']];
-            $team_id = array_filter($team_id);
-
-            $insert_emp_sub = [];
-            foreach ($result as $key => $value){
-                $quantity_tmp = $data['quantity'][$key];
-                $result[$key]['dispatch_no'] = $dispatch_no;
-                $result[$key]['process_id'] = $data['process_id'];
-                $result[$key]['dispatch_time_start'] = $data['dispatch_time'][0];
-                $result[$key]['dispatch_time_end'] = $data['dispatch_time'][1];
-                $result[$key]['dispatch_quantity'] = $quantity_tmp;
-                $result[$key]['crt_time'] = $time;
-                $result[$key]['crt_id'] = $user['id'];
-
-                $tmp = $this->makeData($equipment_id,$team_id,$data['employee_id'],$result[$key]);
-                $insert_emp_sub = array_merge_recursive($insert_emp_sub,$tmp);
-
-                $process_model->where('order_product_id',$value['order_product_id'])
-                    ->where('process_id',$data['process_id'])
-                    ->where('dispatch_no','')
-                    ->take($quantity_tmp)
-                    ->update([
-                        'dispatch_no' => $dispatch_no,
-                        'status' => 1
-                    ]);
+            if($data['is_split']){
+                foreach ($msg as $value){
+                    $this->insertDispatch([$value],$data,$user);
+                }
+            }else{
+                $this->insertDispatch($msg,$data,$user);
             }
 
-            DispatchSub::insert($result);
-
-            if(! empty($insert_emp_sub)) DispatchEmpSub::insert($insert_emp_sub);
-
             //反写已派工数量
-            $this->writeDispatchQuantity(array_column($result,'order_product_id'));
+            $this->writeDispatchQuantity(array_column($msg,'order_product_id'));
 
             DB::commit();
         }catch (\Exception $e){
@@ -104,7 +68,7 @@ class DispatchService extends Service
             return [false,$e->getLine().':'.$e->getMessage()];
         }
 
-        return [true,'保存成功!'];
+        return [true,''];
     }
 
     public function makeData($equipment_id, $team_id,$employee_id,$message){
@@ -181,6 +145,53 @@ class DispatchService extends Service
         return $arr;
     }
 
+    public function insertDispatch($msg, $data, $user){
+        //生产数据的源数据
+        $result = $msg;
+        $time = time();
+
+        $dispatch_no = $this->setOrderNO();
+        //主表
+        Dispatch::insert(['dispatch_no' => $dispatch_no,'crt_time' => $time]);
+
+        date_default_timezone_set("PRC");
+        $time_tmp = date("Ymd", $data['out_order_no_time'][0]);
+        $process_model = new OrdersProductProcess(['channel' => $time_tmp]);
+
+        $equipment_id = is_array($data['equipment_id']) ? $data['equipment_id'] : [$data['equipment_id']];
+        $equipment_id = array_filter($equipment_id);
+        $team_id = is_array($data['team_id']) ? $data['team_id'] : [$data['team_id']];
+        $team_id = array_filter($team_id);
+
+        $insert_emp_sub = [];
+        foreach ($result as $key => $value){
+            $result[$key]['dispatch_no'] = $dispatch_no;
+            $result[$key]['process_id'] = $data['process_id'];
+            $result[$key]['dispatch_time_start'] = $data['dispatch_time'][0];
+            $result[$key]['dispatch_time_end'] = $data['dispatch_time'][1];
+            $result[$key]['dispatch_quantity'] = $value['quantity'];
+            $result[$key]['crt_time'] = $time;
+            $result[$key]['crt_id'] = $user['id'];
+
+            $tmp = $this->makeData($equipment_id,$team_id,$data['employee_id'],$result[$key]);
+            $insert_emp_sub = array_merge_recursive($insert_emp_sub,$tmp);
+
+            $process_model->where('order_product_id',$value['order_product_id'])
+                ->where('process_id',$data['process_id'])
+                ->where('dispatch_no','')
+                ->take($value['quantity'])
+                ->update([
+                    'dispatch_no' => $dispatch_no,
+                    'status' => 1
+                ]);
+            unset($result[$key]['quantity']);
+        }
+
+        DispatchSub::insert($result);
+
+        if(! empty($insert_emp_sub)) DispatchEmpSub::insert($insert_emp_sub);
+    }
+
     public function del($data){
         if($this->isEmpty($data,'id')) return [false,'ID不能为空!'];
 
@@ -270,24 +281,40 @@ class DispatchService extends Service
         if(empty($data['dispatch_time'][0]) || empty($data['dispatch_time'][1])) return [false,'计划生产时间不能为空!'];
         if(empty($data['out_order_no_time'][0]) || empty($data['out_order_no_time'][1])) return [false,'制单时间不能为空!'];
         if($this->isEmpty($data,'process_id')) return [false,'工序不能为空!'];
+        if(! isset($data['is_split'])) return [false,'是否拆分标识不能为空!'];
 
         $result = OrdersProduct::whereIn('id',$data['id'])
             ->select('id as order_product_id','sale_orders_product_id','order_no','table_header_mark','product_no','product_title','product_size','product_unit','production_quantity','technology_material','technology_name','wood_name','process_mark','table_body_mark','sale_orders_product_id','out_order_no_time','price','customer_name')
             ->orderBy('id','desc')
             ->get()->toArray();
+        $result_map = array_column($result,null,'order_product_id');
 
         //已派工数据
         $map = $this->getDispatchQuantity($data['id']);
 
+        $total_map = $return = [];
+        foreach ($data['id'] as $key => $value){
+            if(isset($total_map[$value])){
+                $total_map[$value] += $data['quantity'][$key];
+            }else{
+                $total_map[$value] = $data['quantity'][$key];
+            }
+            $tmp = $result_map[$value];
+            $tmp['quantity'] = $data['quantity'][$key];
+            $return[] = $tmp;
+        }
+
         foreach ($result as $key => $value){
+            //数据校验
+            $quantity_tmp = $total_map[$value['order_product_id']];
             if(isset($map[$value['order_product_id']])){
-                if($map[$value['order_product_id']] + $data['quantity'][$key] > $value['production_quantity']) return [false,'派单数量不能大于生产订单数量'];
+                if($map[$value['order_product_id']] + $quantity_tmp > $value['production_quantity']) return [false,'派单数量不能大于生产订单数量'];
             }else{
-                if($data['quantity'][$key] > $value['production_quantity']) return [false,'派单数量不能大于生产订单数量'];
+                if($quantity_tmp > $value['production_quantity']) return [false,'派单数量不能大于生产订单数量'];
             }
         }
 
-        return [true, $result];
+        return [true, $return];
     }
 
     public function fillData($data){
@@ -329,7 +356,7 @@ class DispatchService extends Service
 
     public function dispatchOrderList($data){
         $model = DispatchSub::where('del_time',0)
-            ->select('id','order_no','table_header_mark','product_no','product_title','product_size','product_unit','dispatch_quantity','technology_material','technology_name','wood_name','process_mark','table_body_mark','production_quantity','dispatch_no','status','crt_id','process_id','dispatch_time_start','dispatch_time_end','crt_time','finished_num','waste_num','customer_name')
+            ->select('id','order_no','table_header_mark','product_no','product_title','product_size','product_unit','dispatch_quantity','technology_material','technology_name','wood_name','process_mark','table_body_mark','production_quantity','dispatch_no','status','crt_id','process_id','dispatch_time_start','dispatch_time_end','crt_time','finished_num','waste_num','customer_name','order_product_id')
             ->orderBy('id','desc');
 
         if(isset($data['finished_num'])) $model->where('finished_num', '>',0);
@@ -411,8 +438,14 @@ class DispatchService extends Service
             ->pluck('title','id')
             ->toArray();
 
+        $order_map = Orders::where('del_time',0)
+            ->whereIn('order_no',array_column($data['data'],'order_no'))
+            ->pluck('out_order_no','order_no')
+            ->toArray();
+
         date_default_timezone_set("PRC");
         foreach ($data['data'] as $key => $value){
+            $data['data'][$key]['out_order_no'] = $order_map[$value['order_no']] ?? '';
             $data['data'][$key]['crt_time'] = $value['crt_time'] ? date('Y-m-d',$value['crt_time']) : '';
 
             $time1 = $value['dispatch_time_start'] ? date('Y-m-d',$value['dispatch_time_start']) : '';
@@ -432,7 +465,7 @@ class DispatchService extends Service
         return $data;
     }
 
-    //反写写派工数量
+    //反写写派工数量(增加)
     public function writeDispatchQuantity($order_product_id){
         if(empty($order_product_id)) return;
 
@@ -452,6 +485,25 @@ class DispatchService extends Service
         }
     }
 
+    //反写写派工数量(删除)
+    public function writeDispatchQuantityDEL($order_product_id){
+        if(empty($order_product_id)) return;
+
+        $result = DispatchSub::where('del_time',0)
+            ->whereIn('order_product_id',$order_product_id)
+            ->select(DB::raw("sum(dispatch_quantity) as dispatch_quantity"),'order_product_id')
+            ->groupby('order_product_id')
+            ->pluck('dispatch_quantity','order_product_id')
+            ->toArray();
+
+        foreach ($order_product_id as $value){
+            $quantity = $result[$value] ?? 0;
+            OrdersProduct::where('id',$value)->update([
+                'dispatch_complete_quantity' => $quantity
+            ]);
+        }
+    }
+
     //设备上的去完工列表
     public function dispatchMobileOrderList($data){
         $model = DispatchSub::where('del_time',0)

+ 13 - 10
app/Service/EmployeeService.php

@@ -33,9 +33,13 @@ class EmployeeService extends Service
         $model->emp_name = $data['emp_name'];
         $model->is_admin = $data['is_admin'];
         if($model->is_admin == 1){
-            $model->account = $data['account'];
+            $model->account = $data['number'];
             if($data['password'] !== '********'){
-                $model->password   = Hash::make($data['password']);
+                $model->password = Hash::make($data['password']);
+            }
+            $model->sqlserver_account = $data['sqlserver_account'] ?? '';
+            if($data['sqlserver_password'] !== '********'){
+                $model->sqlserver_password = $data['sqlserver_password'];
             }
         }
         $model->save();
@@ -68,8 +72,10 @@ class EmployeeService extends Service
         $model->crt_id = $user['id'];
         $model->is_admin = $data['is_admin'];
         if($model->is_admin == 1){
-            $model->account = $data['account'];
+            $model->account = $data['number'];
             $model->password   = Hash::make($data['password']);
+            $model->sqlserver_account = $data['sqlserver_account'] ?? '';
+            $model->sqlserver_password = $data['sqlserver_password'] ?? '';
         }
         $model->save();
 
@@ -95,7 +101,7 @@ class EmployeeService extends Service
 
     public function employeeList($data){
         $model = Employee::where('del_time',0)
-            ->select('id_card','emp_name','mobile','crt_time','account','is_admin','upd_time','id','number')
+            ->select('id_card','emp_name','mobile','crt_time','account','is_admin','upd_time','id','number','sqlserver_account','sqlserver_password')
             ->orderBy('id','desc');
 
         if(! empty($data['depart_id'])) {
@@ -141,6 +147,8 @@ class EmployeeService extends Service
         foreach ($data['data'] as $key => $value){
             $data['data'][$key]['depart_id'] = $map[$value['id']]->id ?? '';
             $data['data'][$key]['depart_title'] = $map[$value['id']]->title ?? '';
+            $data['data'][$key]['has_pwd'] = $value['sqlserver_password'] ? 1 : 0;
+            unset($data['data'][$key]['sqlserver_password']);
         }
         return $data;
     }
@@ -153,17 +161,11 @@ class EmployeeService extends Service
             $bool = Employee::where('number',$data['number'])
                 ->where('id','<>',$data['id'])
                 ->where('del_time',0)->exists();
-            $bool_account = Employee::where('account',$data['account'])
-                ->where('id','<>',$data['id'])
-                ->where('del_time',0)->exists();
         }else{
             $bool = Employee::where('number',$data['number'])
                 ->where('del_time',0)->exists();
-            $bool_account = Employee::where('account',$data['account'])
-                ->where('del_time',0)->exists();
         }
         if($bool) return [false,'工号已存在!'];
-        if($bool_account) return [false,'账号已存在!'];
 
         return [true,''];
     }
@@ -518,6 +520,7 @@ class EmployeeService extends Service
 
         $res = Employee::where('del_time',0)
             ->where('account', $data['account'])
+            ->Orwhere('emp_name', $data['account'])
             ->get()->toArray();
 
         if(empty($res)) return [false,'账号不存在或已被删除!'];

+ 4 - 4
app/Service/FinishedOrderService.php

@@ -76,7 +76,7 @@ class FinishedOrderService extends Service
         return [true,'任务已进入队列!'];
     }
 
-    public function addInJob($result,$data){
+    public function addInJob($result,$data,$user){
         try{
             date_default_timezone_set("PRC");
 
@@ -102,7 +102,7 @@ class FinishedOrderService extends Service
             }
 
             if(! empty($insert_sql_server)){
-                $sqlServerModel = new FyySqlServerService();
+                $sqlServerModel = new FyySqlServerService($user['id']);
                 if($sqlServerModel->error) return [false,$sqlServerModel->error];
                 foreach ($insert_sql_server as $value){
                     list($status,$msg) = $sqlServerModel->U8Rdrecord10Save($value);
@@ -441,7 +441,7 @@ class FinishedOrderService extends Service
         return [true,'任务已进入队列!'];
     }
 
-    public function addMobileInJob($result, $data, $count_arr){
+    public function addMobileInJob($result, $data, $count_arr,$user){
         try{
             //用友数据写入------------
             date_default_timezone_set("PRC");
@@ -466,7 +466,7 @@ class FinishedOrderService extends Service
             }
 
             if(! empty($insert_sql_server)){
-                $sqlServerModel = new FyySqlServerService();
+                $sqlServerModel = new FyySqlServerService($user['id']);
                 if($sqlServerModel->error) return [false,$sqlServerModel->error];
                 foreach ($insert_sql_server as $value){
                     list($status,$msg) = $sqlServerModel->U8Rdrecord10Save($value);

+ 45 - 27
app/Service/FyyOrderService.php

@@ -25,7 +25,7 @@ class FyyOrderService extends Service
 
     public function add($data,$user){
         //获取数据
-        $sqlServerModel = new FyySqlServerService();
+        $sqlServerModel = new FyySqlServerService($user['id']);
         list($status,$return,$return_stock_detail) = $sqlServerModel->getDataFromSqlServer($data);
         if(! $status) return [false, $return];
 
@@ -103,7 +103,8 @@ class FyyOrderService extends Service
     public function orderList($data){
         $model = SaleOrdersProduct::where('del_time',0)
             ->select('id','order_no','out_order_no','out_order_no_time','customer_no','customer_name','table_header_mark','product_no','product_title','product_size','product_unit','order_quantity','technology_material','technology_name','wood_name','process_mark','table_body_mark','out_crt_man','out_checker_man','out_checker_time','production_quantity','box_num','finished_num','shipment_num')
-            ->orderBy('id','desc');
+            ->orderBy('crt_time','desc')
+            ->orderBy('id','asc');
 
         if(! empty($data['order_no'])) $model->where('order_no', 'LIKE', '%'.$data['order_no'].'%');
         if(! empty($data['out_order_no'])) $model->where('out_order_no', 'LIKE', '%'.$data['out_order_no'].'%');
@@ -177,9 +178,9 @@ class FyyOrderService extends Service
         return [true,''];
     }
 
-    public function fyyRefreshOnHandQuantity($data){
+    public function fyyRefreshOnHandQuantity($data,$user){
         //获取数据
-        $sqlServerModel = new FyySqlServerService();
+        $sqlServerModel = new FyySqlServerService($user['id']);
         list($status,$return,$return_product) = $sqlServerModel->getDataFromSqlServerForOnHand($data);
         if(! $status) return [false, $return];
 
@@ -231,9 +232,9 @@ class FyyOrderService extends Service
         return [true,'任务已进入队列!'];
     }
 
-    public function addInJob($result,$data){
+    public function addInJob($result,$data,$user){
         try{
-            $sqlServerModel = new FyySqlServerService();
+            $sqlServerModel = new FyySqlServerService($user['id']);
             if($sqlServerModel->error) return [false,$sqlServerModel->error];
 
             list($status,$msg) = $sqlServerModel->U8Rdrecord32Save($data['post']);
@@ -243,11 +244,16 @@ class FyyOrderService extends Service
             DB::beginTransaction();
             Box::whereIn('order_no',$data['order_no'])->update([
                 'state' => 2,
+                'shipment_order_no' => $data['shipment_code'],//发货单号
             ]);
+            $box = new BoxDetail(['channel'=>$data['top_order_no']]);
+            $box->where('order_no',$data['order_no'])->update([
+                'shipment_order_no' => $data['shipment_code']//发货单号
+            ]);
+
             foreach ($data['box_data'] as $value){
-                SaleOrdersProduct::where('out_order_no',$data['order_number'])->update([
-                    'top_id' => $value['top_id'],
-                    'shipment_num' => $value['num'],
+                SaleOrdersProduct::where('id',$value['top_id'])->update([
+                    'shipment_num' => DB::raw("shipment_num + {$value['num']}"),
                 ]);
             }
             DB::commit();
@@ -260,10 +266,12 @@ class FyyOrderService extends Service
     }
 
     public function orderOutRule($data){
-        if(empty($data['order_number'])) return [false,'销售订单号不能为空!'];
         if(empty($data['order_no'])) return [false,'包装单号不能为空!'];
+        if(empty($data['order_number'])) return [false,'销售订单号不能为空!'];
         if(empty($data['post'])) return [false,'发货单数据不能为空!'];
         if(empty($data['box_data'])) return [false,'包装单数据不能为空!'];
+        if(empty($data['top_order_no'])) return [false,'顶部订单号不能为空!'];
+        if(empty($data['shipment_code'])) return [false,'发货单订单号不能为空!'];
 
         $boxList = Box::whereIn('order_no',$data['order_no'])->get()->toArray();
         if(empty($boxList)) return [false,'包装单不存在!'];
@@ -289,16 +297,15 @@ class FyyOrderService extends Service
                 ->get()->toArray();
             $key_list = [];
             foreach ($list as $v){
-                $customer_name = $v['customer_name'];
-                if(!isset($key_list[$customer_name])) $key_list[$customer_name] = [
+                $customer_name = trim($v['customer_name']);
+                if(! isset($key_list[$customer_name])) $key_list[$customer_name] = [
                     'customer_name' => $customer_name,
                     'list' => [],
                 ];
-//                unset($v['customer_name']);
                 $key_list[$customer_name]['list'][] = $v;
-                sort($key_list);
-                $list = $key_list;
             }
+            sort($key_list);
+            $list = $key_list;
         }elseif($data['type'] == 2){
             $list = SaleOrdersProduct::where('del_time',0)
                 ->select('order_no','out_order_no','customer_name')
@@ -316,44 +323,55 @@ class FyyOrderService extends Service
                     'customer_name' => $customer_name,
                     'list' => [],
                 ];
-//                unset($v['customer_name']);
                 $key_list[$customer_name]['list'][] = $v;
-                sort($key_list);
-                $list = $key_list;
             }
+            sort($key_list);
+            $list = $key_list;
         }
 
         return [true, $list];
     }
 
-    public function getShipmentOrder($data){
-        if(empty($data['order_no'])) return ['false', '销售订单号不能为空!'];
+    public function getShipmentOrder($data,$user){
+        if(empty($data['time'][0]) || empty($data['time'][1])) return ['false', '时间范围不能为空!'];
 
-        $sqlServerModel = new FyySqlServerService();
+        $sqlServerModel = new FyySqlServerService($user['id']);
         if($sqlServerModel->error) return [false,$sqlServerModel->error];
 
-        $result = $sqlServerModel->getDataFromDispatchList($data['order_no']);
-        $return = [];
+        $result = $sqlServerModel->getDataFromDispatchList($data);
+        $return = $shipment_code = [];
         if(! empty($result)){
             foreach ($result as $value){
                 $cfree1 = $value['cfree1'] ?? '';
                 $cfree2 = $value['cfree2'] ?? '';
-                $tmp_key = $value['cinvcode'] . $cfree1 . $cfree2;
+                $tmp_key = $value['cdlcode'] . $value['cinvcode'] . $cfree1 . $cfree2;
                 $n = $value['iquantity'] - ($value['out_quantity'] ?? 0);
                 if(isset($return[$tmp_key])){
                     $return[$tmp_key]['num'] += $n;
                 }else{
                     $return[$tmp_key] = [
+                        'cdlcode' => $value['cdlcode'],
                         'product_no' => $value['cinvcode'],
                         'product_title' => $value['product_title'],
-                        'technology_name' => $cfree1,
-                        'wood_name' => $cfree2,
+                        'technology_name' => $cfree1 ?? '',
+                        'wood_name' => $cfree2 ?? '',
                         'num' => $n,
+                        'technology_material' => $value['technology_material'] ?? '',
+                        'process_mark' => $value['process_mark'] ?? '',
+                        'product_size' => $value['product_size'] ?? ''
+                    ];
+                }
+
+                if(! isset($shipment_code[$value['cdlcode']])){
+                    $shipment_code[$value['cdlcode']] = [
+                        'shipment_code' => $value['cdlcode'],
+                        'order_no' => $value['csocode'],
+                        'customer_name' => $value['customer_name']
                     ];
                 }
             }
         }
 
-        return [true,['show'=>array_values($return),'post'=>$result]];
+        return [true,['shipment_code'=>array_values($shipment_code), 'show'=>array_values($return), 'post'=>$result]];
     }
 }

+ 53 - 101
app/Service/FyySqlServerService.php

@@ -3,6 +3,7 @@
 namespace App\Service;
 
 use App\Model\BoxDetail;
+use App\Model\Employee;
 use App\Model\Orders;
 use App\Model\SaleOrdersProduct;
 use Illuminate\Support\Facades\Config;
@@ -22,17 +23,38 @@ class FyySqlServerService extends Service
     public $sAccID = "(default)@999";
     public $sUserID = "demo";
     public $sPassword = "";
+    private $database_select = [
+        '001' => 'UFDATA_001_2023',
+        '002' => 'UFDATA_002_2023',
+        '999' => 'UFDATA_999_2023'
+    ];
 
-    public function __construct()
+    public function __construct($user_id = '')
     {
-        $fyy_array = Redis::get('fyy_sql_server');
+        //用户信息校验
+        if(empty($user_id)) {
+            $this->error = '福羊羊数据库连接用户参数不能为空!';
+            return;
+        }
+        $emp = Employee::where('id',$user_id)->select('sqlserver_account','sqlserver_password')->first();
+        if(empty($emp)) {
+            $this->error = '福羊羊连接构造失败!';
+            return;
+        }
+        //用友接口统一登录账号密码
+        $this->sUserID = $emp->sqlserver_account ?? '';
+        $this->sPassword = $emp->sqlserver_password ?? '';
+
+        //缓存数据提取  主要是账套
+        $key = 'fyy_sql_server' . $user_id;
+        $fyy_array = Redis::get($key);
         if(! empty($fyy_array)) {
             $fyy_array = json_decode($fyy_array,true);
+            if(! empty($fyy_array['sqlserver_database'])) $this->database = $this->database_select[$fyy_array['sqlserver_zt']];
+            if(! empty($fyy_array['sqlserver_zt'])) $this->sAccID = '(default)@' . $fyy_array['sqlserver_zt'];
             if(! empty($fyy_array['sqlserver_host'])) $this->host = $fyy_array['sqlserver_host'];
             if(! empty($fyy_array['sqlserver_host_api'])) $this->host_api = $fyy_array['sqlserver_host_api'];
             if(! empty($fyy_array['sqlserver_port'])) $this->port = $fyy_array['sqlserver_port'];
-            if(! empty($fyy_array['sqlserver_database'])) $this->database = $fyy_array['sqlserver_database'];
-            if(! empty($fyy_array['sqlserver_zt'])) $this->sAccID = '(default)@' . $fyy_array['sqlserver_zt'];
             if(! empty($fyy_array['sqlserver_account'])) $this->sUserID = $fyy_array['sqlserver_account'];
             if(! empty($fyy_array['sqlserver_password'])) $this->sPassword = $fyy_array['sqlserver_password'];
         }
@@ -67,6 +89,7 @@ class FyySqlServerService extends Service
         }
     }
 
+    //假数据
     private function fakeData(){
         $return = [
             [
@@ -332,7 +355,7 @@ class FyySqlServerService extends Service
             "cbmemo"=> "",
             "cfree1"=> $data['technology_name'],
             "cfree2"=> $data['wood_name'],
-            "cdefine28" => $data['technology_material']
+            "cdefine28" => $data['technology_material'],
         ];
         $post = [
             "password"=>"cloud@123456",
@@ -372,11 +395,13 @@ class FyySqlServerService extends Service
 
         $new = [];
         foreach ($data as $value){
-            $new[$value['id']][] = $value;
+            $keys = $value['id'] . $value['cwhcode'];
+            $new[$keys][] = $value;
         }
 
         foreach ($new as $value){
             $main_tmp = $value[0];
+            $bodys_tmp = [];
             foreach ($value as $val){
                 $bodys_tmp[] = [
                     "idlsid"=>$val['idlsid'],
@@ -389,9 +414,13 @@ class FyySqlServerService extends Service
                     "iquantity"=>$val['iquantity'],
                     "inum"=>$val['inum'],
                     "iinvexchrate"=> $val['iinvexchrate'] ?? 0,
-                    "iunitcost"=>$val['iunitcost'],
-                    "iprice"=>$val['imoney'],
+                    "iunitcost"=>$val['iunitcost'] * 0.95,
+                    "iprice"=>$val['iunitcost'] * 0.95 * $val['iquantity'],
                     "cbmemo"=>"",
+                    "cfree1"=> $val['cfree1'],
+                    "cfree2"=> $val['cfree2'],
+                    "cdefine28" => $val['technology_material'],
+                    "cdefine30" => $val['process_mark'],
                 ];
             }
             $post_tmp = [
@@ -414,7 +443,8 @@ class FyySqlServerService extends Service
                     "bredvouch"=> $bredvouch,
                     "cwhcode"=>$main_tmp['cwhcode'],
                     "cdepcode"=>$main_tmp['cdepcode'],
-                    "crdcode"=>'',
+                    "ccuscode"=>$main_tmp['cuscode'],
+                    "crdcode"=>'202',
                     "cmemo"=> '',
                     "cdefine10" => $main_tmp['customer_name'], //客户名称
                     "bodys"=>$bodys_tmp,
@@ -431,93 +461,6 @@ class FyySqlServerService extends Service
         return [true,''];
     }
 
-//    public function U8Rdrecord32Save($data,$bredvouch = 0){
-//        if(! empty($this->error)) return [false,$this->error];
-//        date_default_timezone_set("PRC");
-//
-//        //获取包装单内数据
-//        $box = $this->getBoxData($data);
-//        if(empty($box)) return [false,'包装单不能为空!'];
-//
-//        //获取发货单的数据
-//        $return = $this->getDataFromDispatchList(array_column($box,'cSOCode'));
-//        if(empty($return)) return [false,'没有找到发货单!'];
-//
-//        //组织发货单的数据
-//        $map = [];
-//        foreach ($return as $value){
-//            $map[$value['cSOCode']][] = $value;
-//        }
-//
-//        $detail = [];
-//        foreach ($box as $value){
-//            if(! isset($map[$value['cSOCode']])) {
-//                return [false,'包装单内销售订单号:' . $value['cSOCode'] .'没有找到发货单!'];
-//            }
-//            $is_flag = 0;
-//            foreach ($map[$value['cSOCode']] as $m){
-//                if($value['cinvcode'] == $m['cinvcode'] && $value['cfree1'] == $m['cfree1'] && $value['cfree2'] == $m['cfree2']) {
-//                    $is_flag = 1;
-//                    $m['iquantity'] = $value['iquantity'];
-//                    $detail[$m['cSOCode']][] = $m;
-//                }
-//            }
-//            if(! $is_flag) return [false,'包装单内销售订单号:' . $value['cSOCode'] .'产品:' . $value['cinvcode'] . $value['cfree1'] . $value['cfree2'] . '在发货单中不存在!'];
-//        }
-//
-//        foreach ($detail as $value){
-//            $main_tmp = $value[0];
-//            foreach ($value as $val){
-//                $bodys_tmp[] = [
-//                    "idlsid"=>$val['idlsid'],
-//                    "cdlcode"=>"",
-//                    "dlrowno"=>"",
-//                    "cbdlcode"=>"",
-//                    "cinvcode"=>$val['cinvcode'],
-//                    "cposition"=>$val['cposition'],
-//                    "cbatch"=>$val['cbatch'],
-//                    "iquantity"=>$val['iquantity'],
-//                    "inum"=>$val['iquantity'],
-//                    "iinvexchrate"=>$value['iinvexchrate'],
-//                    "iunitcost"=>"",
-//                    "iprice"=>"",
-//                    "cbmemo"=>"",
-//                ];
-//            }
-//            $post_tmp = [
-//                "password"=>"cloud@123456",
-//                "entity"=>"U8Rdrecord32Save",
-//                "login"=>[
-//                    "sAccID"=> $this->sAccID,
-//                    "sDate"=> date("Y-m-d"),
-//                    "sServer"=> '127.0.0.1',
-//                    "sUserID"=> $this->sUserID,
-//                    "sSerial"=> "",
-//                    "sPassword"=> $this->sPassword
-//                ],
-//                "data"=>[
-//                    "ccode"=>'',
-//                    "ddate"=>date("Y-m-d"),
-//                    "cmaker"=>$this->sUserID,
-//                    "dnmaketime"=> date("Y-m-d"),
-//                    "IsExamine"=>true,
-//                    "bredvouch"=> $bredvouch,
-//                    "cwhcode"=>"02",
-//                    "cdepcode"=>"06",
-//                    "crdcode"=>"102",
-//                    "cmemo"=> '',
-//                    "cdefine10" => $main_tmp['customer_name'], //客户名称
-//                    "bodys"=>$bodys_tmp
-//                ]
-//            ];
-//
-//            $return = $this->post_helper($this->url,json_encode($post_tmp), ['Content-Type:application/json']);
-//            if(! $return['flag']) return [false,$return['msg']];
-//        }
-//
-//        return [true,''];
-//    }
-
     public function getBoxData($data){
         $boxData = BoxDetail::from('box_detail as a')
             ->leftJoin('sale_orders_product as b','b.id','a.top_id')
@@ -529,14 +472,23 @@ class FyySqlServerService extends Service
     }
 
     //获取发货单数据 还没发的
-    public function getDataFromDispatchList($order_number){
-        $message = $this->db->table('DispatchList as a')
+    public function getDataFromDispatchList($data){
+        $model = $this->db->table('DispatchList as a')
             ->leftJoin('DispatchLists as b','b.DLID','a.DLID')
-            ->where('a.cSOcode',$order_number)
+            ->leftJoin('Inventory as c','c.cInvCode','b.cInvCode')
             ->whereNotNull('a.cVerifier')
-            ->whereColumn('b.iQuantity', '>', 'b.fOutQuantity')
-            ->select('a.DLID as id','a.cDefine10 as customer_name','a.cSOCode','a.cDepCode as cdepcode','a.cCusCode as cuscode','b.iDLsID as idlsid','b.cWhCode as cwhcode','b.cInvCode as cinvcode','b.cInvName as product_title','b.cFree1 as cfree1','b.cFree2 as cfree2','b.cPosition as cposition','b.cBatch as cbatch','b.iQuantity as iquantity','b.iNum as inum','b.iInvExchRate as iinvexchrate','b.fOutQuantity as out_quantity','b.iUnitPrice as iunitcost','b.iMoney as imoney')
+            ->whereColumn('b.iQuantity', '>', 'b.fOutQuantity');
+
+        //检索条件
+        if(! empty($data['time'][0]) && ! empty($data['time'][1])) {
+            $model->where('a.dDate','>=',$data['time'][0]);
+            $model->where('a.dDate','<=',$data['time'][1]);
+        }
+        if(! empty($data['order_no'])) $model->where('a.cSOcode',$data['order_no']);
+
+        $message = $model->select('a.cDLCode as cdlcode','a.DLID as id','a.cDefine10 as customer_name','a.cSOCode as csocode','a.cDepCode as cdepcode','a.cCusCode as cuscode','b.iDLsID as idlsid','b.cWhCode as cwhcode','b.cInvCode as cinvcode','b.cInvName as product_title','b.cFree1 as cfree1','b.cFree2 as cfree2','b.cPosition as cposition','b.cBatch as cbatch','b.iQuantity as iquantity','b.iNum as inum','b.iInvExchRate as iinvexchrate','b.fOutQuantity as out_quantity','b.iUnitPrice as iunitcost','b.iMoney as imoney','b.cDefine28 as technology_material','b.cDefine30 as process_mark','c.cInvStd as product_size')
             ->get()->toArray();
+
         if(! empty($message)){
             foreach ($message as $key => $value){
 //                $message[$key]->iquantity = $value->iquantity - $value->out_quantity;

+ 21 - 2
app/Service/ProductionOrderService.php

@@ -187,7 +187,7 @@ class ProductionOrderService extends Service
 
         $result = SaleOrdersProduct::whereIn('id',$data['id'])
             ->select('id as sale_orders_product_id','order_no','out_order_no','out_order_no_time','customer_no','customer_name','table_header_mark','product_no','product_title','product_size','product_unit','order_quantity','technology_material','technology_name','wood_name','process_mark','table_body_mark','out_crt_man','out_checker_man','out_checker_time','production_quantity','price')
-            ->orderBy('id','desc')
+            ->orderBy('id','asc')
             ->get()->toArray();
 
         foreach ($result as $key => $value){
@@ -215,7 +215,7 @@ class ProductionOrderService extends Service
         return $data;
     }
 
-    //反写已生产数量
+    //反写已生产数量(添加)
     public function writeProductionQuantity($sale_orders_product_id){
         if(empty($sale_orders_product_id)) return;
 
@@ -235,6 +235,25 @@ class ProductionOrderService extends Service
         }
     }
 
+    //反写已生产数量(删除)
+    public function writeProductionQuantityDEL($sale_orders_product_id){
+        if(empty($sale_orders_product_id)) return;
+
+        $result = OrdersProduct::where('del_time',0)
+            ->whereIn('sale_orders_product_id',$sale_orders_product_id)
+            ->select(DB::raw("sum(production_quantity) as production_quantity"),'sale_orders_product_id')
+            ->groupby('sale_orders_product_id')
+            ->pluck('production_quantity','sale_orders_product_id')
+            ->toArray();
+
+        foreach ($sale_orders_product_id as $value){
+            $quantity = $result[$value] ?? 0;
+            SaleOrdersProduct::where('id',$value)->update([
+                'production_quantity' => $quantity
+            ]);
+        }
+    }
+
     //返回已生产数量
     public function getProductionOrderQuantity($data){
         if(empty($data)) return [];

+ 504 - 0
app/Service/ReportFormsService.php

@@ -0,0 +1,504 @@
+<?php
+
+namespace App\Service;
+
+use App\Model\Employee;
+use App\Model\OrdersProduct;
+use App\Model\OrdersProductProcess;
+use App\Model\Scrapp;
+use App\Model\Team;
+use Illuminate\Support\Facades\DB;
+
+class ReportFormsService extends Service
+{
+    //生产进度
+    public function productionReport($data){
+        if(empty($data['production_time'][0]) || empty($data['production_time'][1])) return [false, '生产订单时间必须选择!'];
+
+        //检索条件 生产订单主表----------------
+        $model = OrdersProduct::where('del_time',0)->select('production_time','production_no','out_order_no','out_order_no_time','customer_no','customer_name','table_header_mark','order_quantity','production_quantity');
+        $model->whereBetween('production_time',[$data['production_time'][0],$data['production_time'][1]]);
+        if(! empty($data['production_no'])) $model->where('production_no', 'LIKE', '%'.$data['production_no'].'%');
+        if(! empty($data['out_order_no_time'][0]) && ! empty($data['out_order_no_time'][1])) $model->whereBetween('out_order_no_time',[$data['out_order_no_time'][0],$data['out_order_no_time'][1]]);
+        if(! empty($data['out_order_no'])) $model->where('out_order_no', 'LIKE', '%'.$data['out_order_no'].'%');
+        if(! empty($data['customer_no'])) $model->where('customer_no', 'LIKE', '%'.$data['customer_no'].'%');
+        if(! empty($data['customer_name'])) $model->where('customer_name', 'LIKE', '%'.$data['customer_name'].'%');
+        $orderList = $model->get()->toArray();
+        //生产订单主表----------------
+
+        //筛选出制单日期 分表的依据
+        $out_order_no_time = array_unique(array_column($orderList,'out_order_no_time'));
+        //制单日期
+        $out_time = $this->checkSameQuarter($out_order_no_time);
+
+        //分组以后的订单列表
+        $list = [];
+        foreach ($orderList as $value){
+            if(! isset($list[$value['production_no']])){
+                $list[$value['production_no']] = $value;
+            }else{
+                $list[$value['production_no']]['order_quantity'] += $value['order_quantity'];
+                $list[$value['production_no']]['production_quantity'] += $value['production_quantity'];
+            }
+        }unset($orderList);
+
+        //查询分表数据
+        $production_no = array_column($list,'production_no');
+        $detail = [];
+        $process_id = $data['process_id'] ?? [];
+        foreach ($out_time as $value){
+            //子表搜索
+            $models = new OrdersProductProcess(['channel' => $value]);
+            $tmp = $models->whereIn('production_no',$production_no)
+                ->where('del_time',0)
+                ->whereIn('status',array(1,2))
+                ->when(!empty($process_id), function ($query) use ($process_id) {
+                    return $query->whereIn('process_id', $process_id);
+                })
+                ->select('production_no','process_id',DB::raw('SUM(CASE WHEN status >= 1 THEN 1 ELSE 0 END) as dispatch_count'),DB::raw('SUM(CASE WHEN status = 2 THEN 1 ELSE 0 END) as finish_count'))
+                ->groupBy('production_no','process_id')
+                ->get()->toArray();//派工和完工数据
+
+            foreach ($tmp as $t){
+                $keys = $t['production_no'] . "|" .$t['process_id'];
+                if(isset($detail[$keys])){
+                    $detail[$keys]['dispatch_count'] += $t['dispatch_count'];
+                    $detail[$keys]['finish_count'] += $t['finish_count'];
+                }else{
+                    $detail[$keys] = $t;
+                }
+            }
+        }
+
+        //返回统计数据
+        date_default_timezone_set("PRC");
+        foreach ($list as $key => $value) {
+            $list[$key]['production_time'] = $value['production_time'] ? date('Y-m-d',$value['production_time']) : '';
+            $list[$key]['out_order_no_time'] = $value['out_order_no_time'] ? date('Y-m-d',$value['out_order_no_time']) : '';
+
+            $detail_key = $value['production_no'] . "|";
+            foreach ($detail as $key_son => $value_son) {
+                if (strpos($key_son,$detail_key) !== false) {
+                    $value_son['rate'] = number_format($value_son['finish_count'] / $value['order_quantity'], 2);
+                    $list[$key]['process'][] = $value_son;
+                }
+            }
+
+            if(empty($list[$key]['process'])) unset($list[$key]);
+        }
+
+        return [true,array_values($list)];
+    }
+
+    private function checkSameQuarter($timestamps) {
+        date_default_timezone_set("PRC");
+        $quarters = $out_time = [];
+        foreach ($timestamps as $timestamp) {
+            $date = date('Ym', $timestamp);
+            $year = intval(date('Y', $timestamp));
+            $quarter = ceil(intval(date('n', $timestamp)) / 3);
+            if(! isset($quarters[$year]) || ! in_array($quarter,$quarters[$year])){
+                $quarters[$year][] = $quarter;
+                $out_time[] = $date;
+            }
+        }
+        return $out_time;
+    }
+
+    //班组
+    public function teamReport($data){
+        if(empty($data['finish_time'][0]) || empty($data['finish_time'][1])) return [false, '完工时间必须选择!'];
+
+        //班组
+        $team_id = $data['team_id'] ?? [];
+        //根据完工时间 扩大时间戳范围前后三个月
+        $new_finish_time = $this->increaseTimeArea($data['finish_time']);
+        //根据时间戳范围 获取分表的时间
+        $return_time = $this->getTimeAreaData($new_finish_time);
+
+        //检索分表数据
+        $result = $team = [];
+        foreach ($return_time as $value){
+            //子表搜索
+            $models = new OrdersProductProcess(['channel' => $value]);
+            $tmp = $models->where('del_time',0)
+                ->whereBetween('finished_time',[$data['finish_time'][0], $data['finish_time'][1]])
+                ->where('status',2)
+                ->when(!empty($team_id), function ($query) use ($team_id) {
+                    return $query->whereIn('team_id', $team_id);
+                })
+                ->select('team_id','finished_time','production_no')
+                ->get()->toArray();//完工数据
+            $result = array_merge_recursive($result,$tmp);
+            $team = array_merge_recursive($team,array_unique(array_column($tmp,'team_id')));
+        }
+
+        if(empty($result)) return [true , []];
+
+        //组织数据
+        $team_map = Team::whereIn('id',array_unique($team))
+            ->pluck('title','id')
+            ->toArray();
+        $return_team = $return_team_time_tmp = $return_team_time= [];
+        date_default_timezone_set("PRC");
+        foreach ($result as $value){
+            if(isset($return_team[$value['team_id']])){
+                $return_team[$value['team_id']]['num'] += 1;
+                if(! in_array($value['production_no'], $return_team[$value['team_id']]['production_no'])) {
+                    $return_team[$value['team_id']]['production_no'] = array_merge_recursive($return_team[$value['team_id']]['production_no'],[$value['production_no']]);
+                }
+            }else{
+                $return_team[$value['team_id']] = [
+                    'num' => 1,
+                    'team_name' => $team_map[$value['team_id']] ?? '',
+                    'production_no' => [$value['production_no']]
+                ];
+            }
+
+            $tmp = date("Y-m-d",$value['finished_time']);
+            if(isset($return_team_time_tmp[$tmp][$value['team_id']])){
+                $return_team_time_tmp[$tmp][$value['team_id']]['num'] += 1;
+            }else{
+                $return_team_time_tmp[$tmp][$value['team_id']] = [
+                    'time' => $tmp,
+                    'num' => 1,
+                    'team_name' => $team_map[$value['team_id']] ?? '',
+                ];
+            }
+        }ksort($return_team_time_tmp);unset($result);
+
+        $all_team_map = Team::where('del_time',0)
+            ->pluck('title','id')
+            ->toArray();
+        foreach ($return_team_time_tmp as $key => $value){
+            $t_k = array_keys($value);
+            foreach ($all_team_map as $k => $v){
+                if(! in_array($k,$t_k)){
+                    $return_team_time_tmp[$key][$k] = [
+                        'time' => $key,
+                        'num' => 0,
+                        'team_name' => $v,
+                    ];
+                }
+            }
+            ksort($return_team_time_tmp[$key]);
+            $tmp = [];
+            $tmp['time'] = $key;
+            $tmp['sub'] = array_values($return_team_time_tmp[$key]);
+            $return_team_time[] = $tmp;
+        }unset($return_team_time_tmp);
+
+        //列表数据 图表数据
+        return [true,['list'=>array_values($return_team),'chart'=>$return_team_time]];
+    }
+
+    private function increaseTimeArea($time_area){
+        // 增加三个月的时间戳
+        $newStartTimestamp = strtotime('-3 months', $time_area[0]);
+        $newEndTimestamp = strtotime('+3 months', $time_area[1]);
+
+        return [$newStartTimestamp,$newEndTimestamp];
+    }
+
+    private function getTimeAreaData($time_area){
+        $startYear = date('Y', $time_area[0]);
+        $endYear = date('Y', $time_area[1]);
+
+        $return = [];
+
+        for ($year = $startYear; $year <= $endYear; $year++) {
+            for ($quarter = 1; $quarter <= 4; $quarter++) {
+                $quarterStart = strtotime($year . '-' . (($quarter - 1) * 3 + 1) . '-01');
+                $quarterEnd = strtotime($year . '-' . ($quarter * 3) . '-01') - 1;
+
+                if ($quarterStart <= $time_area[1] && $quarterEnd >= $time_area[0]) {
+//                    $tmp = $year . sprintf('%02d', $quarter);//年季度
+                    $return[] = $year .sprintf('%02d',($quarter - 1) * 3 + 1);
+                }
+            }
+        }
+
+        return $return;
+    }
+
+    //班组 详情
+    public function teamReportDetail($data){
+        if(empty($data['production_no'])) return [false,'生产订单号不能为空!'];
+
+        $list = OrdersProduct::whereIn('production_no',$data['production_no'])
+            ->select('production_time','production_no','customer_no','customer_name','table_header_mark','product_no','product_title','product_size','product_unit','dispatch_complete_quantity','finished_num','technology_material','technology_name','wood_name','process_mark','table_body_mark')
+            ->get()->toArray();
+
+        date_default_timezone_set("PRC");
+        foreach ($list as $key => $value) {
+            $list[$key]['production_time'] = $value['production_time'] ? date('Y-m-d',$value['production_time']) : '';
+        }
+
+        return [true,$list];
+    }
+
+    //不良品
+    public function badGoodsReport($data){
+        if(empty($data['production_time'][0]) || empty($data['production_time'][1])) return [false, '生产订单时间必须选择!'];
+
+        //检索条件 生产订单主表----------------
+        $model = OrdersProduct::where('del_time',0)->select('production_time','production_no','out_order_no','out_order_no_time','customer_no','customer_name','table_header_mark','order_quantity','production_quantity','out_crt_man');
+        $model->whereBetween('production_time',[$data['production_time'][0],$data['production_time'][1]]);
+        if(! empty($data['production_no'])) $model->where('production_no', 'LIKE', '%'.$data['production_no'].'%');
+        if(! empty($data['out_order_no_time'][0]) && ! empty($data['out_order_no_time'][1])) $model->whereBetween('out_order_no_time',[$data['out_order_no_time'][0],$data['out_order_no_time'][1]]);
+        if(! empty($data['out_order_no'])) $model->where('out_order_no', 'LIKE', '%'.$data['out_order_no'].'%');
+        if(! empty($data['customer_no'])) $model->where('customer_no', 'LIKE', '%'.$data['customer_no'].'%');
+        if(! empty($data['customer_name'])) $model->where('customer_name', 'LIKE', '%'.$data['customer_name'].'%');
+        if(! empty($data['out_crt_man'])) $model->where('out_crt_man', 'LIKE', '%'.$data['out_crt_man'].'%');
+        $orderList = $model->get()->toArray();
+        //生产订单主表----------------
+
+        //筛选出制单日期 分表的依据
+        $out_order_no_time = array_unique(array_column($orderList,'out_order_no_time'));
+        //制单日期
+        $out_time = $this->checkSameQuarter($out_order_no_time);
+
+        //分组以后的订单列表
+        $list = [];
+        foreach ($orderList as $value){
+            if(! isset($list[$value['production_no']])){
+                $list[$value['production_no']] = $value;
+            }else{
+                $list[$value['production_no']]['order_quantity'] += $value['order_quantity'];
+                $list[$value['production_no']]['production_quantity'] += $value['production_quantity'];
+            }
+        }unset($orderList);
+
+        //查询分表数据
+        $production_no = array_column($list,'production_no');
+        $detail = [];
+        foreach ($out_time as $value){
+            //子表搜索
+            $models = new OrdersProductProcess(['channel' => $value]);
+            $tmp = $models->whereIn('production_no',$production_no)
+                ->where('del_time',0)
+                ->where('status',4)
+                ->select('production_no',DB::raw('COUNT(id) as bad_goods_num'))
+                ->groupBy('production_no')
+                ->get()->toArray();//不良品数据
+
+            foreach ($tmp as $t){
+                if(isset($detail[$t['production_no']])){
+                    $detail[$t['production_no']]['bad_goods_num'] += $t['bad_goods_num'];
+                }else{
+                    $detail[$t['production_no']] = $t;
+                }
+            }
+        }
+
+        //返回统计数据
+        date_default_timezone_set("PRC");
+        foreach ($list as $key => $value) {
+            $list[$key]['production_time'] = $value['production_time'] ? date('Y-m-d',$value['production_time']) : '';
+            $list[$key]['out_order_no_time'] = $value['out_order_no_time'] ? date('Y-m-d',$value['out_order_no_time']) : '';
+
+            $del_num = $detail[$value['production_no']] ?? 0;
+            $list[$key]['bad_goods_num'] = $del_num;
+            $list[$key]['rate'] = number_format($del_num / $value['production_quantity'], 2);
+        }
+
+        return [true,array_values($list)];
+    }
+
+    //不良品 详情
+    public function badGoodsReportDetail($data){
+        if(empty($data['production_no'])) return [false,'生产订单号不能为空!'];
+
+        $list = OrdersProduct::where('production_no',$data['production_no'])
+            ->select('id','production_time','production_no','out_order_no','out_order_no_time','customer_no','customer_name','table_header_mark','product_no','product_title','product_size','product_unit','dispatch_complete_quantity','finished_num','technology_material','technology_name','wood_name','process_mark','table_body_mark','out_crt_man','production_quantity')
+            ->get()->toArray();
+
+        //筛选出制单日期 分表的依据
+        $out_order_no_time = array_unique(array_column($list,'out_order_no_time'));
+        //制单日期
+        $out_time = $this->checkSameQuarter($out_order_no_time);
+
+        $detail = $detail_scrapp = [];
+        foreach ($out_time as $value){
+            //子表搜索
+            $models = new OrdersProductProcess(['channel' => $value]);
+            $tmp = $models->where('production_no',$data['production_no'])
+                ->where('del_time',0)
+                ->where('status',4)
+                ->select('order_product_id',DB::raw('COUNT(id) as bad_goods_num'), DB::raw("GROUP_CONCAT(DISTINCT scrapp_id ORDER BY scrapp_id SEPARATOR ',') as scrapp_ids"))
+                ->groupBy('order_product_id')
+                ->get()
+                ->toArray();//不良品数据
+
+            foreach ($tmp as $v){
+                if(isset($detail[$v['order_product_id']])){
+                    $detail[$v['order_product_id']] += $v['bad_goods_num'];
+                }else{
+                    $detail[$v['order_product_id']] = $v['bad_goods_num'];
+                }
+                if(isset($detail_scrapp[$v['order_product_id']])){
+                    $detail_scrapp[$v['order_product_id']] .= "," . $v['scrapp_ids'];
+                }else{
+                    $detail_scrapp[$v['order_product_id']] = $v['scrapp_ids'];
+                }
+            }
+        }
+
+        date_default_timezone_set("PRC");
+
+        $scrapp_map = Scrapp::where('del_time',0)->pluck('title','id')->toArray();
+        foreach ($list as $key => $value) {
+            $list[$key]['production_time'] = $value['production_time'] ? date('Y-m-d',$value['production_time']) : '';
+            $list[$key]['out_order_no_time'] = $value['out_order_no_time'] ? date('Y-m-d',$value['out_order_no_time']) : '';
+            $list[$key]['bad_goods_num'] = $detail[$value['id']] ?? 0;
+            $list[$key]['rate'] =  number_format($list[$key]['bad_goods_num'] / $value['production_quantity'], 2);
+            $scrapp = $detail_scrapp[$value['id']] ?? '';
+            $tmp_str = '';
+            if(! empty($scrapp)){
+                $tmp = explode(',',$scrapp);
+                foreach ($tmp as $vv){
+                    $tmp_str .= ($scrapp_map[$vv] ? $scrapp_map[$vv] . ',' : '');
+                }
+            }
+            $list[$key]['scrapp_name'] = rtrim($tmp_str,',');
+        }
+        return [true, $list];
+    }
+
+    //不良品原因
+    public function badGoodsReasonReport($data){
+        if(empty($data['production_time'][0]) || empty($data['production_time'][1])) return [false, '生产订单时间必须选择!'];
+
+        //检索条件 生产订单主表----------------
+        $model = OrdersProduct::where('del_time',0)->select('production_time','production_no','out_order_no','out_order_no_time','customer_no','customer_name','table_header_mark','order_quantity','production_quantity','out_crt_man');
+        $model->whereBetween('production_time',[$data['production_time'][0],$data['production_time'][1]]);
+        if(! empty($data['production_no'])) $model->where('production_no', 'LIKE', '%'.$data['production_no'].'%');
+        if(! empty($data['out_order_no_time'][0]) && ! empty($data['out_order_no_time'][1])) $model->whereBetween('out_order_no_time',[$data['out_order_no_time'][0],$data['out_order_no_time'][1]]);
+        if(! empty($data['out_order_no'])) $model->where('out_order_no', 'LIKE', '%'.$data['out_order_no'].'%');
+        if(! empty($data['customer_no'])) $model->where('customer_no', 'LIKE', '%'.$data['customer_no'].'%');
+        if(! empty($data['customer_name'])) $model->where('customer_name', 'LIKE', '%'.$data['customer_name'].'%');
+        if(! empty($data['out_crt_man'])) $model->where('out_crt_man', 'LIKE', '%'.$data['out_crt_man'].'%');
+        $orderList = $model->get()->toArray();
+        //生产订单主表----------------
+
+        //筛选出制单日期 分表的依据
+        $out_order_no_time = array_unique(array_column($orderList,'out_order_no_time'));
+        //制单日期
+        $out_time = $this->checkSameQuarter($out_order_no_time);
+
+        //分组以后的订单列表
+        $list = [];
+        foreach ($orderList as $value){
+            if(! isset($list[$value['production_no']])){
+                $list[$value['production_no']] = $value;
+            }else{
+                $list[$value['production_no']]['order_quantity'] += $value['order_quantity'];
+                $list[$value['production_no']]['production_quantity'] += $value['production_quantity'];
+            }
+        }unset($orderList);
+
+        //查询分表数据
+        $production_no = array_column($list,'production_no');
+        $detail = [];
+        foreach ($out_time as $value){
+            //子表搜索
+            $models = new OrdersProductProcess(['channel' => $value]);
+            $tmp = $models->whereIn('production_no',$production_no)
+                ->where('del_time',0)
+                ->where('status',4)
+                ->select('production_no',DB::raw('COUNT(id) as bad_goods_num'))
+                ->groupBy('production_no')
+                ->get()->toArray();//不良品数据
+
+            foreach ($tmp as $t){
+                if(isset($detail[$t['production_no']])){
+                    $detail[$t['production_no']]['bad_goods_num'] += $t['bad_goods_num'];
+                }else{
+                    $detail[$t['production_no']] = $t;
+                }
+            }
+        }
+
+        //返回统计数据
+        date_default_timezone_set("PRC");
+        foreach ($list as $key => $value) {
+            $list[$key]['production_time'] = $value['production_time'] ? date('Y-m-d',$value['production_time']) : '';
+            $list[$key]['out_order_no_time'] = $value['out_order_no_time'] ? date('Y-m-d',$value['out_order_no_time']) : '';
+
+            $del_num = $detail[$value['production_no']] ?? 0;
+            $list[$key]['bad_goods_num'] = $del_num;
+            $list[$key]['rate'] = number_format($del_num / $value['production_quantity'], 2);
+        }
+
+        return [true,array_values($list)];
+    }
+
+    //不良品原因 详情
+    public function badGoodsReasonReportDetail($data){
+        if(empty($data['production_no'])) return [false,'生产订单号不能为空!'];
+
+        $list = OrdersProduct::where('production_no',$data['production_no'])
+            ->select('id','production_time','production_no','out_order_no','out_order_no_time','customer_no','customer_name','table_header_mark','product_no','product_title','product_size','product_unit','dispatch_complete_quantity','finished_num','technology_material','technology_name','wood_name','process_mark','table_body_mark','out_crt_man','production_quantity')
+            ->get()->toArray();
+
+        //筛选出制单日期 分表的依据
+        $out_order_no_time = array_unique(array_column($list,'out_order_no_time'));
+        //制单日期
+        $out_time = $this->checkSameQuarter($out_order_no_time);
+
+        $detail = $scrapp_id = $team = $man = [];
+        foreach ($out_time as $value){
+            //子表搜索
+            $models = new OrdersProductProcess(['channel' => $value]);
+            $tmp = $models->where('production_no',$data['production_no'])
+                ->where('del_time',0)
+                ->where('status',4)
+                ->select('order_product_id','scrapp_id','team_id','finished_id',DB::raw('COUNT(id) as bad_goods_num'))
+                ->groupBy('order_product_id','scrapp_id')
+                ->get()->toArray();//不良品数据
+
+            foreach ($tmp as $v){
+                if(! in_array($v['scrapp_id'], $scrapp_id)) $scrapp_id[] = $v['scrapp_id'];
+                if(! in_array($v['team_id'], $team)) $team[] = $v['team_id'];
+                if(! in_array($v['finished_id'], $man)) $man[] = $v['finished_id'];
+                if(isset($detail[$v['order_product_id']])){
+                    foreach ($detail[$v['order_product_id']] as $k => $d){
+                        if($d['scrapp_id'] == $v['scrapp_id']){
+                            $detail[$v['order_product_id']][$k]['bad_goods_num'] += $v['bad_goods_num'];
+                        }else{
+                            $detail[$v['order_product_id']][] = $v;
+                        }
+                    }
+                }else{
+                    $detail[$v['order_product_id']][] = $v;
+                }
+            }
+        }
+
+        date_default_timezone_set("PRC");
+        //次品原因 班组 人员
+        $map = Scrapp::whereIn('id',$scrapp_id)
+            ->pluck('title','id')
+            ->toArray();
+        $map1 = Team::whereIn('id',$team)
+            ->pluck('title','id')
+            ->toArray();
+        $map2 = Employee::whereIn('id',$man)
+            ->pluck('emp_name','id')
+            ->toArray();
+        foreach ($list as $key => $value) {
+            $list[$key]['production_time'] = $value['production_time'] ? date('Y-m-d',$value['production_time']) : '';
+            $list[$key]['out_order_no_time'] = $value['out_order_no_time'] ? date('Y-m-d',$value['out_order_no_time']) : '';
+            $list[$key]['rate'] =  number_format(($detail[$value['id']] ?? 0) / $value['production_quantity'], 2);
+            $del_tmp = $detail[$value['id']] ?? [];
+            foreach ($del_tmp as $dk => $dv){
+                $del_tmp[$dk]['rate'] = number_format($dv['bad_goods_num'] / $value['production_quantity'], 2);
+                $del_tmp[$dk]['scrapp_name'] = $map[$dv['scrapp_id']] ?? '';
+                $del_tmp[$dk]['team_name'] = $map1[$dv['team_id']] ?? '';
+                $del_tmp[$dk]['man_name'] = $map2[$dv['finished_id']] ?? '';
+            }
+            $list[$key]['bad_goods'] = $del_tmp;
+        }
+        return [true, $list];
+    }
+}

+ 20 - 0
routes/api.php

@@ -24,6 +24,7 @@ Route::any('getHeaderSetting', 'Api\HeaderWordController@getHeaderSettings');
 Route::any('deviceList', 'Api\Device\DeviceController@deviceList');
 Route::any('fyy_set','Api\FyyOrderController@setFyy');
 Route::any('getProductionOrder/{file_name}','Api\ProductionOrderController@getItemFile');
+Route::any('getCloudData','Api\CloudDataController@getCloudData');
 
 //测试接口
 Route::any('test', 'Api\TestController@aa');
@@ -40,6 +41,16 @@ Route::any('capacity','Api\TestController@capacity');
 Route::any('product_num','Api\TestController@product_num');
 Route::any('work_order','Api\TestController@work_order');
 Route::any('nu_work_order','Api\TestController@nu_work_order');
+
+//Route::any('output_value','Api\ScreenController@output_value');
+//Route::any('order_process1','Api\ScreenController@order_process1');
+//Route::any('project_region','Api\ScreenController@project_region');
+//Route::any('output_value_month1','Api\ScreenController@output_value_month1');
+//Route::any('output_value_efficiency','Api\ScreenController@output_value_efficiency');
+//Route::any('capacity','Api\ScreenController@capacity');
+//Route::any('product_num','Api\ScreenController@product_num');
+//Route::any('work_order','Api\ScreenController@work_order');
+//Route::any('nu_work_order','Api\ScreenController@nu_work_order');
 Route::group(['middleware'=> ['checkLogin']],function ($route){
     $route->any('HeaderSettingsAdd', 'Api\HeaderWordController@add');
     $route->any('HeaderSettingsDetail', 'Api\HeaderWordController@detail');
@@ -169,6 +180,15 @@ Route::group(['middleware'=> ['checkLogin']],function ($route){
     //队列任务错误列表
     $route->any('errorList','Api\ErrorOperationController@errorList');
 
+    //报表
+    $route->any('productionReport', 'Api\ReportFormsController@productionReport');
+    $route->any('teamReport', 'Api\ReportFormsController@teamReport');
+    $route->any('teamReportDetail','Api\ReportFormsController@teamReportDetail');
+    $route->any('badGoodsReport', 'Api\ReportFormsController@badGoodsReport');
+    $route->any('badGoodsReportDetail','Api\ReportFormsController@badGoodsReportDetail');
+    $route->any('badGoodsReasonReport', 'Api\ReportFormsController@badGoodsReasonReport');
+    $route->any('badGoodsReasonReportDetail','Api\ReportFormsController@badGoodsReasonReportDetail');
+
     $route->any('productList', 'Api\MaterialController@productList');
     $route->any('productEdit', 'Api\MaterialController@edit');
     $route->any('productAdd', 'Api\MaterialController@edd');