You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

457 lines
18 KiB

<?php
/**
* Created by PhpStorm.
* User: weizongsong
* Date: 2019-04-12
* Time: 22:34
*/
namespace App\Http\Controllers\Admin;
use App\Customer;
use App\Libs\AlipayF2F;
use App\Libs\WxMicroPay;
use App\Models\AdminAreaLink;
use App\Models\Area;
use App\Models\Balance;
use App\Models\Bed;
use App\Models\Factor;
use App\Models\FactorItems;
use App\Models\OrderItems;
use App\Models\Orders;
use App\Models\Paramedic;
use App\Models\Product;
use App\Models\ProductItems;
use App\Models\Project;
use App\Models\Recharge;
use App\Models\Refund;
use App\Scopes\AdminProjectScope;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
class StatisticsController extends CommonController
{
public $bladePath = "admin.statistics";
public $urlPrefix = "admin/statistics";
public $modelName = "数据统计";
public $noProjects = "用户名下没有可以管理的项目";
public function _checkProjects()
{
$projects = (new Project())->adminProject()->orderBy("id", "desc")->get();
view()->share(compact("projects"));
return $projects;
}
public function getYears()
{
$start_year = config("start_year");
$years = [];
for ($i = date("Y"); $i >= $start_year; $i--) {
$years[] = $i;
}
view()->share(compact("years"));
}
public function _getMonths()
{
$months = [];
for ($i = 1; $i <= 12; $i++) {
$mm = $i < 10 ? "0" . $i : $i;
$months[] = (date("Y") - 2) . "-" . $mm;
}
for ($i = 1; $i <= 12; $i++) {
$mm = $i < 10 ? "0" . $i : $i;
$months[] = (date("Y") - 1) . "-" . $mm;
}
for ($i = 1; $i <= 12; $i++) {
$mm = $i < 10 ? "0" . $i : $i;
$months[] = date("Y") . "-" . $mm;
}
view()->share(compact("months"));
return $months;
}
public function _getMonthData()
{
$projects = $this->_checkProjects();
$project_id = request()->project_id ?? $projects->first()->id;
$project = $projects->keyBy("id")->toArray()["{$project_id}"];
$month = request()->month ?? date("Y-m");
$months = $this->_getMonths();
DB::enableQueryLog();
$paramedics = (new Paramedic())->withoutGlobalScope(AdminProjectScope::class)->where(function ($query) use ($project_id, $month) {
$order_item_paramedic_ids = (new OrderItems())
->whereRaw("(DATE_FORMAT(`service_date`,'%Y-%m') = '{$month}' or DATE_FORMAT(`paid_at`,'%Y-%m') = '{$month}')")
->whereHas("order", function ($query) use ($project_id) {
$query->where("project_id", $project_id);
})->pluck("paramedic_id")->toArray();
$query->where("project_id", $project_id)->orWhereIn("id", $order_item_paramedic_ids);
})->with(["orderItems" => function ($query) use ($month, $project_id) {
$query->whereRaw("(DATE_FORMAT(`service_date`,'%Y-%m') = '{$month}' or DATE_FORMAT(`paid_at`,'%Y-%m') = '{$month}')")
->where("total", ">", 0)
->whereHas("order", function ($query) use ($project_id) {
$query->where("project_id", $project_id);
})
->with(["order", "product", "productItem", "productParamedicLevel", "paramedic" => function ($query) {
$query->withoutGlobalScope(AdminProjectScope::class);
}, "bed", "room", "building", "area"])
->orderBy("id");
}])->get();
$allItems = collect();
foreach ($paramedics as $paramedic) {
foreach ($paramedic->orderItems as $orderItem) {
if ($orderItem->paid_at) {
$paid_at_this_month = Carbon::parse($orderItem->paid_at)->isSameMonth($month) ? true : false;
} else {
$paid_at_this_month = false;
}
if (Carbon::parse($orderItem->service_date)->isSameMonth($month)) {
$orderItem->service_date_in_this_month = $orderItem->service_date;
} else {
$orderItem->service_date_in_this_month = OrderItems::PREV_MONTH;
}
$orderItem->paid_at_this_month = $paid_at_this_month;
$orderItem = $orderItem->calculateFee();
}
$paramedic->originalOrderItems = $paramedic->orderItems;
$allItems = $allItems->concat($paramedic->orderItems);
$paramedic->orderItems = $paramedic->orderItems->groupBy("service_date_in_this_month");
}
$days = date("t", strtotime($month));
$dates = [];
for ($i = 1; $i <= $days; $i++) {
$dd = $i < 10 ? "0" . $i : $i;
$dates[] = $dd;
}
$dates[] = OrderItems::PREV_MONTH;
view()->share(compact("projects", "project_id", "month", "months", "dates", "paramedics", "allItems"));
return compact("projects", "project_id", "month", "months", "dates", "paramedics", "allItems");
}
public function salary(Request $request)
{
$projects = $this->_checkProjects();
if (!$projects->count()) {
return $this->error($this->noProjects);
}
$this->_getMonthData();
$laravel_duration = microtime(true) - LARAVEL_START;
return view($this->urlPrefix . "/salary", compact("laravel_duration"));
}
public function overview(Request $request)
{
$projects = $this->_checkProjects();
if (!$projects->count()) {
return $this->error($this->noProjects);
}
$project_id = request()->project_id ?? $projects->first()->id;
$project = Project::find($project_id);
$month = request()->month ?? date("Y-m");
$months = $this->_getMonths();
$start_timestamp = strtotime($month);
$end_timestamp = strtotime("+1 month", strtotime($month));
//根据项目获取相关数据
$prev_month_balance = Balance::whereRaw("UNIX_TIMESTAMP(`created_at`) < " . $start_timestamp)
->whereHas("order", function ($query) use ($project_id) {
$query->where("project_id", $project_id);
})->sum("money");
$this_month_balance = Balance::whereRaw("UNIX_TIMESTAMP(`created_at`) < " . $end_timestamp)
->whereHas("order", function ($query) use ($project_id) {
$query->where("project_id", $project_id);
})->sum("money");
$this_month_balances = Balance::whereRaw("UNIX_TIMESTAMP(`created_at`) >= " . $start_timestamp . " and UNIX_TIMESTAMP(`created_at`) < " . $end_timestamp)
->whereHas("order", function ($query) use ($project_id) {
$query->where("project_id", $project_id);
})->get();
return view($this->urlPrefix . "/overview", compact("project_id", "month", "project", "prev_month_balance", "this_month_balance", "this_month_balances"));
}
public function syncOrderItems(Request $request)
{
DB::enableQueryLog();
//采用指定订单号
$model = OrderItems::whereHas("order", function ($query) {
$query->whereIn("serial", [
"20210910000003",
"20210914000006",
"20210826000004",
"20210909000022",
"20210903000007",
"20210918000013",
"20210906000015"
]);
})->where("service_date", ">=", "2021-09-01");
//采用指定订单号结束
if ($request->last_id) {
$model = $model->where("id", ">", $request->last_id);
}
$orderItems = $model->with("order")->limit(50)->get();
if (!$orderItems->count()) {
dd("已处理完毕");
}
DB::beginTransaction();
try {
foreach ($orderItems as $orderItem) {
$factors = json_decode($orderItem->factors);
foreach ($factors as $factor) {
$current_factor = FactorItems::find(3);
$factor->fee = $current_factor->fee;
$factor->fee_percent = $current_factor->fee_percent;
$factor->factor_name = $current_factor->name;
}
$orderItem->update([
"factors" => json_encode($factors)
]);
}
DB::commit();
return $this->success("处理成功一批,正在跳转到下一批!", url($this->urlPrefix . "/salary/sync-order-items?month={$request->month}&last_id=" . $orderItems->last()->id));
} catch (\Exception $exception) {
DB::rollBack();
dd($exception->getMessage());
}
}
public function finance(Request $request)
{
$projects = $this->_checkProjects();
if (!$projects->count()) {
return $this->error($this->noProjects);
}
$project_id = request()->project_id ?? $projects->first()->id;
$project = $projects->keyBy("id")->toArray()["{$project_id}"];
$month = request()->month ?? date("Y-m");
$months = $this->_getMonths();
// 判断是否护士长
$userId = auth()->id();
$roleId = Role::where('name', 'like', '%护士长%')->where('guard_name', 'admin')->value('id');
$hushizhang = DB::table('model_has_roles')->where('role_id', $roleId)
->where('model_type', 'App\Admin')
->where('model_id', $userId)
->count();
// 获取这个护士长病区的订单
$user = auth()->user();
$areaId = AdminAreaLink::where('project_id', $project_id)->where('admin_id', $user->id)->pluck('area_id');
$bedList = Bed::whereIn('area_id', $areaId)->pluck('id');
$orderIds = Orders::whereIn('bed_id', $bedList)->pluck('id');
$recharges = Recharge::with(["manager", "order", "patient"])
->where(function ($query) use ($hushizhang, $orderIds) {
if ($hushizhang) {
$query->whereIn('order_id', $orderIds);
}
})
->withCount("refunds")
->whereNotNull("paid_at")
->whereRaw("DATE_FORMAT(`paid_at`,'%Y-%m') = '{$month}'")
->whereHas("order", function ($query) use ($project_id) {
$query->where("project_id", $project_id);
})
->get();
$refunds = Refund::whereNotNull("paid_at")
->where(function ($query) use ($hushizhang, $orderIds) {
if ($hushizhang) {
$query->whereIn('order_id', $orderIds);
}
})
->whereRaw("DATE_FORMAT(`paid_at`,'%Y-%m') = '{$month}'")
->whereHas("order", function ($query) use ($project_id) {
$query->where("project_id", $project_id);
})
->get();
return view($this->bladePath . ".finance", compact("recharges", "refunds", "projects", "project_id", "months", "month"));
}
public function memberBalanceByDate(Request $request)
{
$projects = $this->_checkProjects();
if (!$projects->count()) {
return $this->error($this->noProjects);
}
$project_id = request()->project_id ?? $projects->first()->id;
$before_date = $request->before_date ?: date("Y-m-d");
$before_datetime = strtotime($before_date . " 23:59:59");
DB::enableQueryLog();
$customers = (new Customer())
->whereNull("deleted_at")
->with([
"patients" => function ($query) use ($before_datetime) {
$query->whereRaw("UNIX_TIMESTAMP(`created_at`) <= {$before_datetime}")->orderBy("id", "desc");
},
// "oneBalance" => function ($query) use ($before_datetime) {
// $query->whereRaw("UNIX_TIMESTAMP(`created_at`) <= {$before_datetime}")->orderBy("id", "desc");
// }
])
// ->whereHas("oneBalance", function ($query) use ($before_datetime) {
// $query->whereRaw("UNIX_TIMESTAMP(`created_at`) <= {$before_datetime}")->where("balance", ">", 0)->orderBy("id", "desc");
// })
->whereHas("orders", function ($query) use ($before_datetime, $project_id) {
$query
// ->whereRaw("UNIX_TIMESTAMP(`created_at`) <= {$before_datetime}")
->where("project_id", $project_id);
})
->get();
$laravel_duration = microtime(true) - LARAVEL_START;
return view($this->bladePath . ".customer-balance", compact("customers", "before_datetime", "project_id", "laravel_duration"));
}
public function fixMonthLastDayCheckout(Request $request)
{
$day = $request->day;
if (!$day) {
dd("日期不正确");
}
DB::enableQueryLog();
$orders = Orders::whereIn("serial", ["20201130000003", "20201130000005", "20201128000004", "20201126000006", "20201127000005", "20201126000003", "20201130000004", "20201127000008", "20201130000001", "20201126000008"])->get();
$orderItems = OrderItems::with(["balance", "order"])
->whereNotNull("paid_at")
->whereRaw("UNIX_TIMESTAMP(`paid_at`) > " . strtotime("2020-12-01"))
->whereRaw("UNIX_TIMESTAMP(`paid_at`) < " . strtotime("2020-12-04"))
->whereIn("order_id", $orders->pluck("id")->toArray())
->limit(100)->get();
try {
foreach ($orderItems as $orderItem) {
$new_paid_at = "{$day} 22:00:01";
$orderItem->update([
"paid_at" => $new_paid_at
]);
$orderItem->balance->update([
"created_at" => $new_paid_at,
"remark" => "本条经过时间校准处理。原始创建时间为:" . $orderItem->balance->created_at
]);
}
DB::commit();
dd("处理完毕");
} catch (\Exception $exception) {
DB::rollBack();
dd($exception->getMessage());
}
}
public function fixBalanceOrderId()
{
$balances = Balance::whereNull("order_id")->with("belongs")->limit("100")->get();
if (!$balances->count()) {
return $this->success("处理完毕", url($this->urlPrefix . "/overview"));
}
foreach ($balances as $balance) {
$balance->timestamps = false;
$balance->update([
"order_id" => $balance->belongs->order_id
]);
}
return $this->success("处理完毕" . $balances->count() . "条数据,正在进入下一批数据。", url($this->urlPrefix . "/finance/fix-balance-order-id?timer=" . time()));
}
public function manualQueryRecharge($id)
{
$recharge = Recharge::find($id);
$res = (new AlipayF2F())->manualQuery($recharge);
dd($res);
}
public function huli(Request $request)
{
$projects = (new StatisticsController())->_checkProjects();
$defaultProjectsId = ($projects[0]->id) ?? '';
$project_id = $request->get('project_id', $defaultProjectsId);
$userId = auth()->id();
// 判断是否护士长
$roleId = Role::where('name', 'like', '%护士长%')->where('guard_name', 'admin')->value('id');
$hushizhang = DB::table('model_has_roles')->where('role_id', $roleId)
->where('model_type', 'App\Admin')
->where('model_id', $userId)->count();
$areaId = [];
if ($hushizhang) {
$user = auth()->user();
$areaId = AdminAreaLink::where(function ($qeury) use ($project_id) {
if ($project_id) {
$qeury->where('project_id', $project_id);
}
})->where('admin_id', $user->id)->pluck('area_id');
}
$data = Area::with('project', 'building')->where(function ($query) use ($areaId) {
if ($areaId) {
$query->whereIn('id', $areaId);
}
})->paginate(10);
foreach ($data as $item) {
// 获取所有床位id
$bedIds = Bed::where('area_id', $item->id)->pluck('id');
$order = Orders::whereIn('bed_id', $bedIds)->where('status', 100)->get();
$item->order_total = $order->sum('total');
$item->lies = $this->getLies($project_id, $order->pluck('id'));
}
// dd($data->toArray());
// 获取所有列
$lie = array_column($data[0]->lies,'name');
return view($this->bladePath . ".huli", compact("data","lie"));
}
/**
* 获取动态列
*/
public function getLies($project_id, $orderIds)
{
$product = Product::where('project_id', $project_id)->first();
$productItem = ProductItems::where('product_id', $product->id)->get();
$factor = FactorItems::where('factor_id', $product->factor_id)->get();
$list = [];
foreach ($productItem as $item) {
foreach ($factor as $v) {
$list[$item->id.'-'.$v->id] = [
'name' => $item->price + $v->price . '元/天',
'total_price' => $item->price + $v->price,
'product_item_id' => $item->id,
'factor_item_id' => $v->id,
'total' => $this->lieToMoney($item->id, $v->id, $orderIds)
];
}
}
return $list;
}
/**
* 根据产品子项id和因素子项id算出收入
*/
public function lieToMoney($product_item_id, $factor_item_id, $orderIds)
{
$total = OrderItems::where('product_item_id', $product_item_id)
->whereJsonContains('factors->factor_item_id', $factor_item_id)
->whereIn('order_id', $orderIds)
->sum('total');
return $total;
}
}