<?php
namespace App\Controller\Admin\StockTransfer;
use App\Dto\Stock\StockTransferProductsDto;
use App\Entity\BuyInTurkey;
use App\Entity\Container;
use App\Entity\NewStockTransfer;
use App\Entity\NewTransferProducts;
use App\Entity\Product;
use App\Entity\Sales;
use App\Entity\Stock;
use App\Entity\StockInfo;
use App\Entity\StockTransaction;
use App\Entity\StockTransfer;
use App\Entity\StockTransferProducts;
use App\Entity\Warehouse;
use App\Enum\StockTransactionSource;
use App\Exception\StockNotAvaibleException;
use App\Exception\StockNotFoundException;
use App\Exception\StockTransferWasAdded;
use App\Form\AddStockTransferFormType;
use App\Form\AddStockTransferProductsFormType;
use App\Form\NewStockTransferFormType;
use App\Services\BuyInTurkey\BuyInTurkeyService;
use App\Services\Product\ProductService;
use App\Services\Stock\StockInfoService;
use App\Services\Stock\StockService;
use App\Services\Stock\StockTransferService;
use App\Services\StockTransactionService;
use App\Services\Warehouse\WarehouseService;
use App\Utils\CurrencyHelper;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query;
use PHPUnit\Exception;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
class StockTransferController extends AbstractController
{
private WarehouseService $warehouseService;
private ProductService $productService;
private StockTransferService $stockTransferService;
private StockInfoService $stockInfoService;
private EntityManagerInterface $entityManager;
private TranslatorInterface $translator;
private StockService $stockService;
private BuyInTurkeyService $buyInTurkeyService;
private LoggerInterface $logger;
private StockTransactionService $stockTransactionService;
/**
* @param EntityManagerInterface $entityManager
*/
public function __construct(EntityManagerInterface $entityManager, TranslatorInterface $translator, LoggerInterface $logger, StockTransactionService $stockTransactionService)
{
$this->entityManager = $entityManager;
$this->translator = $translator;
$this->logger = $logger;
$this->stockTransactionService = $stockTransactionService;
}
#[Route('/admin/stock-transfer', name: 'app_admin_stock_transfer')]
public function index(Request $request, EntityManagerInterface $entityManager): Response
{
$transactions = $entityManager->getRepository(StockTransaction::class)->findAll();
return $this->render('admin/stock_transfer/index.html.twig', [
'transactions' => $transactions
]);
}
#[Route('/admin/stock-transfer/new', name: 'app_admin_stock_transfer_new')]
public function new(Request $request, EntityManagerInterface $entityManager): Response
{
$stocktransfer = new StockTransfer();
$form = $this->createForm(AddStockTransferFormType::class, $stocktransfer);
$stocktransferProducts = new StockTransferProducts();
$stockTransferProductForm = $this->createForm(AddStockTransferProductsFormType::class, $stocktransferProducts);
$mainWarehouse = $this->warehouseService->getMainWarehouse();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($request->get('productName')) {
$stocktransferProducts = new ArrayCollection();
for ($i = 0; $i < count($request->get('productName')); $i++) {
try {
$this->stockInfoService->checkIsStockAvailable($request->get('quantity')[$i], $request->get('productId')[$i], $mainWarehouse->getId());
} catch (StockNotAvaibleException | StockNotFoundException $e) {
$this->addFlash('error', $e->getMessage());
return $this->redirectToRoute('app_admin_stock_transfer_new');
}
$stocktransferProducts->add(
new StockTransferProductsDto(
$request->get('productName')[$i],
$request->get('quantity')[$i],
round($request->get('unitPriceFob')[$i], 3),
round($request->get('unitPriceNavlun')[$i], 3),
round($request->get('totalUnitPrice')[$i], 3),
round($request->get('totalSalePrice')[$i], 3),
round($request->get('productId')[$i], 3),
)
);
}
try {
$stocktransfer = $this->stockTransferService->create($form->getData(), $stocktransferProducts);
dd("asdasd");
return $this->redirectToRoute('app_admin_stock_transfer');
} catch (Exception | StockTransferWasAdded $exception) {
$this->addFlash('error', $exception->getMessage());
}
}
}
$warehousesWithoutMain = $this->warehouseService->getAll();
return $this->render('admin/stock_transfer/add.html.twig', [
'controller_name' => 'StockTransferController',
'form' => $form->createView(),
'mainWarehouse' => $mainWarehouse,
'warehouses' => $warehousesWithoutMain,
'stockTransferProducts' => $stockTransferProductForm->createView()
]);
}
#[Route('/admin/stock-transfer/add-containers', name: 'app_admin_stock_transfer_addcontainers')]
public function addContainers(Request $request)
{
$arrivalWarehouse = $request->get('arrival_warehouse');
$containerNumber = $request->get('container_number');
$invoiceNumber = $request->get('invoice_number');
$konsimento = $request->get('konsimento');
$totalNavlun = $request->get('total_navlun');
$description = $request->get('description');
$warehouseOutDate = $request->get('warehouse_out_date');
$warehouseArrivalDate = $request->get('warehouse_arrival_date');
if (!$arrivalWarehouse || !$containerNumber || !$invoiceNumber || !$konsimento || !$totalNavlun || !$description || !$warehouseOutDate) {
return $this->redirectToRoute('app_admin_stock_transfer_new');
}
return $this->render('admin/stock_transfer/addcontainers.html.twig', [
'numberOfContainer' => $containerNumber,
'arrivalWarehouse' => $arrivalWarehouse,
'invoiceNumber' => $invoiceNumber,
'konsimento' => $konsimento,
'totalNavlun' => $totalNavlun,
'description' => $description,
'warehouseOutDate' => $warehouseOutDate,
'warehouseArrivalDate' => $warehouseArrivalDate
]);
}
private function checkTransfer($transferId)
{
$stockTransferRepo = $this->entityManager->getRepository(NewStockTransfer::class);
$stockTransfer = $stockTransferRepo->find($transferId);
$totalPrice = 0.00;
foreach ($stockTransfer->getContainers() as $container) {
$totalContainer = 0.00;
foreach ($container->getNewTransferProducts() as $transferProduct) {
$totalPrice += round($transferProduct->getTotalCostPrice(), 3) * round($transferProduct->getQuantity(), 3);
$totalContainer += round($transferProduct->getTotalCostPrice(), 3) * round($transferProduct->getQuantity(), 3);
}
$container->setTotalPrice($totalContainer);
$this->entityManager->persist($container);
$this->entityManager->flush();
}
return CurrencyHelper::convertToCurrency($totalPrice);
}
#[Route('/admin/stock-transfer/accept/{id}', name: 'app_admin_stock_transfer_accep')]
public function acceptTransfer(Request $request, $id, EntityManagerInterface $entityManager)
{
$stocktransfer = $this->entityManager->getRepository(NewStockTransfer::class)->find($id);
$form = $this->createForm(NewStockTransferFormType::class, $stocktransfer);
$stocktransferProduct = new StockTransferProducts();
$stockTransferProductForm = $this->createForm(AddStockTransferProductsFormType::class, $stocktransferProduct);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($request->get('containerId')) {
$this->entityManager->beginTransaction();
try {
$stocktransferProductsArr = new ArrayCollection();
for ($i = 0; $i < count($request->get('containerId')); $i++) {
if ($request->get('isTransfered')[$i] == 1) {
$containerId = $request->get('containerId')[$i];
$containerRepository = $this->entityManager->getRepository(Container::class);
$container = $containerRepository->find($containerId);
if ($container->isTransfered() == false) {
$products = $request->get($container->getId());
$productNames = $products['productName'];
$productQuantities = $products['quantity'];
$productTotalPrices = $products['totalPrice'];
$productIds = $products['productId'];
for ($j = 0; $j < count($productIds); $j++) {
$product = $this->productService->getEntityId($productIds[$j]);
$container->setIsTransfered(true);
$newStockTransferProduct = $this->entityManager->getRepository(NewTransferProducts::class)
->findOneBy(['container' => $container, 'product' => $product]);
$newStockTransferProduct->setOnaylananQuantity($productQuantities[$j]);
$entityManager->persist($newStockTransferProduct);
$entityManager->flush();
$stock = new Stock();
$stock->setProduct($product);
$stock->setNewStockTransfer($stocktransfer);
$stock->setPriceNavlun($newStockTransferProduct->getNavlun());
$stock->setPriceFob($newStockTransferProduct->getPriceFob());
$stock->setQuantity($productQuantities[$j]);
$stock->setTotalUnitPrice($productTotalPrices[$j]);
$stock->setWarehouse($stocktransfer->getArrivalWarehouse());
$stock->setInvoiceNumber($stocktransfer->getInvoiceNumber());
$stock->setWarehouseArrivalDate(new \DateTimeImmutable('now'));
$stock->setBuyingDate(new \DateTimeImmutable('now'));
$stock->setBuyingCompany('transfer');
$stock->setContainerNumber($container->getContainerNumber());
$stock->setKonsimento($stocktransfer->getKonsimento());
$stock->setPurchaseTotalAmount(0);
$this->entityManager->persist($stock);
$this->entityManager->flush();
$beforeQuantity = $this->stockInfoService->getStockInfoByProductAndWarehouse($product, $stocktransfer->getArrivalWarehouse())->getTotalQuantity();
$this->stockInfoService->addStock($product, $stocktransfer->getArrivalWarehouse(), CurrencyHelper::convertToFloat($productQuantities[$j]));
$this->log(
$product->getName(),
"Stock Transfer eklendi bu yüzden stok eklendi",
CurrencyHelper::convertToFloat($productQuantities[$j]),
$beforeQuantity,
$this->stockInfoService->getStockInfoByProductAndWarehouse($product, $stocktransfer->getArrivalWarehouse())->getTotalQuantity(),
"IN",
$stocktransfer,
$product,
null,
$stocktransfer->getArrivalWarehouse()
);
$this->entityManager->persist($container);
$this->entityManager->flush();
$this->logger->info(sprintf(
"Stok transfer onaylandı. Stok eklendi. Ürün adı= %s, ÜrünId= %s, Miktar= %s, StockId= %s, StokTransferId= %s",
$product->getName(),
$product->getId(),
$productQuantities[$j],
$stock->getId(),
$stocktransfer->getId()
));
}
}
}
}
$isTransferedCompleted = true;
foreach ($stocktransfer->getContainers() as $container) {
if (!$container->isTransfered()) {
$isTransferedCompleted = false;
break;
}
}
if ($isTransferedCompleted) {
$stocktransfer->setIsCompleted(true);
$this->entityManager->persist($stocktransfer);
$this->entityManager->flush();
} else {
$stocktransfer->setIsCompleted(false);
$this->entityManager->persist($stocktransfer);
$this->entityManager->flush();
}
$this->entityManager->commit();
// $this->stockTransferService->acceptTransfer($form->getData(), $stocktransferProductsArr);
return $this->redirect('/admin/stock-transfer');
} catch (Exception | StockTransferWasAdded $exception) {
$this->entityManager->rollback();
$this->addFlash('error', $exception->getMessage());
}
}
}
// dd($stocktransfer->getContainers()->get(0)->getNewTransferProducts()->get(0)->getProduct()->getId());
$warehousesWithoutMain = $this->warehouseService->getAllWithoutMainWarehouse();
$this->checkTransfer($id);
return $this->render('admin/stock_transfer/acceptransfer.html.twig', [
'form' => $form->createView(),
'stockTransfer' => $stocktransfer,
'stockTransferProducts' => $stockTransferProductForm->createView()
]);
}
#[Route('/new-stock-transfer-delete/{id}', name: 'new_stock_transfer_delete')]
public function delete(Request $request, $id)
{
$repo = $this->entityManager->getRepository(NewStockTransfer::class);
$entity = $repo->find($id);
if (!$entity) {
$this->addFlash('error', sprintf("%s id ile kayıtlı stock transfer bulunamadı", $id));
return $this->redirectToRoute('app_admin_stock_transfer');
}
$this->entityManager->beginTransaction();
try {
$warehouse = $entity->getArrivalWarehouse();
foreach ($entity->getContainers() as $container) {
if ($container->isTransfered()) {
foreach ($container->getNewTransferProducts() as $product) {
$beforeQuantity = $this->stockInfoService->getStockInfoByProductAndWarehouse($product->getProduct(), $warehouse)->getTotalQuantity();
$this->stockInfoService->dropStock($product->getQuantity(), $warehouse, $product->getProduct());
$this->log(
$product->getProduct()->getName(),
"Stok transfer siliniyor bu yüzden stok düşülüyor",
$product->getQuantity(),
$beforeQuantity,
$this->stockInfoService->getStockInfoByProductAndWarehouse($product->getProduct(), $warehouse)->getTotalQuantity(),
"OUT",
null,
$product->getProduct(),
null,
$warehouse
);
$this->entityManager->remove($product);
}
$this->entityManager->remove($container);
} else {
foreach ($entity->getContainers() as $container) {
foreach ($container->getNewTransferProducts() as $product)
$this->entityManager->remove($product);
$this->entityManager->remove($container);
}
}
}
$stocks = $this->entityManager->getRepository(Stock::class)->findBy(['newStockTransfer' => $entity]);
foreach ($stocks as $stock) {
$this->entityManager->remove($stock);
}
$this->entityManager->remove($entity);
$this->entityManager->flush();
$this->entityManager->commit();
$this->addFlash('success', "Stok transferi başarıyla silindi. Stoklar geri alındı.");
return $this->redirectToRoute('app_admin_stock_transfer');
} catch (\Exception $exception) {
$this->entityManager->rollback();
throw $exception;
}
}
#[Route('/admin/stocktransfer/add-new', name: 'admin_stocktransfer_add_new')]
public function addStockTransfer(Request $request, EntityManagerInterface $entityManager)
{
$entityManager->beginTransaction();
try {
$warehouse = $this->warehouseService->getEntityById($request->get('arrivalWarehouse'));
$stockTransfer = new NewStockTransfer();
$stockTransfer->setDescription($request->get('description'));
$stockTransfer->setArrivalWarehouse($warehouse);
$stockTransfer->setInvoiceNumber($request->get('invoiceNumber'));
$stockTransfer->setKonsimento($request->get('konsimento'));
$stockTransfer->setTotalNavlun(CurrencyHelper::convertToFloat($request->get('totalNavlun')));
$stockTransfer->setContainerNumber($request->get('numberOfContainer'));
$stockTransfer->setDateOfOutCustoms(new \DateTime($request->get('warehouseOutDate')));
$stockTransfer->setDateOfArrivalWarehouse(new \DateTime($request->get('warehouseOutDate')));
$stockTransfer->setIsCompleted(false);
$entityManager->persist($stockTransfer);
$entityManager->flush();
$navlunPricePerContainer = CurrencyHelper::convertToFloat($request->get('totalNavlun')) / CurrencyHelper::convertToFloat($request->get('numberOfContainer'));
for ($i = 0; $i < $request->get('numberOfContainer'); $i++) {
$containerNumber = $request->get('containerNumber-' . $i + 1)[0];
$container = new Container();
$container->setContainerNumber($containerNumber);
$container->setTotalNavlun($navlunPricePerContainer);
$container->setNewStockTransfer($stockTransfer);
$container->setIsTransfered(false);
$totalPriceInContainer = $request->get($i + 1);
$totalPrice = 0.00;
foreach ($totalPriceInContainer['totalSalePrice'] as $singlePrice) {
$totalPrice += CurrencyHelper::convertToFloat($singlePrice);
}
$totalQuantity = 0.00;
foreach ($totalPriceInContainer['quantity'] as $singleQuantity) {
$totalQuantity += CurrencyHelper::convertToFloat($singleQuantity);
}
$container->setTotalPrice($totalPrice + $navlunPricePerContainer);
$container->setTotalProductUnit($totalQuantity);
$totalUnitNavlunPrice = $navlunPricePerContainer / $totalQuantity;
$container->setUnitNavlunPrice($totalUnitNavlunPrice);
$entityManager->persist($container);
$entityManager->flush();
for ($j = 0; $j < count($request->get($i + 1)['productName']); $j++) {
$productInfo = $request->get($i + 1);
$newStockTransferProduct = new NewTransferProducts();
$newStockTransferProduct->setQuantity(CurrencyHelper::convertToFloat($productInfo['quantity'][$j]));
$newStockTransferProduct->setBooking(CurrencyHelper::convertToFloat($productInfo['unitPriceNavlun'][$j]));
$newStockTransferProduct->setQuantity(CurrencyHelper::convertToFloat($productInfo['quantity'][$j]));
$newStockTransferProduct->setCustomsPrice(CurrencyHelper::convertToFloat($productInfo['customsPrice'][$j]));
$newStockTransferProduct->setLashing(CurrencyHelper::convertToFloat($productInfo['lashing'][$j]));
$newStockTransferProduct->setPriceFob(CurrencyHelper::convertToFloat($productInfo['unitPriceFob'][$j]));
$newStockTransferProduct->setProfitMargin(CurrencyHelper::convertToFloat($productInfo['profitMargin'][$j]));
$unitPriceFob = round(CurrencyHelper::convertToFloat($productInfo['unitPriceFob'][$j]), 3);
$unitNavlunPrice = round(CurrencyHelper::convertToFloat($productInfo['unitPriceNavlun'][$j]), 3);
$totalCostPrice = $unitPriceFob + $unitNavlunPrice + round($totalUnitNavlunPrice, 3);
$newStockTransferProduct->setTotalCostPrice($totalCostPrice);
$newStockTransferProduct->setTransportPrice(CurrencyHelper::convertToFloat($productInfo['transportPrice'][$j]));
$buyInTurkeyRepo = $this->entityManager->getRepository(BuyInTurkey::class);
$product = $this->productService->getEntityId($buyInTurkeyRepo->find($productInfo['productId'][$j])->getProduct());
$newStockTransferProduct->setProduct($product);
$newStockTransferProduct->setContainer($container);
$newStockTransferProduct->setBuyingPrice(0);
$newStockTransferProduct->setNavlun($totalUnitNavlunPrice);
$totalPurchasePrice = $totalCostPrice * CurrencyHelper::convertToFloat($productInfo['quantity'][$j]);
$newStockTransferProduct->setTotalPurchasePrice($totalPurchasePrice);
$entityManager->persist($newStockTransferProduct);
$entityManager->flush();
$buyInTurkeyRow = $entityManager->getRepository(BuyInTurkey::class)->find($productInfo['productId'][$j]);
$quantity = $buyInTurkeyRow->getQuantity();
$newQuantity = CurrencyHelper::convertToFloat($quantity) - CurrencyHelper::convertToFloat($productInfo['quantity'][$j]);
$buyInTurkeyRow->setQuantity($newQuantity);
if ($newQuantity <= 0) {
$buyInTurkeyRow->setIsTransported(true);
}
$entityManager->persist($buyInTurkeyRow);
$entityManager->flush();
}
}
$entityManager->commit();
$this->checkTransfer($stockTransfer->getId());
} catch (\Exception $exception) {
$entityManager->rollback();
throw $exception;
}
return $this->redirectToRoute('app_admin_stock_transfer');
}
#[Route('/admin/stocktransfer/report', name: 'admin_stocktransfer_report')]
public function reportStockTransfer(Request $request)
{
$year = $request->get('year');
$year = new \DateTime($year . '-01-01');
$nextYear = clone $year;
$nextYear->modify('+1 years');
$fields = [
'SUM(newtransferproducts.quantity) as totalQuantity',
// 'SUM(newtransferproducts.totalPurchasePrice) as totalPurchasePrice',
// 'AVG(newtransferproducts.navlun) as averageNavlun', // Navlunun ortalama değeri
// 'AVG(newtransferproducts.totalCostPrice / newtransferproducts.quantity) as averageUnitCost', // Birim başına maliyetin ortalama değeri
'product.name as name',
'measurementUnit.name as measurement',
'product.code as code',
'product.id as productId'
];
$stockTransfer = $this->entityManager->getRepository(NewStockTransfer::class)
->createQueryBuilder('c')
->select($fields)
->leftJoin('c.containers', 'containers')
->leftJoin('containers.newTransferProducts', 'newtransferproducts')
->leftJoin('newtransferproducts.product', 'product')
->leftJoin('product.measurementUnit', 'measurementUnit')
->where('c.dateOfOutCustoms >= :year')
->andWhere('c.dateOfOutCustoms <= :nextYear')
->setParameter('year', $year)
->setParameter('nextYear', $nextYear)
->groupBy('newtransferproducts.product')
->getQuery()
->getResult();
return $this->render('admin/stock_transfer/stocktransferreport.html.twig', [
'datas' => $stockTransfer
]);
}
#[Route('/admin/stocktransfer/gettransferspermonth/{id}/{year}', name: 'admin_stocktransfer_getTransfersPerMonth')]
public function getTransfersPerMount(Request $request, $id, $year)
{
$product = $this->entityManager->getRepository(Product::class)->find($id);
$transferedProductsRepo = $this->entityManager->getRepository(NewTransferProducts::class);
$startDate = new \DateTime($year . '-01-01');
$endDate = new \DateTime($year . '-12-31');
$data[] = [];
$data['product'] = $product->getName();
$data['productId'] = $product->getId();
$data['productCode'] = $product->getCode();
$data['productMeasurement'] = $product->getMeasurementUnit()->getName();
while ($startDate <= $endDate) {
$month = $startDate->format('m');
$year = $startDate->format('Y');
// echo "AY :" . $month . "<br>";
$data['months'][$month] = [];
while ($startDate->format('Y') == $year && $startDate->format('m') == $month) {
$weekStartDate = clone $startDate;
$weekEndDate = clone $startDate;
$weekEndDate->modify('+6 days');
$startDateClone = clone $startDate;
$nextMonth = $startDate->format('m') !== $startDateClone->modify('+7 days')->format('m');
if ($nextMonth) {
$weekEndDate = $startDate->modify('last day of this month');
}
$transferedQuantity = $transferedProductsRepo
->createQueryBuilder('c')
->leftJoin('c.container', 'container')
->leftJoin('container.newStockTransfer', 'newStockTransfer')
->select("SUM(c.quantity) as quantity")
->where('c.product = :product')
->setParameter('product', $product->getId())
->andWhere('newStockTransfer.dateOfOutCustoms >= :startDate')
->andWhere('newStockTransfer.dateOfOutCustoms <= :finishDate')
->setParameter('startDate', $weekStartDate)
->setParameter('finishDate', $weekEndDate)
->getQuery()
->getResult()[0];
if ($transferedQuantity["quantity"])
$data['months'][$month][$weekStartDate->format('d-m-Y') . "_" . $weekEndDate->format('d-m-Y')] = $transferedQuantity['quantity'];
//echo "Hafta başlangıç :" . $weekStartDate->format('d.m.Y') . " Hafta Bitiş :" . $weekEndDate->format('d.m.Y') . "<br>";
if ($nextMonth)
$startDate->modify('first day of next month'); // Ay sonraki ayın 1. gününe geçmek için
else
$startDate->modify('+7 days');
}
if (empty($data['months'][$month]))
unset($data['months'][$month]);
}
return $this->render('admin/stock_transfer/stocktransferdetailrow.html.twig', [
'datas' => $data
]);
dd($data);
dd("assd");
while ($startDate <= $endDate) {
$year = $startDate->format('Y');
$month = $startDate->format('m');
$week = $startDate->format('W');
echo $startDate->format('F Y') . ":\n";
while ($startDate->format('Y') === $year && $startDate->format('m') === $month) {
$weekStartDate = clone $startDate;
$weekEndDate = clone $startDate;
$weekEndDate->modify('+6 days');
echo "Week $week: " . $weekStartDate->format('d.m.Y') . " - " . $weekEndDate->format('d.m.Y') . "\n";
$startDate->modify('+1 week');
$week = $startDate->format('W');
}
}
// dd($stockTransferStartDate->format('Y'), $stockTransferEndDate->format('Y'));
dd("sada");
return new Response();
}
#[Route('/admin/stocktransfer/main-warehouse-avaible-products', name: 'admin_stocktransfer_getmainwarehouse_avaible_stocks')]
public function getMainWarehouseAvaibleStocks(Request $request)
{
$fields = ['c.id as buyingId', 'product.code as code', 'product.id as productId', 'product.name as productName', 'c.quantity as totalQuantity'];
$buyinTurkeyRepo = $this->entityManager->getRepository(BuyInTurkey::class);
$avaibleStocks = $buyinTurkeyRepo->createQueryBuilder('c')
->select($fields)
->leftJoin('c.product', 'product')
->where('c.isTransported = 0')
->getQuery()
->getArrayResult();
// $avaibleStocks = $this->buyInTurkeyService->getUnTransferedProducts();
return $this->json($avaibleStocks);
}
#[Route('/admin/stocktransfer/accepted/{id}', name: 'admin_stocktransfer_accepted')]
public function acceptedTransfer(Request $request, $id)
{
$stocktransfer = $this->entityManager->getRepository(StockTransfer::class)->find($id);
if ($stocktransfer->getTransaction()->getName() == 'YOLDA') {
return $this->redirectToRoute('admin_stock_transfer_edit', ['id' => $stocktransfer->getId()]);
}
$stocks = $this->stockService->getByStockTransfer($stocktransfer);
$form = $this->createForm(AddStockTransferFormType::class, $stocktransfer);
$stocktransferProduct = new StockTransferProducts();
$stockTransferProductForm = $this->createForm(AddStockTransferProductsFormType::class, $stocktransferProduct);
$stocktransferProductsData = $stocktransfer->getProducts();
$mainWarehouse = $this->warehouseService->getMainWarehouse();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($request->get('productName')) {
$stocktransferProductsArr = new ArrayCollection();
for ($i = 0; $i < count($request->get('productName')); $i++) {
$stocktransferProductsArr->add(
new StockTransferProductsDto(
$request->get('productName')[$i],
$request->get('quantity')[$i],
$request->get('unitPriceFob')[$i],
$request->get('unitPriceNavlun')[$i],
$request->get('totalUnitPrice')[$i],
$request->get('totalSalePrice')[$i],
$request->get('productId')[$i]
)
);
}
try {
$this->stockTransferService->acceptTransfer($form->getData(), $stocktransferProductsArr);
$this->checkTransfer($id);
return $this->redirect('/admin/stock-transfer');
} catch (Exception | StockTransferWasAdded $exception) {
$this->addFlash('error', $exception->getMessage());
}
}
}
$this->checkTransfer($id);
$warehousesWithoutMain = $this->warehouseService->getAllWithoutMainWarehouse();
return $this->render('admin/stock_transfer/acceptedtransfers.html.twig', [
'form' => $form->createView(),
'stockTransferProductsData' => $stocktransferProductsData,
'stockTransferProducts' => $stockTransferProductForm->createView(),
'stocks' => $stocks
]);
}
#[Route('/admin/stocktransfer/product/information/{buyinTurkeyId}', name: 'admin_stocktransfer_product_info')]
public function getProductInfoFromBuyinTurkey(Request $request, $buyinTurkeyId)
{
$fields = [
'measurement.thickness',
'measurement.width as width',
'measurement.length as length',
'c.totalCostPrice as avgUnitPrice',
'c.lashing as lashing',
'c.customsPrice as customsPrice',
'c.buyingPrice as buyingPrice',
'c.totalCostPrice as avgPriceFob',
'c.profitMargin as profitMargin',
'c.transportPrice as transportPrice',
];
$repo = $this->entityManager->getRepository(BuyInTurkey::class);
$query = $repo->createQueryBuilder('c')
->leftJoin('c.product', 'product')
->leftJoin('product.measurement', 'measurement')
->leftJoin('product.measurementUnit', 'measurementUnit')
->select($fields)
->where('c.id = :id')
->setParameter('id', $buyinTurkeyId)
->andWhere('c.isTransported = false')
->getQuery()
->getSingleResult();
// $productInfo = $this->buyInTurkeyService->getProductInfoById($productid);
// dd($query);
return $this->json($query);
}
#[Route('/admin/stock-transfer/edit/{id}', name: 'admin_stock_transfer_edit')]
public function edit(Request $request, $id)
{
$stocktransfer = $this->entityManager->getRepository(StockTransfer::class)->find($id);
if ($stocktransfer->getTransaction()->getName() == 'TAMAMLANDI') {
return $this->redirectToRoute('admin_stocktransfer_accepted', ['id' => $stocktransfer->getId()]);
}
$form = $this->createForm(AddStockTransferFormType::class, $stocktransfer);
$stocktransferProduct = new StockTransferProducts();
$stockTransferProductForm = $this->createForm(AddStockTransferProductsFormType::class, $stocktransferProduct);
$stocktransferProductsData = $stocktransfer->getProducts();
$mainWarehouse = $this->warehouseService->getMainWarehouse();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
if ($request->get('productName')) {
$stocktransferProductsArr = new ArrayCollection();
for ($i = 0; $i < count($request->get('productName')); $i++) {
try {
$this->stockInfoService->checkIsStockAvailable($request->get('quantity')[$i], $request->get('productId')[$i], $mainWarehouse->getId());
} catch (StockNotAvaibleException | StockNotFoundException $e) {
$this->addFlash('error', $e->getMessage());
return $this->redirectToRoute('app_admin_stock_transfer_new');
}
$stocktransferProductsArr->add(
new StockTransferProductsDto(
$request->get('productName')[$i],
$request->get('quantity')[$i],
$request->get('unitPriceFob')[$i],
$request->get('unitPriceNavlun')[$i],
$request->get('totalUnitPrice')[$i],
$request->get('totalSalePrice')[$i],
$request->get('productId')[$i]
)
);
}
try {
$this->stockTransferService->update($form->getData(), $stocktransferProductsArr);
return $this->redirectToRoute('admin_stock_transfer_edit', ['id' => $stocktransfer->getId()]);
} catch (Exception | StockTransferWasAdded $exception) {
$this->addFlash('error', $exception->getMessage());
}
}
}
$warehousesWithoutMain = $this->warehouseService->getAllWithoutMainWarehouse();
return $this->render('admin/stock_transfer/edit.html.twig', [
'form' => $form->createView(),
'stockTransferProductsData' => $stocktransferProductsData,
'stockTransferProducts' => $stockTransferProductForm->createView()
]);
}
#[Route('/admin/stock-transfer/show', name: 'app_admin_stock_transfer_show')]
public function show(Request $request)
{
$s = $request->get('search')['value'];
$id = $request->get('id');
$column = $request->get('order')[0]['column'];
$dir = $request->get('order')[0]['dir'];
$limit = $request->get('length');
if ($request->get('start'))
$page = 1 + ($request->get('start') / $limit);
else
$page = 1;
$stockTransferStatusId = $request->get('transactionid');
$stocks = $this->createArrayForDataTable(
$this->stockTransferService->getAllStockTransfersPaginate($page, $limit, $stockTransferStatusId, 1, $dir, $s)
);
$this->sortArrayByKey($stocks['data'], $column, false, $dir == 'asc');
return new JsonResponse($stocks);
}
function sortArrayByKey(&$array, $key, $string = false, $asc = true)
{
if ($string) {
usort($array, function ($a, $b) use (&$key, &$asc) {
if ($asc)
return strcmp(strtolower($a[$key]), strtolower($b[$key]));
else
return strcmp(strtolower($b[$key]), strtolower($a[$key]));
});
} else {
usort($array, function ($a, $b) use (&$key, &$asc) {
if ($a[$key] == $b[$key]) {
return 0;
}
if ($asc)
return ($a[$key] < $b[$key]) ? -1 : 1;
else
return ($a[$key] > $b[$key]) ? -1 : 1;
});
}
}
public function log(
$name,
$description,
$quantity,
$beforeQuantity,
$afterQuantity,
$action,
?NewStockTransfer $stockTransfer,
?Product $product,
?Sales $sales,
?Warehouse $warehouse,
) {
$stockTransaction = new StockTransaction();
$stockTransaction->setName($name);
$stockTransaction->setDescription($description);
$stockTransaction->setQuantity($quantity);
$stockTransaction->setAfterQuantity($afterQuantity);
$stockTransaction->setBeforeQuantity($beforeQuantity);
$stockTransaction->setSource(StockTransactionSource::TRANSFER);
$stockTransaction->setAction($action);
// $stockTransaction->addStockTransfer(null);
$stockTransaction->setProductId($product);
$stockTransaction->setSale($sales);
$stockTransaction->setWarehouse($warehouse);
$this->stockTransactionService->create($stockTransaction);
}
private function createArrayForDataTable($stocks): array
{
$records = [];
$records['recordsTotal'] = $stocks->getTotalItemCount();
$records['recordsFiltered'] = $stocks->getTotalItemCount();
$records["data"] = [];
foreach ($stocks as $entity) {
// $entity = new NewStockTransfer();
$totalAmount = 0.00;
foreach ($entity->getContainers() as $container) {
$totalAmount += $container->getTotalPrice();
}
$records["data"][] = array(
$entity->getId(),
$entity->getInvoiceNumber(),
$entity->getContainerNumber(),
$entity->getKonsimento(),
$entity->getArrivalWarehouse()->getName(),
CurrencyHelper::convertToCurrency($totalAmount),
$entity->getDateOfOutCustoms()->format('d.m.Y'),
!$entity->isIsCompleted() ? '<a class="btn btn-success" target="_blank" href="' . $this->generateUrl('app_admin_stock_transfer_accep', ['id' => $entity->getId()]) . '">' . $this->translator->trans('forms.stocktransfer.newstocktransfer.accept') . '</a>' : "Tamamlandı",
);
}
return $records;
}
public function getUnTransferedStockTransfers()
{
$repo = $this->entityManager->getRepository(NewStockTransfer::class);
$result = $repo->findBy(['isCompleted' => false]);
return $this->render('admin/components/customswaitingfr.html.twig', [
'result' => $result,
'resultCount' => count($result)
]);
}
public function setWarehouseService(WarehouseService $warehouseService): void
{
$this->warehouseService = $warehouseService;
}
public function setProductService(ProductService $productService): void
{
$this->productService = $productService;
}
public function setStockTransferService(StockTransferService $stockTransferService): void
{
$this->stockTransferService = $stockTransferService;
}
public function setStockInfoService(StockInfoService $stockInfoService): void
{
$this->stockInfoService = $stockInfoService;
}
public function setStockService(StockService $stockService): void
{
$this->stockService = $stockService;
}
public function setBuyInTurkeyService(BuyInTurkeyService $buyInTurkeyService): void
{
$this->buyInTurkeyService = $buyInTurkeyService;
}
}