<?php
namespace App\Controller\Backend;
use App\Controller\Base\BaseController;
use App\Entity\MPlant;
use App\Entity\TLogplant;
use App\Entity\Tplant;
use App\Filter\MPlantFilterType;
use App\Filter\TplantFilterType;
use App\Form\MPlantType;
use App\Form\TplantType;
use App\Repository\MKategoriRepository;
use App\Repository\MPlantRepository;
use App\Repository\MSektorDetailRepository;
use App\Repository\MSektorRepository;
use App\Repository\TDivRepository;
use App\Repository\TLogplantRepository;
use App\Repository\TLogRepository;
use App\Repository\TplantRepository;
use App\Service\EmailSender;
use App\Services\FileUploader;
use App\Utils\ObjectManager;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
use Kematjaya\Breadcrumb\Lib\Builder as BreacrumbBuilder;
use Kematjaya\Export\Manager\ManagerInterface;
use Kematjaya\Export\Processor\Excel\SpreadsheetFromArrayProcessor;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Mailer\MailerInterface;
class MPlantController extends BaseController
{
private $pageName = 'plant';
private $class = MPlant::class;
/**
* @Route("/plant", name="plant", methods={"GET", "POST"})
*/
public function index(BreacrumbBuilder $builder, Request $request, PaginatorInterface $paginatorInterface): Response
{
$builder->add('Dashboard ', "dashboard", array(), " <i class='fa fa-home'></i>");
$builder->add('Plant');
$roles = $this->getUser()->getRoles()[0];
$form = $this->createFormFilter(MPlantFilterType::class);
$queryBuilder = $this->getQueryBuilder($this->class);
// if($roles == 'ROLE_KOTA' || $roles == 'ROLE_OPERATOR') {
// $queryBuilder->andWhere('this.div = :div_id');
// $queryBuilder->andWhere('this.status IN (:status)');
// $queryBuilder->setParameter('status', [2,3,4]);
// $queryBuilder->setParameter('div_id', $this->getUser()->getDivAkses()[0]);
// }
$queryBuilder = $this->buildFilter($request, $form, $queryBuilder)->addOrderBy("this.id", "DESC");
$this->setSessionLimit($request);
$maxPerPage = $request->getSession()->get("limit") ? $request->getSession()->get("limit") : $this->getLimit();
$pagination = $paginatorInterface->paginate($queryBuilder, $request->query->getInt('page', 1), $maxPerPage);
return $this->render('backend/plant/index.html.twig', [
'page_name' => $this->pageName,
'button_credential' => $this->buttonCredentials($this->pageName),
'filter' => $form->createView(),
'pagination' => $pagination,
]);
}
/**
* @Route("/plant/form/{id}", defaults={"id"= null}, name="plant_form", methods={"POST", "GET"})
*/
public function form(?string $id = null, Request $request, MPlantRepository $mPlantRepo)
{
if($id){
$m_plant = $mPlantRepo->find($id);
} else {
$m_plant = new MPlant();
}
if(!$m_plant){
throw new NotFoundHttpException();
}
$form = $this->createForm(MPlantType::class, $m_plant, ['action' => $this->generateUrl('plant_form', ['id' => $m_plant->getId()])]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($user);
$entityManager->flush();
return $this->redirectToRoute('plant');
}
return $this->render('/backend/plant/form.html.twig', ['form' => $form->createView()]);
}
/**
* @Route("/plant/{id}/delete_plant", name="plant_delete", methods={"GET"})
*/
public function delete(?string $id = null, MPlantRepository $mPlantRepo)
{
$plant = $mPlantRepo->find($id);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($plant);
$entityManager->flush();
$this->addFlash('notice', 'plant "' . $plant->getNama() . '" berhasil dihapus');
return $this->redirectToRoute('plant');
}
/**
* @Route("/add_selected", name="plant_add_selected", methods={"POST"})
*/
public function add_selected(Request $request, ObjectManager $objectManager)
{
$sessionName = $request->get("name");
$this->get('session')->set($sessionName, $request->get('selected'));
$selected = (!empty($this->get('session')->get($sessionName))) ? $this->get('session')->get($sessionName) : [];
return $this->json($selected);
}
/**
* @Route("plant/action_selected", name="plant_action_selected", methods={"POST"})
*/
public function action_selected(Request $request, ObjectManager $objectManager)
{
$sessionName = $request->get("name");
if ($this->isCsrfTokenValid($sessionName . '_action_selected', $request->request->get('_token')))
{
$selected = (!empty($this->get('session')->get($sessionName))) ? $this->get('session')->get($sessionName) : [];
$deleted = $objectManager->deleteByIds($this->class, $selected);
if($deleted) {
$this->get('session')->set($sessionName, []);
$this->addFlash('success', $this->getTranslator()->trans('messages.deleted.success'));
} else {
$this->addFlash('error', $this->getTranslator()->trans('messages.deleted.error'));
}
}
return $this->redirectToRoute('plant');
}
/**
* @Route("/plant/{id}/detail_plant", name="plant_detail", methods={"GET","POST"})
*/
public function detail(
BreacrumbBuilder $builder,
TplantRepository $tplantrepo,
Tplant $tplant,
TDivRepository $tDivRepository,
MSektorDetailRepository $mSektorDetailRepository,
TLogplantRepository $tLogplantRepository
)
{
$builder->add('Dashboard ', "dashboard", array(), " <i class='fa fa-home'></i>");
$builder->add('plant', 'plant');
$builder->add('Detail');
$detail = $tplantrepo->find($tplant);
$sektor = $detail->getSektor();
$m_opd = $tDivRepository->findAll();
$opd = $detail->getDiv() ? $detail->getDiv()->getId() : null;
if($sektor != null) {
if($detail->getDiv()) {
$m_sektor = $sektor ? $mSektorDetailRepository->findBy(['div' => $detail->getDiv()->getId()]) : null;
} else {
$m_sektor = $mSektorDetailRepository->findOneBy(['sektor' => $sektor->getId()]);
$opd = $m_sektor->getDiv()->getId();
}
} else {
$m_sektor = null;
}
return $this->render('backend/plant/detail.html.twig', [
'plants' => $detail,
'm_opd' => $m_opd,
'selected_sektor' => $sektor ? $sektor->getId() : null,
'm_sektor' => $m_sektor,
'selected_opd' => $opd,
]);
}
/**
* @Route("/plant/filter_sektor", name="plant_filter_sektor", methods={"GET","POST"})
*/
public function getSektorByOpd(Request $request, MSektorDetailRepository $mSektorDetailRepository) {
$mSektor = $mSektorDetailRepository->findBy(['div' => $request->get('div_id')], ['sektor' => 'asc']);
$results = [];
foreach($mSektor as $sektor) {
array_push($results, [
'id' => $sektor->getSektor()->getId(),
'nama' => $sektor->getSektor()->getNama()
]);
}
return new JsonResponse($results);
}
/**
* @Route("/plant/update_status", name="plant_update_status", methods={"POST"})
*/
public function updateStatus(Request $request,
ManagerRegistry $managerRegistry,
TplantRepository $tplantRepository,
TDivRepository $tDivRepository,
MSektorRepository $mSektorRepository
) {
$sektor = $request->get('sektor');
$opd = $request->get('perangkat_daerah');
$id = $request->get('plant_id');
$file = $request->files->get('input_file');
$status = $request->get('status');
$deskripsi = $request->get('deskripsi');
$plant = $tplantRepository->find(number_format($id));
$roles = $this->getUser()->getRoles()[0];
if (in_array('ROLE_WALIDATA', $this->getUser()->getRoles())) {
if($opd === "" || $sektor === "") {
$this->addFlash('error', 'Pilih OPD dan Sektor Terlebih Dahulu.');
return $this->redirectToRoute('plant_detail', ['id' => $id]);
}
$plant->setDiv($tDivRepository->find($opd));
$plant->setSektor($mSektorRepository->find($sektor));
$plant->setStatus(2);
}
$doctrine = $managerRegistry->getManager();
$doctrine->persist($plant);
$doctrine->flush();
$this->curlplant($plant);
$this->addFlash('notice', 'Update Status Berhasil.');
return $this->redirectToRoute('plant_detail', ['id' => $id]);
}
public function curlplant(Tplant $plant)
{
// dump( $this->getParameter('api_plant')); exit;
$data = [
"reff_id" => $plant->getId(),
"nama" => $plant->getNama(),
"telepon" => $plant->getTelepon(),
"email" => $plant->getEmail(),
"pekerjaan_id" => ($plant->getPekerjaan()) ? $plant->getPekerjaan()->getId() : null,
"desk_pekerjaan" => $plant->getDeskPekerjaan(),
"judul_data" => $plant->getJudulData(),
"desk_kebutuhan" => $plant->getDeskKebutuhan(),
"tujuan_data" => $plant->getTujuanData(),
"is_done" => $plant->getIsDone(),
"sektor" => $plant->getSektor() ? $plant->getSektor()->getId() : null,
"div_id" => ($plant->getDiv()) ? $plant->getDiv()->getId() : null,
'status' => $plant->getStatus()
];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $this->getParameter('api_plant'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Content-Type: multipart/form-data",
"x-token: " . $this->getParameter('token_post_plant')
),
CURLOPT_POSTFIELDS => $data
));
$response = curl_exec($curl);
// dump($response); exit;
curl_close($curl);
}
/**
* @Route("/plant/{id}/update_form", name="form_plant_update", methods={"GET"})
*/
public function formUpdateplantDataset(string $id) {
return $this->render('backend/plant/form_plant_dataset.html.twig', [
'id' => $id
]);
}
/**
* @Route("/plant/{path}/download_attachment", name="plant_download_attachment", methods={"GET"})
*/
public function downloadAttachmentData(string $path) {
$uploads_directory = $this->getParameter('uploads_directory');
$path = $uploads_directory . '/' . $path;
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/zip');
header("Content-Transfer-Encoding: Binary");
header('Content-Disposition: attachment; filename="' . $path . '"');
readfile($path);
}
/**
* @Route("/plant/{id}/done_plant", name="plant_done", methods={"GET", "POST"})
*/
public function done(Tplant $plant){
$plant->setIsDone(true);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($plant);
$entityManager->flush();
$this->addFlash('notice', 'plant "' . $plant->getNama() . '" berhasil diselesaikan');
return $this->redirectToRoute('plant');
}
/**
* @Route("/plant/report", name="plant_report", methods={"GET"})
*/
public function report(Request $request, MKategoriRepository $mKategoriRepo)
{
$kategori = $mKategoriRepo->findAll();
$bulan = $this->getBulan();
return $this->render('backend/plant/report.html.twig', [
'kategori' => $kategori,
'bulans' => $bulan
]);
}
/**
* @Route("/plant/download_report", name="plant_download_report", methods={"GET"})
*/
public function download_report(Request $request, TplantRepository $tplantrepo, ManagerInterface $managerInterface)
{
$filterSektor = [];
if ($request->get('sektor')) {
$filterSektor['sektor'] = $request->get('sektor') == "" ? null : $request->get('sektor');
}
$bulan = $request->get('bulan');
$tahun = $request->get('tahun');
$startDate = new \DateTimeImmutable("01-$bulan-$tahun-01T00:00:00");
$endDate = $startDate->modify('last day of this month')->setTime(23, 59, 59);
$tplant = $tplantrepo->getPerhonanByMonthSectorAndYear($filterSektor, $startDate, $endDate);
$data = [["No", "Nama", "Telepon", "Email", "Pekerjaan", "Deskripsi Pekerjaan", "Tanggal Buat", "Judul Data", "Perangkat Daerah", "Tujuan Data", "Sektor", "Status"]];
$no = 1;
foreach ($tplant as $plant) {
$data[] = [
$no++,
$plant->getNama(),
$plant->getTelepon(),
$plant->getEmail(),
($plant->getPekerjaan()) ? $plant->getPekerjaan()->getNama() : "",
$plant->getDeskPekerjaan(),
$plant->getCreatedAt(),
$plant->getJudulData(),
($plant->getDiv()) ? $plant->getDiv()->getDivNama() : "",
$plant->getTujuanData(),
($plant->getSektor()) ? $plant->getSektor()->getNama() : "",
($plant->getIsDone()) ? "Selesai" : "Belum"
];
}
$arrayToExcel = $managerInterface->render($data, new SpreadsheetFromArrayProcessor('plant_data.xlsx'));
return $arrayToExcel;
}
}