Merge branch 'master' into matias

This commit is contained in:
2021-07-14 01:25:23 -04:00
15 changed files with 465 additions and 64 deletions

23
backend/Dockerfile.prod Normal file
View File

@@ -0,0 +1,23 @@
FROM alpine:3
RUN apk update
RUN apk --no-cache add php8 php8-openssl php8-pdo php8-pdo_mysql \
php8-pdo_sqlite php8-pdo_pgsql php8-mbstring \
php8-phar php8-curl php8-dom php8-xml \
php8-xmlwriter php8-tokenizer \
zip unzip curl sqlite
RUN ln -s /usr/bin/php8 /usr/bin/php
RUN curl -s https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin/ --filename=composer
WORKDIR /lumen
COPY composer.json .
COPY composer.lock .
RUN composer install --no-ansi --no-dev --no-interaction --no-plugins \
--no-progress --no-scripts --optimize-autoloader
COPY . /lumen
ENTRYPOINT ["php", "-S", "0.0.0.0:8080", "-t", "public"]

View File

@@ -45,7 +45,7 @@ class UsuariosController extends Controller {
*/ */
public function get(Request $request, $id) { public function get(Request $request, $id) {
if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id); if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id);
$usuario = Usuario::findOrFail($id); $usuario = Usuario::findOrFail(urldecode($id));
return response()->json($usuario); return response()->json($usuario);
} }
@@ -107,7 +107,7 @@ class UsuariosController extends Controller {
'roles.*' => ['sometimes', Rule::in(['admin', 'mesero', 'recaudador', 'productor'])], 'roles.*' => ['sometimes', Rule::in(['admin', 'mesero', 'recaudador', 'productor'])],
]); ]);
$usuario = Usuario::findOrFail($id); $usuario = Usuario::findOrFail(urldecode($id));
$metadata = []; $metadata = [];
if ($request->input('roles')) $metadata['roles'] = $request->input('roles'); if ($request->input('roles')) $metadata['roles'] = $request->input('roles');
@@ -140,7 +140,7 @@ class UsuariosController extends Controller {
public function delete(Request $request, $id) { public function delete(Request $request, $id) {
if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id); if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id);
$usuario = Usuario::findOrFail($id); $usuario = Usuario::findOrFail(urldecode($id));
$auth0 = app(Auth0Service::class); $auth0 = app(Auth0Service::class);
$auth0Response = $auth0->deleteUser($usuario->auth0_id); $auth0Response = $auth0->deleteUser($usuario->auth0_id);
@@ -157,6 +157,16 @@ class UsuariosController extends Controller {
return response()->json([], 204); return response()->json([], 204);
} }
/**
* Obtiene los usuarios de un restaurant
*/
public function getRestaurantes(Request $request, $id) {
if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id);
$usuario = Usuario::findOrFail(urldecode($id));
return response()->json($usuario->restaurantes);
}
/** /**
* Agrega usuario a un restaurant * Agrega usuario a un restaurant
*/ */
@@ -164,7 +174,7 @@ class UsuariosController extends Controller {
if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id); if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id);
app(UuidService::class)->validOrFail($restaurant); app(UuidService::class)->validOrFail($restaurant);
$usuario = Usuario::findOrFail($id); $usuario = Usuario::findOrFail(urldecode($id));
$restaurant = Restaurante::findOrFail($restaurant); $restaurant = Restaurante::findOrFail($restaurant);
if ($usuario->restaurantes->contains($restaurant)) { if ($usuario->restaurantes->contains($restaurant)) {
@@ -186,7 +196,7 @@ class UsuariosController extends Controller {
if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id); if (!str_starts_with($id, 'auth0')) app(UuidService::class)->validOrFail($id);
app(UuidService::class)->validOrFail($restaurant); app(UuidService::class)->validOrFail($restaurant);
$usuario = Usuario::findOrFail($id); $usuario = Usuario::findOrFail(urldecode($id));
$restaurant = Restaurante::findOrFail($restaurant); $restaurant = Restaurante::findOrFail($restaurant);
if (!$usuario->restaurantes->contains($restaurant)) { if (!$usuario->restaurantes->contains($restaurant)) {

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware {
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json([], 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}

View File

@@ -79,6 +79,10 @@ $app->routeMiddleware([
'log_endpoint' => App\Http\Middleware\LogEndpointHitMiddleware::class 'log_endpoint' => App\Http\Middleware\LogEndpointHitMiddleware::class
]); ]);
$app->middleware([
App\Http\Middleware\CorsMiddleware::class,
]);
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Register Service Providers | Register Service Providers

View File

@@ -13,6 +13,7 @@ $router->group(['prefix' => 'api/v1', 'middleware' => ['auth', 'log_endpoint']],
$router->post( '/', ['as' => 'users.create', 'uses' => 'UsuariosController@create']); $router->post( '/', ['as' => 'users.create', 'uses' => 'UsuariosController@create']);
$router->put( '/{id}', ['as' => 'users.update', 'uses' => 'UsuariosController@update']); $router->put( '/{id}', ['as' => 'users.update', 'uses' => 'UsuariosController@update']);
$router->delete('/{id}', ['as' => 'users.delete', 'uses' => 'UsuariosController@delete']); $router->delete('/{id}', ['as' => 'users.delete', 'uses' => 'UsuariosController@delete']);
$router->get( '/{id}/restaurantes/', ['as' => 'users.get_restaurantes', 'uses' => 'UsuariosController@getRestaurantes']);
$router->put( '/{id}/restaurantes/{restaurant}', ['as' => 'users.add_to_restaurant', 'uses' => 'UsuariosController@addToRestaurant']); $router->put( '/{id}/restaurantes/{restaurant}', ['as' => 'users.add_to_restaurant', 'uses' => 'UsuariosController@addToRestaurant']);
$router->delete('/{id}/restaurantes/{restaurant}', ['as' => 'users.remove_from_restaurant', 'uses' => 'UsuariosController@removeFromRestaurant']); $router->delete('/{id}/restaurantes/{restaurant}', ['as' => 'users.remove_from_restaurant', 'uses' => 'UsuariosController@removeFromRestaurant']);
}); });

View File

@@ -33,7 +33,8 @@ drop table if exists medios_pago cascade;
drop table if exists cajas cascade; drop table if exists cajas cascade;
drop table if exists estados_produccion cascade; drop table if exists estados_produccion cascade;
create table restaurantes ( create table restaurantes
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -41,7 +42,8 @@ create table restaurantes (
deleted_at timestamptz deleted_at timestamptz
); );
create table categorias ( create table categorias
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
restaurante_id uuid references restaurantes, restaurante_id uuid references restaurantes,
@@ -50,7 +52,8 @@ create table categorias (
deleted_at timestamptz deleted_at timestamptz
); );
create table zonas_produccion ( create table zonas_produccion
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
restaurante_id uuid references restaurantes, restaurante_id uuid references restaurantes,
@@ -59,7 +62,8 @@ create table zonas_produccion (
deleted_at timestamptz deleted_at timestamptz
); );
create table usuarios ( create table usuarios
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
auth0_id text not null, auth0_id text not null,
nombre text not null, nombre text not null,
@@ -68,7 +72,8 @@ create table usuarios (
deleted_at timestamptz deleted_at timestamptz
); );
create table usuarios_restaurantes ( create table usuarios_restaurantes
(
usuario_id uuid references usuarios, usuario_id uuid references usuarios,
restaurante_id uuid references restaurantes, restaurante_id uuid references restaurantes,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -77,7 +82,8 @@ create table usuarios_restaurantes (
primary key (usuario_id, restaurante_id) primary key (usuario_id, restaurante_id)
); );
create table productores ( create table productores
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
usuario_id uuid references usuarios, usuario_id uuid references usuarios,
zona_produccion_id uuid references zonas_produccion, zona_produccion_id uuid references zonas_produccion,
@@ -86,7 +92,8 @@ create table productores (
deleted_at timestamptz deleted_at timestamptz
); );
create table recaudadores ( create table recaudadores
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
usuario_id uuid references usuarios, usuario_id uuid references usuarios,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -94,7 +101,8 @@ create table recaudadores (
deleted_at timestamptz deleted_at timestamptz
); );
create table meseros ( create table meseros
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
usuario_id uuid references usuarios, usuario_id uuid references usuarios,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -102,7 +110,8 @@ create table meseros (
deleted_at timestamptz deleted_at timestamptz
); );
create table administradores ( create table administradores
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
usuario_id uuid references usuarios, usuario_id uuid references usuarios,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -110,7 +119,8 @@ create table administradores (
deleted_at timestamptz deleted_at timestamptz
); );
create table ingredientes ( create table ingredientes
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
medida text not null, medida text not null,
@@ -120,7 +130,8 @@ create table ingredientes (
deleted_at timestamptz deleted_at timestamptz
); );
create table productos ( create table productos
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
precio_venta bigint not null, precio_venta bigint not null,
@@ -132,7 +143,8 @@ create table productos (
deleted_at timestamptz deleted_at timestamptz
); );
create table recetas ( create table recetas
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
producto_id uuid references productos, producto_id uuid references productos,
ingrediente_id uuid references ingredientes, ingrediente_id uuid references ingredientes,
@@ -143,7 +155,8 @@ create table recetas (
primary key (producto_id, ingrediente_id) primary key (producto_id, ingrediente_id)
); );
create table proveedores ( create table proveedores
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
rut text not null, rut text not null,
nombre text not null, nombre text not null,
@@ -156,7 +169,8 @@ create table proveedores (
deleted_at timestamptz deleted_at timestamptz
); );
create table compras ( create table compras
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
fecha_compra date not null, fecha_compra date not null,
en_arqueo bool not null default true, en_arqueo bool not null default true,
@@ -167,7 +181,8 @@ create table compras (
deleted_at timestamptz deleted_at timestamptz
); );
create table facturas ( create table facturas
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
numero text not null, numero text not null,
monto_bruto bigint not null, monto_bruto bigint not null,
@@ -182,7 +197,8 @@ create table facturas (
deleted_at timestamptz deleted_at timestamptz
); );
create table compra_ingredientes ( create table compra_ingredientes
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
unidades numeric not null, unidades numeric not null,
monto_unitario_bruto bigint not null, monto_unitario_bruto bigint not null,
@@ -194,7 +210,8 @@ create table compra_ingredientes (
deleted_at timestamptz deleted_at timestamptz
); );
create table sectores ( create table sectores
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
restaurante_id uuid references restaurantes, restaurante_id uuid references restaurantes,
@@ -203,7 +220,8 @@ create table sectores (
deleted_at timestamptz deleted_at timestamptz
); );
create table tipos_canal ( create table tipos_canal
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -211,7 +229,8 @@ create table tipos_canal (
deleted_at timestamptz deleted_at timestamptz
); );
create table canales_venta ( create table canales_venta
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
sector_id uuid references sectores, sector_id uuid references sectores,
@@ -222,7 +241,8 @@ create table canales_venta (
deleted_at timestamptz deleted_at timestamptz
); );
create table medios_pago ( create table medios_pago
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -230,7 +250,8 @@ create table medios_pago (
deleted_at timestamptz deleted_at timestamptz
); );
create table cajas ( create table cajas
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
fondo bigint not null, fondo bigint not null,
apertura timestamptz not null, apertura timestamptz not null,
@@ -240,7 +261,8 @@ create table cajas (
deleted_at timestamptz deleted_at timestamptz
); );
create table efectivos ( create table efectivos
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
veinte_mil bigint not null, veinte_mil bigint not null,
diez_mil bigint not null, diez_mil bigint not null,
@@ -257,7 +279,8 @@ create table efectivos (
deleted_at timestamptz deleted_at timestamptz
); );
create table ventas ( create table ventas
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
tiempo_venta timestamptz, tiempo_venta timestamptz,
mesero_id uuid references meseros, mesero_id uuid references meseros,
@@ -270,7 +293,8 @@ create table ventas (
deleted_at timestamptz deleted_at timestamptz
); );
create table boletas_electronicas ( create table boletas_electronicas
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
numero_boleta text not null, numero_boleta text not null,
venta_id uuid references ventas, venta_id uuid references ventas,
@@ -280,7 +304,8 @@ create table boletas_electronicas (
deleted_at timestamptz deleted_at timestamptz
); );
create table boletas_exentas ( create table boletas_exentas
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
venta_id uuid references ventas, venta_id uuid references ventas,
restaurante_id uuid references restaurantes, restaurante_id uuid references restaurantes,
@@ -289,7 +314,8 @@ create table boletas_exentas (
deleted_at timestamptz deleted_at timestamptz
); );
create table estados_produccion ( create table estados_produccion
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
nombre text not null, nombre text not null,
created_at timestamptz not null default current_timestamp, created_at timestamptz not null default current_timestamp,
@@ -297,7 +323,8 @@ create table estados_produccion (
deleted_at timestamptz deleted_at timestamptz
); );
create table venta_productos ( create table venta_productos
(
id uuid primary key default gen_random_uuid(), id uuid primary key default gen_random_uuid(),
tiempo_entrada timestamptz not null, tiempo_entrada timestamptz not null,
tiempo_salida timestamptz null, tiempo_salida timestamptz null,
@@ -309,6 +336,28 @@ create table venta_productos (
deleted_at timestamptz deleted_at timestamptz
); );
create table bodega_egresos
(
unidades numeric not null,
fecha timestamptz not null,
ingrediente_id uuid references ingredientes,
restaurante_id uuid references restaurantes,
created_at timestamptz not null default current_timestamp,
updated_at timestamptz not null default current_timestamp,
deleted_at timestamptz
);
create table bodega_ingresos
(
unidades numeric not null,
fecha timestamptz not null,
ingrediente_id uuid references ingredientes,
restaurante_id uuid references restaurantes,
created_at timestamptz not null default current_timestamp,
updated_at timestamptz not null default current_timestamp,
deleted_at timestamptz
);
------------------------------------ ------------------------------------
--- Indexes para todas las referencias --- Indexes para todas las referencias
------------------------------------ ------------------------------------
@@ -343,31 +392,114 @@ create index boletas_exentas_restaurante_id on boletas_exentas (restaurante_id);
create index venta_productos_venta_id on venta_productos (venta_id); create index venta_productos_venta_id on venta_productos (venta_id);
create index venta_productos_producto_id on venta_productos (producto_id); create index venta_productos_producto_id on venta_productos (producto_id);
create index venta_productos_estado_id on venta_productos (estado_id); create index venta_productos_estado_id on venta_productos (estado_id);
create index bodega_egresos_ingrediente_id on bodega_egresos (ingrediente_id);
create index bodega_egresos_restaurante_id on bodega_egresos (restaurante_id);
create index bodega_ingresos_ingrediente_id on bodega_ingresos (ingrediente_id);
create index bodega_ingresos_restaurante_id on bodega_ingresos (restaurante_id);
------------------------------------
--- Triggers para poblar la bodega
------------------------------------
create or replace function bodega_egresos_trigger_insert_procedure() returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_egresos (ingrediente_id, unidades, fecha, restaurante_id)
select recetas.ingrediente_id as ingrediente_id,
recetas.unidades as unidades,
date(venta_productos.tiempo_entrada) as fecha,
ventas.restaurante_id as restaurante_id
from ventas
join venta_productos on ventas.id = venta_productos.venta_id
join productos on venta_productos.producto_id = productos.id
join recetas on productos.id = recetas.producto_id
where venta_productos.id = NEW.id;
RETURN null;
END;
$$;
create or replace function bodega_egresos_trigger_delete_procedure()
returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_egresos (ingrediente_id, unidades, fecha, restaurante_id)
select recetas.ingrediente_id as ingrediente_id,
recetas.unidades * -1 as unidades,
date(venta_productos.tiempo_entrada) as fecha,
ventas.restaurante_id as restaurante_id
from ventas
join venta_productos on ventas.id = venta_productos.venta_id
join productos on venta_productos.producto_id = productos.id
join recetas on productos.id = recetas.producto_id
where venta_productos.id = OLD.id;
RETURN null;
END;
$$;
create or replace function bodega_ingresos_trigger_insert_procedure()
returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_ingresos (ingrediente_id, unidades, fecha, restaurante_id)
select compra_ingredientes.ingrediente_id as ingrediente_id,
compra_ingredientes.unidades as unidades,
compras.fecha_compra as fecha,
compras.restaurante_id as restaurante_id
from compras
join compra_ingredientes on compras.id = compra_ingredientes.compra_id
where compra_ingredientes.id = NEW.id;
RETURN null;
END;
$$;
create or replace function bodega_ingresos_trigger_delete_procedure()
returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_ingresos (ingrediente_id, unidades, fecha, restaurante_id)
select compra_ingredientes.ingrediente_id as ingrediente_id,
compra_ingredientes.unidades * -1 as unidades,
compras.fecha_compra as fecha,
compras.restaurante_id as restaurante_id
from compras
join compra_ingredientes on compras.id = compra_ingredientes.compra_id
where compra_ingredientes.id = OLD.id;
RETURN null;
END;
$$;
create trigger bodega_egresos_insert_trigger
after insert
on venta_productos
for each row
execute procedure bodega_egresos_trigger_insert_procedure();
create trigger bodega_egresos_delete_trigger
after update of deleted_at
on venta_productos
for each row
execute procedure bodega_egresos_trigger_delete_procedure();
create trigger bodega_ingresos_insert_trigger
after insert
on compra_ingredientes
for each row
execute procedure bodega_ingresos_trigger_insert_procedure();
create trigger bodega_ingresos_delete_trigger
after update of deleted_at
on compra_ingredientes
for each row
execute procedure bodega_ingresos_trigger_delete_procedure();
------------------------------------ ------------------------------------
--- Views para crear la bodega --- Views para crear la bodega
------------------------------------ ------------------------------------
--- View para obtener la lista de egresos de bodega
create view bodega_egresos as
select recetas.ingrediente_id as ingrediente_id,
recetas.unidades as unidades,
date(venta_productos.tiempo_entrada) as fecha,
ventas.restaurante_id as restaurante_id
from ventas
join venta_productos on ventas.id = venta_productos.venta_id
join productos on venta_productos.producto_id = productos.id
join recetas on productos.id = recetas.producto_id;
--- View para obtener la lista de ingresos a bodega
create view bodega_ingresos as
select compra_ingredientes.ingrediente_id as ingrediente_id,
compra_ingredientes.unidades as unidades,
compras.fecha_compra as fecha,
compras.restaurante_id as restaurante_id
from compras
join compra_ingredientes on compras.id = compra_ingredientes.compra_id;
--- View que une el estado de bodega en una sola tabla --- View que une el estado de bodega en una sola tabla
create view bodega_movimientos as create view bodega_movimientos as
select ingrediente_id, unidades * -1 as unidades, fecha, restaurante_id select ingrediente_id, unidades * -1 as unidades, fecha, restaurante_id

Binary file not shown.

View File

@@ -0,0 +1 @@
update usuarios set auth0_id = 'auth0|606df4dea32e970069755bd8' where auth0_id = 'auth0|6083af726b4de900695cb232';

View File

@@ -0,0 +1,144 @@
start transaction;
drop view bodega_actual cascade;
drop view bodega_movimientos cascade;
drop view bodega_egresos cascade;
drop view bodega_ingresos cascade;
create table bodega_egresos
(
unidades numeric not null,
fecha timestamptz not null,
ingrediente_id uuid references ingredientes,
restaurante_id uuid references restaurantes,
created_at timestamptz not null default current_timestamp,
updated_at timestamptz not null default current_timestamp,
deleted_at timestamptz
);
create table bodega_ingresos
(
unidades numeric not null,
fecha timestamptz not null,
ingrediente_id uuid references ingredientes,
restaurante_id uuid references restaurantes,
created_at timestamptz not null default current_timestamp,
updated_at timestamptz not null default current_timestamp,
deleted_at timestamptz
);
create index bodega_egresos_ingrediente_id on bodega_egresos (ingrediente_id);
create index bodega_egresos_restaurante_id on bodega_egresos (restaurante_id);
create index bodega_ingresos_ingrediente_id on bodega_ingresos (ingrediente_id);
create index bodega_ingresos_restaurante_id on bodega_ingresos (restaurante_id);
create or replace function bodega_egresos_trigger_insert_procedure() returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_egresos (ingrediente_id, unidades, fecha, restaurante_id)
select recetas.ingrediente_id as ingrediente_id,
recetas.unidades as unidades,
date(venta_productos.tiempo_entrada) as fecha,
ventas.restaurante_id as restaurante_id
from ventas
join venta_productos on ventas.id = venta_productos.venta_id
join productos on venta_productos.producto_id = productos.id
join recetas on productos.id = recetas.producto_id
where venta_productos.id = NEW.id;
RETURN null;
END;
$$;
create or replace function bodega_egresos_trigger_delete_procedure()
returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_egresos (ingrediente_id, unidades, fecha, restaurante_id)
select recetas.ingrediente_id as ingrediente_id,
recetas.unidades * -1 as unidades,
date(venta_productos.tiempo_entrada) as fecha,
ventas.restaurante_id as restaurante_id
from ventas
join venta_productos on ventas.id = venta_productos.venta_id
join productos on venta_productos.producto_id = productos.id
join recetas on productos.id = recetas.producto_id
where venta_productos.id = OLD.id;
RETURN null;
END;
$$;
create or replace function bodega_ingresos_trigger_insert_procedure()
returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_ingresos (ingrediente_id, unidades, fecha, restaurante_id)
select compra_ingredientes.ingrediente_id as ingrediente_id,
compra_ingredientes.unidades as unidades,
compras.fecha_compra as fecha,
compras.restaurante_id as restaurante_id
from compras
join compra_ingredientes on compras.id = compra_ingredientes.compra_id
where compra_ingredientes.id = NEW.id;
RETURN null;
END;
$$;
create or replace function bodega_ingresos_trigger_delete_procedure()
returns trigger
language PLPGSQL as
$$
BEGIN
insert into bodega_ingresos (ingrediente_id, unidades, fecha, restaurante_id)
select compra_ingredientes.ingrediente_id as ingrediente_id,
compra_ingredientes.unidades * -1 as unidades,
compras.fecha_compra as fecha,
compras.restaurante_id as restaurante_id
from compras
join compra_ingredientes on compras.id = compra_ingredientes.compra_id
where compra_ingredientes.id = OLD.id;
RETURN null;
END;
$$;
create trigger bodega_egresos_insert_trigger
after insert
on venta_productos
for each row
execute procedure bodega_egresos_trigger_insert_procedure();
create trigger bodega_egresos_delete_trigger
after update of deleted_at
on venta_productos
for each row
execute procedure bodega_egresos_trigger_delete_procedure();
create trigger bodega_ingresos_insert_trigger
after insert
on compra_ingredientes
for each row
execute procedure bodega_ingresos_trigger_insert_procedure();
create trigger bodega_ingresos_delete_trigger
after update of deleted_at
on compra_ingredientes
for each row
execute procedure bodega_ingresos_trigger_delete_procedure();
--- View que une el estado de bodega en una sola tabla
create view bodega_movimientos as
select ingrediente_id, unidades * -1 as unidades, fecha, restaurante_id
from bodega_egresos
union all
select ingrediente_id, unidades, fecha, restaurante_id
from bodega_ingresos;
--- View que muestra el estado actual de la bodega por cada ingrediente
create view bodega_actual as
select ingrediente_id as ingrediente_id, sum(unidades) as stock, restaurante_id as restaurante_id
from bodega_movimientos
group by bodega_movimientos.ingrediente_id, bodega_movimientos.restaurante_id;
commit;

39
docker-compose.prod.yml Normal file
View File

@@ -0,0 +1,39 @@
version: "3.9"
services:
backend:
build:
context: ./backend
dockerfile: ./Dockerfile.prod
ports:
- 8080:8080
frontend:
build:
context: ./frontend
dockerfile: ./Dockerfile.prod
ports:
- 4200:80
database:
image: postgres:13
restart: unless-stopped
environment:
POSTGRES_PASSWORD: admin
PGDATA: "/var/lib/postgresql/data/pgdata"
volumes:
- ./database/init:/docker-entrypoint-initdb.d
- database:/var/lib/postgresql/data
ports:
- 5400:5432
cache:
image: redis
restart: unless-stopped
volumes:
- cache:/data
volumes:
database:
cache:

View File

@@ -24,17 +24,16 @@ services:
build: build:
context: ./frontend context: ./frontend
dockerfile: ./Dockerfile dockerfile: ./Dockerfile
ports:
- 4200:4200
volumes: volumes:
- ./frontend/src:/angular/src - ./frontend/src:/angular/src
- ./frontend/karma.conf.js:/angular/karma.conf.js
- ./frontend/angular.json:/angular/angular.json - ./frontend/angular.json:/angular/angular.json
- ./frontend/karma.conf.js:/angular/karma.conf.js
- ./frontend/README.md:/angular/README.md
- ./frontend/tsconfig.app.json:/angular/tsconfig.app.json - ./frontend/tsconfig.app.json:/angular/tsconfig.app.json
- ./frontend/tsconfig.json:/angular/tsconfig.json - ./frontend/tsconfig.json:/angular/tsconfig.json
- ./frontend/tsconfig.spec.json:/angular/tsconfig.spec.json - ./frontend/tsconfig.spec.json:/angular/tsconfig.spec.json
- ./frontend/.editorconfig:/angular/.editorconfig ports:
- ./frontend/.browserslistrc:/angular/.browserslistrc - 4200:4200
database: database:
image: postgres:13 image: postgres:13
@@ -45,6 +44,8 @@ services:
volumes: volumes:
- ./database/init:/docker-entrypoint-initdb.d - ./database/init:/docker-entrypoint-initdb.d
- database:/var/lib/postgresql/data - database:/var/lib/postgresql/data
ports:
- 5400:5432
cache: cache:
image: redis image: redis

View File

@@ -1,11 +1,8 @@
FROM node:14-alpine FROM node:alpine as build
WORKDIR /angular WORKDIR /angular
COPY package.json package-lock.json /angular/
COPY package.json /angular
RUN npm install RUN npm install
COPY . /angular COPY . /angular
ENTRYPOINT ["/angular/node_modules/@angular/cli/bin/ng", "serve", "--host", "0.0.0.0"] ENTRYPOINT ["npm", "run", "start"]

10
frontend/Dockerfile.prod Normal file
View File

@@ -0,0 +1,10 @@
FROM node:alpine as build
WORKDIR /angular
COPY package.json package-lock.json /angular/
RUN npm install
COPY . /angular
RUN npm run build --prod
FROM nginx:stable-alpine
COPY --from=build /angular/dist/frontend /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf

8
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,8 @@
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
}

View File

@@ -3,7 +3,7 @@
"version": "0.0.0", "version": "0.0.0",
"scripts": { "scripts": {
"ng": "ng", "ng": "ng",
"start": "ng serve", "start": "ng serve --host 0.0.0.0",
"build": "ng build", "build": "ng build",
"watch": "ng build --watch --configuration development", "watch": "ng build --watch --configuration development",
"test": "ng test" "test": "ng test"