show with canevas some statistics

This commit is contained in:
Kayn Ty 2018-05-22 16:38:51 +02:00
parent 70bbc42b93
commit fe4f202bed
No known key found for this signature in database
GPG Key ID: 55B09AA0ED327CD3
6 changed files with 533 additions and 436 deletions

View File

@ -22,7 +22,7 @@
</div> </div>
{% if not (app.user.products |length) %} {% if not (app.user.products |length) %}
<div class="alert alert-info"> <div class="alert alert-info" ng-if="!productsFromDB.length && initLoadDone">
<i class="fa fa-info"></i> <i class="fa fa-info"></i>
Créez facilement vos catégories de produits et vos produits juste en écrivant un nom par ligne dans Créez facilement vos catégories de produits et vos produits juste en écrivant un nom par ligne dans

View File

@ -7,6 +7,10 @@
<div class="row"> <div class="row">
<h1>Historique</h1> <h1>Historique</h1>
</div> </div>
<div id="chartContainer" style="display: inline-block; height: 300px; width: 49%;"></div>
<div id="chartContainerChiffreAffaire" style="display: inline-block; height: 300px; width: 49%;"></div>
<div class="row"> <div class="row">
<div class="col-xs-6"> <div class="col-xs-6">
<div class="sells"> <div class="sells">
@ -83,4 +87,48 @@
</div> </div>
</div> </div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script>
var dataPoints = [
{% for pair in statisticsSoldProducts %}
{ label: "{{ pair.name }}", y: {{ pair.count }} },
{% endfor %}
];
var dataPointsChiffreAffaire = [
{% for pair in statisticsSoldProducts %}
{ label: "{{ pair.name }}", y: {{ pair.value }} },
{% endfor %}
];
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "Volume de produits vendus"
},
animationEnabled: true,
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "pie",
dataPoints: dataPoints
}
]
});
chart.render();
var chartContainerChiffreAffaire = new CanvasJS.Chart("chartContainerChiffreAffaire", {
title:{
text: "Valeur en euros des produits vendus"
},
animationEnabled: true,
data: [
{
// Change type to "doughnut", "line", "splineArea", etc.
type: "pie",
dataPoints: dataPointsChiffreAffaire
}
]
});
chartContainerChiffreAffaire.render();
</script>
{% endblock %} {% endblock %}

View File

@ -1,8 +1,10 @@
// require('../../../node_modules/canvasjs/dist/canvasjs.3');
var $ = require('jquery'); var $ = require('jquery');
// JS is equivalent to the normal "bootstrap" package // JS is equivalent to the normal "bootstrap" package
// no need to set this to a variable, just require it // no need to set this to a variable, just require it
require('bootstrap-sass'); require('bootstrap-sass');
// or you can include specific pieces // or you can include specific pieces
// require('bootstrap-sass/javascripts/bootstrap/tooltip'); // require('bootstrap-sass/javascripts/bootstrap/tooltip');
// require('bootstrap-sass/javascripts/bootstrap/popover'); // require('bootstrap-sass/javascripts/bootstrap/popover');

View File

@ -10,6 +10,7 @@
"dependencies": { "dependencies": {
"angular": "1.5", "angular": "1.5",
"bootstrap": "^4.0.0", "bootstrap": "^4.0.0",
"canvasjs": "^1.8.1",
"font-awesome": "^4.7.0", "font-awesome": "^4.7.0",
"jquery": "1.12.2" "jquery": "1.12.2"
} }

View File

@ -14,497 +14,539 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
class DefaultController extends Controller { class DefaultController extends Controller
{
private $tokenManager; private $tokenManager;
public function __construct( CsrfTokenManagerInterface $tokenManager = null ) { public function __construct(CsrfTokenManagerInterface $tokenManager = null)
$this->tokenManager = $tokenManager; {
} $this->tokenManager = $tokenManager;
}
/** /**
* @Route("/", name="homepage") * @Route("/", name="homepage")
*/ */
public function indexAction( Request $request ) { public function indexAction(Request $request)
$m = $this->getDoctrine()->getManager(); {
$userRepo = $m->getRepository( 'AppBundle:User' ); $m = $this->getDoctrine()->getManager();
$allUsers = $userRepo->findAll(); $userRepo = $m->getRepository('AppBundle:User');
$allUsers = $userRepo->findAll();
// replace this example code with whatever you need // replace this example code with whatever you need
return $this->render( 'default/index.html.twig', return $this->render('default/index.html.twig',
[ [
'usersCount' => count( $allUsers ), 'usersCount' => count($allUsers),
'base_dir' => realpath( $this->getParameter( 'kernel.project_dir' ) ) . DIRECTORY_SEPARATOR, 'base_dir' => realpath($this->getParameter('kernel.project_dir')) . DIRECTORY_SEPARATOR,
] ); ]);
} }
/** /**
* @Route("/dashboard", name="dashboard") * @Route("/dashboard", name="dashboard")
*/ */
public function dashboardAction( Request $request ) { public function dashboardAction(Request $request)
$m = $this->getDoctrine()->getManager(); {
$currentUser = $this->getUser(); $m = $this->getDoctrine()->getManager();
$currentUser = $this->getUser();
// TODO on first login set default values // TODO on first login set default values
$lastFestival = $currentUser->getActiveFestival(); $lastFestival = $currentUser->getActiveFestival();
if ( ! $lastFestival ) { if (!$lastFestival) {
$lastFestival = $m->getRepository( 'AppBundle:Festival' ) $lastFestival = $m->getRepository('AppBundle:Festival')
->findOneBy( [ 'user' => $this->getUser()->getId() ], ->findOneBy(['user' => $this->getUser()->getId()],
[ 'id' => 'desc' ], ['id' => 'desc'],
0, 0,
1 ); 1);
} }
if ( $lastFestival ) { if ($lastFestival) {
$lastFestival->recalculateChiffreAffaire(); $lastFestival->recalculateChiffreAffaire();
} }
$categRepo = $m->getRepository( 'AppBundle:ProductCategory' ); $categRepo = $m->getRepository('AppBundle:ProductCategory');
$sellingRepo = $m->getRepository( 'AppBundle:SellRecord' ); $sellingRepo = $m->getRepository('AppBundle:SellRecord');
$categories = $categRepo->findAll(); $categories = $categRepo->findAll();
$recentSells = $sellingRepo->findBy( [ 'user' => $currentUser->getId() ], [ 'id' => 'desc' ], 0, 5 ); $recentSells = $sellingRepo->findBy(['user' => $currentUser->getId()], ['id' => 'desc'], 0, 5);
return $this->render( 'logged/dashboard.html.twig', return $this->render('logged/dashboard.html.twig',
[ [
'lastFestival' => $lastFestival, 'lastFestival' => $lastFestival,
'categories' => $categories, 'categories' => $categories,
'currentUser' => $currentUser, 'currentUser' => $currentUser,
'recentSells' => $recentSells, 'recentSells' => $recentSells,
'base_dir' => realpath( $this->getParameter( 'kernel.project_dir' ) ) . DIRECTORY_SEPARATOR, 'base_dir' => realpath($this->getParameter('kernel.project_dir')) . DIRECTORY_SEPARATOR,
] ); ]);
} }
/** /**
* envoyer un email * envoyer un email
*/ */
public function emailAction() { public function emailAction()
$name = "noble barbare"; {
$message = \Swift_Message::newInstance() $name = "noble barbare";
->setSubject( 'Hello Email' ) $message = \Swift_Message::newInstance()
->setFrom( 'test-symfony-tykayn@caisse.ciperbliss.com' ) ->setSubject('Hello Email')
->setTo( 'tykayn@gmail.com' ) ->setFrom('test-symfony-tykayn@caisse.ciperbliss.com')
->setBody( $this->renderView( 'default/test-email.html.twig' ), ->setTo('tykayn@gmail.com')
'text/html' ); ->setBody($this->renderView('default/test-email.html.twig'),
$this->get( 'mailer' )->send( $message ); 'text/html');
$this->get('mailer')->send($message);
//return 'yay test de mail'; //return 'yay test de mail';
return $this->render( return $this->render(
'default/test-email.html.twig', 'default/test-email.html.twig',
[ [
] ]
); );
} }
/** /**
* get user products * get user products
* @return JsonResponse * @return JsonResponse
*/ */
public function getMyProductsAction() { public function getMyProductsAction()
$m = $this->getDoctrine()->getManager(); {
$m = $this->getDoctrine()->getManager();
$currentUser = $this->getUser(); $currentUser = $this->getUser();
if ( ! $currentUser ) { if (!$currentUser) {
return new JsonResponse( [ return new JsonResponse([
'categories' => [ [ 'name' => 'demo category', 'products' => [] ] ], 'categories' => [['name' => 'demo category', 'products' => []]],
'recentSells' => [ [ '' ] ], 'recentSells' => [['']],
] ); ]);
} }
$activeFestival = $currentUser->getActiveFestival(); $activeFestival = $currentUser->getActiveFestival();
if ( ! $activeFestival ) { if (!$activeFestival) {
$activeFestival = $m->getRepository( 'AppBundle:Festival' ) $activeFestival = $m->getRepository('AppBundle:Festival')
->findOneBy( [ 'user' => $this->getUser()->getId() ], ->findOneBy(['user' => $this->getUser()->getId()],
[ 'id' => 'desc' ], ['id' => 'desc'],
0, 0,
1 ); 1);
if ( ! $activeFestival ) { if (!$activeFestival) {
$activeFestival = new Festival(); $activeFestival = new Festival();
$activeFestival->setDateCreation( new \DateTime() ) $activeFestival->setDateCreation(new \DateTime())
->setName( 'default festival' ) ->setName('default festival')
->setChiffreAffaire( 0 ) ->setChiffreAffaire(0)
->setFondDeCaisseAvant( 0 ) ->setFondDeCaisseAvant(0)
->setFondDeCaisseApres( 0 ) ->setFondDeCaisseApres(0)
->setUser( $currentUser ); ->setUser($currentUser);
} }
$currentUser->setActiveFestival( $activeFestival ); $currentUser->setActiveFestival($activeFestival);
$m->persist( $activeFestival ); $m->persist($activeFestival);
$m->persist( $currentUser ); $m->persist($currentUser);
$m->flush(); $m->flush();
} }
$categRepo = $m->getRepository( 'AppBundle:ProductCategory' ); $categRepo = $m->getRepository('AppBundle:ProductCategory');
$sellingRepo = $m->getRepository( 'AppBundle:SellRecord' ); $sellingRepo = $m->getRepository('AppBundle:SellRecord');
$categories = $currentUser->getCategories(); $categories = $currentUser->getCategories();
if ( ! count( $categories ) ) { if (!count($categories)) {
$categories = $defaultCategories = $categRepo->findById( [ 1, 2 ] ); $categories = $defaultCategories = $categRepo->findById([1, 2]);
$currentUser->setCategories( $defaultCategories ); $currentUser->setCategories($defaultCategories);
$m->persist( $currentUser ); $m->persist($currentUser);
} }
$serializedCategories = []; $serializedCategories = [];
foreach ( $categories as $category ) { foreach ($categories as $category) {
$products = $category->getProducts(); $products = $category->getProducts();
if ( $products ) { if ($products) {
$listOfProductsInArray = []; $listOfProductsInArray = [];
foreach ( $products as $product ) { foreach ($products as $product) {
$listOfProductsInArray[] = [ $listOfProductsInArray[] = [
'id' => $product->getId(), 'id' => $product->getId(),
'name' => $product->getName(), 'name' => $product->getName(),
'category' => $category->getId(), 'category' => $category->getId(),
'price' => 1 * $product->getPrice(), 'price' => 1 * $product->getPrice(),
'stockCount' => $product->getStockCount(), 'stockCount' => $product->getStockCount(),
]; ];
} }
$products = $listOfProductsInArray; $products = $listOfProductsInArray;
} }
$serializedCategories[] = $serializedCategories[] =
[ [
'id' => $category->getId(), 'id' => $category->getId(),
'name' => $category->getName(), 'name' => $category->getName(),
'products' => $products ? $products : null, 'products' => $products ? $products : null,
]; ];
} }
$categories = $serializedCategories; $categories = $serializedCategories;
$recentSells = $sellingRepo->findBy( [ 'user' => $currentUser->getId() ], [ 'id' => 'desc' ], 0, 5 ); $recentSells = $sellingRepo->findBy(['user' => $currentUser->getId()], ['id' => 'desc'], 0, 5);
return new JsonResponse( [ return new JsonResponse([
'categories' => $categories, 'categories' => $categories,
'recentSells' => count( $recentSells ), 'recentSells' => count($recentSells),
'lastFestival' => [ 'lastFestival' => [
'id' => $activeFestival->getId(), 'id' => $activeFestival->getId(),
'name' => $activeFestival->getName(), 'name' => $activeFestival->getName(),
'commentaire' => $activeFestival->getComment(), 'commentaire' => $activeFestival->getComment(),
'dateCreation' => $activeFestival->getDateCreation(), 'dateCreation' => $activeFestival->getDateCreation(),
'chiffreAffaire' => $activeFestival->getChiffreAffaire(), 'chiffreAffaire' => $activeFestival->getChiffreAffaire(),
'clientsCount' => count( $activeFestival->getSellRecords() ), 'clientsCount' => count($activeFestival->getSellRecords()),
'fondDeCaisseAvant' => $activeFestival->getFondDeCaisseAvant(), 'fondDeCaisseAvant' => $activeFestival->getFondDeCaisseAvant(),
'fondDeCaisseApres' => $activeFestival->getFondDeCaisseApres(), 'fondDeCaisseApres' => $activeFestival->getFondDeCaisseApres(),
], ],
] ); ]);
} }
/** /**
* @param Request $request * @param Request $request
* add a selling record corresponding to one client * add a selling record corresponding to one client
* *
* @return JsonResponse * @return JsonResponse
*/ */
public function addSellingAction( Request $request ) { public function addSellingAction(Request $request)
{
$json = json_decode( $request->getContent(), true ); $json = json_decode($request->getContent(), true);
$currentUser = $this->getUser(); $currentUser = $this->getUser();
$m = $this->getDoctrine()->getManager(); $m = $this->getDoctrine()->getManager();
$newSellRecord = new SellRecord(); $newSellRecord = new SellRecord();
// sort user categories // sort user categories
$myCategories = $m->getRepository( 'AppBundle:ProductCategory' )->findAll(); $myCategories = $m->getRepository('AppBundle:ProductCategory')->findAll();
$categoriesByID = []; $categoriesByID = [];
foreach ( $myCategories as $my_category ) { foreach ($myCategories as $my_category) {
$categoriesByID[ $my_category->getId() ] = $my_category; $categoriesByID[$my_category->getId()] = $my_category;
} }
$productsModels = $m->getRepository( 'AppBundle:Product' )->findAll(); $productsModels = $m->getRepository('AppBundle:Product')->findAll();
$productsModelsByID = []; $productsModelsByID = [];
foreach ( $productsModels as $product ) { foreach ($productsModels as $product) {
$productsModelsByID[ $product->getId() ] = $product; $productsModelsByID[$product->getId()] = $product;
} }
$sumAmount = 0; $sumAmount = 0;
foreach ( $json[ 'activeSelling' ] as $record ) { foreach ($json['activeSelling'] as $record) {
$productModel = $productsModelsByID[ $record[ 'id' ] ]; $productModel = $productsModelsByID[$record['id']];
$newProductSold = new ProductSold(); $newProductSold = new ProductSold();
$newProductSold->setName( $record[ 'name' ] ); $newProductSold->setName($record['name']);
$newProductSold->setImage( "image mock" ); $newProductSold->setImage("image mock");
$newProductSold->setUser( $currentUser ); $newProductSold->setUser($currentUser);
$newProductSold->setPrice( $record[ 'price' ] ); $newProductSold->setPrice($record['price']);
$newProductSold->setComment( $json[ 'sellingComment' ] ); $newProductSold->setComment($json['sellingComment']);
$newProductSold->setProduct( $productModel ); $newProductSold->setProduct($productModel);
$newProductSold->setSellRecords( $newSellRecord ); $newProductSold->setSellRecords($newSellRecord);
// link selling record with user, festival // link selling record with user, festival
$currentUser->addProductsSold( $newProductSold ); $currentUser->addProductsSold($newProductSold);
// persist all // persist all
$productModel->setStockCount( $productModel->getStockCount() - 1 ); $productModel->setStockCount($productModel->getStockCount() - 1);
$m->persist( $productModel ); $m->persist($productModel);
$m->persist( $newProductSold ); $m->persist($newProductSold);
$m->persist( $newProductSold ); $m->persist($newProductSold);
$sumAmount += $record[ 'price' ]; $sumAmount += $record['price'];
} }
$festivalFound = $m->getRepository( 'AppBundle:Festival' )->find( $json[ 'activeFestival' ][ 'id' ] ); $festivalFound = $m->getRepository('AppBundle:Festival')->find($json['activeFestival']['id']);
$newSellRecord->setFestival( $festivalFound ); $newSellRecord->setFestival($festivalFound);
$newSellRecord->setAmount( $sumAmount ); $newSellRecord->setAmount($sumAmount);
$newSellRecord->setDate( new \DateTime() ); $newSellRecord->setDate(new \DateTime());
$newSellRecord->setUser( $currentUser ); $newSellRecord->setUser($currentUser);
$newSellRecord->setPaidByClient( $json[ 'paidByClient' ] ); $newSellRecord->setPaidByClient($json['paidByClient']);
$newSellRecord->setComment( $json[ 'sellingComment' ] ); $newSellRecord->setComment($json['sellingComment']);
$festivalFound->addSellRecord( $newSellRecord ); $festivalFound->addSellRecord($newSellRecord);
$currentUser->addSellRecords( $newSellRecord ); $currentUser->addSellRecords($newSellRecord);
$m->persist( $newSellRecord ); $m->persist($newSellRecord);
$m->persist( $currentUser ); $m->persist($currentUser);
$m->persist( $festivalFound ); $m->persist($festivalFound);
$m->flush(); $m->flush();
$festivalFound->recalculateChiffreAffaire(); $festivalFound->recalculateChiffreAffaire();
$m->persist( $festivalFound ); $m->persist($festivalFound);
$m->flush(); $m->flush();
// setup dates // setup dates
// fetch back history of selling // fetch back history of selling
$sellingRepo = $m->getRepository( 'AppBundle:SellRecord' ); $sellingRepo = $m->getRepository('AppBundle:SellRecord');
$lastSellings = $sellingRepo->findBy( [ 'user' => $currentUser->getId() ], [ 'id' => 'desc' ], 0, 3 ); $lastSellings = $sellingRepo->findBy(['user' => $currentUser->getId()], ['id' => 'desc'], 0, 3);
return new JsonResponse( [ return new JsonResponse([
"message" => "ok", "message" => "ok",
"newChiffreAffaire" => $festivalFound->getChiffreAffaire(), "newChiffreAffaire" => $festivalFound->getChiffreAffaire(),
"clientsCount" => count( $festivalFound->getSellRecords() ), "clientsCount" => count($festivalFound->getSellRecords()),
"recent_sellings" => json_encode( $lastSellings ), "recent_sellings" => json_encode($lastSellings),
"dump" => $json, "dump" => $json,
], 200 ); ], 200);
} }
/** /**
* get the history of user's sellings * get the history of user's sellings
* @Route("/history", name="history") * @Route("/history", name="history")
*/ */
public function historyAction() { public function historyAction()
$currentUser = $this->getUser(); {
$m = $this->getDoctrine()->getManager(); $currentUser = $this->getUser();
$sellingRepo = $m->getRepository( 'AppBundle:SellRecord' ); $m = $this->getDoctrine()->getManager();
$mySellings = $sellingRepo->findByUser( $currentUser->getId() ); $sellingRepo = $m->getRepository('AppBundle:SellRecord');
$chiffreAffaires = 0; $mySellings = $sellingRepo->findByUser($currentUser->getId());
foreach ( $mySellings as $client ) { $chiffreAffaires = 0;
foreach ( $client->getProductsSold() as $product ) {
$chiffreAffaires += $product->getPrice();
}
}
return $this->render( 'logged/history.html.twig',
[
'chiffreAffaires' => $chiffreAffaires,
'recentSells' => $mySellings,
'base_dir' => realpath( $this->getParameter( 'kernel.project_dir' ) ) . DIRECTORY_SEPARATOR,
] );
}
/** $productsSoldOfUser = $currentUser->getProductsSold();
* export all clients $statisticsSoldProducts = [
* @Route("/export-all", name="export_all") // ['name' => 'bidule', 'count' => 0, 'value' => 0],
*/ ];
public function exportAllAction() {
// TODO
$currentUser = $this->getUser();
$m = $this->getDoctrine()->getManager();
$sellingRepo = $m->getRepository( 'AppBundle:SellRecord' );
$mySellings = $sellingRepo->findByUser( $currentUser->getId() );
$fileName = "export_caisse-cipherbliss_" . $currentUser->getUsername() . '_' . date( 'Y-m-d_H-i-s' ); $statsForFestival = [
['name' => 'festoche bidule', 'clients_count' => 125, 'chiffre_affaire' => 236],
];
foreach ($mySellings as $client) {
foreach ($client->getProductsSold() as $product) {
$chiffreAffaires += $product->getPrice();
$handle = fopen( 'php://memory', 'r+' ); if (!isset($statisticsSoldProducts[$product->getName()])) {
$firstLine = [ $statisticsSoldProducts[$product->getName()] =
'product sold id', [
'date', 'name' => $product->getName(),
'hour', 'count' => 0,
'min', 'value' => 0
'sec', ];
'client comment', }
'client paid',
'product name', // echo '<pre>';
'product image', // var_dump(intval($product->getPrice()));
'product category id', // echo '</pre>';
'product category name', $statisticsSoldProducts[$product->getName()]['count']++;
'product price', $statisticsSoldProducts[$product->getName()]['value'] = $statisticsSoldProducts[$product->getName()]['value'] + intval($product->getPrice());
'festival id',
'festival name', }
'festival creation date', }
'caisse before', // echo '<pre>';
'caisse after', // var_dump($statisticsSoldProducts);
'festival ca', // echo '</pre>';
'festival comment',
]; return $this->render('logged/history.html.twig',
[
'statisticsSoldProducts' => $statisticsSoldProducts,
'chiffreAffaires' => $chiffreAffaires,
'recentSells' => $mySellings,
'base_dir' => realpath($this->getParameter('kernel.project_dir')) . DIRECTORY_SEPARATOR,
]);
}
/**
* export all clients
* @Route("/export-all", name="export_all")
*/
public function exportAllAction()
{
// TODO
$currentUser = $this->getUser();
$m = $this->getDoctrine()->getManager();
$sellingRepo = $m->getRepository('AppBundle:SellRecord');
$mySellings = $sellingRepo->findByUser($currentUser->getId());
$fileName = "export_caisse-cipherbliss_" . $currentUser->getUsername() . '_' . date('Y-m-d_H-i-s');
$handle = fopen('php://memory', 'r+');
$firstLine = [
'product sold id',
'date',
'hour',
'min',
'sec',
'client comment',
'client paid',
'product name',
'product image',
'product category id',
'product category name',
'product price',
'festival id',
'festival name',
'festival creation date',
'caisse before',
'caisse after',
'festival ca',
'festival comment',
];
// save the column headers // save the column headers
fputcsv( $handle, fputcsv($handle,
$firstLine ); $firstLine);
$chiffreAffaires = 0; $chiffreAffaires = 0;
foreach ( $mySellings as $sellRecord ) { foreach ($mySellings as $sellRecord) {
foreach ( $sellRecord->getProductsSold() as $productSold ) { foreach ($sellRecord->getProductsSold() as $productSold) {
$chiffreAffaires += $productSold->getPrice(); $chiffreAffaires += $productSold->getPrice();
// add a line to the csv file // add a line to the csv file
fputcsv( $handle, fputcsv($handle,
[ [
$productSold->getId(), $productSold->getId(),
$sellRecord->getDate()->format( 'c' ), $sellRecord->getDate()->format('c'),
$sellRecord->getDate()->format( 'H' ), $sellRecord->getDate()->format('H'),
$sellRecord->getDate()->format( 'i' ), $sellRecord->getDate()->format('i'),
$sellRecord->getDate()->format( 's' ), $sellRecord->getDate()->format('s'),
$sellRecord->getComment(), $sellRecord->getComment(),
$sellRecord->getPaidByClient(), $sellRecord->getPaidByClient(),
$productSold->getName(), $productSold->getName(),
$productSold->getImage(), $productSold->getImage(),
$productSold->getProduct()->getCategory()->getId(), $productSold->getProduct()->getCategory()->getId(),
$productSold->getProduct()->getCategory()->getName(), $productSold->getProduct()->getCategory()->getName(),
$productSold->getPrice(), $productSold->getPrice(),
] ); ]);
if ( $sellRecord->getFestival() ) { if ($sellRecord->getFestival()) {
fputcsv( $handle, fputcsv($handle,
[ [
'', '',
'', '',
'', '',
'', '',
'', '',
'', '',
'', '',
'', '',
'', '',
'', '',
'', '',
'', '',
$sellRecord->getFestival()->getId(), $sellRecord->getFestival()->getId(),
$sellRecord->getFestival()->getName(), $sellRecord->getFestival()->getName(),
$sellRecord->getFestival()->getDateCreation()->format( 'c' ), $sellRecord->getFestival()->getDateCreation()->format('c'),
$sellRecord->getFestival()->getFondDeCaisseAvant(), $sellRecord->getFestival()->getFondDeCaisseAvant(),
$sellRecord->getFestival()->getFondDeCaisseApres(), $sellRecord->getFestival()->getFondDeCaisseApres(),
$sellRecord->getFestival()->getChiffreAffaire(), $sellRecord->getFestival()->getChiffreAffaire(),
$sellRecord->getFestival()->getComment(), $sellRecord->getFestival()->getComment(),
] ); ]);
} }
} }
} }
rewind( $handle ); rewind($handle);
$content = stream_get_contents( $handle ); $content = stream_get_contents($handle);
fclose( $handle ); fclose($handle);
return new Response( return new Response(
$content, 200, [ $content, 200, [
'Content-Type' => 'application/force-download', 'Content-Type' => 'application/force-download',
'Content-Disposition' => 'attachment; filename="' . $fileName . '.csv"', 'Content-Disposition' => 'attachment; filename="' . $fileName . '.csv"',
] ]
); );
} }
/** /**
* @Route("/set-active-festival/{id}", name="set_active_festival") * @Route("/set-active-festival/{id}", name="set_active_festival")
*/ */
public function setActiveFestivalAction( $id ) { public function setActiveFestivalAction($id)
$currentUser = $this->getUser(); {
$m = $this->getDoctrine()->getManager(); $currentUser = $this->getUser();
$repo = $m->getRepository( 'AppBundle:Festival' ); $m = $this->getDoctrine()->getManager();
$repo = $m->getRepository('AppBundle:Festival');
$currentUser->setActiveFestival( $repo->find( $id ) ); $currentUser->setActiveFestival($repo->find($id));
$m->persist( $currentUser ); $m->persist($currentUser);
$m->flush(); $m->flush();
// replace this example code with whatever you need // replace this example code with whatever you need
return $this->redirectToRoute( 'dashboard' ); return $this->redirectToRoute('dashboard');
} }
/** /**
* @Route("/import", name="import") * @Route("/import", name="import")
*/ */
public function importAction() { public function importAction()
$currentUser = $this->getUser(); {
$m = $this->getDoctrine()->getManager(); $currentUser = $this->getUser();
$sellingRepo = $m->getRepository( 'AppBundle:SellRecord' ); $m = $this->getDoctrine()->getManager();
$sellingRepo = $m->getRepository('AppBundle:SellRecord');
return $this->render( 'logged/import.html.twig', return $this->render('logged/import.html.twig',
[ [
'base_dir' => '', 'base_dir' => '',
] ); ]);
} }
/** /**
* @Route("/mass-create", name="mass_create") * @Route("/mass-create", name="mass_create")
*/ */
public function massCreateAction( Request $request ) { public function massCreateAction(Request $request)
$currentUser = $this->getUser(); {
$m = $this->getDoctrine()->getManager(); $currentUser = $this->getUser();
$m = $this->getDoctrine()->getManager();
$myCategories = $currentUser->getCategories(); $myCategories = $currentUser->getCategories();
$myCategoriesByName = []; $myCategoriesByName = [];
$myProductsByName = []; $myProductsByName = [];
$currentCategory = new ProductCategory(); $currentCategory = new ProductCategory();
$currentCategory $currentCategory
->addUser( $currentUser ) ->addUser($currentUser)
->setName( 'default category' ); ->setName('default category');
foreach ( $myCategories as $my_category ) { foreach ($myCategories as $my_category) {
$myCategoriesByName [ $my_category->getName() ] = $my_category; $myCategoriesByName [$my_category->getName()] = $my_category;
foreach ( $my_category->getProducts() as $product ) { foreach ($my_category->getProducts() as $product) {
$myProductsByName[ $product->getName() ] = $product; $myProductsByName[$product->getName()] = $product;
} }
$currentCategory = $my_category; $currentCategory = $my_category;
} }
$massLines = $request->request->get( 'produits' ); $massLines = $request->request->get('produits');
if ( $request->getMethod() == 'POST' ) { if ($request->getMethod() == 'POST') {
$lines = preg_split( '/$\R?^/m', trim( $massLines ) ); $lines = preg_split('/$\R?^/m', trim($massLines));
foreach ( $lines as $line ) { foreach ($lines as $line) {
if ( strpos( $line, ':' ) ) { if (strpos($line, ':')) {
// manage catgegories // manage catgegories
$boom = explode( ':', trim( $line ) ); $boom = explode(':', trim($line));
$firstPart = $boom[ 0 ]; $firstPart = $boom[0];
$value = $boom[ 1 ]; $value = $boom[1];
echo "gérer une catégorie nommée: $value"; echo "gérer une catégorie nommée: $value";
if ( $firstPart === 'catégorie' && $value ) { if ($firstPart === 'catégorie' && $value) {
// look for category by name // look for category by name
if ( ! isset( $myCategoriesByName[ $value ] ) ) { if (!isset($myCategoriesByName[$value])) {
$newCateg = new ProductCategory(); $newCateg = new ProductCategory();
$newCateg $newCateg
->addUser( $currentUser ) ->addUser($currentUser)
->setName( $value ); ->setName($value);
$currentUser->addCategory( $newCateg ); $currentUser->addCategory($newCateg);
$m->persist( $newCateg ); $m->persist($newCateg);
$currentCategory = $newCateg; // associate further categories with the newly created one $currentCategory = $newCateg; // associate further categories with the newly created one
} else { } else {
echo " la catégorie existe déjà"; echo " la catégorie existe déjà";
} }
} }
} else { } else {
// manage product // manage product
echo "<br/> $line"; echo "<br/> $line";
$boom = explode( ';', $line ); $boom = explode(';', $line);
$productName = $boom[ 0 ]; $productName = $boom[0];
$price = 0; $price = 0;
if ( $boom[ 1 ] ) { if ($boom[1]) {
$price = intval( str_replace( '€', '', $boom[ 1 ] ) ); $price = intval(str_replace('€', '', $boom[1]));
} }
// or create new product // or create new product
if ( $productName && ! isset( $myProductsByName[ $productName ] ) ) { if ($productName && !isset($myProductsByName[$productName])) {
$newProduct = new Product(); $newProduct = new Product();
$newProduct->setCategory( $currentCategory ) $newProduct->setCategory($currentCategory)
->setName( $productName ) ->setName($productName)
->setUser( $currentUser ) ->setUser($currentUser)
->setPrice( $price ) // removing euro symbol ->setPrice($price) // removing euro symbol
; ;
$currentUser->addProduct( $newProduct ); $currentUser->addProduct($newProduct);
$m->persist( $newProduct ); $m->persist($newProduct);
}// look for existing products }// look for existing products
else { else {
$myProductsByName[ $productName ]->setPrice( $price ); $myProductsByName[$productName]->setPrice($price);
} }
} }
$m->persist( $currentUser ); $m->persist($currentUser);
} }
// check with existing categories and products, sort them by name. // check with existing categories and products, sort them by name.
// save all // save all
$m->flush(); $m->flush();
} }
return $this->render( 'logged/import.html.twig', return $this->render('logged/import.html.twig',
[] ); []);
} }
} }

View File

@ -1078,6 +1078,10 @@ caniuse-lite@^1.0.30000792:
version "1.0.30000819" version "1.0.30000819"
resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30000819.tgz#aabee5fd15a080febab6ae5d30c9ea15f4c6d4e2" resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30000819.tgz#aabee5fd15a080febab6ae5d30c9ea15f4c6d4e2"
canvasjs@^1.8.1:
version "1.8.1"
resolved "https://registry.yarnpkg.com/canvasjs/-/canvasjs-1.8.1.tgz#698a4e002e336ce83ef2f9101a6bd276ba7657a3"
caseless@~0.11.0: caseless@~0.11.0:
version "0.11.0" version "0.11.0"
resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7" resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.11.0.tgz#715b96ea9841593cc33067923f5ec60ebda4f7d7"