Compare commits

..

No commits in common. "10b1dd738e177e5bae38381c03594066ee954178" and "197230a4baa254643baffd104c970d00207fc93a" have entirely different histories.

7 changed files with 90 additions and 142 deletions

View file

@ -2,12 +2,9 @@
namespace App\Models; namespace App\Models;
use App\Utils\TransporteUtils;
use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use League\Csv\CannotInsertRecord; use League\Csv\CannotInsertRecord;
use League\Csv\Writer; use League\Csv\Writer;
@ -38,47 +35,22 @@ class Barrio extends Model
return $this->hasMany(Pedido::class); return $this->hasMany(Pedido::class);
} }
public function crearPedido(string $nombre) : Pedido { function crearPedido(string $nombre) : Pedido {
return $this->pedidos()->create(['nombre' => $nombre]); return $this->pedidos()->create(['nombre' => $name]);
} }
public function productosPedidos() { function totalARecaudar() : float {
return DB::table('productos') return $this->calcularTotalPagados();
->join('pedido_producto', 'productos.id', '=', 'pedido_producto.producto_id')
->join('pedidos', 'pedidos.id', '=', 'pedido_producto.pedido_id')
->where(['pedidos.barrio_id' => $this->id, 'pedidos.pagado' => true])
->select('productos.*',
DB::raw('SUM(pedido_producto.cantidad) as cantidad'),
DB::raw('SUM(pedido_producto.cantidad * productos.precio) as total'))
->groupBy('productos.id');
} }
public function totalARecaudar() : float { private function calcularTotalPagados(Closure $closure = null) : float {
return $this->pedidos()->where(['pagado' => true])->get()->sum( if (!$closure)
fn($p) => $p->totalATransferir() $closure = fn($p) => $p->totalChismosa();
); return $this->pedidosPagados()->sum($closure);
} }
public function totalATransferir() : float { function totalATransferir() : float {
return $this->totalNoBarriales() + $this->totalBonosDeTransporte(); return $this->calcularTotalPagados($p->totalATransferir());
}
public function totalNoBarriales() {
return $this->totalProductosIf(['barrial' => false]);
}
public function totalBarriales() {
return $this->totalProductosIf(['barrial' => true]);
}
private function totalProductosIf($predicado) : float {
return $this->productosPedidos()->where($predicado)->get()->sum(
fn($producto) => $producto->total
);
}
public function totalBonosDeTransporte() : int {
return TransporteUtils::calcularTotal($this->totalNoBarriales());
} }
/** /**
@ -89,52 +61,51 @@ class Barrio extends Model
return $this->hasMany(Producto::class); return $this->hasMany(Producto::class);
} }
public function exportarPedidoACsv() { function exportarPedidoACsv() {
if ($this->productosPedidos()->get()->isNotEmpty()) { if ($this->pedidosPagados()->exists()) {
$columnaProductos = $this->armarColumnaTotales(); $columnaProductos = $this->armarColumnasPedido();
try { try {
$writer = Writer::createFromPath(resource_path('csv/exports/'.$this->nombre.'.csv'), 'w'); $writer = Writer::createFromPath(resource_path('csv/exports/'.$this->nombre.'.csv'), 'w');
$writer->setDelimiter("|");
$writer->setEnclosure("'");
$writer->insertAll($columnaProductos); $writer->insertAll($columnaProductos);
return true;
} catch (CannotInsertRecord $e) { } catch (CannotInsertRecord $e) {
var_export($e->getRecords()); var_export($e->getRecords());
return false;
} }
} }
} }
private function armarColumnaTotales() : array { private function armarColumnasPedido() : array {
$columnaProductos = []; $columnaProductos = [];
$filasVaciasAgregadas = false; $filasVaciasAgregadas = false;
$productos = $this->productosPedidos()->where(['barrial' => false])->get();
foreach (Categoria::orderBy('id')->get() as $keyC => $categoria) { foreach (Categoria::orderBy('id')->get() as $keyC => $categoria) {
if ($categoria->productos()->where(['barrial' => false])->count() == 0) $columnaProductos[] = ['name' => $categoria->name, 'cantidad' => null];
continue;
$columnaProductos[] = ['nombre' => $categoria->nombre, 'cantidad' => null]; if ($categoria->name == 'TRANSPORTE, BONOS Y FINANCIAMIENTO SORORO')
$columnaProductos[] = ['name' => 'Bono de Transporte', 'cantidad' => TransporteUtils::cantidad($this->totalParaTransporte)];
if ($categoria->nombre == 'TRANSPORTE, BONOS Y FINANCIAMIENTO SORORO') else if ($categoria->name == 'PRODUCTOS DE GESTIÓN MENSTRUAL')
$columnaProductos[] = ['nombre' => 'Bono de Transporte', 'cantidad' => $this->totalBonosDeTransporte()]; $columnaProductos[] = ['name' => '¿Cuántas copas quieren y pueden comprar en el grupo?', 'cantidad' => null];
else if ($categoria->nombre == 'PRODUCTOS DE GESTIÓN MENSTRUAL')
$columnaProductos[] = ['nombre' => '¿Cuántas copas quieren y pueden comprar en el grupo?', 'cantidad' => null];
foreach ($categoria->productos()->orderBy('id')->get() as $keyP => $producto) { foreach ($categoria->productos()->orderBy('id')->get() as $keyP => $producto) {
if ($producto->precio == 0 && !$filasVaciasAgregadas) { if ($producto->price == 0 && !$filasVaciasAgregadas) {
$columnaProductos[] = ['nombre' => '¿Cuántas copas quieren adquirir a través del financiamiento sororo?', 'cantidad' => null]; $columnaProductos[] = ['name' => '¿Cuántas copas quieren adquirir a través del financiamiento sororo?', 'cantidad' => null];
$filasVaciasAgregadas = true; $filasVaciasAgregadas = true;
} }
$columnaProductos[] = ['nombre' => $producto->nombre, 'cantidad' => $this->cantidadPedida($producto->id, $productos)]; $columnaProductos[] = ['name' => $producto->name, 'cantidad' => $this->cantidadPedida($producto->id)];
}
} }
} }
return $columnaProductos; private function cantidadPedida($productoId) {
} $pedidos = $this->pedidos()
->whereHas('productos',
function ($query) use ($productoId) {
$query->where('producto_id', $productoId);})
->get();
private function cantidadPedida($productoId, $productos) { return $pedidos->sum(function ($pedido) use ($productoId) {
return $productos->first(fn($p) => $p->id == $productoId)->cantidad ?? 0; return $pedido->productos
->find($productoId)
->pivot->cantidad ?? 0;});
} }
} }

View file

@ -26,13 +26,13 @@ class Pedido extends Model
return $this->belongsTo(Barrio::class); return $this->belongsTo(Barrio::class);
} }
public function togglePagado() : bool { function togglePagado() : bool {
$this->pagado = !$this->pagado; $this->pagado = !$this->pagado;
$this->save(); $this->save();
return $this->pagado; return $this->pagado;
} }
public function toggleTerminado() : bool { function toggleTerminado() : bool {
$this->terminado = !$this->terminado; $this->terminado = !$this->terminado;
$this->save(); $this->save();
return $this->terminado; return $this->terminado;
@ -45,18 +45,11 @@ class Pedido extends Model
return $this->belongsToMany(Producto::class)->withPivot(['cantidad']); return $this->belongsToMany(Producto::class)->withPivot(['cantidad']);
} }
public function productosConTransporte() { function agregarProducto(Producto $producto, int $cantidad) {
return $this->productos()->where(['bono' => false, 'barrial' => false])->get();
}
public function agregarProducto(Producto $producto, int $cantidad) : Producto {
$productoEnChismosa = $this->productos()->where('id', $producto->id)->first(); $productoEnChismosa = $this->productos()->where('id', $producto->id)->first();
if ($productoEnChismosa) { if ($productoEnChismosa) {
$productoEnChismosa->pivot->cantidad += $cantidad; $productoEnChismosa->pivot->cantidad += $cantidad;
if ($productoEnChismosa->pivot->cantidad != 0)
$productoEnChismosa->save(); $productoEnChismosa->save();
else
$this->quitarProducto($producto);
return $productoEnChismosa; return $productoEnChismosa;
} else { } else {
$this->productos()->attach($producto, ['cantidad' => $cantidad]); $this->productos()->attach($producto, ['cantidad' => $cantidad]);
@ -64,7 +57,7 @@ class Pedido extends Model
} }
} }
public function quitarProducto(Producto $producto) { function quitarProducto(Producto $producto) {
$this->productos()->detach($producto); $this->productos()->detach($producto);
} }
@ -72,8 +65,8 @@ class Pedido extends Model
* El total de los productos del pedido * El total de los productos del pedido
* sumado al total de los bonos de transporte * sumado al total de los bonos de transporte
*/ */
public function totalATransferir() : float { function totalChismosa() : float {
return $this->totalProductos() + $this->totalBonosDeTransporte(); return $this->totalProductos() + $this->totalTransporte();
} }
/** /**
@ -84,21 +77,22 @@ 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.
*/ */
private function totalProductos($productos = null) { function totalProductos($productos = null) : float {
if (!$productos) if (!$productos)
$productos = $this->productos()->get(); $productos = $this->productos();
return $productos->map( return $productos->sum(fn($p) => $p->price * $p->pivot->cantidad);
fn($producto) => $producto->precio * $producto->pivot->cantidad
)->sum();
} }
/** /**
* El total de bonos de transporte del pedido * El total de bonos de transporte del pedido
*/ */
public function totalBonosDeTransporte() : int { function totalBonosDeTransporte() : int {
return TransporteUtils::calcularTotal( return TransporteUtils::calcularTotal($this->productosConTransporte());
$this->totalProductos($this->productosConTransporte()) }
);
function totalATransferir() : float {
$productos = $this->productos()->where(['bono' => false, 'barrial' => false])->get();
return $this->totalProductos($productos);
} }
} }

View file

@ -1,19 +1,19 @@
<?php <?php
namespace App\Utils; namespace App;
class TransporteUtils class TransporteUtils
{ {
public const COSTO_TRANSPORTE = 15; public const COSTO_TRANSPORTE = 15;
public const DIVISOR_TRANSPORTE = 500; public const DIVISOR_TRANSPORTE = 500;
private static function cantidad(float $total) : int { static function cantidad(float $total) : int {
if ($total) if ($total)
return 1 + floor($total / TransporteUtils::DIVISOR_TRANSPORTE); return 1 + floor($total / DIVISOR_TRANSPORTE);
return 0; return 0;
} }
public static function calcularTotal(float $total) : int { static function calcularTotal(float $total) : int {
return TransporteUtils::cantidad($total) * TransporteUtils::COSTO_TRANSPORTE; return cantidad($total) * COSTO_TRANSPORTE;
} }
} }

View file

@ -21,16 +21,6 @@ return new class extends Migration
$table->foreign('barrio_id')->references('id')->on('barrios'); $table->foreign('barrio_id')->references('id')->on('barrios');
$table->unique(['barrio_id','nombre']); $table->unique(['barrio_id','nombre']);
}); });
Schema::create('pedido_producto', function (Blueprint $table) {
$table->unsignedBigInteger('pedido_id');
$table->unsignedBigInteger('producto_id');
$table->unsignedInteger('cantidad');
$table->timestamps();
$table->primary(['pedido_id','producto_id']);
$table->foreign('pedido_id')->references('id')->on('pedidos');
$table->foreign('producto_id')->references('id')->on('productos');
});
} }
/** /**
@ -39,6 +29,5 @@ return new class extends Migration
public function down(): void public function down(): void
{ {
Schema::dropIfExists('pedidos'); Schema::dropIfExists('pedidos');
Schema::dropIfExists('pedido_producto');
} }
}; };

View file

@ -0,0 +1,34 @@
<?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;
use App\Models\Producto;
use App\Models\Categoria;
class BonoBarrialSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Producto::create([
'nombre' => 'Bono barrial',
'precio' => 20,
'solidario' => false,
'bono' => true,
'categoria_id' => Categoria::firstOrCreate([
'nombre' => 'TRANSPORTE, BONOS Y FINANCIAMIENTO SORORO'
])->id,
'barrio_id' => Barrio::firstOrCreate([
'nombre'=>'PRUEBA'
])->id,
]);
}
}

View file

@ -18,7 +18,7 @@ class DatabaseSeeder extends Seeder
CaracteristicaSeeder::class, CaracteristicaSeeder::class,
CanastaSeeder::class, CanastaSeeder::class,
BarrioSeeder::class, BarrioSeeder::class,
TestDataSeeder::class, BonoBarrialSeeder::class,
]); ]);
} }
} }

View file

@ -1,40 +0,0 @@
<?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;
use App\Models\Producto;
use App\Models\Categoria;
class TestDataSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$barrioPrueba = Barrio::find(1);
$productoBarrial = $barrioPrueba->productos()->create([
'nombre' => 'Producto Barrial',
'precio' => 100,
'solidario' => true,
'bono' => true,
'barrial' => true,
'categoria_id' => Categoria::firstOrCreate([
'nombre' => 'PRODUCTOS BARRIALES'
])->id
]);
$pedido = $barrioPrueba->crearPedido("Pedido de prueba");
$pedido->agregarProducto($productoBarrial, 2);
$pedido->agregarProducto(Producto::find(1), 1);
$segundoPedido = $barrioPrueba->crearPedido("Segunda prueba");
$segundoPedido->agregarProducto($productoBarrial, 5);
$tercerPedido = $barrioPrueba->crearPedido("Tercera prueba");
$tercerPedido->agregarProducto($productoBarrial, 3);
}
}