Files
xk-api-yii/admin/controllers/base/FinanceController.php
2025-03-14 16:49:08 +08:00

1010 lines
36 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace admin\controllers\base;
use admin\components\BaseAdminController;
use admin\models\Admin;
use common\enums\UserRoleEnum;
use common\forms\ProductRefundForm;
use common\helpers\FuncHelper;
use common\models\newDb\MonthlyPaymentModel;
use common\models\oldDb\CashApply;
use common\models\oldDb\FundWater;
use common\models\oldDb\Ledger;
use common\models\oldDb\ProductOrder;
use common\models\oldDb\ProductOrderRefund;
use common\models\oldDb\Reconciliation;
use common\models\oldDb\Register;
use common\models\oldDb\Store;
use common\models\oldDb\SystemNotice;
use common\services\ExportService;
use yii\db\Exception;
use yii\web\Response;
class FinanceController extends BaseAdminController
{
/**
* @doc-name 退款申请记录
* @doc-param string refund_no 退款单号 / optional
* @doc-return @List{id,order_id-int-订单id,user_id-int-用户ID,reason-string-原因,remark-string-备注,refund_images-string-退款图片,refund_type-int-0仅退款 1退货退款,refund_no-string-退款单号,fail_reason-string-失败原因refund_price-float-金额,is_refund-int-0待退款 1已退款 -1退款失败,refund_time-string-退款时间,status-int-0退款申请中 1申请通过 2撤销申请3拒绝退款} 退款申请记录
*/
public function actionRefundApply()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
if ($user->role == UserRoleEnum::STORE_ADMIN) {
$query = ProductOrderRefund::find()->alias('po')->where([
'po.is_deleted' => 0
])->orderBy(['po.id' => SORT_DESC]);
// $query->joinWith(['order' => function ($model) use ($user) {
// $model->andWhere(['drugstore_id' => $user->drugstore]);
// }]);
}
if ($user->role == UserRoleEnum::SUPER_ADMIN) {
$query = ProductOrderRefund::find()->alias('po')->where([
'is_deleted' => 0
])->orderBy(['po.id' => SORT_DESC]);
}
if (!empty($get['refund_no'])) {
$query->andWhere(['refund_no' => $get['refund_no']]);
}
$this->field = [
ProductOrderRefund::class => [
'id', 'order_id', 'user_id', 'reason', 'remark', 'refund_images', 'refund_type', 'refund_no', 'refund_price', 'is_refund', 'refund_time',
'status', 'created_at' => function ($m) {
return date('Y-m-d H:i:s', $m->created_at);
}
]
];
return $this->create($query, $get);
}
/**
* @doc-name 同意退款操作
* @doc-param int id 退款申请记录ID
*/
public function actionRefundAgree()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
['id', 'required'],
]);
$user = \Yii::$app->user->identity;
$t = \Yii::$app->db->beginTransaction();
try {
$ProductOrderRefund = ProductOrderRefund::find()->where([
'id' => $post['id'],
'is_deleted' => 0,
])->with(['order'])->one();
if (!$ProductOrderRefund) {
throw new Exception('退款申请记录不存在');
}
$ProductOrder = ProductOrder::find()->where(['id' => $ProductOrderRefund->order_id])->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
$ProductOrder->refund_status = 3;//已退款
$ProductOrder->saveOrFail();
$ProductOrderRefund->is_refund = 1;
$ProductOrderRefund->status = 1;
$ProductOrderRefund->refund_time = date('Y-m-d H:i:s', time());
$ProductOrderRefund->saveOrFail();
$form = new ProductRefundForm();
$form->refundMoney($ProductOrderRefund);
$t->commit();
return ['success'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* 管理员退款
*
* @return string[]
* @throws Exception
*/
public function actionAdminRefundAgree()
{
$identity = \Yii::$app->user->identity;
if ($identity->role != 10) {
throw new Exception('权限不足,仅超管有权限退款');
}
// 获取前端传递的POST数据
$post = \Yii::$app->request->post();
// 对必要的字段进行验证
$this->requestValidate($post, [
['id', 'required'],
['refund_type', 'required'],
['refund_type', 'required'],
]);
// 实例化ProductOrder模型
$orderModel = new ProductOrder();
// 根据POST数据中的id查询对应的订单信息
$orderInfo = $orderModel->find()->where(['id' => $post['id']])->asArray()->one();
// 开启数据库事务
$t = \Yii::$app->db->beginTransaction();
try {
// 实例化退款申请模型
$model = new ProductOrderRefund();
// 填充退款申请模型的基础信息
$model->order_id = $post['id'];
$model->user_id = \Yii::$app->user->id;
$model->reason = !empty($post['reason']) ? $post['reason'] : '管理员-' . \Yii::$app->user->id . '-发起退款';
// 如果POST数据中包含退款图片则填充退款图片字段
if (!empty($post['refund_images'])) {
$model->refund_images = $post['refund_images'];
}
// 填充其他退款申请字段
$model->remark = '平台申请退款';
$model->refund_no = $orderInfo['order_no'];
$model->refund_price = $orderInfo['total_pay_price'];
$model->refund_time = date('Y-m-d H:i:s');
// 保存退款申请模型
$model->save();
// 根据刚保存的退款申请ID查找退款申请记录确保其存在且未被删除
$ProductOrderRefund = ProductOrderRefund::find()->where([
'id' => $model->id,
'is_deleted' => 0,
])->with(['order'])->one();
// 如果找不到退款申请记录,则抛出异常
if (!$ProductOrderRefund) {
throw new Exception('退款申请记录不存在');
}
// 根据退款申请记录中的订单ID查找对应的订单确保订单存在
$ProductOrder = ProductOrder::find()->where(['id' => $ProductOrderRefund->order_id])->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
if ($ProductOrder->order_type === 5) {
$client = new \GuzzleHttp\Client();
$response = $client->post( 'https://api.xiaokang88.com/open-api/client-confirm', [
'json' => [
'order_id' => $this->orderId,
]
]);
$body = json_decode($response->getBody()->getContents(), true);
if ($body['code'] != 0) {
exit($body['message']);
}
}
// 更新订单的退款状态为“已退款”
$ProductOrder->refund_status = 3;
$ProductOrder->saveOrFail();
// 更新退款申请记录的状态,标记为已退款
$ProductOrderRefund->is_refund = 1;
$ProductOrderRefund->status = 1;
$ProductOrderRefund->refund_time = date('Y-m-d H:i:s', time());
$ProductOrderRefund->saveOrFail();
// 执行退款操作
$form = new ProductRefundForm();
$form->refundMoney($ProductOrderRefund);
// 提交事务
$t->commit();
// 返回成功标识
return ['success'];
} catch (\Exception $e) {
// 如果发生异常,则回滚事务
$t->rollBack();
// 重新抛出异常,传递错误信息
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 拒绝退款操作
* @doc-param int id 退款申请记录ID
* @doc-param string check_result 拒绝原因
*/
public function actionRefundRefuse()
{
$post = \Yii::$app->request->post();
$this->requestValidate($post, [
[['id_id', 'check_result'], 'required'],
]);
$id = $post['id_id'];
$user = \Yii::$app->user->identity;
if ($user->role == UserRoleEnum::SUPER_ADMIN) {//超管
$ProductOrderRefund = ProductOrderRefund::find()->where([
'id' => $id,
'is_deleted' => 0,
])->with(['order'])->one();
}
if ($user->role == UserRoleEnum::STORE_ADMIN) {//门店管理员
$ProductOrderRefund = ProductOrderRefund::find()->alias('po')->where([
'po.id' => $id,
'po.is_deleted' => 0,
])->with(['order'])->one();
}
if (!$ProductOrderRefund) throw new Exception('退款申请记录不存在');
$t = \Yii::$app->db->beginTransaction();
try {
$ProductOrder = ProductOrder::find()->where(['id' => $ProductOrderRefund->order_id])->one();
if (!$ProductOrder) throw new Exception('产品订单不存在');
if ($ProductOrder->is_send == 1) {
$ProductOrder->status = 6;//确认收货
} else {
$ProductOrder->status = 1;//待发货
}
$ProductOrder->refund_status = 4;//拒绝退款
$ProductOrder->saveOrFail();
$ProductOrderRefund->is_refund = 0;
$ProductOrderRefund->status = 3;//拒绝退款
$ProductOrderRefund->check_result = $post['check_result'];//审核结果
$ProductOrderRefund->refund_time = date('Y-m-d H:i:s', time());
$ProductOrderRefund->saveOrFail();
//拒绝退款通知
$systemNotice = new SystemNotice();
$systemNotice->store_id = $ProductOrder->store_id;
$systemNotice->content = '工作人员已拒绝退款,原因:' . $post['check_result'];
$systemNotice->base_type = 7;
$systemNotice->scene_type = 1;
$systemNotice->user_id = $ProductOrderRefund->user_id;
$systemNotice->notice_at = date('Y-m-d h:i:s', time());
$systemNotice->saveOrFail();
$t->commit();
return ['success'];
} catch (\Exception $e) {
$t->rollBack();
throw new Exception($e->getMessage());
}
}
/**
* @doc-name 资金流水记录
* @doc-param string start_time 时间 / optional
* @doc-param string end_time 时间 / optional
* @doc-param string doctor 医生 / optional
* @doc-param string store 诊所 / optional
* @doc-param string order_no 订单号 / optional
* @doc-param string refund_no 退款单号 / optional
* @doc-return @List{id,order_id-int-订单id,order_type-int-订单类型1产品订单2问诊订单,user_id-int-用户ID,type-string-类型enter入账refund出账,price-float-金额,order_no-string-订单号,refund_no-string-退款单号,created_at-string-收入或支出时间,pay_type-int-支付类型1为微信} 资金流水记录
*/
public function actionFundWater()
{
$get = \Yii::$app->request->get();
$user = \Yii::$app->user->identity;
$start_time = strtotime($get['start_time']);
$end_time = strtotime($get['end_time']);
$doctor = $get['doctor'];
$store = $get['store'];
if ($user->role == UserRoleEnum::STORE_ADMIN) {
$query = FundWater::find()->where([
'f.store_id' => $user->store_id
])->alias('f')->orderBy(['id' => SORT_DESC]);
}
if ($user->role == UserRoleEnum::SUPER_ADMIN) {
$query = FundWater::find()->alias('f')->orderBy(['id' => SORT_DESC]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time == $end_time) {//筛选当天
$time = FuncHelper::getDayBE($get['start_time']);
$end_time = $time[1];
}
$query->andWhere(['between', 'f.created_at', $start_time, $end_time]);
}
if (!empty($doctor)) {
$query->joinWith(['doctor' => function ($d) use ($doctor) {
$d->alias('d');
$d->andWhere(['like', 'd.name', $doctor]);
}]);
}
if (!empty($store)) {
$query->joinWith(['store' => function ($s) use ($store) {
$s->alias('s');
$s->andWhere(['like', 's.name', $store]);
}]);
}
if (!empty($get['order_no'])) {
$query->andWhere(['f.order_no' => $get['order_no']]);
}
if (!empty($get['refund_no'])) {
$query->andWhere(['f.refund_no' => $get['refund_no']]);
}
$this->field = [
FundWater::class => [
'id', 'order_id', 'order_type', 'user_id', 'type', 'price', 'order_no', 'refund_no', 'pay_type', 'store_id',
'created_at' => function ($m) {
return date('Y-m-d H:i:s', $m->created_at);
},
'store' => 'store.name', 'service_user_id', 'doctor' => 'doctor.name',
'user' => 'user.nickname'
]
];
return $this->create($query, $get);
}
/**
* @doc-name 导出资金流水
*/
public function actionExportFundWater()
{
\Yii::$app->response->format = Response::FORMAT_RAW;
$params = \Yii::$app->request->post();
$parameter['header'] = ['订单类型', '医生', '用户', '价格', '诊所', '时间'];
$parameter['data'] = FundWater::inventory($params, \Yii::$app->user->identity->store_id);
ExportService::ExportByCors($parameter);
}
/**
* @doc-name 财务数据--结算记录(包括平台和门诊的)
* @doc-param string order_no 产品订单号
* @doc-param string register_no 挂号订单号
* @doc-param string start_time 开始时间
* @doc-param string end_time 结束时间
* @doc-param string order_no 订单
* @doc-return mixed @List{id,user_id-int-用户ID,user_type-int-用户类型1诊所2总部,order_no-int-订单,order_id-int-订单id,su_id-int-医生iddrugstore_id-int-仓库id,drug_id-string-药品id,status-string-结算状态 0待结算 1已结算 2已取消,money-string-分佣金额time-string-时间} 平台/诊所是否结算管理
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionJiesuanList()
{
$get = \Yii::$app->request->get();
$order_no = $get['order_no']?? '';
$register_no = $get['register_no']?? '';
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
$query = Ledger::find()->alias('l')->where(['l.status' => [0, 1]])->orderBy(['id' => SORT_DESC])->groupBy('l.order_id,l.order_type');
if (!empty($order_no)) {
$query->joinWith(['productOrder' => function ($p) use ($order_no) {
$p->where(['order_no' => $order_no]);
}]);
}
if (!empty($register_no)) {
$query->joinWith(['register' => function ($p) use ($register_no) {
$p->where(['order_no' => $register_no]);
}]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time == $end_time) {//筛选当天
$time = FuncHelper::getDayBE($get['start_time']);
$end_time = $time[1];
}
$query->andWhere(['between', 'l.created_at', $start_time, $end_time]);
}
$this->field = [
Ledger::class => [
'id', 'user_id', 'user_type', 'su_id', 'drugstore_id', 'drug_id', 'status', 'money' => function ($m) {
return $this->actionTotal($m->order_id);
},
'order_id',
'order_no' => function ($order) {
if ($order->order_type == 1) {
return ProductOrder::find()->select(['order_no'])->where(['id' => $order->order_id])->column();
}
if ($order->order_type == 2) {
return Register::find()->select(['order_no'])->where(['id' => $order->order_id])->column();
}
},
'type' => function ($l) {
if ($l->order_type == 1) {
return '产品订单';
} else {
return '挂号订单';
}
},
'fee_type' => function ($f) {
if ($f->fee_type == 1) {
return '药品费用';
} elseif ($f->fee_type == 2) {
return '挂号费用';
} elseif ($f->fee_type == 3) {
return '快递费用';
} elseif ($f->fee_type == 4) {
return '代煎费用';
} else {
return '其他';
}
},
'price_from' => 'productOrder.user.nickname',
'time' => function ($le) {
return date('Y-m-d H:i:s', $le->created_at);
}
],
];
return $this->create($query, $get);
}
public function actionTotal($order_id)
{
$money = Ledger::find()->alias('l')->where(['l.order_id' => $order_id, 'l.status' => [0, 1]])->sum('money');
return $money ?? 0;
}
/**
* @doc-name 财务数据--提现记录
* @doc-param string order_no 订单号
* @doc-param string start_time 开始时间
* @doc-param string end_time 结束时间
* @doc-return mixed @List{id,user_id-int-用户ID,user_type-int-用户类型1诊所2总部,order_no-int-订单,apply_cash-float-申请提现金额,true_cash-float-实际到账金额charge_cash-string-手续费,check_id-string-关联admin表 审核人ID,check_status-string-审核状态0待审核1审核中2已通过3已拒绝,check_result-string-审核结果/拒绝原因check_time-string-审核时间,apply_time-string-申请时间,dakuan_status-string-打款状态-1失败0未知1成功,dakuan_time-string-打款时间,payee-string-收款人} 平台/诊所提现管理
* @doc-return mixed @Pagination{total-int-总数量,totalPage-int-总页数,pageSize-int-每页条数} 分页数据
*/
public function actionWithdrawnManage()
{
$get = \Yii::$app->request->get();
$order_no = $get['order_no'];
$start_time = strtotime($get['start_time'] . ' ' . '00:00:00');
$end_time = strtotime($get['end_time'] . ' ' . '23:59:59');
$query = CashApply::find()->alias('c')->orderBy(['id' => SORT_DESC]);
if (!empty($order_no)) {
$query->where(['c.order_no' => $order_no]);
}
if (!empty($start_time) && !empty($end_time)) {
if ($start_time == $end_time) {//筛选当天
$time = FuncHelper::getDayBE($get['start_time']);
$start_time = $get['start_time'];
$end_time = date('Y-m-d H:i:s', $time);
} else {
$start_time = $get['start_time'];
$end_time = $get['end_time'];
}
$query->andWhere(['between', 'c.apply_time', $start_time, $end_time]);
}
$this->field = [
CashApply::class => [
'id', 'user_id', 'user_type', 'order_no', 'apply_cash', 'true_cash', 'charge_cash', 'check_id', 'check_status', 'check_result', 'check_time', 'apply_time', 'dakuan_status', 'dakuan_time', 'payee' => function ($m) {
if ($m->user_id == 0) {
return Admin::find()->where(['role' => UserRoleEnum::SUPER_ADMIN])->one();
} else {
return Store::find()->where(['id' => $m->user_id])->one();
}
},
'type' => function ($c) {//结算类别
return '提现记录';
},
'status' => function ($ca) {
if ($ca->check_status == 1) {
return '审核中';
} elseif ($ca->check_status == 2) {
return '审核通过,提现成功';
} elseif ($ca->check_status == 3) {
return '申请已拒绝,手续费未扣';
} elseif ($ca->check_status == 4) {
return '审核通过,提现失败';
} else {
return '未知';
}
},
'tixian_person' => function ($m) {
if ($m->user_type == 1) return '诊所';
if ($m->user_type == 2) return '平台';
},
],
];
return $this->create($query, $get);
}
/**
* @doc-name 导出提现、结算记录
*/
public function actionExportSettlement()
{
\Yii::$app->response->format = Response::FORMAT_RAW;
$params = \Yii::$app->request->get();
if ($params['type'] == 1) {
$parameter['header'] = ['单号', '提现方', '提现金额', '到账金额', '手续费', '状态', '时间'];
$parameter['data'] = CashApply::inventory1($params);
} else {
$parameter['header'] = ['单号', '订单类型', '用户', '金额', '状态', '时间'];
$parameter['data'] = Ledger::inventory($params, \Yii::$app->user->identity->store_id);
}
ExportService::ExportByCors($parameter);
}
/**
* 总销售金额统计方法
*
* @return array
* @throws Exception
*/
public function actionSaleMoney()
{
$get = \Yii::$app->request->get();
$admin = \Yii::$app->user->identity;
$role = $admin->role;
$timeType = \Yii::$app->request->get('time_type');
$startTime = strtotime($get['start_time']. ' 00:00:00');
$endTime = strtotime($get['end_time']. ' 23:59:59');
$day = $this->getDayList($startTime, $endTime);
$month = $this->getMonthsList($startTime, $endTime);
if (count($day) > 60) {
$day = [];
}
// switch ($timeType) {
// case 1:
// $startTime = strtotime(date('Y-m-1 00:00:00'));
// $endTime = strtotime(date('Y-m-d H:i:s'));
// $week = $this->getWeekList($startTime, $endTime);
// $day = $this->getDayList($startTime, $endTime);
// break;
// case 2:
// $startTime = strtotime(date('Y-1-1 00:00:00'));
// $endTime = strtotime(date('Y-m-d H:i:s'));
// $month = $this->getMonthsList($startTime, $endTime);
// break;
// case 3:
// $thisYear = date('Y');
// $lastYear = $thisYear - 1;
// $startTime = strtotime($lastYear . '-01-01 00:00:00');
// $endTime = strtotime($lastYear . '-12-31 23:59:59');
// $month = $this->getMonthsList($startTime, $endTime);
// break;
// case 4:
// $startTime = strtotime('2023-01-01 00:00:00');
// $endTime = time();
// $month = $this->getMonthsList($startTime, $endTime);
// break;
// default:
// throw new Exception('参数错误');
// }
$where = $this->getFinanceWhere($role, $admin);
$result = $this->getSleMoney($startTime, $endTime, $month, [], $day, $where);
return [
'line' => [
'month' => !empty($day) ? $day : $month,
'sale_money' => $result['sale_money'],
'legend' => $result['line_legend'],
],
'drug' => [
'data' => $result['drug_data']
],
'total_money' => $result['total_money'],
];
}
/**
* 获取财务统计条件
*
* @param $role
* @param $admin
* @return array
* @throws Exception
*/
public function getFinanceWhere($role, $admin)
{
$where = [];
switch ($role) {
case UserRoleEnum::SUPER_ADMIN:
// 管理员
break;
case UserRoleEnum::STORE_ADMIN:
// 门店
if (empty($admin->store_id)) throw new Exception('门店信息获取失败');
$where[] = ['store_id' => $admin->store_id];
break;
case UserRoleEnum::PROVINCE_DAI:
// 省代
if (empty($admin->province_id)) throw new Exception('省区经理信息获取失败' . $admin->province_id);
$store_id = Store::find()->select(['id'])->where(['province_id' => $admin->province_id])->column();
$where[] = ['in', 'store_id', $store_id];
break;
case UserRoleEnum::CITY_DAI:
// 市代
if (empty($admin->city_id)) throw new Exception('市区经理信息获取失败' . $admin->city_id);
$store_id = Store::find()->select(['id'])->where(['city_id' => $admin->city_id])->column();
$where[] = ['in', 'store_id', $store_id];
break;
case UserRoleEnum::SUPPLY:
// 业务员
if (empty($admin->code)) throw new Exception('市区经理信息获取失败' . $admin->code);
$store_id = Store::find()->select(['id'])->where(['code' => $admin->code])->column();
$where[] = ['in', 'store_id', $store_id];
break;
default:
throw new Exception('角色参数错误');
break;
}
return $where;
}
/**
* @doc-name 统计函数
*
* @param $startTime
* @param $endTime
* @param $month
* @param $week
* @param $day
* @param array $where
* @return array[]
*/
public function getSleMoney($startTime, $endTime, $month, $week, $day, $where = [])
{
// 根据$month列表的月份统计数据
$query = Reconciliation::find()->where(['between', 'created_at', $startTime, $endTime])->andWhere(['status' => 1])->select([
'drug_type',
'total_buy_price',
'total_price',
'created_at',
]);
if (!empty($where)) {
foreach ($where as $v) {
$query->andWhere($v);
}
}
$model = $query->all();
$saleMoney = [];
// 药品分类
$drugType = [
1 => '中药',
2 => '西药',
3 => '颗粒药',
4 => '中成药',
5 => '产品服务包',
];
$drugSaleMoney = [];
// 总金额
$totalMoney = 0;
// TODO 暂时不统计供货价
// 判断获取时间方法
$dateStr = !empty($day) ? 'm-d' : 'Y-m';
$dateArr = !empty($day) ? $day : $month;
foreach ($dateArr as $v) {
if (!isset($saleMoney[$v])) $saleMoney[$v] = '0.00';
}
foreach ($model as $v) {
$thisMonth = date($dateStr, $v['created_at']);
if (!isset($saleMoney[$thisMonth])) $saleMoney[$thisMonth] = '0.00';
$saleMoney[$thisMonth] = bcadd($saleMoney[$thisMonth] ?? '0', $v['total_price'], 2);
$totalMoney = bcadd($totalMoney, $v['total_price'], 2);
// 药品
if (!isset($drugSaleMoney[$v['drug_type']])) {
$drugSaleMoney[$v['drug_type']] = [
'name' => $drugType[$v['drug_type']],
'value' => $v['total_price'],
];
} else {
$drugSaleMoney[$v['drug_type']]['value'] = bcadd($drugSaleMoney[$v['drug_type']]['value'] ?? '0', $v['total_price'], 2);
}
}
return [
'sale_money' => $this->getArrValues($saleMoney),
'total_money' => $totalMoney,
'line_legend' => ['销售金额'],
'drug_data' => $this->getArrValues($drugSaleMoney),
];
}
/**
* 重置键值
* @param $originalArray
* @return array
*/
public function getArrValues($originalArray)
{
$newArr = [];
foreach ($originalArray as $v) {
$newArr[] = $v;
}
return $newArr;
}
/**
* 地区分类统计方法
*
* @return array[]
* @throws Exception
*/
public function actionAddressStatistics()
{
$admin = \Yii::$app->user->identity;
$role = $admin->role;
$timeType = \Yii::$app->request->get('time_type');
if ($role == UserRoleEnum::STORE_ADMIN) return [];
switch ($timeType) {
case 1:
$startTime = strtotime(date('Y-m-1 00:00:00'));
$endTime = strtotime(date('Y-m-d H:i:s'));
break;
case 2:
$startTime = strtotime(date('Y-1-1 00:00:00'));
$endTime = strtotime(date('Y-m-d H:i:s'));
break;
case 3:
$thisYear = date('Y');
$lastYear = $thisYear - 1;
$startTime = strtotime($lastYear . '-01-01 00:00:00');
$endTime = strtotime($lastYear . '-12-31 23:59:59');
break;
case 4:
$startTime = strtotime('2023-01-01 00:00:00');
$endTime = time();
break;
default:
throw new Exception('参数错误');
}
$where = $this->getFinanceWhere($role, $admin);
return $this->getAddress($startTime, $endTime, $where);
}
/**
* @doc-name 统计函数-地区
*
* @param $startTime
* @param $endTime
* @param array $where
* @return array[]
*/
public function getAddress($startTime, $endTime, $where = [])
{
$query = Reconciliation::find()
->where(['between', 'created_at', $startTime, $endTime])
->andWhere(['status' => 1])
->select(['store_id', 'total_price', 'created_at'])
->with(['store.province']); // 预加载关联数据
if (!empty($where)) {
foreach ($where as $condition) {
$query->andWhere($condition);
}
}
// 执行查询并获取结果
$models = $query->asArray()->all();
// 初始化结果数组
$result = [];
foreach ($models as $model) {
$provinceName = $model['store']['province']['name'];
if (!isset($result[$provinceName])) {
$result[$provinceName] = $model['total_price'];
} else {
$result[$provinceName] = bcadd($result[$provinceName], $model['total_price'], 2);
}
}
// 提取地址和金额
$address = [];
$money = [];
foreach ($result as $key => $value) {
$address[] = $key;
$money[] = $value;
}
return [
'address' => $address,
'money' => $money,
];
}
/**
* 获取月份
*
* @param $startTime
* @param $endTime
* @return array
*/
public function getMonthsList($startTime, $endTime)
{
$monthList = [];
$currentTime = $startTime;
while ($currentTime <= $endTime) {
$monthList[] = date('Y-m', $currentTime);
$currentTime = strtotime('+1 month', $currentTime);
}
return $monthList;
}
/**
* 获取选中的时间段有几周
*
* @param $startTime
* @param $endTime
* @return array
*/
public function getWeekList($startTime, $endTime)
{
$weeks = [];
$currentTime = $startTime;
while ($currentTime <= $endTime) {
$weeks[] = date('W', $currentTime);
$currentTime = strtotime('+1 week', $currentTime);
}
return $weeks;
}
/**
* 获取选中的时间段有几周
*
* @param $startTime
* @param $endTime
* @return array
*/
public function getDayList($startTime, $endTime)
{
$weeks = [];
$currentTime = $startTime;
while ($currentTime <= $endTime) {
$weeks[] = date('m-d', $currentTime);
$currentTime = strtotime('+1 day', $currentTime);
}
return $weeks;
}
/**
* 月度付款列表 - 店铺
* @return array
*/
public function actionMonthlyPaymentByStore()
{
$results = MonthlyPaymentModel::find()->with([
'order' => function ($query) {
$query->select(['id', 'order_no']);
},
'store' => function ($query) {
$query->select(['id', 'name']);
},
])->where(['store_id' => \Yii::$app->user->identity->store_id])->all();
$results = array_map(function ($item) {
$item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
return $item;
}, $results);
return [
'data' => $results,
'count' => $this->actionCountStoreMonthlyPayment(\Yii::$app->user->identity->store_id),
];
}
/**
* 月度付款列表 - 平台
* @return array
*/
public function actionMonthlyPayment()
{
$params = \Yii::$app->request->get();
$query = MonthlyPaymentModel::find()->with([
'order' => function ($query) {
$query->select(['id', 'order_no']);
},
'store' => function ($query) {
$query->select(['id', 'name']);
},
]);
// 使用andWhere来追加条件避免覆盖
if (!empty($params['store_id'])) {
$query->andWhere(['store_id' => $params['store_id']]);
}
if (!empty($params['status'])) {
$query->andWhere(['status' => $params['status']]);
}
if (!empty($params['start_time']) && !empty($params['end_time'])) {
$query->andWhere(['between', 'created_at', strtotime($params['start_time']), strtotime($params['end_time'])]);
}
// 执行查询并返回结果数组
$results = $query->asArray()->all();
$results = array_map(function ($item) {
$item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
return $item;
}, $results);
return [
'data' => $results,
'count' => $this->actionCountStoreMonthlyPayment(!empty($params['store_id'])? $params['store_id']: 0, $params['start_time'], $params['end_time'])
];
}
/**
* 统计店铺月度付款总额
* @param $storeId
* @return array
*/
public function actionCountStoreMonthlyPayment($storeId = 0, $startTime = '', $endTime = '')
{
$model = MonthlyPaymentModel::find()->andWhere(['status' => 0]);
if (!empty($storeId)) {
$model->andWhere(['store_id' => $storeId])->all();
}
if (!empty($startTime) && !empty($endTime)) {
$model->andWhere(['between', 'created_at', strtotime($startTime), strtotime($endTime)]);
}
return [
'count' => $model->count(),
'sum' => $model->sum('amount')?? 0,
];
}
/**
* 结算
* @return array
*/
public function actionSettlement()
{
$params = \Yii::$app->request->post();
$storeId = $params['store_id'];
$startTime = $params['start_time'];
$endTime = $params['end_time'];
if (empty($storeId)) {
return ['请选择诊所'];
}
// 批量修改MonthlyPaymentModel
$model = MonthlyPaymentModel::updateAll(['status' => 1,'updated_at' => time()], [
'and',
['store_id' => $storeId],
['status' => 0],
['between', 'created_at', strtotime($startTime), strtotime($endTime)]
]);
if ($model) {
return ['结算成功'];
}
return ['结算失败'];
}
}