Server_AccessControl/controllers/DeviceController.php
2020-10-15 11:20:21 +07:00

481 lines
20 KiB
PHP

<?php
namespace app\controllers;
use Yii;
use app\models\Device;
use app\models\DeviceSearch;
use app\models\Area;
use app\models\common;
use app\models\Door;
use app\models\Staff;
use app\models\Schedule;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Html;
use yii\helpers\Url;
use app\models\Logs;
/**
* DeviceController implements the CRUD actions for Device model.
*/
class DeviceController extends Controller {
public function init() {
parent::init();
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 = 'Thiết bị';
$searchModel = new DeviceSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'statusArray' => Device::$statusArray,
'typeArray' => Device::$typeArray,
'areaArray' => Area::areaArray()
]);
}
public function actionCreate() {
$model = new Device();
Yii::$app->response->format = "json";
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
$check = Device::findOne(['ip_address' => $data['Ip']]);
if ($check)
return ["status" => false, "type" => "ip"];
$searchDevice = json_decode(common::requestToCardService("/SearchDevice", ["NetMask" => "255.255.255.255"]), true);
$device = false;
foreach ($searchDevice as $key => $value) {
if ($value["IP"] === $data["Ip"])
$device = $value;
}
if (!$device)
return ["status" => false, "type" => "connect"];
$requestToCardService = json_decode(common::requestToCardService("/CheckConnection", ["DeviceIP" => $data["Ip"]]), true);
if ($requestToCardService["Status"] === "ERROR")
return ["status" => false, "type" => "connect"];
$device_id = $model->create([
'name' => $data["Name"],
'serial' => isset($device['SN']) ? $device['SN'] : "",
'ip_address' => isset($device['IP']) ? $device['IP'] : "",
'subnet_mask' => isset($device['NetMask']) ? $device['NetMask'] : "",
'gateway' => isset($device['GATEIPAddress']) ? $device['GATEIPAddress'] : "",
'mac_address' => isset($device['MAC']) ? $device['MAC'] : "",
'status' => 1,
'type' => isset($device['Device']) ? $device['Device'] : "",
'version' => isset($device['Ver']) ? $device['Ver'] : "",
'area_id' => $data["Area"]
]);
if ($device_id) {
$datas = [];
for ($i = 1; $i <= intval($requestToCardService["LockCount"]); $i++) {
$datas[] = [$device_id, $data["Name"] . "-" . $i, $i, time(), time()];
}
$door = new Door();
$door->multiCreate($datas);
common::insertSystemLogs(["action" => "insert", "description" => "Thêm mới thiết bị: " . $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"]),
"areaArray" => Area::areaArray()
])
];
}
}
public function actionUpdate($id) {
$model = $this->findModel($id);
Yii::$app->response->format = "json";
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
$model->name = $data["Name"];
$model->area_id = $data["Area"];
$model->modified_at = time();
if ($model->save()) {
common::insertSystemLogs(["action" => "update", "description" => "Chỉnh sửa thiết bị: " . $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]),
"areaArray" => Area::areaArray()
])
];
}
}
public function actionDelete() {
if (Yii::$app->request->post()) {
$lists = Yii::$app->request->post("lists");
foreach ($lists as $key => $value) {
Device::deleteDevice($value);
}
}
}
protected function findModel($id) {
if (($model = Device::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
public function actionCheckConnection() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
return json_decode(common::requestToCardService("/CheckConnection", ["DeviceIP" => Yii::$app->request->post("Ip")]), true);
}
}
public function actionExport() {
$objPHPExcel = new \PHPExcel();
$objPHPExcel->setActiveSheetIndex(0);
$toExcelFile[] = ["Tên thiết bị", "Serial", "Địa chỉ IP", "Loại thiết bị", "Khu vực"];
$devices = Device::find()->all();
$areaArray = Area::areaArray();
$typeArray = Device::$typeArray;
foreach ($devices as $k => $v) {
$ExportData[] = $v->name;
$ExportData[] = $v->serial;
$ExportData[] = $v->ip_address;
$ExportData[] = isset($typeArray[$v->type]) ? $typeArray[$v->type] : "";
$ExportData[] = isset($areaArray[$v->area_id]) ? $areaArray[$v->area_id] : "";
$toExcelFile[] = $ExportData;
unset($ExportData);
}
$totals = count($devices) + 1;
$activeSheet = $objPHPExcel->getActiveSheet();
$activeSheet->getStyle("A1:E" . $totals)->getFont()->setName('Time New Roman')->setSize(10);
$activeSheet->getStyle("A1:E1")->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:E" . $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="device_' . date("YmdHis") . '.xlsx"');
header('Cache-Control: max-age=0');
common::SaveViaTempFile($objWriter);
exit();
}
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 actionChangeIp($id) {
$model = $this->findModel($id);
Yii::$app->response->format = "json";
if (Yii::$app->request->post()) {
$data = Yii::$app->request->post();
$OldIpAddress = $model->ip_address;
if ($OldIpAddress !== $data["Ip"]) {
$check = Device::findOne(['ip_address' => $data['Ip']]);
if ($check)
return ["status" => false, "type" => "ip"];
$res = common::requestToCardService("/ModifyIPAddress", [
"OldIPAddress" => $OldIpAddress,
"NewIPAddress" => $data["Ip"],
"NetMask" => $data["SubnetMask"],
"MAC" => $model->mac_address
]);
if ($res == 0) {
$model->ip_address = $data["Ip"];
$model->subnet_mask = $data["SubnetMask"];
$model->save();
return ["status" => true];
}
}
return ["status" => true];
} else {
return [
"title" => Html::tag("i", "", ["class" => "fa fa-pencil"]) . " Thay đổi địa chỉ IP",
"form" => $this->renderPartial("change-ip", [
"model" => $model,
"url" => Url::to(["change-ip", "id" => $id])
])
];
}
}
public function actionSearch() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$datas = json_decode(common::requestToCardService("/SearchDevice", ["NetMask" => Yii::$app->request->post("SubnetMask")]), true);
return [
"form" => $this->renderPartial("device-lists", [
"datas" => $datas,
"deviceIpLists" => Device::deviceIpLists()
]),
"totals" => count($datas)
];
} else {
$this->view->title = 'Tìm kiếm thiết bị';
return $this->render('search', [
]);
}
}
public function actionProcess() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
return [
"title" => Html::tag("i", "", ["class" => "fa fa-plus"]) . " Thêm thiết bị",
"form" => $this->renderPartial("process"),
"lists" => Yii::$app->request->post("lists")
];
}
}
public function actionImport() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$data = json_decode(Yii::$app->request->post("data"), true);
$check = Device::findOne(['ip_address' => $data["IP"]]);
if ($check)
return ["status" => false, "IP" => $data["IP"]];
$model = new Device();
$device_id = $model->create([
'name' => isset($data['IP']) ? $data['IP'] : "",
'serial' => isset($data['SN']) ? $data['SN'] : "",
'ip_address' => isset($data['IP']) ? $data['IP'] : "",
'subnet_mask' => isset($data['NetMask']) ? $data['NetMask'] : "",
'gateway' => isset($data['GATEIPAddress']) ? $data['GATEIPAddress'] : "",
'mac_address' => isset($data['MAC']) ? $data['MAC'] : "",
'status' => 1,
'type' => isset($data['Device']) ? $data['Device'] : "",
'version' => isset($data['Ver']) ? $data['Ver'] : "",
'area_id' => 1
]);
if ($device_id) {
$checkConnection = json_decode(common::requestToCardService("/CheckConnection", ["DeviceIP" => $data["IP"]]), true);
$datas = [];
for ($i = 1; $i <= intval($checkConnection["LockCount"]); $i++) {
$datas[] = [$device_id, $data["IP"] . "-" . $i, $i, time(), time()];
}
$door = new Door();
$door->multiCreate($datas);
common::insertSystemLogs(["action" => "insert", "description" => "Thêm mới thiết bị: " . $data["IP"], "type" => Yii::$app->controller->id]);
return ["status" => true, "IP" => $data["IP"], "SN" => $data["SN"]];
} else
return ["status" => false, "IP" => $data["IP"], "SN" => $data["SN"]];
}
}
public function actionSync() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
return [
"title" => Html::tag("i", "", ["class" => "fa fa-refresh"]) . " Đồng bộ dữ liệu đến thiết bị",
"form" => $this->renderPartial("sync"),
"lists" => Yii::$app->request->post("lists")
];
}
}
public function actionGetDataSync() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$device_id = Yii::$app->request->post("data");
$doors = Door::find()->andWhere(["device_id" => $device_id])->all();
$filter = ["OR"];
foreach ($doors as $key => $value) {
$filter[] = ["LIKE", "door_access", '"' . $value->id . '"'];
}
$staffs = Staff::find()->andWhere($filter)->all();
$schedule = [];
foreach ($staffs as $key => $value) {
$schedule[] = $value->schedule_id;
}
$schedule = array_unique($schedule);
return [
"IP" => $this->findModel($device_id)->ip_address,
"staffs" => $staffs,
"schedule" => $schedule
];
}
}
public function actionSyncSchedule() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$post = Yii::$app->request->post();
$schedule_lists = $post["data"];
$TimeZoneInfos = [];
foreach ($schedule_lists as $key => $value) {
$schedule = Schedule::findOne($value);
$TimeZoneInfos[] = [
"TimezoneId" => $schedule->id,
"SunTime1" => Schedule::convertTimeAttr($schedule->SunTime1), "SunTime2" => Schedule::convertTimeAttr($schedule->SunTime2), "SunTime3" => Schedule::convertTimeAttr($schedule->SunTime3),
"MonTime1" => Schedule::convertTimeAttr($schedule->MonTime1), "MonTime2" => Schedule::convertTimeAttr($schedule->MonTime2), "MonTime3" => Schedule::convertTimeAttr($schedule->MonTime3),
"TueTime1" => Schedule::convertTimeAttr($schedule->TueTime1), "TueTime2" => Schedule::convertTimeAttr($schedule->TueTime2), "TueTime3" => Schedule::convertTimeAttr($schedule->TueTime3),
"WedTime1" => Schedule::convertTimeAttr($schedule->WedTime1), "WedTime2" => Schedule::convertTimeAttr($schedule->WedTime2), "WedTime3" => Schedule::convertTimeAttr($schedule->WedTime3),
"ThuTime1" => Schedule::convertTimeAttr($schedule->ThuTime1), "ThuTime2" => Schedule::convertTimeAttr($schedule->ThuTime2), "ThuTime3" => Schedule::convertTimeAttr($schedule->ThuTime3),
"FriTime1" => Schedule::convertTimeAttr($schedule->FriTime1), "FriTime2" => Schedule::convertTimeAttr($schedule->FriTime2), "FriTime3" => Schedule::convertTimeAttr($schedule->FriTime3),
"SatTime1" => Schedule::convertTimeAttr($schedule->SatTime1), "SatTime2" => Schedule::convertTimeAttr($schedule->SatTime2), "SatTime3" => Schedule::convertTimeAttr($schedule->SatTime3),
"Hol1Time1" => 0, "Hol1Time2" => 0, "Hol1Time3" => 0,
"Hol2Time1" => 0, "Hol2Time2" => 0, "Hol2Time3" => 0,
"Hol3Time1" => 0, "Hol3Time2" => 0, "Hol3Time3" => 0
];
}
$res = json_decode(common::requestToCardService("/SetDeviceData/TimeZone", [
"DeviceIP" => $post["ip"],
"TimeZoneInfos" => $TimeZoneInfos
]), true);
return [
"res" => $res,
"IP" => $post["ip"]
];
}
}
public function actionSyncStaffs() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$post = Yii::$app->request->post();
$staff_lists = $post["data"];
$UserInfos = [];
$UserAuthorizeInfos = [];
foreach ($staff_lists as $key => $value) {
$UserInfos[] = [
"CardNo" => $value["card_number"],
"Pin" => $value["id"],
"Password" => "",
"Group" => "",
"StartTime" => "",
"EndTime" => ""
];
$doors = json_decode($value["door_access"], true);
foreach ($doors as $k => $v) {
$doorInfo = Door::findOne($v);
$UserAuthorizeInfos[] = [
"Pin" => $value["id"],
"AuthorizeTimezoneId" => $value["schedule_id"],
"AuthorizeDoorId" => $doorInfo->code
];
}
}
$resUser = json_decode(common::requestToCardService("/SetDeviceData/User", [
"DeviceIP" => $post["ip"],
"UserInfos" => $UserInfos
]), true);
common::requestToCardService("/SetDeviceData/UserAuthorize", [
"DeviceIP" => $post["ip"],
"UserAuthorizeInfos" => $UserAuthorizeInfos
]);
return [
"resUser" => $resUser,
"IP" => $post["ip"]
];
}
}
public function actionGetLogs() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
return [
"title" => Html::tag("i", "", ["class" => "fa fa-exchange"]) . " Lấy các sự kiện",
"form" => $this->renderPartial("logs"),
"lists" => Yii::$app->request->post("lists")
];
}
}
public function actionSyncLogs() {
if (Yii::$app->request->post()) {
Yii::$app->response->format = "json";
$device = $this->findModel(Yii::$app->request->post("data"));
$response = json_decode(common::requestToCardService("/GetDeviceData/GetLog", ["DeviceIP" => $device->ip_address]), true);
$datas = [];
foreach ($response as $key => $value) {
if ($value["Cardno"] !== "0")
$datas[] = [$value["Pin"], $value["Cardno"], $device->id, $value["DoorID"], $value["InOutState"], Logs::parseTime($value["Time_second"]), $value["EventType"]];
}
$model = new Logs();
if ($model->multiCreate($datas)) {
common::requestToCardService("/DeleteDeviceData/DeleteLog", ["DeviceIP" => $device->ip_address]);
}
return [
"totals" => count($datas),
"IP" => $device->ip_address
];
}
}
}