Compare commits

..

No commits in common. "master" and "chismosa-la-venganza" have entirely different histories.

186 changed files with 5629 additions and 35520 deletions

View file

@ -1,9 +0,0 @@
[Dolphin]
HeaderColumnWidths=372,72,103
SortRole=modificationtime
Timestamp=2022,6,1,16,36,48
Version=4
ViewMode=1
[Settings]
HiddenFilesShown=true

Binary file not shown.

View file

@ -6,11 +6,9 @@ APP_URL=http://localhost
LOG_CHANNEL=stack
USERID=
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT_EXPOSED=3306
DB_PORT=3306
DB_DATABASE=pedi2
DB_USERNAME=pedi2
DB_PASSWORD=pedi2
@ -49,5 +47,4 @@ MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
WEB_CLIENT_EMAIL=informaticamps@buzon.uy
WEB_CLIENT_NAME=web
WEB_CLIENT_PASS=pass
NGINX_PORT=8000
WEB_CLIENT_PASS=pass

8
.gitignore vendored
View file

@ -10,11 +10,3 @@ Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
.idea
/resources/csv/exports/*.csv
/resources/csv/canastas/*.csv
/storage/csv/exports/*.csv
/storage/csv/canastas/*.csv
/public/css/
/public/js/
/public/mix-manifest.json

8
.idea/.gitignore generated vendored Normal file
View file

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="framework" type="frameworkType"/>
<xs:complexType name="commandType">
<xs:all>
<xs:element type="xs:string" name="name" minOccurs="1" maxOccurs="1"/>
<xs:element type="xs:string" name="params" minOccurs="0" maxOccurs="1"/>
<xs:element type="xs:string" name="help" minOccurs="0" maxOccurs="1"/>
<xs:element type="optionsBeforeType" name="optionsBefore" minOccurs="0" maxOccurs="1"/>
</xs:all>
</xs:complexType>
<xs:complexType name="frameworkType">
<xs:sequence>
<xs:element type="xs:string" name="extraData" minOccurs="0" maxOccurs="1"/>
<xs:element type="commandType" name="command" maxOccurs="unbounded" minOccurs="0"/>
<xs:element type="xs:string" name="help" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
<xs:attribute type="xs:string" name="name" use="required"/>
<xs:attribute type="xs:string" name="invoke" use="required"/>
<xs:attribute type="xs:string" name="alias" use="required"/>
<xs:attribute type="xs:boolean" name="enabled" use="required"/>
<xs:attribute type="xs:integer" name="version" use="required"/>
<xs:attribute type="xs:string" name="frameworkId" use="optional"/>
</xs:complexType>
<xs:complexType name="optionsBeforeType">
<xs:sequence>
<xs:element type="optionType" name="option" maxOccurs="unbounded" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="optionType">
<xs:sequence>
<xs:element type="xs:string" name="help" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
<xs:attribute type="xs:string" name="name" use="required"/>
<xs:attribute type="xs:string" name="shortcut" use="optional"/>
<xs:attribute name="pattern" use="optional">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="space"/>
<xs:enumeration value="equals"/>
<xs:enumeration value="unknown"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:schema>

8
.idea/modules.xml generated Normal file
View file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/pedi2.iml" filepath="$PROJECT_DIR$/.idea/pedi2.iml" />
</modules>
</component>
</project>

85
.idea/pedi2.iml generated Normal file
View file

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/app" isTestSource="false" packagePrefix="App\" />
<sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
<sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" packagePrefix="Tests\" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/event-dispatcher" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-php81" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/log" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/routing" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/simple-cache" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/event-dispatcher" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/css-selector" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-ctype" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/event-dispatcher-contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-intl-grapheme" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/console" />
<excludeFolder url="file://$MODULE_DIR$/vendor/egulias/email-validator" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/process" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-php72" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-intl-normalizer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-php73" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/http-kernel" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/finder" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/translation" />
<excludeFolder url="file://$MODULE_DIR$/vendor/asm89/stack-cors" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-mbstring" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/translation-contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/http-foundation" />
<excludeFolder url="file://$MODULE_DIR$/vendor/brick/math" />
<excludeFolder url="file://$MODULE_DIR$/vendor/swiftmailer/swiftmailer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/league/flysystem" />
<excludeFolder url="file://$MODULE_DIR$/vendor/opis/closure" />
<excludeFolder url="file://$MODULE_DIR$/vendor/league/csv" />
<excludeFolder url="file://$MODULE_DIR$/vendor/league/mime-type-detection" />
<excludeFolder url="file://$MODULE_DIR$/vendor/ramsey/collection" />
<excludeFolder url="file://$MODULE_DIR$/vendor/ramsey/uuid" />
<excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/inflector" />
<excludeFolder url="file://$MODULE_DIR$/vendor/doctrine/lexer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/composer" />
<excludeFolder url="file://$MODULE_DIR$/vendor/voku/portable-ascii" />
<excludeFolder url="file://$MODULE_DIR$/vendor/facade/ignition-contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/facade/flare-client-php" />
<excludeFolder url="file://$MODULE_DIR$/vendor/facade/ignition" />
<excludeFolder url="file://$MODULE_DIR$/vendor/fideloper/proxy" />
<excludeFolder url="file://$MODULE_DIR$/vendor/laravel/tinker" />
<excludeFolder url="file://$MODULE_DIR$/vendor/laravel/framework" />
<excludeFolder url="file://$MODULE_DIR$/vendor/laravel/ui" />
<excludeFolder url="file://$MODULE_DIR$/vendor/laravel/sanctum" />
<excludeFolder url="file://$MODULE_DIR$/vendor/fruitcake/laravel-cors" />
<excludeFolder url="file://$MODULE_DIR$/vendor/vlucas/phpdotenv" />
<excludeFolder url="file://$MODULE_DIR$/vendor/phpoption/phpoption" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psy/psysh" />
<excludeFolder url="file://$MODULE_DIR$/vendor/nunomaduro/collision" />
<excludeFolder url="file://$MODULE_DIR$/vendor/nesbot/carbon" />
<excludeFolder url="file://$MODULE_DIR$/vendor/ralouphie/getallheaders" />
<excludeFolder url="file://$MODULE_DIR$/vendor/nikic/php-parser" />
<excludeFolder url="file://$MODULE_DIR$/vendor/tijsverkoyen/css-to-inline-styles" />
<excludeFolder url="file://$MODULE_DIR$/vendor/league/commonmark" />
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/guzzle" />
<excludeFolder url="file://$MODULE_DIR$/vendor/filp/whoops" />
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/psr7" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/var-dumper" />
<excludeFolder url="file://$MODULE_DIR$/vendor/guzzlehttp/promises" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/error-handler" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/deprecation-contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/monolog/monolog" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/string" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/service-contracts" />
<excludeFolder url="file://$MODULE_DIR$/vendor/fakerphp/faker" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/container" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/mime" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/http-client" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-iconv" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/http-factory" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-intl-idn" />
<excludeFolder url="file://$MODULE_DIR$/vendor/dragonmantank/cron-expression" />
<excludeFolder url="file://$MODULE_DIR$/vendor/psr/http-message" />
<excludeFolder url="file://$MODULE_DIR$/vendor/symfony/polyfill-php80" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

83
.idea/php.xml generated Normal file
View file

@ -0,0 +1,83 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="PhpIncludePathManager">
<include_path>
<path value="$PROJECT_DIR$/vendor/psr/event-dispatcher" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-php81" />
<path value="$PROJECT_DIR$/vendor/psr/log" />
<path value="$PROJECT_DIR$/vendor/symfony/routing" />
<path value="$PROJECT_DIR$/vendor/psr/simple-cache" />
<path value="$PROJECT_DIR$/vendor/symfony/event-dispatcher" />
<path value="$PROJECT_DIR$/vendor/symfony/css-selector" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-ctype" />
<path value="$PROJECT_DIR$/vendor/symfony/event-dispatcher-contracts" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-grapheme" />
<path value="$PROJECT_DIR$/vendor/symfony/console" />
<path value="$PROJECT_DIR$/vendor/egulias/email-validator" />
<path value="$PROJECT_DIR$/vendor/symfony/process" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-php72" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-normalizer" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-php73" />
<path value="$PROJECT_DIR$/vendor/symfony/http-kernel" />
<path value="$PROJECT_DIR$/vendor/symfony/finder" />
<path value="$PROJECT_DIR$/vendor/symfony/translation" />
<path value="$PROJECT_DIR$/vendor/asm89/stack-cors" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-mbstring" />
<path value="$PROJECT_DIR$/vendor/symfony/translation-contracts" />
<path value="$PROJECT_DIR$/vendor/symfony/http-foundation" />
<path value="$PROJECT_DIR$/vendor/brick/math" />
<path value="$PROJECT_DIR$/vendor/swiftmailer/swiftmailer" />
<path value="$PROJECT_DIR$/vendor/league/flysystem" />
<path value="$PROJECT_DIR$/vendor/opis/closure" />
<path value="$PROJECT_DIR$/vendor/league/csv" />
<path value="$PROJECT_DIR$/vendor/league/mime-type-detection" />
<path value="$PROJECT_DIR$/vendor/ramsey/collection" />
<path value="$PROJECT_DIR$/vendor/ramsey/uuid" />
<path value="$PROJECT_DIR$/vendor/doctrine/inflector" />
<path value="$PROJECT_DIR$/vendor/doctrine/lexer" />
<path value="$PROJECT_DIR$/vendor/composer" />
<path value="$PROJECT_DIR$/vendor/voku/portable-ascii" />
<path value="$PROJECT_DIR$/vendor/facade/ignition-contracts" />
<path value="$PROJECT_DIR$/vendor/facade/flare-client-php" />
<path value="$PROJECT_DIR$/vendor/facade/ignition" />
<path value="$PROJECT_DIR$/vendor/fideloper/proxy" />
<path value="$PROJECT_DIR$/vendor/laravel/tinker" />
<path value="$PROJECT_DIR$/vendor/laravel/framework" />
<path value="$PROJECT_DIR$/vendor/laravel/ui" />
<path value="$PROJECT_DIR$/vendor/laravel/sanctum" />
<path value="$PROJECT_DIR$/vendor/fruitcake/laravel-cors" />
<path value="$PROJECT_DIR$/vendor/vlucas/phpdotenv" />
<path value="$PROJECT_DIR$/vendor/phpoption/phpoption" />
<path value="$PROJECT_DIR$/vendor/psy/psysh" />
<path value="$PROJECT_DIR$/vendor/nunomaduro/collision" />
<path value="$PROJECT_DIR$/vendor/nesbot/carbon" />
<path value="$PROJECT_DIR$/vendor/ralouphie/getallheaders" />
<path value="$PROJECT_DIR$/vendor/nikic/php-parser" />
<path value="$PROJECT_DIR$/vendor/tijsverkoyen/css-to-inline-styles" />
<path value="$PROJECT_DIR$/vendor/league/commonmark" />
<path value="$PROJECT_DIR$/vendor/guzzlehttp/guzzle" />
<path value="$PROJECT_DIR$/vendor/filp/whoops" />
<path value="$PROJECT_DIR$/vendor/guzzlehttp/psr7" />
<path value="$PROJECT_DIR$/vendor/symfony/var-dumper" />
<path value="$PROJECT_DIR$/vendor/guzzlehttp/promises" />
<path value="$PROJECT_DIR$/vendor/symfony/error-handler" />
<path value="$PROJECT_DIR$/vendor/symfony/deprecation-contracts" />
<path value="$PROJECT_DIR$/vendor/monolog/monolog" />
<path value="$PROJECT_DIR$/vendor/symfony/string" />
<path value="$PROJECT_DIR$/vendor/symfony/service-contracts" />
<path value="$PROJECT_DIR$/vendor/fakerphp/faker" />
<path value="$PROJECT_DIR$/vendor/psr/container" />
<path value="$PROJECT_DIR$/vendor/symfony/mime" />
<path value="$PROJECT_DIR$/vendor/psr/http-client" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-iconv" />
<path value="$PROJECT_DIR$/vendor/psr/http-factory" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-intl-idn" />
<path value="$PROJECT_DIR$/vendor/dragonmantank/cron-expression" />
<path value="$PROJECT_DIR$/vendor/psr/http-message" />
<path value="$PROJECT_DIR$/vendor/symfony/polyfill-php80" />
</include_path>
</component>
<component name="PhpProjectSharedConfiguration" php_language_level="7.2">
<option name="suggestChangeDefaultLanguageLevel" value="false" />
</component>
</project>

6
.idea/vcs.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View file

@ -14,10 +14,6 @@ RUN apt-get update && apt-get install -y \
zip \
unzip
# Install node
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash - && \
apt-get install -y nodejs
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

View file

@ -1,6 +1,6 @@
# Pedi2
Aplicación de pedidos del Mercado Popular de Subsistencia.
Aplicación de compras del Mercado Popular de Subsistencia.
Pedi2 está hecha en Laravel 7 y utiliza laravel7-docker de dyarleniber.
@ -17,39 +17,41 @@ Se utilizan los siguientes servicios, separadamente:
## Instalación
1. Una vez descargado el proyecto, hacé una copia del archivo `.env.example` que se encuentra en la raíz del proyecto y nombrala `.env`. Seteá los valores correctos - específicamente, para las variables, `APP_URL`, `DB_USERNAME` y `DB_PASSWORD`. Prestá atención a que `DB_HOST` sea el nombre del servicio que corre MySQL (por defecto `DB_HOST=db`).
2. Levantá los contenedores, construyendo la imagen de la app primero
2. Construí la imagen de la app
```bash
docker-compose up -d --build
docker-compose build app
```
3. Cuando termine, levantá los contenedores:
```bash
docker-compose up -d
```
El ambiente ahora está andando, pero necesitamos ejecutar un par de comandos para terminar la instalación de Laravel. Podemos usar `docker-compose exec [nombre-del-servicio]` previo a un comando para ejecutarlo dentro del contenedor.
3. Terminá de instalar las dependencias de la app, según fueron definidas en `composer.json`.
4. Terminá de instalar las dependencias de la app, según fueron definidas en `composer.json`.
```bash
docker-compose exec app composer install
docker-compose exec app composer update
```
4. Generá una clave de aplicación. Esta clave se usa para encriptar datos sensibles.
5. Generá una clave de aplicación. Esta clave se usa para encriptar datos sensibles.
```bash
docker-compose exec app php artisan key:generate
```
5. Corré las migraciones y seeders de Laravel
6. Corré las migraciones y seeders de Laravel
```bash
docker-compose exec app php artisan migrate:fresh --seed
docker-compose exec app php artisan migrate --seed
```
6. Copia el token que se imprime al correr los seeders. Lo necesitamos para autenticar las llamadas que hagamos desde nuestro cliente web
7. Copia el token que se imprime al correr los seeders. Lo necesitamos para autenticar las llamadas que hagamos desde nuestro cliente web
7. Instala las dependencias de npm
```bash
docker-compose exec app npm install
```
Ahora la aplicación está corriendo y la podés ver en el puerto 8000 de tu dominio o IP. En caso de que estés en tu máquina local, la vas a ver accediendo a `http://localhost:8000` desde tu navegador.
@ -59,11 +61,6 @@ Podés usar el comando `logs` para ver los logs generados por tus servicios:
docker-compose logs nginx
```
8. Ejecuta npm para compilar el js y css
```bash
docker-compose exec app npm run prod
```
## Services description
### Dockerfile
@ -123,4 +120,4 @@ DB_PASSWORD=password
- https://docs.docker.com/
- https://docs.docker.com/compose/
- https://github.com/dyarleniber/laravel7-docker
- https://laravel.com/docs/7.x/installation
- https://laravel.com/docs/7.x/installation

View file

@ -4,7 +4,7 @@ namespace App;
use Illuminate\Database\Eloquent\Model;
class UserRole extends Model
class Admin extends Model
{
protected $fillable = ["nombre"];
//
}

View file

@ -1,11 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CanastaLog extends Model
{
protected $fillable = ["path", "descripcion"];
protected $table = "carga_de_canastas";
}

View file

@ -1,72 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class AgregarEsBonoAPedidosAprobados extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'command:AgregarEsBonoAPedidosAprobados';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Agrega "producto_bono" a la view PedidosAprobados';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
DB::statement("
ALTER VIEW pedidos_aprobados(
grupo_de_compra_id,
grupo_de_compra_nombre,
grupo_de_compra_region,
producto_id,
producto_nombre,
producto_precio,
cantidad_pedida,
total_por_producto,
producto_es_bono
) AS
SELECT
g.id as grupo_de_compra_id,
g.nombre as grupo_de_compra_nombre,
g.region as grupo_de_compra_region,
pr.id AS producto_id,
pr.nombre as producto_nombre,
pr.precio as producto_precio,
SUM(ps.cantidad) as cantidad_pedida,
pr.precio*SUM(ps.cantidad) as total_por_producto,
pr.bono
FROM grupos_de_compra g
JOIN subpedidos s ON (s.grupo_de_compra_id = g.id AND s.aprobado=1)
JOIN producto_subpedido ps ON (ps.subpedido_id = s.id)
JOIN productos pr ON (pr.id = ps.producto_id)
GROUP BY
g.id, g.nombre, pr.id, pr.nombre
;");
return 0;
}
}

View file

@ -1,62 +0,0 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class CrearPedidosAprobadosViewCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'view:CrearPedidosAprobadosView';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Crea view "pedidos_aprobados"';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle(): int
{
DB::statement("
CREATE OR REPLACE VIEW pedidos_aprobados
AS
SELECT
g.id as grupo_de_compra_id,
g.nombre as grupo_de_compra_nombre,
g.region as grupo_de_compra_region,
pr.id AS producto_id,
pr.nombre as producto_nombre,
pr.precio as producto_precio,
SUM(ps.cantidad) as cantidad_pedida,
pr.precio*SUM(ps.cantidad) as total_por_producto
FROM grupos_de_compra g
JOIN subpedidos s ON (s.grupo_de_compra_id = g.id AND s.aprobado=1)
JOIN producto_subpedido ps ON (ps.subpedido_id = s.id)
JOIN productos pr ON (pr.id = ps.producto_id)
GROUP BY
g.id, g.nombre, pr.id, pr.nombre
;");
return 0;
}
}

View file

@ -5,15 +5,12 @@ namespace App\Filtros;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Builder;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;
use TypeError;
class Filtro extends Model
{
protected Request $request;
protected $request;
protected $builder;
protected array $MENSAJES_ERROR = [
protected $MENSAJES_ERROR = [
'ARGUMENTO' => 'Argumento inválido para el parámetro %s. Revise la documentación.'
];
@ -25,10 +22,10 @@ class Filtro extends Model
/**
* Apply all existing filters, if available.
*
* @param Builder $builder
* @return Builder
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return \Illuminate\Database\Eloquent\Builder
*/
public function aplicar(Builder $builder): Builder
public function aplicar(Builder $builder)
{
$this->builder = $builder;
@ -46,24 +43,17 @@ class Filtro extends Model
//Obtener nombre del método (snake_case a camelCase)
$metodo = str_replace('_', '', lcfirst(ucwords($filtro, '_')));
if (!method_exists($this, $metodo))
continue;
if(!method_exists($this, $metodo)) { continue; }
//Llamar métodos sin argumentos
if ($valor === null || (is_a($valor,'String') && trim($valor)=='')) {
$this->$metodo();
continue;
}
if ($valor === null|| (is_a($valor,'String') && trim($valor)=='')){ $this->$metodo(); continue; }
//Llamar métodos con argumentos
try {
$this->$metodo($valor);
} catch (Throwable $error) {
if (is_a($error,'TypeError')) {
$mensaje = sprintf($this->MENSAJES_ERROR['ARGUMENTO'], $filtro);
throw new HttpException(400, $mensaje);
}
throw $error;
} catch (\Throwable $th) {
if (is_a($th,'TypeError') ) { throw new HttpException(400, sprintf($this->MENSAJES_ERROR['ARGUMENTO'],$filtro)); }
throw $th;
}
}
@ -73,16 +63,12 @@ class Filtro extends Model
//Buscar un término en el nombre
public function nombre(String $valor)
{
$this->builder
->where('nombre', "LIKE", "%" . $valor . "%")
->orderByRaw("IF(nombre = '$valor',2,IF(nombre LIKE '$valor%',1,0)) DESC");
$this->builder->where('nombre', "LIKE", "%" . $valor . "%")->orderByRaw("IF(nombre = '{$valor}',2,IF(nombre LIKE '{$valor}%',1,0)) DESC");
}
public function alfabetico(String $order = 'asc')
{
if (!in_array($order,['asc','desc']))
throw new TypeError();
if(!in_array($order,['asc','desc'])) { throw new TypeError(); }
$this->builder->orderBy('nombre', $order);
}
}

View file

@ -1,6 +1,7 @@
<?php
namespace App\Filtros;
use Illuminate\Database\Eloquent\Builder;
class FiltroDeProducto extends Filtro {
@ -9,4 +10,4 @@ class FiltroDeProducto extends Filtro {
$this->builder->where('categoria', $valor);
}
}
}

View file

@ -2,23 +2,13 @@
namespace App\Filtros;
use TypeError;
use Illuminate\Database\Eloquent\Model;
class FiltroDeSubpedido extends Filtro
{
public function grupoDeCompra(String $valor)
{
if (!is_numeric($valor))
throw new TypeError();
if (!is_numeric($valor)) { throw new TypeError();}
$this->builder->where('grupo_de_compra_id', intval($valor));
}
public function tipoPedido(String $valor)
{
if (!is_numeric($valor))
throw new TypeError();
$this->builder->where('tipo_pedido_id', intval($valor));
}
}

View file

@ -2,205 +2,17 @@
namespace App;
use App\Helpers\CsvHelper;
use App\Helpers\PdfHelper;
use App\Helpers\TransporteHelper;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use League\Csv\Exception;
use Mpdf\MpdfException;
class GrupoDeCompra extends Model
{
protected $fillable = ["nombre", "region", "devoluciones_habilitadas", "saldo"];
protected $table = 'grupos_de_compra';
public $timestamps = false;
protected $fillable = [ "nombre","region","telefono","correo","referente_finanzas","cantidad_de_nucleos"];
protected $table = 'grupos_de_compra';
protected $hidden = ['password'];
public function subpedidos(): HasMany
{
return $this->hasMany(Subpedido::class);
}
public function users(): HasMany
{
return $this->hasMany(User::class);
}
public function toggleDevoluciones(): bool
{
$this->devoluciones_habilitadas = !$this->devoluciones_habilitadas;
$this->save();
return $this->devoluciones_habilitadas;
}
public function pedidosAprobados()
{
return $this->pedidosHogares()
->where('aprobado', 1);
}
public function pedidosHogares()
{
return $this->subpedidos
->where('tipo_pedido_id', '=', 1);
}
public function totalARecaudar()
{
$total = 0;
foreach ($this->pedidosAprobados() as $subpedido) {
$total = $total + $subpedido->total();
}
return $total;
}
public function totalSinDevoluciones() {
$total = 0;
foreach ($this->pedidosAprobados() as $subpedido) {
$total = $total + $subpedido->totalSinDevoluciones();
}
return $total;
}
public function totalBarrial()
{
$total = 0;
foreach ($this->pedidosAprobados() as $subpedido) {
$total = $total + $subpedido->totalBarrial();
}
return $total;
}
public function totalDevoluciones()
{
$total = 0;
foreach ($this->pedidosAprobados() as $subpedido) {
$total = $total + $subpedido->devoluciones_total;
}
return $total;
}
public function totalDePedido()
{
return $this->totalCentralesQueNoPaganTransporte()
+ $this->totalCentralesQuePaganTransporte()
+ $this->totalTransporte()
;
}
public function totalATransferir()
{
return $this->totalDePedido() - $this->saldo;
}
public function totalCentralesQueNoPaganTransporte()
{
$total = 0;
foreach ($this->pedidosAprobados() as $subpedido) {
$total = $total + $subpedido->totalCentralesQueNoPaganTransporte();
}
return $total;
}
public function totalCentralesQuePaganTransporte()
{
$total = 0;
foreach ($this->pedidosAprobados() as $subpedido) {
$total = $total + $subpedido->totalCentralesQuePaganTransporte();
}
return $total;
}
public function totalTransporte()
{
return TransporteHelper::totalTransporte($this->totalCentralesQuePaganTransporte());
}
/**
* @return int
* Calcula la cantidad de bonos de transporte del barrio
*/
public function cantidadTransporte(): int
{
return TransporteHelper::cantidadTransporte($this->totalCentralesQuePaganTransporte());
}
/**
* @throws MpdfException
*/
public function exportarPedidosAPdf()
{
$subpedidos = $this->pedidosAprobados();
$fecha = now()->format('Y-m-d');
$filepath = $this->nombre . '-' . $fecha . '.pdf';
PdfHelper::exportarPedidos($filepath, $subpedidos);
}
function pedidoParaPdf(): array
{
$productos = $this->productosPedidos(true, 'producto_id');
$pedido = [];
$pedido['productos'] = [];
$pedido['nombre'] = $this->nombre;
foreach ($productos as $producto) {
$productoParaPdf = [];
$productoParaPdf['pivot'] = [];
$productoParaPdf['nombre'] = $producto->producto_nombre;
$productoParaPdf['pivot']['cantidad'] = $producto->cantidad_pedida;
$productoParaPdf['pivot']['notas'] = false;
$productoParaPdf['bono'] = $producto->producto_es_bono;
$pedido['productos'][] = $productoParaPdf;
}
return $pedido;
}
public function generarHTML()
{
$view = view("pdfgen.pedido_tabla", ["pedido" => $this->pedidoParaPdf()]);
return $view->render();
}
/**
* @throws MpdfException
*/
public static function exportarPedidosBarrialesAPdf()
{
$barrios = GrupoDeCompra::barriosMenosPrueba()->get();
$fecha = now()->format('Y-m-d');
$filepath = 'pedidos_por_barrio-' . $fecha . '.pdf';
PdfHelper::exportarPedidos($filepath, $barrios);
}
public static function barriosMenosPrueba(): Builder
{
return self::where('nombre', '<>', 'PRUEBA')
->orderBy('region')
->orderBy('nombre');
}
public function productosPedidos($excluirBonos = false, $orderBy = 'producto_nombre'): Collection
{
$query = DB::table('pedidos_aprobados')
->where('grupo_de_compra_id', $this->id)
->where('producto_nombre','NOT LIKE','%barrial%');
if ($excluirBonos)
$query = $query->where('producto_es_bono',false);
return $query
->orderBy($orderBy)
->get()
->keyBy('producto_id');
}
public function setSaldo(float $saldo) {
$this->saldo = $saldo;
$this->save();
}
public function subpedidos() {
return $this->hasMany('App\Subpedido');
}
}

View file

@ -1,144 +0,0 @@
<?php
namespace App\Helpers;
use App\Producto;
use App\CanastaLog;
use DatabaseSeeder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use League\Csv\Exception;
class CanastaHelper
{
const TIPO = "Tipo";
const PRODUCTO = 'Producto';
const PRECIO = 'Precio';
const REGEX_BONO = "/^[BF]/i";
const ARCHIVO_SUBIDO = 'Archivo subido';
const CANASTA_CARGADA = 'Canasta cargada';
const PRODUCTO_TALLE_COLOR = "PTC";
public static function canastaActual() {
$result = [];
$log = CanastaLog::where('descripcion', self::CANASTA_CARGADA)
->orderBy('created_at', 'desc')
->first();
$nombre = str_replace(storage_path(), "", $log->path);
$nombre = str_replace("/csv/canastas/", "", $nombre);
$result["nombre"] = str_replace(".csv", "", $nombre);
$result["fecha"] = $log->created_at;
return $result;
}
public static function guardarCanasta($data, $path): string {
if (!File::exists(storage_path('csv/canastas'))) {
File::makeDirectory(storage_path('csv/canastas'), 0755, true);
}
$nombre = $data->getClientOriginalName();
$storage_path = storage_path($path);
$data->move($storage_path, $nombre);
self::log($storage_path . $nombre, self::ARCHIVO_SUBIDO);
return $nombre;
}
/**
* @throws Exception
*/
public static function cargarCanasta($archivo) {
self::limpiarTablas();
$registros = CsvHelper::getRecords($archivo, "No se pudo leer el archivo.");
$toInsert = [];
$categoria = '';
foreach($registros as $i => $registro) {
// saltear bono de transporte y filas que no tienen tipo
if (self::noTieneTipo($registro) || $registro[self::TIPO] == "T")
continue;
// obtener categoria si no hay producto
if ($registro[self::PRODUCTO] == '') {
// no es la pregunta de la copa?
if (!Str::contains($registro[self::TIPO],"¿"))
$categoria = $registro[self::TIPO];
continue; // saltear si es la pregunta de la copa
}
// completar producto
$toInsert[] = DatabaseSeeder::addTimestamps([
'fila' => $i,
'categoria' => $categoria,
'nombre' => trim(str_replace('*', '',$registro[self::PRODUCTO])),
'precio' => $registro[self::PRECIO],
'es_solidario' => Str::contains($registro[self::PRODUCTO],"*"),
'bono' => preg_match(self::REGEX_BONO, $registro[self::TIPO]),
'requiere_notas'=> $registro[self::TIPO] == self::PRODUCTO_TALLE_COLOR,
]);
}
foreach (array_chunk($toInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
Producto::insert($chunk);
self::agregarBonoBarrial();
self::log($archivo, self::CANASTA_CARGADA);
}
/**
* @param $path
* @param $descripcion
* @return void
*/
private static function log($path, $descripcion): void
{
$log = new CanastaLog([
'path' => $path,
'descripcion' => $descripcion,
]);
$log->save();
}
private static function limpiarTablas()
{
DB::delete('delete from producto_subpedido');
DB::delete('delete from productos');
DB::delete('delete from subpedidos');
}
private static function agregarBonoBarrial()
{
$categoria = Producto::all()
->pluck('categoria')
->unique()
->flatten()
->first(function ($c) {
return Str::contains($c, 'BONO');
});
Producto::create([
'nombre' => "Bono barrial",
'precio' => 20,
'categoria' => $categoria,
'bono' => 1,
'es_solidario' => 0,
'requiere_notas'=> false,
]);
}
/**
* @param $registro
* @return bool
*/
public static function noTieneTipo($registro): bool
{
return !Arr::has($registro, self::TIPO) || trim($registro[self::TIPO]) == '';
}
}

View file

@ -1,101 +0,0 @@
<?php
namespace App\Helpers;
use App\Http\Controllers\ComisionesController;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Iterator;
use League\Csv\CannotInsertRecord;
use League\Csv\Exception;
use League\Csv\InvalidArgument;
use League\Csv\Reader;
use League\Csv\Writer;
class CsvHelper
{
/**
* @throws Exception
*/
public static function getRecords($filePath, $message): Iterator {
try {
$csv = self::getReader($filePath);
return $csv->getRecords();
} catch (InvalidArgument|Exception $e) {
Log::error($e->getMessage());
throw new Exception($message, $e);
}
}
/**
* @throws Exception
*/
public static function cambiarParametro(string $id, string $valor): void
{
try {
$updated = false;
$filePath = resource_path(ComisionesController::PARAMETROS_PATH);
$csv = self::getReader($filePath);
$headers = $csv->getHeader();
$records = array_map(fn($r) => (array) $r, iterator_to_array($csv->getRecords()));
foreach ($records as &$record) {
if ($record['id'] === $id) {
$record['valor'] = $valor;
$updated = true;
break;
}
}
unset($record);
if (!$updated)
throw new Exception("Parametro '{$id}' no encontrado.");
self::generarCsv($filePath, $records, $headers, "|", "'", false);
} catch (CannotInsertRecord | InvalidArgument $e) {
Log::error("Error al actualizar csv: " . $e->getMessage());
throw new Exception("Error al actualizar csv", $e);
}
}
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
*/
public static function generarCsv($filePath, $contenido, $headers = null, $delimiter = null, $enclosure = null, $export = true): void
{
$path = $filePath;
if ($export) {
if (!File::exists(storage_path('csv/exports')))
File::makeDirectory(storage_path('csv/exports'), 0755, true);
$path = storage_path($filePath);
}
$writer = Writer::createFromPath($path, 'w');
if ($delimiter)
$writer->setDelimiter($delimiter);
if ($enclosure)
$writer->setEnclosure($enclosure);
if ($headers)
$writer->insertOne($headers);
$writer->insertAll($contenido);
}
/**
* @param string $filePath
* @return Reader
* @throws InvalidArgument
* @throws Exception
*/
private static function getReader(string $filePath): Reader
{
$csv = Reader::createFromPath($filePath);
$csv->setDelimiter("|");
$csv->setEnclosure("'");
$csv->setHeaderOffset(0);
return $csv;
}
}

View file

@ -1,29 +0,0 @@
<?php
namespace App\Helpers;
use Mpdf\Mpdf;
use Mpdf\MpdfException;
class PdfHelper
{
/**
* Requiere que el segundo argumento tenga definida la función generarHTML()
* para crear la tabla con los datos del pedido que se inserta en el pdf.
*
* @return void
* @throws MpdfException
*/
public static function exportarPedidos($filepath, $pedidos)
{
$mpdf = new Mpdf();
foreach ($pedidos as $pedido) {
$html = $pedido->generarHTML();
$mpdf->WriteHTML($html);
$mpdf->AddPage();
}
$mpdf->Output($filepath, 'D');
}
}

View file

@ -1,258 +0,0 @@
<?php
namespace App\Helpers;
use App\GrupoDeCompra;
use App\TipoPedido;
use Closure;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use League\Csv\CannotInsertRecord;
use League\Csv\Exception;
use League\Csv\InvalidArgument;
class PedidosExportHelper
{
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
* @throws Exception
*/
static public function pedidosBarriales()
{
$filePath = "csv/exports/pedidos-por-barrio-" . now()->format('Y-m-d') . ".csv";
$barrios = GrupoDeCompra::barriosMenosPrueba()->get();
self::exportarCSV(
$filePath,
$barrios,
self::generarContenidoCSV(
$barrios,
fn ($grupoId) =>
"subpedidos.grupo_de_compra_id = $grupoId
AND subpedidos.aprobado = 1
AND subpedidos.tipo_pedido_id = 1"
)
);
}
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
* @throws Exception
*/
static public function pedidosDeOllas()
{
$filePath = "csv/exports/pedidos-de-ollas-" . now()->format('Y-m-d') . ".csv";
$barrios = GrupoDeCompra::barriosMenosPrueba()
->whereHas('subpedidos', function ($query) {
$tipo_olla = self::getTipoId('olla');
$query->where('tipo_pedido_id', $tipo_olla);
})
->get();
$contenido = self::generarContenidoCSV($barrios,
fn($grupoId) => "subpedidos.grupo_de_compra_id = $grupoId
AND subpedidos.tipo_pedido_id = 2");
$ollas = self::cantidadDeOllasParaCSV($barrios, $contenido);
self::exportarCSV(
$filePath,
$barrios,
$contenido->concat([$ollas])
);
}
/**
* @throws Exception
*/
public static function cantidadDeOllasParaCSV(Collection $barrios, Collection $contenido)
{
$tipo_olla = self::getTipoId('olla');
$parametros = collect(CsvHelper::getRecords(resource_path("csv/parametros.csv"), "No se pudo leer el archivo."));
$fila = [
"producto" => "Cantidad de ollas",
"precio" => $parametros->where('id','monto-olla')->pluck('valor')->first(),
"paga_transporte" => false,
"fila" => $contenido->last()->fila + 1,
];
foreach ($barrios as $barrio) {
$pedido = $barrio->subpedidos()->where('tipo_pedido_id', $tipo_olla)->first();
$fila[$barrio->nombre] = $pedido->cantidad_ollas;
}
return (object) $fila;
}
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
* @throws Exception
*/
static public function pedidoTotalDeBarrio(GrupoDeCompra $grupo)
{
$filePath = "csv/exports/" . $grupo->nombre . "-" . now()->format('Y-m-d') . ".csv";
$falsoBarrio = new GrupoDeCompra(['nombre' => 'Total']);
$falsoBarrio->id = $grupo->id;
$header = collect([$falsoBarrio]);
self::exportarCSV(
$filePath,
$header,
self::generarContenidoCSV(
$header,
fn($grupoId) => "subpedidos.grupo_de_compra_id = $grupoId
AND subpedidos.aprobado = 1"
),
);
}
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
* @throws Exception
*/
static public function pedidosDeBarrio(GrupoDeCompra $grupo)
{
$filePath = "csv/exports/" . $grupo->nombre . "-completo-" . now()->format('Y-m-d') . ".csv";
$subpedidos = $grupo->subpedidos()->where('aprobado', true)->get();
self::exportarCSV(
$filePath,
$subpedidos,
self::generarContenidoCSV(
$subpedidos,
fn ($subpedidoId) => "subpedidos.id = $subpedidoId",
)
);
}
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
* @throws Exception
*/
private static function exportarCSV(
string $filename,
Collection $headers,
Collection $contenido
): void {
$nombresColumnas = $headers->pluck('nombre')->toArray();
$columnas = array_merge(['Producto'], $nombresColumnas);
$filaTransporte = TransporteHelper::filaTransporte();
$planilla = [];
$ultimaFila = 1;
foreach ($contenido as $fila) {
$filaActual = $fila->fila;
while ($filaActual - $ultimaFila > 1) {
$ultimaFila++;
$planilla[$ultimaFila] = [$ultimaFila === $filaTransporte ? 'Bono de transporte' : '---'];
}
$planilla[$filaActual] = [$fila->producto];
foreach ($nombresColumnas as $nombre)
$planilla[$filaActual][] = $fila->$nombre ?? 0;
$ultimaFila = $filaActual;
}
$planilla[$filaTransporte] = array_merge(['Bono de transporte'], self::cantidadesTransporte($nombresColumnas, $contenido));
ksort($planilla);
CsvHelper::generarCsv($filename, $planilla, $columnas);
}
/**
* @param Collection $headers
* @param Closure $filtroCallback
* <br>
* Ejemplo de uso:
* ``
* PedidosExportHelper::generarContenidoCSV(GrupoDeCompra::barriosMenosPrueba(),
* fn($gdc_id) => "subpedidos.grupo_de_compra_id = $gdc_id");
* ``
* @return Collection
* Los elementos son de la forma
* {
* fila: int (fila del producto),
* producto: string (nombre del producto),
* precio: float (precio del producto),
* paga_transporte: bool (1 o 0, calculado a partir de bono y categoria),
* barrio_1: string (cantidad pedida por barrio_1),
* ...
* barrio_n: string (cantidad pedida por barrio_n)
* }
*/
public static function generarContenidoCSV(
Collection $headers,
Closure $filtroCallback
): Collection {
$expresionesColumnas = $headers->map(function ($header) use ($filtroCallback) {
$id = $header['id'];
$nombre = $header['nombre'];
$filtro = $filtroCallback($id);
return DB::raw("
SUM(CASE WHEN $filtro THEN producto_subpedido.cantidad ELSE 0 END) as `$nombre`
");
})->toArray();
$query = DB::table('productos')
->where('productos.nombre', 'not like', '%barrial%')
->leftJoin('producto_subpedido', 'productos.id', '=', 'producto_subpedido.producto_id')
->leftJoin('subpedidos', 'subpedidos.id', '=', 'producto_subpedido.subpedido_id');
$columnasProducto = [
'productos.fila as fila',
'productos.nombre as producto',
'productos.precio as precio',
self::pagaTransporte(),
];
return $query->select(array_merge(
$columnasProducto,
$expresionesColumnas
))->groupBy('productos.fila', 'productos.id', 'productos.nombre')
->orderBy('productos.fila')
->get();
}
/**
* @return Expression
*/
public static function pagaTransporte(): Expression
{
return DB::raw('CASE WHEN productos.bono OR productos.categoria LIKE "%SUBSIDIADO%" THEN 0 ELSE 1 END as paga_transporte');
}
/**
* @param array $nombresColumnas
* @param Collection $contenido
* @return array
*/
public static function cantidadesTransporte(array $nombresColumnas, Collection $contenido): array
{
$transporte = [];
foreach ($nombresColumnas as $nombre) {
$suma = 0;
foreach ($contenido as $fila) {
if ($fila->paga_transporte) {
$cantidad = $fila->$nombre ?? 0;
$precio = $fila->precio ?? 0;
$suma += $cantidad * $precio;
}
}
$transporte[] = TransporteHelper::cantidadTransporte($suma);
}
return $transporte;
}
/**
* @return mixed
*/
public static function getTipoId(string $tipo)
{
$tipo_olla = TipoPedido::where('nombre', $tipo)->first()->id;
return $tipo_olla;
}
}

View file

@ -1,76 +0,0 @@
<?php
namespace App\Helpers;
use App\CanastaLog;
use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
use League\Csv\Exception;
class TransporteHelper
{
private const COSTO_TRANSPORTE = "bono-transporte";
private const MONTO_TRANSPORTE = "monto-transporte";
private static ?array $parametros = null;
/**
* @throws Exception
*/
public static function cantidadTransporte($monto)
{
return ceil($monto / self::getParametro(self::MONTO_TRANSPORTE));
}
/**
* @throws Exception
*/
public static function totalTransporte($monto)
{
return self::cantidadTransporte($monto) * self::getParametro(self::COSTO_TRANSPORTE);
}
/**
* @throws Exception
*/
public static function filaTransporte()
{
$ultimaCanasta = CanastaLog::where('descripcion', CanastaHelper::CANASTA_CARGADA)
->orderBy('created_at', 'desc')
->pluck('path')
->first();
$registros = CsvHelper::getRecords($ultimaCanasta, "No se encontró la ultima canasta.");
$error = 'No hay fila de tipo T en la planilla: ' . $ultimaCanasta;
foreach ($registros as $key => $registro)
if ($registro[CanastaHelper::TIPO] == 'T')
return $key;
Log::error($error);
throw new Exception($error);
}
/**
* @throws Exception
*/
public static function getParametro(string $id): int
{
if (self::$parametros === null) {
$records = CsvHelper::getRecords(resource_path('csv/parametros.csv'), "No se pudo leer el archivo.");
self::$parametros = [];
foreach ($records as $row) {
self::$parametros[$row['id']] = $row;
}
}
if (!isset(self::$parametros[$id])) {
throw new InvalidArgumentException("Parámetro '$id' no encontrado.");
}
return (int) self::$parametros[$id]['valor'];
}
public static function resetParametros(): void {
self::$parametros = null;
}
}

View file

@ -2,62 +2,9 @@
namespace App\Http\Controllers;
use App\GrupoDeCompra;
use App\Helpers\PedidosExportHelper;
use League\Csv\Exception;
use Mpdf\MpdfException;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function show()
{
return view('auth/login');
}
public function index() {
return view('auth/admin_subpedidos');
}
public function exportarPedidosAPdf(GrupoDeCompra $gdc) {
try {
$gdc->exportarPedidosAPdf();
return response();
} catch (MpdfException $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
}
public function exportarPedidoACSV(GrupoDeCompra $gdc)
{
try {
PedidosExportHelper::pedidoTotalDeBarrio($gdc);
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()]);
}
$pattern = storage_path('csv/exports/'. $gdc->nombre . '-*.csv');
$files = glob($pattern);
usort($files, function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return response()->download($files[0]);
}
public function exportarPedidoConNucleosACSV(GrupoDeCompra $gdc)
{
try {
PedidosExportHelper::pedidosDeBarrio($gdc);
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()]);
}
$pattern = storage_path('csv/exports/'.$gdc->nombre.'-completo-*.csv');
$files = glob($pattern);
usort($files, function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return response()->download($files[0]);
}
//
}

View file

@ -1,13 +0,0 @@
<?php
namespace App\Http\Controllers\Api;
use App\Helpers\CanastaHelper;
use App\Http\Controllers\Controller;
class CanastaController extends Controller
{
public function canastaActual() {
return response()->json(CanastaHelper::canastaActual());
}
}

View file

@ -1,48 +0,0 @@
<?php
namespace App\Http\Controllers\Api;
use App\GrupoDeCompra;
use App\Http\Controllers\Controller;
use App\Http\Resources\GrupoDeCompraComisionesResource;
use App\Http\Resources\GrupoDeCompraResource;
class GrupoDeCompraController extends Controller
{
public function index()
{
return GrupoDeCompraResource::collection(GrupoDeCompra::all());
}
public function show(GrupoDeCompra $grupoDeCompra)
{
return new GrupoDeCompraResource($grupoDeCompra);
}
public function regiones()
{
return GrupoDeCompra::all()->pluck('region')->unique()->flatten();
}
public function region(string $region)
{
return GrupoDeCompra::where('region', $region)->get();
}
public function toggleDevoluciones(int $gdc) {
GrupoDeCompra::find($gdc)->toggleDevoluciones();
return response()->noContent();
}
public function setSaldo(int $gdc) {
$valid = request()->validate([
'saldo' => ['required', 'min:0'],
]);
$grupoDeCompra = GrupoDeCompra::find($gdc);
$grupoDeCompra->setSaldo($valid['saldo']);
return response()->noContent();
}
public function saldos()
{
return GrupoDeCompraComisionesResource::collection(GrupoDeCompra::all());
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class PedidoController extends Controller
{
public function generarTablas()
{
//GENERAR TABLA GENERAL
DB::unprepared("DROP VIEW if exists productos_por_grupo_de_compra;
SET @barrios = NULL;
SELECT
GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(`grupo_de_compra_nombre` = \"', `grupo_de_compra_nombre`,'\", `cantidad_pedida`,NULL)) AS \"',`grupo_de_compra_nombre`,'\"')) INTO @barrios
FROM pedidos;
SET @sql = CONCAT('CREATE VIEW productos_por_grupo_de_compra AS SELECT producto_nombre, ', @barrios, ' FROM pedidos GROUP BY producto_nombre');
PREPARE stmt FROM @sql;
EXECUTE stmt;");
return "Tabla productos_por_grupo_de_compra generada. " . date('l jS \of F Y h:i:s A');
}
}

View file

@ -2,21 +2,35 @@
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Filtros\FiltroDeProducto;
use App\Http\Resources\ProductoResource;
use App\Producto;
class ProductoController extends Controller
{
/**
* Mostrar una lista de productos.
*
* @param App\Filtros\FiltroDeProducto $filtros
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function index(FiltroDeProducto $filtros, Request $request)
{
return ProductoResource::collection(Producto::filtrar($filtros)->paginate(Producto::getPaginar($request)));
}
public function categorias()
/**
* Display the specified resource.
*
* @param \App\Producto $producto
* @return \Illuminate\Http\Response
*/
public function show(Producto $producto)
{
return Producto::all()->pluck('categoria')->unique()->flatten();
return new ProductoResource($producto);
}
}

View file

@ -4,7 +4,6 @@ namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Producto;
use App\TipoPedido;
use Illuminate\Http\Request;
use App\Filtros\FiltroDeSubpedido;
use App\Subpedido;
@ -13,54 +12,56 @@ use App\Http\Resources\SubpedidoResource;
use Illuminate\Validation\Rule;
use Symfony\Component\HttpKernel\Exception\HttpException;
class SubpedidoController extends Controller
{
/**
* Mostrar una lista de productos.
*
* @param App\Filtros\FiltroDeSubpedido $filtros
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function index(FiltroDeSubpedido $filtros, Request $request)
{
return Subpedido::filtrar($filtros)->select('id','nombre')->get();
return Subpedido::filtrar($filtros)->get();
}
public function indexResources(FiltroDeSubpedido $filtros, Request $request)
{
return SubpedidoResource::collection(Subpedido::filtrar($filtros)->get());
}
public function store(Request $request)
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validado = $this->validateSubpedido();
if (Subpedido::where([
"nombre" => $validado["nombre"],
"tipo_pedido_id" => $validado["tipo_id"],
"grupo_de_compra_id" => $validado["grupo_de_compra_id"]])
->get()
->count())
throw new HttpException(400, "Ya existe un pedido con este nombre");
$pedido = new Subpedido();
$pedido->nombre = $validado["nombre"];
$pedido->grupo_de_compra_id = $validado["grupo_de_compra_id"];
$pedido->tipo_pedido_id = $validado["tipo_id"];
$pedido->save();
return $this->show($pedido);
if (Subpedido::where("nombre",$validado["nombre"])->where("grupo_de_compra_id",$validado["grupo_de_compra_id"])->get()->count()) {
throw new HttpException(400, "Ya existe un subpedido con este nombre");
}
$s = new Subpedido();
$s->nombre = $validado["nombre"];
$s->grupo_de_compra_id = $validado["grupo_de_compra_id"];
$s->save();
return $s;
}
protected function validateSubpedido(): array
{
protected function validateSubpedido(){
return request()->validate([
'nombre' => 'required|max:255',
'grupo_de_compra_id' => [
'required',
Rule::in(GrupoDeCompra::all()->pluck('id')),
],
'tipo_id' => [
'required',
Rule::in(TipoPedido::all()->pluck('id')),
],
]
]);
}
/**
* Display the specified resource.
*
* @param \App\Subpedido $subpedido
* @return \Illuminate\Http\Response
*/
public function show(Subpedido $subpedido)
{
return new SubpedidoResource($subpedido);
@ -68,12 +69,8 @@ class SubpedidoController extends Controller
// recibe request, saca producto y cantidad, valida, y pasa a syncProducto en Subpedido
public function syncProductos(Subpedido $subpedido) {
if ($subpedido->aprobado)
abort(400, "No se puede modificar un pedido aprobado.");
$valid = request()->validate([
'cantidad' => ['integer','required','min:0'],
'notas' => 'nullable',
'cantidad' => 'required|min:0',
'producto_id' => [
'required',
Rule::in(Producto::all()->pluck('id')),
@ -81,30 +78,9 @@ class SubpedidoController extends Controller
]);
$producto = Producto::find($valid['producto_id']);
$notas = $valid['notas'];
$cantidad = $valid['cantidad'];
$subpedido->syncProducto($producto, $cantidad, $notas ?? "");
$subpedido->syncProducto($producto, $valid['cantidad']);
return new SubpedidoResource($subpedido);
}
public function toggleAprobacion(Subpedido $subpedido) {
$valid = request()->validate([
'aprobacion' => 'required | boolean'
]);
$subpedido->toggleAprobacion($valid['aprobacion']);
return response()->noContent();
}
public function syncDevoluciones(Subpedido $subpedido) {
if ($subpedido->aprobado)
abort(400, "No se puede modificar un pedido aprobado.");
$valid = request()->validate([
'total' => 'required|min:0',
'notas' => 'min:0'
]);
$subpedido->syncDevoluciones($valid['total'], $valid['notas'] ?? "");
return new SubpedidoResource($subpedido);
}
}

View file

@ -5,7 +5,7 @@ namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
@ -28,11 +28,6 @@ class LoginController extends Controller
*/
protected $redirectTo = RouteServiceProvider::HOME;
protected function authenticated(Request $request, $user)
{
return redirect('/');
}
/**
* Create a new controller instance.
*

View file

@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ChismosaController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware(['auth','subpedido']);
}
public function show()
{
return view('chismosa');
}
}

View file

@ -1,186 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\GrupoDeCompra;
use App\Helpers\CanastaHelper;
use App\Helpers\CsvHelper;
use App\Helpers\PedidosExportHelper;
use App\Helpers\TransporteHelper;
use App\Http\Resources\GrupoDeCompraResource;
use App\Producto;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use League\Csv\CannotInsertRecord;
use League\Csv\Exception;
use League\Csv\InvalidArgument;
use Mpdf\MpdfException;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
class ComisionesController
{
const PARAMETROS_PATH = 'csv/parametros.csv';
const CANASTAS_PATH = 'csv/canastas/';
const BARRIO = "Barrio";
const SALDO = "Saldo";
public function show()
{
return view('auth/login');
}
public function descargarPedidos()
{
try {
PedidosExportHelper::pedidosBarriales();
} catch (CannotInsertRecord|InvalidArgument|Exception $e) {
Log::error($e->getMessage());
return response()->json(['message' => $e->getMessage()], 500);
}
$pattern = storage_path('csv/exports/pedidos-por-barrio-*.csv');
$files = glob($pattern);
usort($files, function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return response()->download($files[0]);
}
public function descargarPedidosDeOllas()
{
try {
PedidosExportHelper::pedidosDeOllas();
} catch (CannotInsertRecord|InvalidArgument|Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
$pattern = storage_path('csv/exports/pedidos-de-ollas-*.csv');
$files = glob($pattern);
usort($files, function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return response()->download($files[0]);
}
public function descargarNotas()
{
try {
Producto::planillaNotas();
} catch (CannotInsertRecord|InvalidArgument $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
$pattern = storage_path('csv/exports/notas-por-barrio-*.csv');
$files = glob($pattern);
usort($files, function ($a, $b) {
return filemtime($b) <=> filemtime($a);
});
return response()->download($files[0]);
}
public function pdf() {
try {
GrupoDeCompra::exportarPedidosBarrialesAPdf();
return response();
} catch (MpdfException $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
}
public function cargarCanasta(Request $request): JsonResponse
{
$request->validate([
'data' => 'required|file|mimes:csv,txt|max:2048',
]);
$nombre = CanastaHelper::guardarCanasta($request->file('data'), self::CANASTAS_PATH);
try {
CanastaHelper::cargarCanasta(storage_path(self::CANASTAS_PATH . $nombre));
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
return response()->json([
'message' => 'Canasta cargada exitosamente',
]);
}
public function descargarCanastaEjemplo(): BinaryFileResponse
{
$file = resource_path('csv/productos.csv');
return response()->download($file);
}
public function cargarSaldos(Request $request): JsonResponse
{
$request->validate([
'data' => 'required|file|mimes:csv,txt|max:2048',
]);
$file = $request->file('data')->getPathname();
try {
$records = CsvHelper::getRecords($file, "No se pudo leer el archivo.");
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
foreach ($records as $record) {
$barrio = $record[self::BARRIO];
$saldo = $record[self::SALDO];
GrupoDeCompra::where('nombre', $barrio)
->update(['saldo' => $saldo]);
}
return response()->json(GrupoDeCompraResource::collection(GrupoDeCompra::all()));
}
public function descargarSaldosEjemplo(): BinaryFileResponse
{
$file = resource_path('csv/saldos.csv');
return response()->download($file);
}
public function obtenerParametros(): JsonResponse
{
try {
$records = self::parametrosRecords();
$result = [];
foreach ($records as $record)
$result[] = $record;
return response()->json($result);
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
}
public function modificarParametros(string $parametro_id, Request $request) {
try {
if (collect(self::parametrosRecords())
->contains('id', $parametro_id)) {
$valid = $request->validate([
'valor' => ['required', 'numeric', 'gte:0'],
]);
CsvHelper::cambiarParametro($parametro_id, $valid['valor']);
TransporteHelper::resetParametros();
return response()->noContent();
}
return response()->json(['message' => 'Parametro no encontrado.'], 404);
} catch (Exception $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
}
/**
* @throws Exception
*/
private static function parametrosRecords(): array
{
$records = CsvHelper::getRecords(resource_path(self::PARAMETROS_PATH), "No se pudo leer el archivo.");
return iterator_to_array($records);
}
}

View file

@ -1,43 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\GrupoDeCompra;
use App\Http\Resources\PedidoOllasResource;
use App\TipoPedido;
use Illuminate\Http\Request;
class OllasController extends Controller
{
public function show()
{
return view('auth/login');
}
public function pedido(GrupoDeCompra $gdc)
{
$tipoOlla = TipoPedido::firstOrCreate(['nombre' => 'olla']);
$pedido = $gdc->subpedidos()->firstOrCreate([
'nombre' => 'Pedido de Ollas de ' . $gdc->nombre,
'tipo_pedido_id' => $tipoOlla->id,
]);
if (!$pedido->cantidad_ollas) {
$pedido->cantidad_ollas = 0;
$pedido->save();
}
return response()->json(new PedidoOllasResource($pedido));
}
public function actualizarCantidadOllas(GrupoDeCompra $gdc, Request $request)
{
$valid = $request->validate([
'cantidad' => 'required|numeric|min:0',
]);
$pedido = $gdc->subpedidos()->where([
'nombre' => 'Pedido de Ollas de ' . $gdc->nombre
])->first();
$pedido->cantidad_ollas = $valid['cantidad'];
$pedido->save();
return response()->noContent();
}
}

View file

@ -2,6 +2,8 @@
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductoController extends Controller
{
/**
@ -14,6 +16,11 @@ class ProductoController extends Controller
$this->middleware(['auth','subpedido']);
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('productos');

View file

@ -1,37 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class RouteController extends Controller
{
function home(Request $request) {
if (!Auth::check())
return redirect('/login');
$barrio = UserRole::where('nombre', 'barrio')->first();
$admin = UserRole::where('nombre', 'admin_barrio')->first();
$comision = UserRole::where('nombre', 'comision')->first();
$ollas = UserRole::where('nombre', 'ollas')->first();
switch ($request->user()->role_id) {
case $barrio->id:
return redirect('/pedido');
case $admin->id:
return redirect('/admin');
case $comision->id:
return redirect('/comisiones');
case $ollas->id:
return redirect('/ollas');
default:
abort(400, 'Rol de usuario invalido');
}
}
function main(Request $request) {
return view('main');
}
}

View file

@ -1,35 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\Subpedido;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
class SessionController extends Controller
{
public function store(Request $request): Response
{
$grupo_de_compra_id = Auth::user()->grupo_de_compra_id;
$validated = $request->validate([
'id' => 'required',
Rule::in(Subpedido::where('grupo_de_compra_id', $grupo_de_compra_id)->pluck('id')),
]);
session()->put('pedido_id', $validated["id"]);
return response()->noContent();
}
public function fetch(): JsonResponse
{
return response()->json(['id' => session('pedido_id')]);
}
public function destroy(): Response
{
session()->forget('pedido_id');
return response()->noContent();
}
}

View file

@ -1,43 +0,0 @@
<?php
namespace App\Http\Controllers;
use App\GrupoDeCompra;
use App\Http\Resources\GrupoDeCompraPedidoResource;
use App\Http\Resources\GrupoDeCompraResource;
use App\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function user(Request $request)
{
return ['user' => $request->user()->name];
}
public function rol(Request $request) {
return ["rol" => UserRole::find($request->user()->role_id)->nombre];
}
public function grupoDeCompra(Request $request)
{
$user = Auth::user();
$result = [ 'grupo_de_compra' => null, ];
$grupo_de_compra = GrupoDeCompra::find($user->grupo_de_compra_id);
switch (UserRole::findOrFail($user->role_id)->nombre) {
case 'ollas':
case 'barrio':
$result['grupo_de_compra'] = new GrupoDeCompraPedidoResource($grupo_de_compra);
break;
case 'admin_barrio':
$result['grupo_de_compra'] = new GrupoDeCompraResource($grupo_de_compra);
break;
case 'comision':
break;
default:
abort(400, 'Rol invalido.');
}
return $result;
}
}

View file

@ -2,7 +2,6 @@
namespace App\Http;
use App\Http\Middleware\CheckRole;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
@ -57,7 +56,6 @@ class Kernel extends HttpKernel
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'role' => \App\Http\Middleware\CheckRole::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,

View file

@ -3,28 +3,19 @@
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*
* @param Request $request
* @param \Illuminate\Http\Request $request
* @return string|null
*/
protected function redirectTo($request): string
protected function redirectTo($request)
{
if (!$request->expectsJson()) {
$path = $request->path();
if (preg_match('~^admin.*~i', $path))
return route('admin.login');
if (preg_match('~^comisiones.*~i', $path))
return route('comisiones.login');
if (preg_match('~^ollas.*~i', $path))
return route('ollas.login');
if (! $request->expectsJson()) {
return route('login');
}
return '';
}
}

View file

@ -1,25 +0,0 @@
<?php
namespace App\Http\Middleware;
use App\UserRole;
use Closure;
use Illuminate\Http\Request;
class CheckRole
{
/**
* Handle the incoming request.
*
* @param Request $request
* @param Closure $next
* @param string $role
* @return mixed
*/
public function handle($request, Closure $next, $role)
{
$role_id = UserRole::where('nombre', $role)->first()->id;
return $request->user()->role_id == $role_id ? $next($request)
: response('No tenés permiso para esto.', 403);
}
}

View file

@ -3,18 +3,17 @@
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class Subpedido
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure $next
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
public function handle($request, Closure $next)
{
if (!session('subpedido_nombre') || !session('subpedido_id')) {
return redirect()->route('subpedidos.create');

View file

@ -1,22 +0,0 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class GrupoDeCompraComisionesResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request): array {
return [
'id' => $this->id,
'nombre' => $this->nombre,
'saldo' => $this->saldo,
];
}
}

View file

@ -1,23 +0,0 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class GrupoDeCompraPedidoResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param Request $request
* @return array
*/
public function toArray($request): array {
return [
'id' => $this->id,
'nombre' => $this->nombre,
'devoluciones_habilitadas' => $this->devoluciones_habilitadas,
];
}
}

View file

@ -1,34 +0,0 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class GrupoDeCompraResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param Request $request
* @return array
*/
public function toArray($request): array
{
return [
'id' => $this->id,
'nombre' => $this->nombre,
'devoluciones_habilitadas' => $this->devoluciones_habilitadas,
'pedidos' => SubpedidoResource::collection($this->pedidosHogares()),
'total_a_recaudar' => number_format($this->totalARecaudar(),2),
'saldo' => number_format($this->saldo, 2, ".", ""),
'total_sin_devoluciones' => number_format($this->totalSinDevoluciones(),2),
'total_barrial' => number_format($this->totalBarrial(),2),
'total_devoluciones' => number_format($this->totalDevoluciones(),2),
'total_de_pedido' => number_format($this->totalDePedido(),2),
'total_a_transferir' => number_format($this->totalATransferir(),2),
'total_transporte' => number_format($this->totalTransporte()),
'cantidad_transporte' => number_format($this->cantidadTransporte()),
];
}
}

View file

@ -1,30 +0,0 @@
<?php
namespace App\Http\Resources;
use App\TipoPedido;
use Illuminate\Http\Resources\Json\JsonResource;
class PedidoOllasResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request): array
{
$productos = $this->productos;
foreach ($productos as $producto) {
$producto['pivot']['total'] = number_format($producto->pivot->cantidad * $producto->precio, 2);
}
return [
'id' => $this->id,
'nombre' => $this->nombre,
'productos' => $productos,
'total' => number_format($this->totalCentralesSinTransporte(),2),
'cantidad_de_ollas' => $this->cantidad_ollas,
];
}
}

View file

@ -2,7 +2,6 @@
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class ProductoResource extends JsonResource
@ -10,19 +9,23 @@ class ProductoResource extends JsonResource
/**
* Transform the resource into an array.
*
* @param Request $request
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request): array
public function toArray($request)
{
return [
'id' => $this->id,
'nombre' => $this->nombre,
'precio' => $this->precio,
'categoria' => $this->categoria,
'economia_solidaria' => $this->es_solidario,
'nacional' => $this->es_solidario,
'requiere_notas' => $this->requiere_notas,
'proveedor' => optional($this->proveedor)->nombre,
'economia_solidaria' => optional($this->proveedor)->economia_solidaria,
'nacional' => optional($this->proveedor)->nacional,
'imagen' => optional($this->poster)->url(),
'descripcion' => $this->descripcion,
'apto_veganxs' => $this->apto_veganxs,
'apto_celiacxs' => $this->apto_celiacxs
];
}
}

View file

@ -2,8 +2,6 @@
namespace App\Http\Resources;
use App\TipoPedido;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class SubpedidoResource extends JsonResource
@ -11,30 +9,21 @@ class SubpedidoResource extends JsonResource
/**
* Transform the resource into an array.
*
* @param Request $request
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request): array
public function toArray($request)
{
$productos = $this->productos;
foreach ($productos as $producto) {
$producto['pivot']['total'] = number_format($producto->pivot->cantidad * $producto->precio, 2);
}
return [
'id' => $this->id,
'nombre' => $this->nombre,
'productos' => $productos,
'aprobado' => (bool) $this->aprobado,
'total' => number_format($this->total(),2),
'total_transporte' => number_format($this->totalTransporte()),
'cantidad_transporte' => number_format($this->cantidadTransporte()),
'total_sin_devoluciones' => number_format($this->totalSinDevoluciones(),2),
'devoluciones_total' => number_format($this->devoluciones_total,2),
'devoluciones_notas' => $this->devoluciones_notas,
'tipo' => [
'id' => $this->tipo_pedido_id,
'nombre' => TipoPedido::find($this->tipo_pedido_id)->nombre
],
'subtotal_productos' => number_format($this->getSubtotalProductos(),0),
'subtotal_bonos' => number_format($this->getSubtotalBonos(),0),
'bonos_de_transporte' => $this->cantidadBDT(),
'subtotal_bonos_de_transporte' => number_format($this->getSubtotalBDT(),0),
'total' => number_format($this->getTotal(),0),
'grupo_de_compra' => $this->grupoDeCompra,
'productos' => $this->productos
];
}
}

View file

@ -2,105 +2,35 @@
namespace App;
use App\Filtros\FiltroDeProducto;
use App\Helpers\CsvHelper;
use App\Helpers\TransporteHelper;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use League\Csv\CannotInsertRecord;
use League\Csv\Exception;
use League\Csv\InvalidArgument;
use App\Filtros\FiltroDeProducto;
class Producto extends Model
{
protected $fillable = ["nombre", "precio", "categoria", "bono", "es_solidario", "requiere_notas"];
public $timestamps = false;
protected $fillable = [ "nombre", "precio", "presentacion", "stock", "categoria" ];
static $paginarPorDefecto = 10;
public function subpedidos(): BelongsToMany
{
return $this->belongsToMany(Subpedido::class, 'productos_subpedidos')
->withPivot(["cantidad", "notas"]);
}
public function subpedidos()
{
return $this->belongsToMany('App\Subpedido','productos_subpedidos')->withPivot(["cantidad"]);
}
public function proveedor()
{
return $this->belongsTo('App\Proveedor');
}
public function scopeFiltrar($query, FiltroDeProducto $filtros): Builder
{
return $filtros->aplicar($query);
}
//Este método permite que se apliquen los filtros al hacer una request (por ejemplo, de búsqueda)
public function scopeFiltrar($query, FiltroDeProducto $filtros)
{
return $filtros->aplicar($query);
}
public static function getPaginar(Request $request): int
{
return $request->has('paginar') && intval($request->input('paginar')) ?
intval($request->input('paginar')) :
self::all()->count();
}
public static function productosFilaID()
{
return self::noBarriales()->pluck('id', 'fila')->all();
}
public static function productosIDFila()
{
return self::noBarriales()->pluck('fila', 'id')->all();
}
public static function productosIDNombre()
{
return self::noBarriales()->pluck('nombre', 'id')->all();
}
public static function noBarriales()
{
return self::where('nombre', 'not like', '%barrial%');
}
public static function notasPorBarrio(): Collection
{
return DB::table('productos')
->where('productos.nombre', 'not like', '%barrial%')
->join('producto_subpedido', 'productos.id', '=', 'producto_subpedido.producto_id')
->join('subpedidos', 'producto_subpedido.subpedido_id', '=', 'subpedidos.id')
->join('grupos_de_compra', 'subpedidos.grupo_de_compra_id', '=', 'grupos_de_compra.id')
->where('productos.requiere_notas', 1)
->where('subpedidos.tipo_pedido_id', '=', 1)
->select(
'productos.nombre as producto',
'grupos_de_compra.nombre as barrio',
'producto_subpedido.notas'
)
->get()
->groupBy('producto');
}
/**
* @throws InvalidArgument
* @throws CannotInsertRecord
*/
static public function planillaNotas() {
$headers = ['Producto'];
$barrios = GrupoDeCompra::barriosMenosPrueba()
->pluck('nombre')->toArray();
$headers = array_merge($headers, $barrios);
$notasPorBarrio = self::notasPorBarrio();
$planilla = [];
foreach ($notasPorBarrio as $producto => $notasGrupo) {
$fila = [$producto];
foreach ($barrios as $barrio) {
$notas = $notasGrupo->where('barrio', $barrio)
->pluck('notas')
->implode('; ');
$fila[] = $notas ?: '';
}
$planilla[] = $fila;
}
$fecha = now()->format('Y-m-d');
$filePath = 'csv/exports/notas-por-barrio-' . $fecha . '.csv';
CsvHelper::generarCsv($filePath, $planilla, $headers);
}
public static function getPaginar(Request $request)
{
return $request->has('paginar') && intval($request->input('paginar')) ? intval($request->input('paginar')) : self::$paginarPorDefecto;
}
}

17
app/Proveedor.php Normal file
View file

@ -0,0 +1,17 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Proveedor extends Model
{
public $timestamps = false;
protected $fillable = [ "nombre","direccion","telefono","correo","comentario" ];
protected $table = 'proveedores';
public function productos()
{
return $this->hasMany('App\Producto');
}
}

View file

@ -2,149 +2,89 @@
namespace App;
use App\Helpers\TransporteHelper;
use Illuminate\Database\Eloquent\Builder;
use League\Csv\Reader;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Facades\DB;
use Log;
use App\Filtros\FiltroDeSubpedido;
class Subpedido extends Model
{
protected $fillable = [
'grupo_de_compra_id',
'aprobado',
'nombre',
'devoluciones_total',
'devoluciones_notas',
'tipo_pedido_id',
'cantidad_ollas'
];
public $timestamps = false;
protected $fillable = ['grupo_de_compra_id', 'aprobado', 'nombre'];
public function productos(): BelongsToMany
{
return $this->belongsToMany(Producto::class)->withPivot(["cantidad", "notas"]);
}
public function productos()
{
return $this->belongsToMany('App\Producto')->withPivot(["cantidad","total"]);
}
public function grupoDeCompra(): BelongsTo
{
return $this->belongsTo(GrupoDeCompra::class);
}
//Bonos del MPS, Sororo, etc. NO devuelve bonos de transporte
private function bonos()
{
return $this->productos()->where('bono',1);
}
public function tipoPedido(): BelongsTo
{
return $this->belongsTo(TipoPedido::class);
}
private function productosSinBonos()
{
return $this->productos()->where('bono',false);
}
// Permite que se apliquen los filtros al hacer una request (por ejemplo, de búsqueda)
public function scopeFiltrar($query, FiltroDeSubpedido $filtros): Builder
{
return $filtros->aplicar($query);
}
public function total()
{
return $this->totalSinDevoluciones() - $this->devoluciones_total;
}
public function grupoDeCompra()
{
return $this->belongsTo('App\GrupoDeCompra');
}
public function totalSinDevoluciones()
{
return $this->totalBarrial() + $this->totalCentral();
}
//Permite que se apliquen los filtros al hacer una request (por ejemplo, de búsqueda)
public function scopeFiltrar($query, FiltroDeSubpedido $filtros)
{
return $filtros->aplicar($query);
}
public function totalBarrial()
{
return DB::table('producto_subpedido')
->join('productos', 'producto_subpedido.producto_id', '=', 'productos.id')
->where('producto_subpedido.subpedido_id', $this->id)
->where('productos.nombre', 'like', '%barrial%')
->selectRaw('SUM(productos.precio * producto_subpedido.cantidad) as total')
->value('total');
}
//Subtotal de dinero de productos del pedido, sin bonos ni transporte
public function getSubtotalProductos()
{
return $this->productosSinBonos()->sum('total');
}
public function totalCentral()
{
return $this->totalCentralesSinTransporte() + $this->totalTransporte();
}
//Cantidad de bonos de transporte
public function cantidadBDT()
{
return ceil($this->getSubtotalProductos() / 500);
}
public function totalCentralesSinTransporte() {
return $this->totalCentralesQueNoPaganTransporte() + $this->totalCentralesQuePaganTransporte();
}
//Subtotal de dinero de bonos de transporte
public function getSubtotalBDT()
{
return $this->cantidadBDT() * 15;
}
public function totalCentralesQueNoPaganTransporte()
{
return DB::table('producto_subpedido')
->join('productos', 'producto_subpedido.producto_id', '=', 'productos.id')
->where('producto_subpedido.subpedido_id', $this->id)
->where('productos.nombre', 'not like', '%barrial%')
->where(function ($query) {
$query->where('productos.categoria', 'like', '%SUBSIDIADO%')
->orWhere('productos.bono', true);
})
->selectRaw('SUM(productos.precio * producto_subpedido.cantidad) as total')
->value('total');
}
//Subtotal de dinero de bonos (MPS, Sororo, etc)
public function getSubtotalBonos()
{
return $this->bonos()->sum('total');
}
public function totalCentralesQuePaganTransporte()
{
return DB::table('producto_subpedido')
->join('productos', 'producto_subpedido.producto_id', '=', 'productos.id')
->where('producto_subpedido.subpedido_id', $this->id)
->where('productos.nombre', 'not like', '%barrial%')
->where('productos.bono', false)
->where('productos.categoria', 'not like', '%SUBSIDIADO%')
->selectRaw('SUM(productos.precio * producto_subpedido.cantidad) as total')
->value('total');
}
public function totalTransporte()
{
return TransporteHelper::totalTransporte($this->totalCentralesQuePaganTransporte());
}
public function getTotal()
{
return $this->getSubtotalProductos() + $this->getSubtotalBDT() + $this->getSubtotalBonos();
}
public function cantidadTransporte()
{
return TransporteHelper::cantidadTransporte($this->totalCentralesQuePaganTransporte());
}
// Actualiza el pedido, agregando o quitando del subpedido según sea necesario. Debe ser llamado desde el controlador de subpedidos, luego de validar que los parámetros $producto y $cantidad son correctos. También calcula el subtotal por producto.
public function syncProducto(Producto $producto, int $cantidad, string $notas)
{
if ($cantidad) {
//si la cantidad es 1 o más se agrega el producto o actualiza la cantidad
$this->productos()->syncWithoutDetaching([
$producto->id => [
'cantidad' => $cantidad,
'notas' => $notas,
]
]);
//Actualiza el pedido, agregando o quitando del subpedido según sea necesario. Debe ser llamado desde el controlador de subpedidos, luego de validar que los parámetros $producto y $cantidad son correctos. También calcula el subtotal por producto.
public function syncProducto(Producto $producto, Int $cantidad) {
if ($cantidad){
//si la cantidad es 1 o más se agrega el producto o actualiza la cantidad
$this->productos()->syncWithoutDetaching([
$producto->id => [
'cantidad' => $cantidad,
'total' => $cantidad * $producto->precio
]
]);
} else {
//si la cantidad es 0, se elimina el producto del subpedido
$this->productos()->detach($producto->id);
}
}
$this->updated_at = now();
$this->save();
}
public function toggleAprobacion(bool $aprobacion)
{
$this->aprobado = $aprobacion;
$this->update(['aprobado' => $aprobacion]);
$this->save();
}
public function generarHTML()
{
$view = view("pdfgen.pedido_tabla", ["pedido" => $this]);
return $view->render();
}
public function syncDevoluciones(float $total, string $notas)
{
$this->devoluciones_total = $total;
$this->devoluciones_notas = $notas;
$this->save();
}
}

View file

@ -1,10 +0,0 @@
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TipoPedido extends Model
{
protected $fillable = ["nombre"];
}

View file

@ -2,7 +2,7 @@
namespace App;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
@ -16,7 +16,7 @@ class User extends Authenticatable
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'role_id',
'name', 'email', 'password',
];
/**
@ -38,8 +38,8 @@ class User extends Authenticatable
];
public function grupoDeCompra(): BelongsTo
public function grupoDeCompra()
{
return $this->belongsTo(GrupoDeCompra::class);
return $this->belongsTo('App\GrupoDeCompra');
}
}

View file

@ -8,8 +8,7 @@
],
"license": "MIT",
"require": {
"php": "^7.4",
"doctrine/dbal": "^2.2.0",
"php": "^7.2.5|^8.0",
"fideloper/proxy": "^4.4",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "^6.3.1|^7.0.1",
@ -17,9 +16,7 @@
"laravel/sanctum": "^2.13",
"laravel/tinker": "^2.5",
"laravel/ui": "*",
"league/csv": "^9.8",
"mpdf/mpdf": "^8.1",
"prexview/prexview": "^1.1"
"league/csv": "^9.8"
},
"require-dev": {
"facade/ignition": "^2.0",
@ -55,13 +52,13 @@
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php7.4 artisan package:discover --ansi"
"@php artisan package:discover --ansi"
],
"post-root-package-install": [
"@php7.4 -r \"file_exists('.env') || copy('.env.example', '.env');\""
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php7.4 artisan key:generate --ansi"
"@php artisan key:generate --ansi"
]
}
}

2307
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -67,7 +67,7 @@ return [
|
*/
'timezone' => 'America/Montevideo',
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------

View file

@ -1,10 +1,9 @@
<?php
/** @var Factory $factory */
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\User;
use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Factory;
use Illuminate\Support\Str;
/*

View file

@ -19,8 +19,6 @@ class CreateUsersTable extends Migration
$table->string('email')->unique()->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->foreignId('grupo_de_compra_id')->nullable();
$table->boolean('is_admin');
$table->unique(['name', 'is_admin']);
$table->string('password');
$table->rememberToken();
$table->timestamps();

View file

@ -17,7 +17,7 @@ class CreateSubpedidosTable extends Migration
$table->id();
$table->string('nombre');
$table->foreignId('grupo_de_compra_id');
$table->boolean('aprobado')->default(false);
$table->boolean('aprobado')->nullable();
$table->timestamps();
});

View file

@ -0,0 +1,43 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePedidosView extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
DB::statement("CREATE VIEW pedidos AS
SELECT
g.id as grupo_de_compra_id,
g.nombre as grupo_de_compra_nombre,
g.region as grupo_de_compra_region,
pr.id AS producto_id,
pr.nombre as producto_nombre,
pr.precio as producto_precio,
SUM(ps.cantidad) as cantidad_pedida,
pr.precio*SUM(ps.cantidad) as total_por_producto
FROM grupos_de_compra g
JOIN subpedidos s ON (s.grupo_de_compra_id = g.id)
JOIN producto_subpedido ps ON (ps.subpedido_id = s.id)
JOIN productos pr ON (pr.id = ps.producto_id)
GROUP BY g.id, g.nombre, pr.id, pr.nombre;"
);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
DB::statement("DROP VIEW pedidos");
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AgregarColumnaFilaEnPlanillaATablaDeProductos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('productos', function (Blueprint $table) {
$table->integer('fila')->after('id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('productos', function (Blueprint $table) {
$table->dropColumn('fila');
});
}
}

View file

@ -1,26 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
class CallCrearPedidosAprobados extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Artisan::call("view:CrearPedidosAprobadosView");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}

View file

@ -1,34 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class DevolucionesPedido extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('subpedidos', function (Blueprint $table) {
$table->double('devoluciones_total', 10, 2)->default(0);
$table->string('devoluciones_notas')->default("");
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('subpedidos', function (Blueprint $table) {
$table->dropColumn('devoluciones_total');
$table->dropColumn('devoluciones_notas');
});
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class HabilitarDevoluciones extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->boolean('devoluciones_habilitadas')->default(false);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->dropColumn('devoluciones_habilitadas');
});
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AgregarIsComprasAUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_compras')->after('is_admin')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('is_compras');
});
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class NotasProducto extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('producto_subpedido', function (Blueprint $table) {
$table->string('notas')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('producto_subpedido', function (Blueprint $table) {
$table->dropColumn('notas');
});
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ProductoRequiereNotas extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('productos', function (Blueprint $table) {
$table->boolean('requiere_notas')->default(false);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('productos', function (Blueprint $table) {
$table->dropColumn('requiere_notas');
});
}
}

View file

@ -1,33 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CrearCargaDeCanastas extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('carga_de_canastas', function (Blueprint $table) {
$table->id();
$table->string('path');
$table->string('descripcion');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('carga_de_canastas');
}
}

View file

@ -1,27 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Artisan;
class CallAgregarEsBonoAPedidosAprobados extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Artisan::call("command:AgregarEsBonoAPedidosAprobados");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}

View file

@ -1,41 +0,0 @@
<?php
use App\UserRole;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CreateUserRolesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_roles', function (Blueprint $table) {
$table->id();
$table->string('nombre');
$table->timestamps();
});
$tipos = ["barrio", "admin_barrio", "comision"];
foreach ($tipos as $tipo) {
UserRole::create([
"nombre" => $tipo,
]);
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_roles');
}
}

View file

@ -1,43 +0,0 @@
<?php
use App\User;
use App\UserRole;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AgregarRolAUser extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->foreignId('role_id');
});
$barrio = UserRole::where('nombre', 'barrio')->first();
$admin_barrio = UserRole::where('nombre', 'admin_barrio')->first();
$comision = UserRole::where('nombre', 'comision')->first();
User::all()->each(function($user) use ($barrio, $comision, $admin_barrio) {
$user->role_id = $user->is_admin ? $admin_barrio->id :
($user->is_compras ? $comision->id : $barrio->id);
$user->save();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('user', function (Blueprint $table) {
$table->dropForeign('role_id');
});
}
}

View file

@ -1,43 +0,0 @@
<?php
use App\User;
use App\UserRole;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class SimplificarUsers extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['is_admin', 'is_compras']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_admin')->default(false);
$table->boolean('is_compras')->default(false);
});
$admin_barrio = UserRole::where('nombre', 'admin_barrio')->first();
$comision = UserRole::where('nombre', 'comision')->first();
foreach (User::all() as $user) {
$user->is_admin = $user->role_id == $admin_barrio->id;
$user->is_compras = $user->role_id == $comision->id;
$user->save();
}
}
}

View file

@ -1,40 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class SimplificarBarrios extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->dropColumn([
'cantidad_de_nucleos',
'telefono',
'correo',
'referente_finanzas',
]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->double('cantidad_de_nucleos');
$table->string('telefono');
$table->string('correo');
$table->string('referente_finanzas');
});
}
}

View file

@ -1,44 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class SimplificarProductos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('productos', function (Blueprint $table) {
$table->dropColumn([
'presentacion',
'stock',
'imagen_id',
'descripcion',
'apto_veganxs',
'apto_celiacxs',
]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('productos', function (Blueprint $table) {
$table->integer('presentacion')->nullable();
$table->integer('stock')->nullable();
$table->foreignId('imagen_id')->nullable();
$table->string('descripcion')->nullable();
$table->boolean('apto_veganxs')->nullable();
$table->boolean('apto_celiacxs')->nullable();
});
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class SimplificarProductoSubpedido extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('producto_subpedido', function (Blueprint $table) {
$table->dropColumn('total');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('producto_subpedido', function (Blueprint $table) {
$table->double('total');
});
}
}

View file

@ -1,38 +0,0 @@
<?php
use App\Producto;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AgregarEsSolidario extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('productos', function (Blueprint $table) {
$table->boolean('es_solidario')->default(false);
});
foreach (Producto::all() as $producto) {
$producto->es_solidario = $producto->proveedor_id != null;
$producto->save();
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('productos', function (Blueprint $table) {
$table->dropColumn('es_solidario');
});
}
}

View file

@ -1,59 +0,0 @@
<?php
use App\Producto;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class EliminarProveedor extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('productos', function (Blueprint $table) {
$table->dropColumn('proveedor_id');
});
Schema::dropIfExists('proveedores');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::create('proveedores', function (Blueprint $table) {
$table->id();
$table->string('nombre');
$table->string('direccion')->nullable();
$table->string('telefono')->nullable();
$table->string('correo')->nullable();
$table->boolean('economia_solidaria')->nullable();
$table->boolean('nacional')->nullable();
$table->text('detalles_de_pago')->nullable();
$table->text('comentario')->nullable();
$table->timestamps();
});
Schema::table('productos', function (Blueprint $table) {
$table->foreignId('proveedor_id')->nullable();
});
$proveedor_id = DB::table('proveedores')->insertGetId([
['nombre' => 'Proveedor de economía solidaria',
'economia_solidaria' => 1,
'nacional' => 1]
]);
foreach (Producto::all() as $producto) {
$producto->proveedor_id = $producto->es_solidario ? $proveedor_id : null;
$producto->save();
}
}
}

View file

@ -1,35 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class EliminarAdmin extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::dropIfExists('admins');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('nombre');
$table->foreignId('grupo_de_compra_id');
$table->string('email');
$table->string('contrasena');
$table->timestamps();
});
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class HacerFilaNullable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('productos', function (Blueprint $table) {
$table->integer('fila')->nullable()->change();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('productos', function (Blueprint $table) {
$table->integer('fila')->nullable(false)->change();
});
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class QuitarPasswordDeGrupoDeCompra extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->dropColumn('password');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->string('password')->nullable();
});
}
}

View file

@ -1,34 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AgregarSaldosABarrios extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
// Agregar columna 'saldo' a la tabla 'grupos_de_compra'
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->double('saldo', 10, 2)->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
// Remover columna 'saldo' de la tabla 'grupos_de_compra'
Schema::table('grupos_de_compra', function (Blueprint $table) {
$table->dropColumn('saldo');
});
}
}

View file

@ -1,43 +0,0 @@
<?php
use App\TipoPedido;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTipoPedidosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tipo_pedidos', function (Blueprint $table) {
$table->id();
$table->string("nombre");
$table->timestamps();
});
$hogar = TipoPedido::firstOrCreate(['nombre' => 'hogar']);
TipoPedido::firstOrCreate(['nombre' => 'olla']);
Schema::table('subpedidos', function (Blueprint $table) use ($hogar) {
$table->foreignId('tipo_pedido_id')->default($hogar->id);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tipo_pedidos');
Schema::table('subpedidos', function (Blueprint $table) {
$table->dropColumn('tipo_pedido_id');
});
}
}

View file

@ -1,40 +0,0 @@
<?php
use App\GrupoDeCompra;
use App\User;
use App\UserRole;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\Hash;
class UserRoleOllas extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
$ollasRol = UserRole::firstOrCreate(['nombre' => 'ollas']);
$barrios = GrupoDeCompra::all();
foreach ($barrios as $barrio) {
$barrio->users()->firstOrCreate([
'name' => $barrio->nombre . '_ollas',
'password' => Hash::make('123'),
'role_id' => $ollasRol->id
]);
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
$ollasRol = UserRole::where('nombre', 'ollas')->firstOrFail();
User::where('role_id', $ollasRol->id)->delete();
$ollasRol->delete();
}
}

View file

@ -1,32 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CantidadOllasPedidos extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('subpedidos', function (Blueprint $table) {
$table->integer('cantidad_ollas')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('subpedidos', function (Blueprint $table) {
$table->dropColumn('cantidad_ollas');
});
}
}

View file

@ -1,20 +0,0 @@
<?php
use App\Helpers\CanastaHelper;
use Illuminate\Database\Seeder;
class CanastaSeeder extends Seeder
{
const ARCHIVO_DEFAULT = 'csv/productos.csv';
/**
* Run the database seeds.
*
* @return void
* @throws \League\Csv\Exception
*/
public function run()
{
CanastaHelper::cargarCanasta(resource_path(self::ARCHIVO_DEFAULT));
}
}

View file

@ -1,19 +1,10 @@
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder
{
const CHUNK_SIZE = 100;
static function addTimestamps($object) {
$now = DB::raw('CURRENT_TIMESTAMP');
$object['created_at'] = $now;
$object['updated_at'] = $now;
return $object;
}
/**
* Seed the application's database.
*
@ -21,9 +12,7 @@ class DatabaseSeeder extends Seeder
*/
public function run()
{
$this->call(CanastaSeeder::class);
$this->call(GrupoDeCompraSeeder::class);
$this->call(UserSeeder::class);
$this->call(UsuarioOllasSeeder::class);
$this->call(ProductoSeeder::class);
}
}

View file

@ -1,11 +1,7 @@
<?php
use App\Helpers\CsvHelper;
use App\GrupoDeCompra;
use App\User;
use App\UserRole;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use League\Csv\Reader;
class GrupoDeCompraSeeder extends Seeder
{
@ -13,36 +9,41 @@ class GrupoDeCompraSeeder extends Seeder
* Run the database seeds.
*
* @return void
* @throws \League\Csv\Exception
*/
public function run()
{
$registros = CsvHelper::getRecords(resource_path('csv/barrios.csv'), 'No se pudo leer la planilla de barrios.');
$csv = Reader::createFromPath(resource_path('csv/barrios.csv'), 'r');
$csv->setDelimiter("|");
$csv->setEnclosure("'");
$csv->setHeaderOffset(0);
$registros = $csv->getRecords();
$gdcToInsert = [];
$usersToInsert = [];
$roles = UserRole::where('nombre', 'barrio')->orWhere('nombre', 'admin_barrio')->get();
foreach($registros as $key => $registro){
$gdcToInsert[] = DatabaseSeeder::addTimestamps([
$gdcToInsert[] = [
'nombre' => $registro['barrio'],
'region' => $registro['region'],
]);
'telefono' => $registro['telefono'],
'correo' => $registro['correo'],
'referente_finanzas' => $registro['referente']
];
foreach($roles as $role) {
$nombre = $registro['barrio'] . ($role->nombre == 'barrio' ? '' : '_admin');
$usersToInsert[] = DatabaseSeeder::addTimestamps([
'name' => $nombre,
'password' => Hash::make("123"),
'role_id' => $role->id,
'grupo_de_compra_id' => $key,
]);
}
$usersToInsert[] = [
'name' => $registro['barrio'],
'password' => Hash::make($registro['barrio']),
'grupo_de_compra_id' => $key
];
}
foreach (array_chunk($gdcToInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
GrupoDeCompra::insert($chunk);
foreach (array_chunk($gdcToInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
{
DB::table('grupos_de_compra')->insert($chunk);
}
foreach (array_chunk($usersToInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
User::insert($chunk);
foreach (array_chunk($usersToInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
{
DB::table('users')->insert($chunk);
}
}
}

View file

@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Seeder;
use League\Csv\Reader;
use App\Proveedor;
class ProductoSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$csv = Reader::createFromPath(resource_path('csv/productos.csv'), 'r');
$csv->setDelimiter("|");
$csv->setEnclosure("'");
$csv->setHeaderOffset(0);
$registros = $csv->getRecords();
$toInsert = [];
foreach($registros as $registro){
$toInsert[] = [
'categoria' => $registro['categoria'],
'nombre' => $registro['producto'],
'precio' => $registro['precio'],
'proveedor_id' => isset($registro['proveedor']) ? Proveedor::firstOrCreate([
'nombre' => $registro['proveedor']
])->id : null,
'bono' => $registro['categoria'] == 'BONOS Y FINANCIAMIENTO SORORO'
];
}
foreach (array_chunk($toInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
{
DB::table('productos')->insert($chunk);
}
}
}

View file

@ -1,29 +0,0 @@
<?php
use App\User;
use App\UserRole;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$usersToInsert = [];
$usersToInsert[] = DatabaseSeeder::addTimestamps([
'name' => 'comi',
'password' => Hash::make("123"),
'role_id' => UserRole::where('nombre', 'comision')->first()->id,
]);
foreach (array_chunk($usersToInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
User::insert($chunk);
}
}

View file

@ -1,34 +0,0 @@
<?php
use App\GrupoDeCompra;
use App\User;
use App\UserRole;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
class UsuarioOllasSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$barrios = GrupoDeCompra::all();
$usersToInsert = [];
$ollas_id = UserRole::where('nombre', 'ollas')->first()->id;
foreach ($barrios as $barrio) {
$usersToInsert[] = DatabaseSeeder::addTimestamps([
'name' => $barrio->nombre . '_ollas',
'password' => Hash::make('123'),
'role_id' => $ollas_id,
'grupo_de_compra_id' => $barrio->id,
]);
}
foreach (array_chunk($usersToInsert,DatabaseSeeder::CHUNK_SIZE) as $chunk)
User::insert($chunk);
}
}

View file

@ -1,2 +0,0 @@
#!/usr/bin/bash
docker-compose up -d && docker-compose exec app npm run watch

View file

@ -1,15 +1,14 @@
version: '3.2'
version: "3.7"
services:
app:
build:
args:
user: www
uid: ${USERID}
uid: 1000
context: ./
dockerfile: Dockerfile
image: laravel-image
container_name: pedi2-app
container_name: laravel-app
restart: unless-stopped
working_dir: /var/www/
volumes:
@ -20,8 +19,10 @@ services:
db:
image: mysql:5.7
container_name: pedi2-db
container_name: laravel-db
restart: unless-stopped
ports:
- "3306:3306"
environment:
MYSQL_DATABASE: ${DB_DATABASE}
MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
@ -35,15 +36,13 @@ services:
- dbdata:/var/lib/mysql
networks:
- app-network
ports:
- ${DB_PORT_EXPOSED}:3306
nginx:
image: nginx:alpine
container_name: pedi2-nginx
container_name: laravel-nginx
restart: unless-stopped
ports:
- ${NGINX_PORT}:80
- 8000:80
volumes:
- ./:/var/www
- ./nginx/conf.d/:/etc/nginx/conf.d/
@ -57,4 +56,4 @@ networks:
#Volumes
volumes:
dbdata:
driver: local
driver: local

26705
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -10,22 +10,17 @@
"production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --config=node_modules/laravel-mix/setup/webpack.config.js"
},
"devDependencies": {
"axios": "^0.19.2",
"cross-env": "^7.0.3",
"axios": "^0.19",
"bootstrap": "^4.0.0",
"cross-env": "^7.0",
"jquery": "^3.2",
"laravel-mix": "^5.0.1",
"lodash": "^4.17.19",
"popper.js": "^1.12",
"resolve-url-loader": "^2.3.1",
"sass": "^1.20.1",
"sass-loader": "^8.0.0",
"vue": "^2.5.17",
"vue-template-compiler": "^2.6.10",
"webpack": "^4.47.0",
"webpack-cli": "^3.3.12"
},
"dependencies": {
"animate.css": "^4.1.1",
"bulma": "^0.9.4",
"bulma-switch": "^2.0.4",
"bulma-toast": "^2.4.1",
"vuex": "^3.6.2"
"vue-template-compiler": "^2.6.10"
}
}

7
public/css/animate.min.css vendored Normal file

File diff suppressed because one or more lines are too long

53
public/css/app.css vendored Normal file
View file

@ -0,0 +1,53 @@
p.navbar-item:empty {
display: none;
}
.breadcrumb a {
color: #cc0f35;
}
.help {
font-size: 1rem;
}
table.table td {
vertical-align: middle;
}
nav.breadcrumb.is-fixed-top {
left: 0;
position: fixed;
right: 0;
z-index: 30;
top: 3.25rem;
height: 3.25rem;
}
main.has-top-padding {
padding-top: 4.5rem !important;
}
.has-text-centered {
text-align: center;
margin: 0 1em;
}
.is-fixed-top {
position: fixed;
z-index: 30;
}
.chismosa-container {
top: 6.5rem;
max-height: 21rem;
overflow-y: scroll;
overflow-x: hidden;
width: 100%;
position: fixed;
z-index: 15;
}
main.chisma-abierta {
padding-top: 25.5rem !important;
}

10
public/css/productos.css vendored Normal file
View file

@ -0,0 +1,10 @@
figure.image.icono {
float: right;
margin: 4px;
}
.is-thin-centered {
width: 50%;
margin-left: auto;
margin-right: auto;
}

109
public/js/app.js vendored Normal file
View file

@ -0,0 +1,109 @@
window.Event = new Vue();
Vue.component('nav-bar', {
template: `
<nav class="navbar is-danger is-fixed-top" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<a class="navbar-item" href="https://mps.org.uy">
<img src="/assets/logoMPS.png" height="28">
</a>
<p style="margin:0 auto" class="navbar-item"><slot name="subpedido"></slot></p>
<a class="navbar-item" href="#chismosa" @click.capture="toggleChismosa">
<img style="padding:0 0.3em;" src="/assets/chismosa.png" height="28">
<p style="margin:0 auto; color:white">$ <span v-text="subpedido == null ? 0 : subpedido.total"></span></p>
</a>
<a role="button" class="navbar-burger" :class="{'is-active':isActive}" aria-label="menu" aria-expanded="false" data-target="navbarBasicExample" @click="toggleState">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div id="navbarBasicExample" class="navbar-menu" :class="{'is-active':isActive}">
<div class="navbar-start has-text-right-mobile">
<!-- Styles nombre del barrio-->
<p class="navbar-item"><slot name="gdc"></slot></p>
<a class="navbar-item"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
Cerrar sesión
</a>
<slot name="logout-form"></slot>
</div>
</div>
</nav>`,
data() {
return {
isActive: false,
subpedido: null
}
},
methods: {
toggleState() {
this.isActive = !this.isActive;
},
actualizarSubpedido(){
axios.get("/api/subpedidos/" + this.subpedido.id)
.then(response => {
this.subpedido = response.data.data;
});
},
toggleChismosa(){
Event.$emit("toggle-chismosa");
}
}, mounted() {
axios.get("/subpedidos/obtener_sesion").then(response => {
this.subpedido = response.data.subpedido;
this.actualizarSubpedido()
});
//Emitir un evento subpedido-actualizado al agregar o eliminar un producto del subpedido para que el total de la chismosa se muestre correctamente
Event.$on('sync-subpedido', (cantidad, id) => {
axios.post("/api/subpedidos/"+this.subpedido.id+"/sync", {
cantidad: cantidad,
producto_id: id
}).then((response) => {
this.subpedido = response.data.data;
Event.$emit('sync-chismosa',this.subpedido);
bulmaToast.toast({
message: 'Pedido actualizado exitosamente',
duration: 1000,
type: 'is-danger',
position: 'bottom-center',
animate: { in: 'fadeIn', out: 'fadeOut' }
});
});
});
}
});
Vue.component('nav-migas', {
data() {
return {
migas: []
}
},
computed: {
visible: function() {
return this.migas.length > 0
}
},
mounted() {
Event.$on('migas-setear-como-inicio', (miga) => {
this.migas = [];
this.migas.push(miga);
});
Event.$on('migas-agregar', (miga) => {
this.migas.push(miga);
});
Event.$on('migas-reset', () => {
this.migas = [];
});
Event.$on('migas-pop', () => {
this.migas.pop();
});
}
});
new Vue({
el: '#app'
});

Some files were not shown because too many files have changed in this diff Show more