| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665 |
- <?php
- namespace App\Http\Controllers;
- use App\Components\AsyncResponse;
- use App\Jobs\OrderCreateInstantBill;
- use App\Jobs\ResetInstantBill;
- use App\Jobs\SettlementBillReportJob;
- use App\Jobs\StoreCreateInstantBill;
- use App\Order;
- use App\Owner;
- use App\OwnerAreaReport;
- use App\OwnerBillReport;
- use App\OwnerFeeDetail;
- use App\OwnerFeeExpress;
- use App\OwnerFeeLogistic;
- use App\OwnerFeeOperation;
- use App\OwnerFeeOperationDetail;
- use App\OwnerFeeStorage;
- use App\OwnerPriceSystem;
- use App\OwnerReport;
- use App\Services\LogService;
- use App\Services\ObligationService;
- use App\Services\OwnerAreaReportService;
- use App\Services\OwnerBillReportService;
- use App\Services\OwnerReportService;
- use App\Services\OwnerService;
- use App\Store;
- use App\UserWorkgroup;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Http\Request;
- use Illuminate\Http\Response;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Gate;
- use Illuminate\Support\Facades\Validator;
- use Oursdreams\Export\Export;
- class CustomerController extends Controller
- {
- use AsyncResponse;
- /**
- * Display a listing of the resource.
- * @param Request $request
- * @return Response
- */
- public function projectReport(Request $request)
- {
- if(!Gate::allows('项目管理-项目-报表')){ return view('customer.index'); }
- $withs = ["ownerBillReport","owner"=>function($query){
- /** @var Builder $query */
- $query->select("id","warehouse_id","name","deleted_at","created_at","customer_id","user_owner_group_id")
- ->with(["customer","userOwnerGroup","warehouse","ownerAreaReport"]);
- }];
- $ownerGroups = app('UserOwnerGroupService')->getSelection();
- $customers = app('CustomerService')->getSelection();
- $owners = app('OwnerService')->getIntersectPermitting();
- $reports = app("OwnerReportService")->paginate($request->input(),$withs);
- $params = $request->input();
- return response()->view('personnel.report',compact("reports","ownerGroups","customers","owners","params"));
- }
- public function projectReportExport(Request $request)
- {
- if(!Gate::allows('项目管理-项目-报表')){ return redirect('denied'); }
- /** @var OwnerReportService $service */
- $service = app('OwnerReportService');
- $withs = ["ownerBillReport","owner"=>function($query){
- /** @var Builder $query */
- $query->select("id","name","deleted_at","created_at","customer_id","user_owner_group_id")
- ->with(["customer","userOwnerGroup"]);
- }];
- if ($request->checkAllSign ?? false){
- $params = $request->input();
- unset($params['checkAllSign']);
- $reports = $service->get($params,$withs);
- }else $reports = $service->get(["id"=>$request->data ?? ''],$withs);
- $column = ["项目小组","客户","子项目","状态","创建日期","在库时长","结算月","日均单量","结算月上月盘点面积","结算月盘点面积","初始账单金额","确认账单金额","确认日期"];
- $list = [];
- foreach ($reports as $report){
- $list[] = [
- $report->owner ? ($report->owner->userOwnerGroup ? $report->owner->userOwnerGroup->name : '') : '',
- $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
- $report->owner ? $report->owner->name : '',
- $report->owner ? ($report->owner->deleted_at ? "冻结" : "激活") : '',
- $report->owner ? (string)$report->owner->created_at : '',
- $report->owner ? ($report->owner->created_at ? ((new \DateTime())->diff(new \DateTime($report->owner->created_at))->days)." 天" : '') : '',
- $report->counting_month,
- $report->daily_average_order_amount,
- $report->last_month_counting_area,
- $report->current_month_counting_area,
- $report->ownerBillReport ? $report->ownerBillReport->initial_fee : '',
- $report->ownerBillReport ? $report->ownerBillReport->confirm_fee : '',
- $report->ownerBillReport ? (string)$report->ownerBillReport->updated_at : '',
- ];
- }
- return Export::make($column,$list,"客户项目报表");
- }
- public function projectIndex()
- {
- if(!Gate::allows('项目管理-项目-查询')){ return redirect('denied'); }
- /** @var OwnerService $service */
- $service = app('OwnerService');
- $owners = $service->paginate(request()->input(),['customer',"userOwnerGroup","userWorkGroup",'departmentObligationOwner.department',
- "ownerStoragePriceModels","storageAudit","operationAudit","expressAudit","logisticAudit","directLogisticAudit","systemAudit"]);
- $owners=app('OwnerService')->combineOwners($owners);
- $models = app('OwnerService')->getIntersectPermitting();
- $customers = app('CustomerService')->getSelection();
- $ownerGroups = app('UserOwnerGroupService')->getSelection();
- $params = request()->input();
- $userWorkGroups = UserWorkgroup::all();
- return response()->view('customer.project.index',compact("owners","models","customers","ownerGroups","params",'userWorkGroups'));
- }
- public function projectIndexExport(Request $request)
- {
- if(!Gate::allows('项目管理-项目-查询')){ return redirect('denied'); }
- /** @var OwnerService $service */
- $service = app('OwnerService');
- $withs = ['customer',"userOwnerGroup","contracts","taxRate","ownerStoragePriceModels","ownerAreaReport"=>function($query){
- $month = date('Y-m');
- /** @var Builder $query */
- $query->where("counting_month","like",$month."%");
- }];
- $params = $request->input();
- $params['customer_id']=true;
- if ($request->checkAllSign ?? false) unset($params['checkAllSign']);
- else $params = ["id"=>$request->data ?? ''];
- $owners = $service->get($params,$withs);
- $column = ["客户","税率","项目","货主代码","创建日期","合同号","销售名称","公司全称","联系人","联系电话","项目小组","用仓类型","当月结算面积","月单量预警","是否激活","项目描述"];
- $list = [];
- foreach ($owners as $owner){
- $list[] = [
- $owner->customer ? $owner->customer->name : '',
- $owner->taxRate->name ?? '',
- $owner->name,
- $owner->code,
- $owner->created_at,
- implode("\r\n",array_column($owner->contracts,"contract_number")),
- implode("\r\n",array_column($owner->contracts,"salesman")),
- $owner->customer ? $owner->customer->company_name : '',
- $owner->linkman,
- $owner->phone_number,
- $owner->userOwnerGroup ? $owner->userOwnerGroup->name : '',
- implode(",",array_unique(array_column(($owner->ownerStoragePriceModels)->toArray(),"using_type"))),
- $owner->ownerAreaReport ? $owner->ownerAreaReport->accounting_area : '',
- $owner->waring_line_on,
- $owner->deleted_at ? '否' : '是',
- $owner->description
- ];
- }
- return Export::make($column,$list,"客户报表");
- }
- public function projectCreate()
- {
- if(!Gate::allows('项目管理-项目-录入')){ return redirect('denied'); }
- $customers = app('CustomerService')->getSelection();
- $ownerGroups = app('UserOwnerGroupService')->getSelection();
- $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
- $warehouses = app('WarehouseService')->getSelection();
- $owner = null;
- return response()->view('customer.project.create',compact("customers","ownerGroups","owner","warehouses","userGroups"));
- }
- public function projectUpdate()
- {
- $this->gate("项目管理-项目-录入");
- if (!request("id"))$this->error("项目不存在,无法补充详细信息");
- $errors = $this->validator(request()->input())->errors();
- if (count($errors)>0)$this->success(["errors"=>$errors]);
- /** @var Owner $owner */
- $owner = app('OwnerService')->find(request("id"));
- if (!$owner)$this->error("项目已被删除,无法操作");
- //if ($owner->tax_rate_id && !request("tax_rate_id"))app('OwnerService')->attachTaxRate($owner);
- //if (!$owner->tax_rate_id && request("tax_rate_id"))app('OwnerService')->removeTaxRate($owner);
- $owner = app('OwnerService')->update($owner,[
- "customer_id" => request("customer_id"),
- "warehouse_id" => request("warehouse_id"),
- "tax_rate_id" => request("tax_rate_id"),
- "linkman" => request("linkman"),
- "phone_number" => request("phone_number"),
- "user_owner_group_id" => request("owner_group_id"),
- "user_workgroup_id" => request("user_workgroup_id"),
- "waring_line_on" => request("waring_line_on"),
- "description" => request("description"),
- "subjection" => request("subjection"),
- "is_tax_exist" => request("is_tax_exist") ? 'Y' : 'N',
- ]);
- /** @var ObligationService $service*/
- $service= app('ObligationService');
- $owner=$service->createOrUpdate(request()->input());
- $this->success($owner);
- }
- //获取货主下所有相关计费模型
- public function getOwnerPriceModel(Request $request)
- {
- $owner = new Owner();
- $owner->id = $request->id;
- $owner->load(["ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics"]);
- return ["success"=>true,"data"=>["ownerPriceOperations"=>$owner->ownerPriceOperations,
- "ownerPriceExpresses"=>$owner->ownerPriceExpresses,
- "ownerPriceLogistics"=>$owner->ownerPriceLogistics,
- "ownerPriceDirectLogistics"=>$owner->ownerPriceDirectLogistics]];
- }
- public function projectEdit($id)
- {
- if(!Gate::allows('项目管理-项目-编辑')){ return redirect('denied'); }
- /** @var Owner $owner */
- $owner = app('OwnerService')->find($id,['departmentObligationOwner']);
- $departmentObligationOwner=$owner->departmentObligationOwner??[];
- if (count($departmentObligationOwner)>0){
- foreach ($departmentObligationOwner as $item){
- if ($item->obligation_code=='kc')$owner->kc=$item->department_id;
- if ($item->obligation_code=='jg')$owner->jg=$item->department_id;
- if ($item->obligation_code=='th')$owner->th=$item->department_id;
- if ($item->obligation_code=='sh')$owner->sh=$item->department_id;
- if ($item->obligation_code=='fh')$owner->fh=$item->department_id;
- }
- }
- $owner->loadCount(["ownerStoragePriceModels","ownerPriceOperations","ownerPriceExpresses","ownerPriceLogistics","ownerPriceDirectLogistics","ownerPriceSystem"]);
- $isExist = false;
- /** @var \stdClass $owner */
- if($owner->owner_storage_price_models_count ||
- $owner->owner_price_operations_count ||
- $owner->owner_price_expresses_count ||
- $owner->owner_price_logistics_count ||
- $owner->owner_price_system_count ||
- $owner->owner_price_direct_logistics_count) $isExist = true;
- $customers = app('CustomerService')->getSelection();
- $ownerGroups = app('UserOwnerGroupService')->getSelection();
- $userGroups = app('UserWorkgroupService')->getSelection(["id","name","warehouse_id"]);
- $warehouses = app('WarehouseService')->getSelection();
- $type = request("type");
- return response()->view('customer.project.create',compact("customers","ownerGroups","warehouses",'owner',"isExist", "type","userGroups"));
- }
- public function projectArea(Request $request)
- {
- if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
- $areas = app('OwnerAreaReportService')->paginate($request->input(),["owner.customer","ownerStoragePriceModel.unit","userOwnerGroup"]);
- $ownerGroups = app('UserOwnerGroupService')->getSelection();
- $customers = app('CustomerService')->getSelection();
- $owners = app('OwnerService')->getIntersectPermitting();
- $params = $request->input();
- return response()->view('customer.project.area',compact("areas","ownerGroups","customers","owners","params"));
- }
- public function updateArea()
- {
- $this->gate("项目管理-项目-面积-编辑");
- if (!request("id")) $this->error("非法参数");
- $total = ((int)request("areaOnTray")*2.5) +
- ((int)request("areaOnHalfTray")*1.8) + ((int)request("areaOnFlat")*1.3);
- $obj = [
- "user_owner_group_id" => request("ownerGroupId"),
- "area_on_tray" => request("areaOnTray"),
- "area_on_half_tray" => request("areaOnHalfTray"),
- "area_on_flat" => request("areaOnFlat"),
- "accounting_area" => intval($total*1000)/1000,
- ];
- $re = app('OwnerAreaReportService')->update(["id"=>request("id")],$obj);
- if ($re===true)$this->success($obj);
- else $this->error($re);
- }
- //面积报表审核
- public function areaReportAudit()
- {
- $this->gate("项目管理-项目-用仓盘点-审核");
- $id = request("id");
- if(!$id)$this->error("非法参数");
- $area = OwnerAreaReport::query()->find($id);
- /** @var \stdClass $area */
- if (!$area || $area->status!='编辑中')$this->error("记录已被操作");
- $area->update(["status"=>"已审核"]);
- $this->success();
- }
- public function projectAreaExport(Request $request)
- {
- if(!Gate::allows('项目管理-项目-面积')){ return redirect('denied'); }
- $params = $request->input();
- if ($request->checkAllSign)unset($params['checkAllSign']);
- else $params = ["id"=>$request->data];
- /** @var OwnerAreaReportService $serves */
- $serves = app('OwnerAreaReportService');
- $areas = $serves->get($params,["owner"=>function($query){$query->with(["customer","ownerStoragePriceModels","userOwnerGroup"]);}]);
- $column = ["状态","项目组","客户","子项目","结算月","录入时间","用仓类型","货物整托","货物半托","平面区面积","结算面积"];
- $list = [];
- foreach ($areas as $area){
- $list[] = [
- $area->status,
- $area->owner ? ($area->owner->userOwnerGroup ? $area->owner->userOwnerGroup->name : '') : '',
- $area->owner ? ($area->owner->customer ? $area->owner->customer->name : '') : '',
- $area->owner ? $area->owner->name : '',
- $area->counting_month,
- $area->updated_at,
- $area->owner ? implode(",",array_unique(array_column(($area->owner->ownerStoragePriceModels)->toArray(),"using_type"))) : '',
- $area->area_on_tray,
- $area->area_on_half_tray,
- $area->area_on_flat,
- $area->accounting_area,
- ];
- }
- return Export::make($column,$list,"项目面积报表");
- }
- public function financeInstantBill(Request $request)
- {
- if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
- $params = $request->input();
- $shops = app('ShopService')->getSelection();
- $customers = app('CustomerService')->getSelection();
- $owners = app('OwnerService')->getIntersectPermitting();
- $details = app('OwnerFeeDetailService')->paginate($params,["owner.customer","shop","processMethod","logistic","items"]);
- return response()->view('finance.instantBill',compact("details","params","shops","customers","owners"));
- }
- public function financeInstantBillExport(Request $request)
- {
- if(!Gate::allows('结算管理-即时账单')){ return redirect('denied'); }
- $params = $request->input();
- if ($request->checkAllSign)unset($params['checkAllSign']);
- else $params = ["id"=>$request->data];
- $sql = app('OwnerFeeDetailService')->getSql($params);
- $rule = ["work_fee"=>"mysqlDate"];
- $e = new Export();
- $e->setMysqlConnection(config('database.connections.mysql.host'),
- config('database.connections.mysql.port'),config('database.connections.mysql.database')
- ,config('database.connections.mysql.username'),config('database.connections.mysql.password'));
- $e->setFileName("即时账单记录");
- return $e->sql($sql,[
- "customer_name"=>"客户","owner_name"=>"项目",
- "worked_at"=>"作业时间","type"=>"类型",
- "shop_name"=>"店铺","operation_bill"=>"单号(发/收/退/提)",
- "consignee_name"=>"收件人","consignee_phone"=>"收件人电话",
- "commodity_amount"=>"商品数量","logistic_bill"=>"物流/快递单号",
- "volume"=>"体积","weight"=>"重量","logistic_name"=>"承运商",
- "work_fee"=>"操作费","logistic_fee"=>"物流费","total"=>"合计"
- ],$rule)->direct();
- }
- public function financeBillConfirmation(Request $request)
- {
- if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
- $params = $request->input();
- $ownerGroups = app('UserOwnerGroupService')->getSelection();
- $customers = app('CustomerService')->getSelection();
- $owners = app('OwnerService')->getIntersectPermitting();
- $bills = app('OwnerBillReportService')->paginate($params,["owner"=>function($query){
- /** @var Builder $query */
- $query->with(["customer","userOwnerGroup"]);
- }]);
- return response()->view('finance.billConfirmation',compact("params","owners","ownerGroups","customers","bills"));
- }
- public function financeBillConfirmationExport(Request $request)
- {
- if(!Gate::allows('结算管理-账单确认')){ return redirect('denied'); }
- $params = $request->input();
- if ($request->checkAllSign)unset($params['checkAllSign']);
- else $params = ["id"=>$request->data];
- /** @var OwnerBillReportService $serves */
- $serves = app('OwnerBillReportService');
- $bills = $serves->get($params,["owner"=>function($query){
- /** @var Builder $query */
- $query->with(["customer","userOwnerGroup"]);
- }]);
- $column = ["项目小组","客户","子项目","结算月","录入日期","原始账单金额","确认账单金额","差额","状态"];
- $list = [];
- foreach ($bills as $bill){
- $list[] = [
- $bill->owner ? ($bill->owner->userOwnerGroup ? $bill->owner->userOwnerGroup->name : '') : '',
- $bill->owner ? ($bill->owner->customer ? $bill->owner->customer->name : '') : '',
- $bill->owner ? $bill->owner->name : '',
- $bill->counting_month,
- $bill->updated_at,
- $bill->initial_fee,
- $bill->confirm_fee,
- $bill->difference,
- $bill->confirmed == '是' ? '已确认' : '未确认',
- ];
- }
- return Export::make($column,$list,"客户账单报表");
- }
- public function updateBillReport(Request $request)
- {
- if(!Gate::allows('结算管理-账单确认-编辑')){ return ["success"=>false,'data'=>"无权操作!"]; }
- if (!$request->confirm_fee || !is_numeric($request->confirm_fee) || $request->confirm_fee<0)return ["success"=>false,"data"=>"非法金额参数"];
- $date = date('Y-m-d H:i:s');
- app('OwnerBillReportService')->update(["id"=>$request->id],["confirm_fee"=>$request->confirm_fee,"difference"=>DB::raw($request->confirm_fee.'- (IFNULL(work_fee,0)+IFNULL(storage_fee,0)+IFNULL(logistic_fee,0))'),"updated_at"=>$date]);
- LogService::log(__METHOD__,"项目管理-修改账单报表",json_encode($request->input()));
- return ["success"=>true,"data"=>$date];
- }
- public function billConfirm()
- {
- $this->gate("结算管理-账单确认-完结");
- if (!request("id"))$this->error("非法参数");
- /** @var OwnerBillReport $bill */
- $bill = app('OwnerBillReportService')->first(["id"=>request("id"),"confirmed"=>"否"]);
- if (!$bill)$this->error("账单状态变更,禁止操作");
- /** @var \stdClass $bill */
- $area = OwnerAreaReport::query()->where("owner_id",$bill->owner_id)
- ->where("counting_month","like",$bill->counting_month."%")->first();
- if (!$area || $area->status!='编辑中')$this->error("对应面积报表状态异常");
- $bill->update(["confirmed"=>"是"]);
- LogService::log(__METHOD__,"项目管理-确认账单",json_encode(request()->input()));
- app('OwnerAreaReportService')->lockArea(null, $bill->owner_id, $bill->counting_month);
- LogService::log(__METHOD__,"项目管理-锁定账单的所有面积",json_encode($bill,JSON_UNESCAPED_UNICODE));
- $this->success();
- }
- private function validator(array $params){
- $validator=Validator::make($params,[
- 'id' => ['required'],
- 'customer_id'=>['required'],
- 'owner_group_id'=>['required'],
- 'warehouse_id'=>['required'],
- 'tax_rate_id' => ["nullable",'integer'],
- 'waring_line_on' => ["nullable",'integer'],
- ],[
- 'required'=>':attribute 为必填项',
- 'integer'=>':attribute 必须为整数',
- 'numeric'=>':attribute 必须为数字',
- ],[
- 'code'=>'项目代码',
- 'name'=>'项目名称',
- 'warehouse_id'=>'仓库',
- 'customer_id'=>'客户',
- 'owner_group_id'=>'工作组',
- 'tax_rate_id' => '税率',
- 'waring_line_on' => '月单量预警'
- ]);
- return $validator;
- }
- public function verifyProject(Request $request)
- {
- $this->success($this->validator($request->input())->errors());
- }
- public function createReport()
- {
- $ids = \request("val");
- if (!$ids)$this->error("未选择任何项目");
- $reports = OwnerReport::query()->with("owner")
- ->where("counting_month",">=",date("Y-m")."-01")
- ->whereIn("owner_id",$ids)->get(["id","owner_id"]);
- $errors = [];
- $exist = [];
- foreach ($reports as $report){
- $errors[] = "“".($report->owner ? $report->owner->name : $report->owner_id)."”已存在本月报表";
- $exist[] = $report->owner_id;
- }
- $ids = array_diff($ids,$exist);
- $insert = [];
- $date = date("Y-m-d H:i:s");
- foreach ($ids as $id){
- $insert[] = [
- "owner_id" => $id,
- "counting_month" => date("Y-m-d"),
- "created_at" => $date
- ];
- }
- if ($insert){
- OwnerReport::query()->insert($insert);
- LogService::log(__METHOD__,"手动生成报表",json_encode($insert));
- }
- $reports = OwnerReport::query()->with(["owner.userOwnerGroup","owner.customer"])
- ->where("counting_month",">=",date("Y-m")."-01")
- ->whereIn("owner_id",$ids)->get();
- $result = [];
- foreach ($reports as $report){
- $result[] = [
- "id" => $report->id,
- "ownerGroupName" => $report->owner ? ($report->owner->userOwnerGroup ? $report->owner->userOwnerGroup->name : '') : '',
- "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
- "ownerName" => $report->owner ? $report->owner->name : '',
- "ownerStatus" => $report->owner ? ($report->owner->deleted_at ? "冻结" : "激活") : '',
- "ownerStorageDuration" => $report->owner ? ($report->owner->created_at ? ((new \DateTime())->diff(new \DateTime($report->owner->created_at))->days) : '') : '',
- "ownerCreatedAt" => $report->owner ? $report->owner->created_at : '',
- "countingMonth" => $report->counting_month,
- ];
- }
- $this->success(["errors"=>$errors,"data"=>$result]);
- }
- public function createAreaReport()
- {
- $ids = \request("val");
- if (!$ids)$this->error("未选择任何项目");
- /** @var OwnerService $service */
- $service = app("OwnerService");
- $owners = $service->get(["id"=>$ids],["ownerStoragePriceModels"],false,true);
- app("OwnerAreaReportService")->notExistToInsert($owners);
- $reports = OwnerAreaReport::query()->with(["owner","ownerStoragePriceModel.unit"])
- ->where("counting_month",">=",date("Y-m")."-01")
- ->whereIn("owner_id",array_column($owners->toArray(),"id"))->get();
- $result = [];
- foreach ($reports as $report){
- $result[] = [
- "id" => $report->id,
- "ownerGroupId" => $report->user_owner_group_id,
- "ownerName" => $report->owner ? $report->owner->name : '',
- "customerName" => $report->owner ? ($report->owner->customer ? $report->owner->customer->name : '') : '',
- "countingMonth" => $report->counting_month,
- "areaOnTray" => $report->area_on_tray,
- "areaOnHalfTray" => $report->area_on_half_tray,
- "areaOnFlat" => $report->area_on_flat,
- "accountingArea" => $report->accounting_area,
- "status" => $report->status,
- "updatedAt" => $report->updated_at,
- "unitName" => $report->ownerStoragePriceModel ? ($report->ownerStoragePriceModel->unit ? $report->ownerStoragePriceModel->unit->name : '') : '',
- "ownerStoragePriceModel"=> $report->ownerStoragePriceModel ? $report->ownerStoragePriceModel->using_type : '' ,
- ];
- }
- $this->success($result);
- }
- public function resetInstantBill()
- {
- ini_set('max_execution_time', 2500);
- $startData = request("startDate");
- $endDate = request("endDate");
- $owner = request("owner");
- if (!$startData)$this->error("非法参数");
- DB::beginTransaction();
- try {
- $details = OwnerFeeDetail::query()->where("worked_at",">=",$startData." 00:00:00");
- if ($endDate)$details->where("worked_at","<=",$endDate." 23:59:59");
- if (count($owner)>0)$details->whereIn("owner_id",$owner);
- $fee = OwnerFeeExpress::query()->where("created_at",">=",$startData." 00:00:00");
- if ($endDate)$fee->where("created_at","<=",$endDate." 23:59:59");
- if (count($owner)>0)$fee->whereIn("owner_id",$owner);
- $fee->delete();
- $feeQuery = OwnerFeeOperation::query()->select("id")->where("worked_at",">=",$startData);
- if ($endDate)$feeQuery->where("worked_at","<=",$endDate);
- if (count($owner)>0)$feeQuery->whereIn("owner_id",$owner);
- OwnerFeeOperationDetail::query()->whereIn("owner_fee_operation_id",$feeQuery)->delete();
- $feeQuery->delete();
- $fee = OwnerFeeLogistic::query()->where("created_at",">=",$startData." 00:00:00");
- if ($endDate)$fee->where("created_at","<=",$endDate." 23:59:59");
- if (count($owner)>0)$fee->whereIn("owner_id",$owner);
- $fee->delete();
- $details->get()->each(function ($detail){
- dispatch(new ResetInstantBill($detail));
- });
- DB::commit();
- $this->success();
- }catch (\Exception $e){
- DB::rollBack();
- $this->error("失败");
- }
- //$this->restoreResetInstantBillOrder($startData,$endDate);
- //$this->restoreResetInstantBillStore($startData,$endDate);
- }
- private function restoreResetInstantBillOrder($startData,$endDate)
- {
- $orders = Order::query()->where("wms_status","订单完成")->whereBetween("updated_at",["{$startData} 00:00:00","{$endDate} 23:59:59"])
- ->whereNotIn("id",OwnerFeeDetail::query()->select("outer_id")->where("outer_table_name","orders")
- ->whereBetween("worked_at",["{$startData} 00:00:00","{$endDate} 23:59:59"]))->get();
- foreach ($orders->chunk(50) as $or){
- dispatch(new OrderCreateInstantBill($or));
- }
- }
- private function restoreResetInstantBillStore($startData,$endDate)
- {
- $stores = Store::query()->where("status","已入库")->whereBetween("updated_at",["{$startData} 00:00:00","{$endDate} 23:59:59"])
- ->whereNotIn("id",OwnerFeeDetail::query()->select("outer_id")->where("outer_table_name","stores")
- ->whereBetween("worked_at",["{$startData} 00:00:00","{$endDate} 23:59:59"]))->get();
- foreach ($stores->chunk(50) as $st){
- dispatch(new StoreCreateInstantBill($st));
- }
- }
- public function resetBillConfirmation()
- {
- $month = request("month");
- if (!$month)$this->error("无日期");
- $owner = request("owner");
- if ($owner && !is_array($owner))$this->error("非法数据");
- $sql = <<<sql
- SELECT owner_id,SUM(IFNULL(work_fee,0)) AS work_fee,SUM(IFNULL(logistic_fee,0)) AS logistic_fee FROM owner_fee_details WHERE worked_at LIKE ? AND
- ((type = '发货' AND logistic_fee IS NOT NULL AND work_fee IS NOT NULL) OR (type <> '发货' AND work_fee IS NOT NULL))
- sql;
- if ($owner && count($owner)>0){
- $sql.=" AND owner_id IN (''";
- foreach ($owner as $o)$sql .=",'{$o}'";
- $sql.=")";
- }
- $sql .= " GROUP BY owner_id";
- $billDetails = DB::select(DB::raw($sql),[$month."%"]);
- $areas = OwnerAreaReport::query()->with(["ownerStoragePriceModel.timeUnit","ownerStoragePriceModel.taxRate"])
- ->where("counting_month","like",$month."%");
- if ($owner && count($owner)>0){
- $areas->whereIn("owner_id",$owner);
- }
- $areas = $areas->get();
- $map = [];
- $mapTax = [];
- foreach($areas as $area){
- if (!$area->ownerStoragePriceModel)continue;
- //信息提取模板
- $GLOBALS["FEE_INFO"] = [
- "counting_type" =>$area->ownerStoragePriceModel->counting_type,
- "using_type" =>$area->ownerStoragePriceModel->using_type,
- "fee_description" =>"",
- "total_fee" =>0,
- "tax_rate" =>0,
- ];
- $key = $area->owner_id."_".$area->counting_month;
- if (!isset($map[$key]))$map[$key] = $mapTax[$key] = 0;
- list($money,$taxFee) = app('OwnerStoragePriceModelService')
- ->calculationAmount($area->ownerStoragePriceModel,$area->accounting_area,$area->owner_id,$area->counting_month);
- $map[$key] += $money;
- $mapTax[$key] += $taxFee;
- $GLOBALS["FEE_INFO"]["total_fee"] = $money;
- OwnerFeeStorage::query()->where("area_id",$area->id)
- ->update($GLOBALS["FEE_INFO"]);
- }
- foreach (OwnerPriceSystem::query()->with(["timeUnit","taxRate"])
- ->select("owner_id","usage_fee")->whereNull("operation")
- ->orWhere("operation","")->get() as $system){
- list($systemFee[$system->owner_id],$systemTaxFee[$system->owner_id]) =
- app("OwnerAreaReportService")->systemFee($system,$month);
- }
- $chunks = array_chunk($billDetails,50);
- foreach ($chunks as $bills){
- foreach ($bills as $bill){
- $key = $bill->owner_id."_".$month;
- OwnerBillReport::query()->where("owner_id",$bill->owner_id)
- ->where("counting_month",$month."-01")
- ->update(["work_fee"=>$bill->work_fee,
- "logistic_fee"=>$bill->logistic_fee,
- "storage_fee"=>$map[$key] ?? 0,
- "other_fee" => $systemFee[$bill->owner_id] ?? null,
- "other_tax_fee" => $systemTaxFee[$bill->owner_id] ?? null,
- "storage_tax_fee" => $mapTax[$key] ?? 0]);
- }
- }
- $this->dispatch(new SettlementBillReportJob($month."-01",$owner));
- $this->success();
- }
- }
|