Server_AccessControl/controllers/StaffController.php

342 lines
14 KiB
PHP

<?php
namespace app\controllers;
use Yii;
use app\models\Staff;
use app\models\StaffSearch;
use app\models\Department;
use app\models\common;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Html;
use yii\helpers\Url;
use app\models\Device;
/**
* StaffController implements the CRUD actions for Staff model.
*/
class StaffController extends Controller {
public function init() {
parent::init();
if (time() > Yii::$app->params["time"])
$this->redirect(["/dashboard"]);
if (Yii::$app->user->isGuest)
return $this->redirect(['/site/login']);
}
/**
* {@inheritdoc}
*/
public function behaviors() {
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function actionIndex() {
$this->view->title = 'Nhân viên';
$searchModel = new StaffSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
"departmentArray" => Department::departmentArray(),
"genderArray" => Staff::$genderArray
]);
}
public function actionCreate() {
$model = new Staff();
Yii::$app->response->format = "json";
if (!Yii::$app->user->can(Yii::$app->controller->id . "Create"))
return [
"title" => Html::tag("i", "", ["class" => "fa fa-info-circle"]) . " Cảnh báo",
"form" => "Bạn không có quyền truy cập"
];
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
$check = Staff::findOne(['code' => $data['Code']]);
if ($check)
return ["status" => false, "type" => "code"];
if ($data['CardNumber'] !== "" && $data['CardNumber'] !== "0") {
$check = Staff::findOne(['card_number' => $data['CardNumber']]);
if ($check)
return ["status" => false, "type" => "card"];
}
if ($model->create($data)) {
common::insertSystemLogs(["action" => "insert", "description" => "Thêm mới nhân viên: " . $data["Name"], "type" => Yii::$app->controller->id]);
return ["status" => true];
} else
return ["status" => false, "type" => "error"];
} else {
return [
"title" => Html::tag("i", "", ["class" => "fa fa-plus-square"]) . " Thêm",
"form" => $this->renderPartial("form", [
"model" => $model,
"url" => Url::to(["create"]),
"departmentArray" => Department::departmentArray(),
"genderArray" => Staff::$genderArray,
"deviceArray" => Device::deviceArray()
])
];
}
}
public function actionUpdate($id) {
$model = $this->findModel($id);
Yii::$app->response->format = "json";
if (!Yii::$app->user->can(Yii::$app->controller->id . "Update"))
return [
"title" => Html::tag("i", "", ["class" => "fa fa-info-circle"]) . " Cảnh báo",
"form" => "Bạn không có quyền truy cập"
];
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
$check = Staff::findOne(['code' => $data['Code']]);
if ($check && $check->id != $id)
return ["status" => false, "type" => "code"];
if ($data['CardNumber'] !== "" && $data['CardNumber'] !== "0") {
$check = Staff::findOne(['card_number' => $data['CardNumber']]);
if ($check && $check->id != $id)
return ["status" => false, "type" => "card"];
}
$model->name = $data["Name"];
$model->code = $data["Code"];
if ($model->card_number !== $data["CardNumber"]) {
$model->card_register_time = time();
}
$model->card_number = $data["CardNumber"] != "" ? $data["CardNumber"] : 0;
$model->department_id = $data["Department"];
$model->gender = $data["Gender"];
$model->birthday = date_format(date_create_from_format('d/m/Y', $data["BirthDay"]), 'U');
$model->email = $data["Email"];
$model->phone = $data["Phone"];
$model->date_in = date_format(date_create_from_format('d/m/Y', $data["DateIn"]), 'U');
$model->address = $data["Address"];
$model->image = $data["Image"];
$model->modified_at = time();
if ($model->save()) {
common::insertSystemLogs(["action" => "update", "description" => "Chỉnh sửa nhân viên: " . $data["Name"], "type" => Yii::$app->controller->id]);
return ["status" => true];
} else
return ["status" => false, "type" => "error"];
} else {
return [
"title" => Html::tag("i", "", ["class" => "fa fa-edit"]) . " Tùy chỉnh",
"form" => $this->renderPartial("form", [
"model" => $model,
"url" => Url::to(["update", "id" => $id]),
"departmentArray" => Department::departmentArray(),
"genderArray" => Staff::$genderArray,
"deviceArray" => Device::deviceArray()
])
];
}
}
public function actionDelete() {
if (!Yii::$app->user->can(Yii::$app->controller->id . "Delete"))
return [
"title" => Html::tag("i", "", ["class" => "fa fa-info-circle"]) . " Cảnh báo",
"form" => "Bạn không có quyền truy cập"
];
if (Yii::$app->request->post()) {
$lists = Yii::$app->request->post("lists");
Staff::deleteAll(["IN", "id", $lists]);
common::insertSystemLogs(["action" => "delete", "description" => "Xóa " . count($lists) . " nhân viên", "type" => Yii::$app->controller->id]);
}
}
protected function findModel($id) {
if (($model = Staff::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
public function actionExport() {
if (!Yii::$app->user->can(Yii::$app->controller->id . "Export"))
throw new \yii\web\HttpException(403, 'Bạn không có quyền truy cập nội dung này');
$objPHPExcel = new \PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$toExcelFile[] = ["Mã nhân viên", "Tên nhân viên", "Số thẻ", "Phòng ban", "Giới tính", "Ngày sinh", "Email", "Điện thoại", "Ngày bắt đầu làm việc", "Địa chỉ"];
$staffs = Staff::find()->all();
$departmentArray = Department::departmentArray();
foreach ($staffs as $k => $v) {
$ExportData[] = $v->code;
$ExportData[] = $v->name;
$ExportData[] = $v->card_number;
$ExportData[] = isset($departmentArray[$v->department_id]) ? $departmentArray[$v->department_id] : "";
$ExportData[] = $v->gender;
$ExportData[] = date("d/m/Y", $v->birthday);
$ExportData[] = $v->email;
$ExportData[] = $v->phone;
$ExportData[] = date("d/m/Y", $v->date_in);
$ExportData[] = $v->address;
$toExcelFile[] = $ExportData;
unset($ExportData);
}
$totals = count($staffs) + 1;
$activeSheet = $objPHPExcel->getActiveSheet();
$activeSheet->getStyle("A1:J" . $totals)->getFont()->setName('Time New Roman')->setSize(10);
$activeSheet->getStyle("A1:J1")->applyFromArray([
'fill' => array(
'type' => \PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => '7ac3ec')
)
]);
$rowCount = 1;
for ($i = 0; $i < count($toExcelFile); $i++) {
$column = 'A';
$row = $toExcelFile[$i];
for ($j = 0; $j < count($row); $j++) {
if (!isset($row[$j]))
$value = NULL;
elseif ($row[$j] != "")
$value = strip_tags($row[$j]);
else
$value = "";
$activeSheet->setCellValue($column . $rowCount, $value);
$column = chr(ord($column) + 1);
}
$rowCount++;
}
$activeSheet->getStyle("A1:J" . $totals)->applyFromArray([
'alignment' => [
'vertical' => \PHPExcel_Style_Alignment::VERTICAL_CENTER,
],
'borders' => [
'allborders' => [
'style' => \PHPExcel_Style_Border::BORDER_THIN
]
]
]);
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_end_clean();
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="staff_' . date("YmdHis") . '.xlsx"');
header('Cache-Control: max-age=0');
common::SaveViaTempFile($objWriter);
exit();
}
public function actionUpload() {
if (Yii::$app->request->post()) {
$common = new common();
$fileUploads = $common->UploadFile("file", ["XLS", "XLSX"], "excel");
$file_type = \PHPExcel_IOFactory::identify($fileUploads);
$objReader = \PHPExcel_IOFactory::createReader($file_type);
$objPHPExcel = $objReader->load($fileUploads);
$sheet_data = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
foreach ($sheet_data as $key => $val) {
if ($key > 1) {
$parent = Department::findOne(["name" => $val["D"]]);
$datas[] = [
$val["A"],
$val["B"],
$val["C"],
$parent ? $parent->code : 1,
in_array($val["E"], ["M", "F"]) ? $val["E"] : "M",
$val["F"] !== "" ? date_format(date_create_from_format('d/m/Y', $val["F"]), 'U') : 0,
$val["G"],
$val["H"],
$val["I"] !== "" ? date_format(date_create_from_format('d/m/Y', $val["I"]), 'U') : 0,
$val["J"],
time(),
time(),
time()
];
}
}
$model = new Staff();
$model->multiCreate($datas);
common::insertSystemLogs(["action" => "import", "description" => "Nhập dữ liệu: " . count($datas) . " nhân viên mới", "type" => Yii::$app->controller->id]);
return true;
// Yii::$app->response->format = 'json';
// return [
// "title" => Html::tag("i", "", ["class" => "fa fa-upload"]) . " Nhập",
// "form" => $this->renderPartial("import", [
// "data" => $sheet_data,
// "model" => new Staff()
// ])
// ];
}
}
public function actionImport() {
if (!Yii::$app->user->can(Yii::$app->controller->id . "Import"))
throw new \yii\web\HttpException(403, 'Bạn không có quyền truy cập nội dung này');
if (Yii::$app->request->post()) {
$post = Yii::$app->request->post("lists");
$datas = [];
foreach ($post as $key => $value) {
$val = json_decode($value, true);
$parent = Department::findOne(["name" => $val["D"]]);
$datas[] = [
$val["A"],
$val["B"],
$val["C"],
$parent ? $parent->code : 1,
in_array($val["E"], ["M", "F"]) ? $val["E"] : "M",
$val["F"] !== "" ? date_format(date_create_from_format('d/m/Y', $val["F"]), 'U') : 0,
$val["G"],
$val["H"],
$val["I"] !== "" ? date_format(date_create_from_format('d/m/Y', $val["I"]), 'U') : 0,
$val["J"],
time(),
time(),
time()
];
}
$model = new Staff();
$model->multiCreate($datas);
common::insertSystemLogs(["action" => "import", "description" => "Nhập dữ liệu: " . count($post) . " nhân viên mới", "type" => Yii::$app->controller->id]);
return;
}
}
public function actionLogs() {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = "json";
return [
"title" => Html::tag("i", "", ["class" => "fa fa-file"]) . " Ghi nhận hệ thống",
"form" => \app\widgets\SystemLogsView::widget(['type' => Yii::$app->controller->id])
];
}
}
public function actionImage() {
if (Yii::$app->request->post()) {
$model = new common();
return $model->UploadFile("AnhNhanVien", ["PNG", "JPG", "JPEG", "GIF"], "staff");
}
}
public function actionGetRtlog() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$device_id = Yii::$app->request->post("device");
$device = Device::findOne($device_id);
return json_decode(common::requestToCardService("/GetRTLog", ["DeviceIP" => $device->ip_address]), true);
}
}
}