Compare commits

...

14 commits

19 changed files with 544 additions and 249 deletions

View file

@ -16,7 +16,7 @@ class Barrio extends Model
* @var array<int, string> * @var array<int, string>
*/ */
protected $fillable = [ protected $fillable = [
'name', 'nombre',
]; ];
/** /**
@ -36,37 +36,21 @@ class Barrio extends Model
} }
function crearPedido(string $nombre) : Pedido { function crearPedido(string $nombre) : Pedido {
return $this->pedidos()->create(['name' => $name]); return $this->pedidos()->create(['nombre' => $name]);
}
function pedidosConfirmados() {
return $this->pedidos()->where('confirmed',true);
} }
function totalARecaudar() : float { function totalARecaudar() : float {
return $this->calcularTotalConfirmados(); return $this->calcularTotalPagados();
} }
function totalNoBarriales() : float { private function calcularTotalPagados(Closure $closure = null) : float {
return $this->calcularTotalConfirmados( if (!$closure)
fn($p) => $p->total($p->productosNoBarriales()) $closure = fn($p) => $p->totalChismosa();
); return $this->pedidosPagados()->sum($closure);
}
function totalParaTransporte() : float {
return $this->calcularTotalConfirmados(
fn($p) => $p->total($p->productosConTransporte())
);
} }
function totalATransferir() : float { function totalATransferir() : float {
return $this->totalNoBarriales() + TransporteUtils::total($this->totalParaTransporte()); return $this->calcularTotalPagados($p->totalATransferir());
}
private function calcularTotalConfirmados(Closure $closure = null) : float {
if (!$closure)
$closure = fn($p) => $p->totalChismosa();
return $this->pedidosConfirmados()->sum($closure);
} }
/** /**
@ -78,7 +62,7 @@ class Barrio extends Model
} }
function exportarPedidoACsv() { function exportarPedidoACsv() {
if ($this->pedidosConfirmados()->exists()) { if ($this->pedidosPagados()->exists()) {
$columnaProductos = $this->armarColumnasPedido(); $columnaProductos = $this->armarColumnasPedido();
try { try {
@ -112,8 +96,7 @@ class Barrio extends Model
} }
} }
private function cantidadPedida($productoId) private function cantidadPedida($productoId) {
{
$pedidos = $this->pedidos() $pedidos = $this->pedidos()
->whereHas('productos', ->whereHas('productos',
function ($query) use ($productoId) { function ($query) use ($productoId) {
@ -122,7 +105,7 @@ class Barrio extends Model
return $pedidos->sum(function ($pedido) use ($productoId) { return $pedidos->sum(function ($pedido) use ($productoId) {
return $pedido->productos return $pedido->productos
->where('id', $productoId) ->find($productoId)
->first()->pivot->cantidad ?? 0;}); ->pivot->cantidad ?? 0;});
} }
} }

View file

@ -13,7 +13,7 @@ class Categoria extends Model
* @var array<int, string> * @var array<int, string>
*/ */
protected $fillable = [ protected $fillable = [
'name', 'nombre',
]; ];
/** /**

View file

@ -16,7 +16,7 @@ class Pedido extends Model
* @var array<int, string> * @var array<int, string>
*/ */
protected $fillable = [ protected $fillable = [
'name', 'confirmed' 'nombre', 'pagado', 'terminado'
]; ];
/** /**
@ -26,6 +26,18 @@ class Pedido extends Model
return $this->belongsTo(Barrio::class); return $this->belongsTo(Barrio::class);
} }
function togglePagado() : bool {
$this->pagado = !$this->pagado;
$this->save();
return $this->pagado;
}
function toggleTerminado() : bool {
$this->terminado = !$this->terminado;
$this->save();
return $this->terminado;
}
/** /**
* Los productos que pertenecen al pedido. * Los productos que pertenecen al pedido.
*/ */
@ -33,34 +45,28 @@ class Pedido extends Model
return $this->belongsToMany(Producto::class)->withPivot(['cantidad']); return $this->belongsToMany(Producto::class)->withPivot(['cantidad']);
} }
/** function agregarProducto(Producto $producto, int $cantidad) {
* Los productos del pedido que no aportan para el $productoEnChismosa = $this->productos()->where('id', $producto->id)->first();
* bono de transporte if ($productoEnChismosa) {
*/ $productoEnChismosa->pivot->cantidad += $cantidad;
function productosSinTransporte() { $productoEnChismosa->save();
return $this->productos()->orWhere(['bono' => true, 'barrial' => true]); return $productoEnChismosa;
} else {
$this->productos()->attach($producto, ['cantidad' => $cantidad]);
return $this->productos()->where('id', $producto->id)->first();
}
}
function quitarProducto(Producto $producto) {
$this->productos()->detach($producto);
} }
/** /**
* Los productos del pedido que aportan para el * El total de los productos del pedido
* bono de transporte. * sumado al total de los bonos de transporte
*/ */
function productosConTransporte() { function totalChismosa() : float {
return $this->productos()->where(['bono' => false, 'barrial' => false]); return $this->totalProductos() + $this->totalTransporte();
}
/**
* Los productos no barriales del pedido.
*/
function productosNoBarriales() {
return $this->productos()->where('barrial',false);
}
/**
* Los bonos del pedido.
*/
function bonos() {
return $this->productos()->where('bono',true);
} }
/** /**
@ -71,7 +77,7 @@ class Pedido extends Model
* Si la colección es null o no se pasa ningún parámetro * Si la colección es null o no se pasa ningún parámetro
* se toman todos los productos del pedido. * se toman todos los productos del pedido.
*/ */
function total($productos = null) : float { function totalProductos($productos = null) : float {
if (!$productos) if (!$productos)
$productos = $this->productos(); $productos = $this->productos();
@ -81,38 +87,12 @@ class Pedido extends Model
/** /**
* El total de bonos de transporte del pedido * El total de bonos de transporte del pedido
*/ */
function totalTransporte() : int { function totalBonosDeTransporte() : int {
if ($this->productos()->every(fn($prod) => !$prod->pagaTransporte())) return TransporteUtils::calcularTotal($this->productosConTransporte());
return 0;
return TransporteUtils::total($this->productosConTransporte());
} }
/** function totalATransferir() : float {
* El total de los productos del pedido $productos = $this->productos()->where(['bono' => false, 'barrial' => false])->get();
* sumado al total de los bonos de transporte return $this->totalProductos($productos);
*/
function totalChismosa() : float {
return $this->total() + $this->totalTransporte();
}
function toggleConfirm() : bool {
$this->confirmed = !$this->confirmed;
$this->save();
return $this->confirmed;
}
function agregarProducto(Producto $producto, int $cantidad) {
$productoEnChismosa = $this->productos()->where('id', $producto->id)->first();
if ($productoEnChismosa) {
$productoEnChismosa->pivot->cantidad += $cantidad;
$productoEnChismosa->save();
} else {
$this->productos()->attach($producto, ['cantidad' => $cantidad]);
}
}
function quitarProducto(Producto $producto) {
$this->productos()->detach($producto);
} }
} }

View file

@ -14,7 +14,7 @@ class Producto extends Model
* @var array<int, string> * @var array<int, string>
*/ */
protected $fillable = [ protected $fillable = [
'name', 'price', 'solidario', 'bono', 'barrial', 'categoria_id', 'barrio_id' 'nombre', 'precio', 'solidario', 'bono', 'barrial', 'categoria_id', 'barrio_id'
]; ];
/** /**
@ -48,17 +48,4 @@ class Producto extends Model
{ {
return $this->belongsTo(Barrio::class); return $this->belongsTo(Barrio::class);
} }
/**
* Los productos centrales.
*/
public static function centrales() {
return Producto::where([
'barrial' => false,
]);
}
function pagaTransporte() : bool {
return !$this->bono && !$this->barrial;
}
} }

View file

@ -20,7 +20,7 @@ class Region extends Model
* @var array<int, string> * @var array<int, string>
*/ */
protected $fillable = [ protected $fillable = [
'name', 'nombre',
]; ];
/** /**

View file

@ -13,7 +13,7 @@ class TransporteUtils
return 0; return 0;
} }
static function total(float $total) : int { static function calcularTotal(float $total) : int {
return cantidad($total) * COSTO_TRANSPORTE; return cantidad($total) * COSTO_TRANSPORTE;
} }
} }

View file

@ -6,6 +6,7 @@
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "^8.1", "php": "^8.1",
"doctrine/dbal": "^3.8",
"guzzlehttp/guzzle": "^7.2", "guzzlehttp/guzzle": "^7.2",
"inertiajs/inertia-laravel": "^0.6.8", "inertiajs/inertia-laravel": "^0.6.8",
"laravel/framework": "^10.10", "laravel/framework": "^10.10",

395
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "8d183499e584f55de945d0a59ab769e7", "content-hash": "58bdc4fc7c5dfbc1a71d9f335386c5b2",
"packages": [ "packages": [
{ {
"name": "bacon/bacon-qr-code", "name": "bacon/bacon-qr-code",
@ -309,6 +309,350 @@
}, },
"time": "2022-10-27T11:44:00+00:00" "time": "2022-10-27T11:44:00+00:00"
}, },
{
"name": "doctrine/cache",
"version": "2.2.0",
"source": {
"type": "git",
"url": "https://github.com/doctrine/cache.git",
"reference": "1ca8f21980e770095a31456042471a57bc4c68fb"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/cache/zipball/1ca8f21980e770095a31456042471a57bc4c68fb",
"reference": "1ca8f21980e770095a31456042471a57bc4c68fb",
"shasum": ""
},
"require": {
"php": "~7.1 || ^8.0"
},
"conflict": {
"doctrine/common": ">2.2,<2.4"
},
"require-dev": {
"cache/integration-tests": "dev-master",
"doctrine/coding-standard": "^9",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
"psr/cache": "^1.0 || ^2.0 || ^3.0",
"symfony/cache": "^4.4 || ^5.4 || ^6",
"symfony/var-exporter": "^4.4 || ^5.4 || ^6"
},
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\Common\\Cache\\": "lib/Doctrine/Common/Cache"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
}
],
"description": "PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.",
"homepage": "https://www.doctrine-project.org/projects/cache.html",
"keywords": [
"abstraction",
"apcu",
"cache",
"caching",
"couchdb",
"memcached",
"php",
"redis",
"xcache"
],
"support": {
"issues": "https://github.com/doctrine/cache/issues",
"source": "https://github.com/doctrine/cache/tree/2.2.0"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fcache",
"type": "tidelift"
}
],
"time": "2022-05-20T20:07:39+00:00"
},
{
"name": "doctrine/dbal",
"version": "3.8.6",
"source": {
"type": "git",
"url": "https://github.com/doctrine/dbal.git",
"reference": "b7411825cf7efb7e51f9791dea19d86e43b399a1"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/dbal/zipball/b7411825cf7efb7e51f9791dea19d86e43b399a1",
"reference": "b7411825cf7efb7e51f9791dea19d86e43b399a1",
"shasum": ""
},
"require": {
"composer-runtime-api": "^2",
"doctrine/cache": "^1.11|^2.0",
"doctrine/deprecations": "^0.5.3|^1",
"doctrine/event-manager": "^1|^2",
"php": "^7.4 || ^8.0",
"psr/cache": "^1|^2|^3",
"psr/log": "^1|^2|^3"
},
"require-dev": {
"doctrine/coding-standard": "12.0.0",
"fig/log-test": "^1",
"jetbrains/phpstorm-stubs": "2023.1",
"phpstan/phpstan": "1.11.5",
"phpstan/phpstan-strict-rules": "^1.6",
"phpunit/phpunit": "9.6.19",
"psalm/plugin-phpunit": "0.18.4",
"slevomat/coding-standard": "8.13.1",
"squizlabs/php_codesniffer": "3.10.1",
"symfony/cache": "^5.4|^6.0|^7.0",
"symfony/console": "^4.4|^5.4|^6.0|^7.0",
"vimeo/psalm": "4.30.0"
},
"suggest": {
"symfony/console": "For helpful console commands such as SQL execution and import of files."
},
"bin": [
"bin/doctrine-dbal"
],
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\DBAL\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
}
],
"description": "Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.",
"homepage": "https://www.doctrine-project.org/projects/dbal.html",
"keywords": [
"abstraction",
"database",
"db2",
"dbal",
"mariadb",
"mssql",
"mysql",
"oci8",
"oracle",
"pdo",
"pgsql",
"postgresql",
"queryobject",
"sasql",
"sql",
"sqlite",
"sqlserver",
"sqlsrv"
],
"support": {
"issues": "https://github.com/doctrine/dbal/issues",
"source": "https://github.com/doctrine/dbal/tree/3.8.6"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fdbal",
"type": "tidelift"
}
],
"time": "2024-06-19T10:38:17+00:00"
},
{
"name": "doctrine/deprecations",
"version": "1.1.3",
"source": {
"type": "git",
"url": "https://github.com/doctrine/deprecations.git",
"reference": "dfbaa3c2d2e9a9df1118213f3b8b0c597bb99fab"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/deprecations/zipball/dfbaa3c2d2e9a9df1118213f3b8b0c597bb99fab",
"reference": "dfbaa3c2d2e9a9df1118213f3b8b0c597bb99fab",
"shasum": ""
},
"require": {
"php": "^7.1 || ^8.0"
},
"require-dev": {
"doctrine/coding-standard": "^9",
"phpstan/phpstan": "1.4.10 || 1.10.15",
"phpstan/phpstan-phpunit": "^1.0",
"phpunit/phpunit": "^7.5 || ^8.5 || ^9.5",
"psalm/plugin-phpunit": "0.18.4",
"psr/log": "^1 || ^2 || ^3",
"vimeo/psalm": "4.30.0 || 5.12.0"
},
"suggest": {
"psr/log": "Allows logging deprecations via PSR-3 logger implementation"
},
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\Deprecations\\": "lib/Doctrine/Deprecations"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"description": "A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.",
"homepage": "https://www.doctrine-project.org/",
"support": {
"issues": "https://github.com/doctrine/deprecations/issues",
"source": "https://github.com/doctrine/deprecations/tree/1.1.3"
},
"time": "2024-01-30T19:34:25+00:00"
},
{
"name": "doctrine/event-manager",
"version": "2.0.1",
"source": {
"type": "git",
"url": "https://github.com/doctrine/event-manager.git",
"reference": "b680156fa328f1dfd874fd48c7026c41570b9c6e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/doctrine/event-manager/zipball/b680156fa328f1dfd874fd48c7026c41570b9c6e",
"reference": "b680156fa328f1dfd874fd48c7026c41570b9c6e",
"shasum": ""
},
"require": {
"php": "^8.1"
},
"conflict": {
"doctrine/common": "<2.9"
},
"require-dev": {
"doctrine/coding-standard": "^12",
"phpstan/phpstan": "^1.8.8",
"phpunit/phpunit": "^10.5",
"vimeo/psalm": "^5.24"
},
"type": "library",
"autoload": {
"psr-4": {
"Doctrine\\Common\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Guilherme Blanco",
"email": "guilhermeblanco@gmail.com"
},
{
"name": "Roman Borschel",
"email": "roman@code-factory.org"
},
{
"name": "Benjamin Eberlei",
"email": "kontakt@beberlei.de"
},
{
"name": "Jonathan Wage",
"email": "jonwage@gmail.com"
},
{
"name": "Johannes Schmitt",
"email": "schmittjoh@gmail.com"
},
{
"name": "Marco Pivetta",
"email": "ocramius@gmail.com"
}
],
"description": "The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.",
"homepage": "https://www.doctrine-project.org/projects/event-manager.html",
"keywords": [
"event",
"event dispatcher",
"event manager",
"event system",
"events"
],
"support": {
"issues": "https://github.com/doctrine/event-manager/issues",
"source": "https://github.com/doctrine/event-manager/tree/2.0.1"
},
"funding": [
{
"url": "https://www.doctrine-project.org/sponsorship.html",
"type": "custom"
},
{
"url": "https://www.patreon.com/phpdoctrine",
"type": "patreon"
},
{
"url": "https://tidelift.com/funding/github/packagist/doctrine%2Fevent-manager",
"type": "tidelift"
}
],
"time": "2024-05-22T20:47:39+00:00"
},
{ {
"name": "doctrine/inflector", "name": "doctrine/inflector",
"version": "2.0.10", "version": "2.0.10",
@ -3125,6 +3469,55 @@
}, },
"time": "2022-06-13T21:57:56+00:00" "time": "2022-06-13T21:57:56+00:00"
}, },
{
"name": "psr/cache",
"version": "3.0.0",
"source": {
"type": "git",
"url": "https://github.com/php-fig/cache.git",
"reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/php-fig/cache/zipball/aa5030cfa5405eccfdcb1083ce040c2cb8d253bf",
"reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf",
"shasum": ""
},
"require": {
"php": ">=8.0.0"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"psr-4": {
"Psr\\Cache\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "PHP-FIG",
"homepage": "https://www.php-fig.org/"
}
],
"description": "Common interface for caching libraries",
"keywords": [
"cache",
"psr",
"psr-6"
],
"support": {
"source": "https://github.com/php-fig/cache/tree/3.0.0"
},
"time": "2021-02-03T23:26:27+00:00"
},
{ {
"name": "psr/clock", "name": "psr/clock",
"version": "1.0.0", "version": "1.0.0",

View file

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

View file

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

View file

@ -1,38 +0,0 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('caracteristicas', function (Blueprint $table) {
$table->id();
$table->string('name', 100);
$table->string('key', 100);
$table->timestamps();
});
Schema::create('producto_caracteristica', function (Blueprint $table) {
$table->unsignedBigInteger('producto_id');
$table->unsignedBigInteger('caracteristica_id');
$table->primary(['producto_id','caracteristica_id']);
$table->foreign('producto_id')->references('id')->on('productos');
$table->foreign('caracteristica_id')->references('id')->on('caracteristicas');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('producto_caracteristica');
Schema::dropIfExists('caracteristicas');
}
};

View file

@ -11,9 +11,15 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('regiones', function (Blueprint $table) {
$table->id();
$table->string('nombre', 100);
$table->timestamps();
});
Schema::create('barrios', function (Blueprint $table) { Schema::create('barrios', function (Blueprint $table) {
$table->id(); $table->id();
$table->string('name', 100); $table->string('nombre', 100);
$table->unsignedBigInteger('region_id'); $table->unsignedBigInteger('region_id');
$table->timestamps(); $table->timestamps();
$table->foreign('region_id')->references('id')->on('regiones'); $table->foreign('region_id')->references('id')->on('regiones');
@ -25,6 +31,7 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::dropIfExists('regiones');
Schema::dropIfExists('barrios'); Schema::dropIfExists('barrios');
} }
}; };

View file

@ -11,10 +11,23 @@ return new class extends Migration
*/ */
public function up(): void public function up(): void
{ {
Schema::create('categorias', function (Blueprint $table) {
$table->id();
$table->string('nombre', 100);
$table->timestamps();
});
Schema::create('caracteristicas', function (Blueprint $table) {
$table->id();
$table->string('nombre', 100);
$table->string('codigo', 100);
$table->timestamps();
});
Schema::create('productos', function (Blueprint $table) { Schema::create('productos', function (Blueprint $table) {
$table->id(); $table->id();
$table->string('name', 200); $table->string('nombre', 200);
$table->double('price', 15, 2); $table->double('precio', 15, 2);
$table->unsignedBigInteger('categoria_id'); $table->unsignedBigInteger('categoria_id');
$table->boolean('solidario'); $table->boolean('solidario');
$table->boolean('bono'); $table->boolean('bono');
@ -25,14 +38,12 @@ return new class extends Migration
$table->foreign('barrio_id')->references('id')->on('barrios'); $table->foreign('barrio_id')->references('id')->on('barrios');
}); });
Schema::create('pedido_producto', function (Blueprint $table) { Schema::create('producto_caracteristica', function (Blueprint $table) {
$table->unsignedBigInteger('pedido_id');
$table->unsignedBigInteger('producto_id'); $table->unsignedBigInteger('producto_id');
$table->unsignedInteger('cantidad'); $table->unsignedBigInteger('caracteristica_id');
$table->timestamps(); $table->primary(['producto_id','caracteristica_id']);
$table->primary(['pedido_id','producto_id']);
$table->foreign('pedido_id')->references('id')->on('pedidos');
$table->foreign('producto_id')->references('id')->on('productos'); $table->foreign('producto_id')->references('id')->on('productos');
$table->foreign('caracteristica_id')->references('id')->on('caracteristicas');
}); });
} }
@ -41,7 +52,9 @@ return new class extends Migration
*/ */
public function down(): void public function down(): void
{ {
Schema::dropIfExists('pedido_producto'); Schema::dropIfExists('producto_caracteristica');
Schema::dropIfExists('productos'); Schema::dropIfExists('productos');
Schema::dropIfExists('caracteristicas');
Schema::dropIfExists('categorias');
} }
}; };

View file

@ -13,12 +13,13 @@ return new class extends Migration
{ {
Schema::create('pedidos', function (Blueprint $table) { Schema::create('pedidos', function (Blueprint $table) {
$table->id(); $table->id();
$table->string('name', 100); $table->string('nombre', 100);
$table->boolean('confirmed')->default(false); $table->boolean('terminado')->default(false);
$table->boolean('pagado')->default(false);
$table->unsignedBigInteger('barrio_id'); $table->unsignedBigInteger('barrio_id');
$table->timestamps(); $table->timestamps();
$table->foreign('barrio_id')->references('id')->on('barrios'); $table->foreign('barrio_id')->references('id')->on('barrios');
$table->unique(['barrio_id','name']); $table->unique(['barrio_id','nombre']);
}); });
} }

View file

@ -0,0 +1,27 @@
<?php
namespace Database\Seeders;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Region;
use App\Models\Barrio;
class BarrioSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$prueba_id = Region::create([
'nombre' => 'PRUEBA',
])->id;
Barrio::create([
'nombre'=>'PRUEBA','region_id'=>$prueba_id, 'created_at'=>Date::now()
]);
}
}

View file

@ -11,7 +11,7 @@ use App\Models\Barrio;
use App\Models\Producto; use App\Models\Producto;
use App\Models\Categoria; use App\Models\Categoria;
class BarrioPruebaSeeder extends Seeder class BonoBarrialSeeder extends Seeder
{ {
/** /**
* Run the database seeds. * Run the database seeds.
@ -19,16 +19,15 @@ class BarrioPruebaSeeder extends Seeder
public function run(): void public function run(): void
{ {
Producto::create([ Producto::create([
'name' => 'Bono barrial', 'nombre' => 'Bono barrial',
'price' => 20, 'precio' => 20,
'solidario' => false, 'solidario' => false,
'bono' => true, 'bono' => true,
'categoria_id' => Categoria::firstOrCreate([ 'categoria_id' => Categoria::firstOrCreate([
'name' => 'TRANSPORTE, BONOS Y FINANCIAMIENTO SORORO' 'nombre' => 'TRANSPORTE, BONOS Y FINANCIAMIENTO SORORO'
])->id, ])->id,
'barrio_id' => Barrio::create([ 'barrio_id' => Barrio::firstOrCreate([
'name'=>'PRUEBA', 'nombre'=>'PRUEBA'
'region_id' => Region::create(['name' => 'PRUEBA'])->id
])->id, ])->id,
]); ]);
} }

View file

@ -37,14 +37,15 @@ class CanastaSeeder extends Seeder
$tipo = trim($record[$tipoColumn]); $tipo = trim($record[$tipoColumn]);
if (!in_array($tipo, $tipos)) { if (!in_array($tipo, $tipos)) {
if (!Str::contains($tipo,'¿') && ($tipo != 'T')) if (!Str::contains($tipo,'¿') && ($tipo != 'T')) {
$currentCategoria = Categoria::firstOrCreate(['name' => $tipo]); $currentCategoria = Categoria::firstOrCreate(['nombre' => $tipo]);
}
} else { } else {
[$solidario, $name, $caracteristicas] = $this->parseAndFormatName($record[$productoColumn]); [$solidario, $nombre, $caracteristicas] = $this->parseAndFormatName($record[$productoColumn]);
$productosToInsert[] = [ $productosToInsert[] = [
'name' => $name, 'nombre' => $nombre,
'price' => $record[$precioColumn], 'precio' => $record[$precioColumn],
'solidario' => $solidario, 'solidario' => $solidario,
'bono' => $tipo == 'B', 'bono' => $tipo == 'B',
'categoria_id' => $currentCategoria->id, 'categoria_id' => $currentCategoria->id,
@ -53,7 +54,7 @@ class CanastaSeeder extends Seeder
]; ];
$caracteristicasToInsert[] = [ $caracteristicasToInsert[] = [
'name' => $name, 'nombre' => $nombre,
'caracteristicas' => $caracteristicas 'caracteristicas' => $caracteristicas
]; ];
} }
@ -68,39 +69,35 @@ class CanastaSeeder extends Seeder
/** /**
* Returns an array with data parsed from productoColumn. * Returns an array with data parsed from productoColumn.
* *
* @return array{solidario: bool, name: string, caracteristicas: array(Caracteristica->id)} * @return array{solidario: bool, nombre: string, caracteristicas: array(Caracteristica)}
*/ */
private function parseAndFormatName($productoColumn): array { private function parseAndFormatName($productoColumn): array {
$solidario = Str::contains($productoColumn, '*'); $solidario = Str::contains($productoColumn, '*');
$name = Str::replace('*','',$productoColumn); $nombre = Str::replace('*','',$productoColumn);
$caracteristicas = []; $caracteristicas = [];
if (Str::contains($name, 'S-G')) if (Str::contains($nombre, 'S-G'))
$caracteristicas[] = Caracteristica::where('key','S-G')->first()->id; $caracteristicas[] = Caracteristica::where('codigo','S-G')->first()->id;
if (Str::contains($name, 'S-A')) if (Str::contains($nombre, 'S-A'))
$caracteristicas[] = Caracteristica::where('key','S-A')->first()->id; $caracteristicas[] = Caracteristica::where('codigo','S-A')->first()->id;
if (Str::contains($name, 'S-S')) if (Str::contains($nombre, 'S-S'))
$caracteristicas[] = Caracteristica::where('key','S-S')->first()->id; $caracteristicas[] = Caracteristica::where('codigo','S-S')->first()->id;
if (Str::contains($name, 'S-P-A')) if (Str::contains($nombre, 'S-P-A'))
$caracteristicas[] = Caracteristica::where('key','S-P-A')->first()->id; $caracteristicas[] = Caracteristica::where('codigo','S-P-A')->first()->id;
if ($caracteristicas) { if ($caracteristicas) {
$name = Str::replaceMatches('/\(S\-.*\)/', '', $name); $nombre = Str::replaceMatches('/\(S\-.*\)/', '', $nombre);
} }
return [ return [$solidario, trim($nombre), $caracteristicas];
$solidario,
trim($name),
$caracteristicas
];
} }
private function insertCaracteristicas($caracteristicasToInsert) : void { private function insertCaracteristicas($caracteristicasToInsert) : void {
foreach ($caracteristicasToInsert as $key => $item) { foreach ($caracteristicasToInsert as $codigo => $item) {
$name = $item['name']; $nombre = $item['nombre'];
$match = Producto::where('name',$name)->first(); $match = Producto::where('nombre',$nombre)->first();
if ($match) { if ($match) {
foreach ($item['caracteristicas'] as $key => $caracteristica) { foreach ($item['caracteristicas'] as $codigo => $caracteristica) {
DB::table('producto_caracteristica')->insert([ DB::table('producto_caracteristica')->insert([
'producto_id' => $match->id, 'producto_id' => $match->id,
'caracteristica_id' => $caracteristica, 'caracteristica_id' => $caracteristica,

View file

@ -15,10 +15,10 @@ class CaracteristicaSeeder extends Seeder
public function run(): void public function run(): void
{ {
DB::table('caracteristicas')->insert([ DB::table('caracteristicas')->insert([
['name' => 'SIN GLUTEN', 'key' => 'S-G', 'created_at' => Date::now(), 'updated_at' => Date::now()], ['nombre' => 'SIN GLUTEN', 'codigo' => 'S-G', 'created_at' => Date::now(), 'updated_at' => Date::now()],
['name' => 'SIN SAL AGREGADA', 'key' => 'S-S', 'created_at' => Date::now(), 'updated_at' => Date::now()], ['nombre' => 'SIN SAL AGREGADA', 'codigo' => 'S-S', 'created_at' => Date::now(), 'updated_at' => Date::now()],
['name' => 'SIN AZÚCAR AGREGADA', 'key' => 'S-A', 'created_at' => Date::now(), 'updated_at' => Date::now()], ['nombre' => 'SIN AZÚCAR AGREGADA', 'codigo' => 'S-A', 'created_at' => Date::now(), 'updated_at' => Date::now()],
['name' => 'SIN PRODUCTOS DE ORIGEN ANIMAL', 'key' => 'S-P-A', 'created_at' => Date::now(), 'updated_at' => Date::now()], ['nombre' => 'SIN PRODUCTOS DE ORIGEN ANIMAL', 'codigo' => 'S-P-A', 'created_at' => Date::now(), 'updated_at' => Date::now()],
]); ]);
} }
} }

View file

@ -17,7 +17,8 @@ class DatabaseSeeder extends Seeder
$this->call([ $this->call([
CaracteristicaSeeder::class, CaracteristicaSeeder::class,
CanastaSeeder::class, CanastaSeeder::class,
BarrioPruebaSeeder::class, BarrioSeeder::class,
BonoBarrialSeeder::class,
]); ]);
} }
} }