diff --git a/app/Http/Controllers/ImportRuleController.php b/app/Http/Controllers/ImportRuleController.php index 53f9525..b6eac23 100644 --- a/app/Http/Controllers/ImportRuleController.php +++ b/app/Http/Controllers/ImportRuleController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Models\Categorie; use App\Models\ImportRule; use Illuminate\Http\Request; @@ -13,6 +14,8 @@ class ImportRuleController extends Controller public function index() { // + $rules = ImportRule::all(); + return view('import_rules.index', compact('rules')); } /** @@ -21,6 +24,11 @@ class ImportRuleController extends Controller public function create() { // + // Return a view to create a new import rule + + $categorie = Categorie::all(); + return view('import_rules.create',compact('categorie')); + //'categories'=>$categorie); } /** @@ -29,6 +37,23 @@ class ImportRuleController extends Controller public function store(Request $request) { // + $request->validate([ + 'pattern' => 'required|string|max:255', + 'category_id' => 'required|exists:categories,id', + 'description' => 'nullable|string|max:255', + 'is_active' => 'boolean', + 'created_by' => 'nullable|string|max:255', + ]); + ImportRule::create( + [ + 'category_id'=>$request->category_id, + 'pattern'=>$request->pattern, + 'description'=>$request->description, + 'is_active'=>1, + ] + + ); + return redirect()->route('import_rules.index'); // Redirect to the index after storing the rule } /** diff --git a/app/Http/Controllers/MovimentiController.php b/app/Http/Controllers/MovimentiController.php index 28d2819..7d0a428 100644 --- a/app/Http/Controllers/MovimentiController.php +++ b/app/Http/Controllers/MovimentiController.php @@ -13,9 +13,14 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Auth; use Rap2hpoutre\FastExcel\FastExcel; +use Illuminate\Support\Facades\Storage; +use DateTime; + class MovimentiController extends Controller { + public $map; + // Gestione dei movimenti public static function newMovimenti() { $categorie=Categorie::list(); // TODO: da risolvere con jquery nella pagina blade conti.movimenti.list @@ -29,13 +34,15 @@ class MovimentiController extends Controller public static function listMovimenti(){ $categorie=Categorie::list(); $tags=tag::getList(); + $contos=Conto::all(); /* Query per visualizzare anche il totale dei documenti presenti per il record */ $movimenti=Movimenti::getList(); - + //dd($movimenti); return view('conti.movimenti.list',[ 'categorie'=>$categorie, 'movimenti'=>$movimenti, + 'contos'=>$contos, 'tags'=>$tags ]); } @@ -222,14 +229,32 @@ class MovimentiController extends Controller $ncategoria=$categoria->cat_name; for ($i=1;$i<=12;$i++) { - $movrow=DB::table('movimentis') - ->whereMonth('mov_data','=',$i) - ->whereYear('mov_data','=',$anno) - ->where('mov_fk_categoria','=',$id) - ->sum('mov_importo'); + $importo_dare = DB::table('movimentis') + ->whereMonth('mov_data', '=', $i) + ->whereYear('mov_data', '=', $anno) + ->where('mov_fk_categoria', '=', $id) + ->sum('mov_importo_dare'); + + $importo_avere = DB::table('movimentis') + ->whereMonth('mov_data', '=', $i) + ->whereYear('mov_data', '=', $anno) + ->where('mov_fk_categoria', '=', $id) + ->sum('mov_importo_avere'); + + // $movrow=DB::table('movimentis') + // ->whereMonth('mov_data','=',$i) + // ->whereYear('mov_data','=',$anno) + // ->where('mov_fk_categoria','=',$id) + // ->sum('mov_importo_dare') + // ->sum('mov_importo_avere'); + $movrow = $importo_avere - $importo_dare; + $coll[]=$movrow; $collx[]=$movrow; } + //TEST + // dd($movrow); + // /TEST $totale[]=array_sum($collx); unset($collx); } @@ -335,6 +360,84 @@ class MovimentiController extends Controller } } + public function importGenericCsv(Request $request) + { + if ($request->hasFile('filename')) + { + $filename=$request->file('filename')->store(); + $csv_headers=Movimenti::retrieveHeaders($filename); + $db_fields=Movimenti::getDbFields(); + + return view('conti.importGeneric',['csv'=>$csv_headers,'db'=>$db_fields,'filename'=>$filename]); + } + + else { + return 'Nessun File trovato'; + } + } + + public function importmappedCsv(Request $request) + { + $this->prepareMapping($request['mapping']); + $filename = Storage::path($request->filename); + + (new FastExcel)->configureCsv(';')->import($filename, function($line) { + $data = $this->mapCsvLineToDb($line); + // dd($data); + if (isset($data['mov_data'])) { + Movimenti::importNoDuplicate($data); + //Movimenti::create($data); + } + }); + + return redirect(Route('movimenti')); + } + + /** + * Prepara la mappatura tra i campi CSV e i campi DB + */ + private function prepareMapping($mapping) + { + foreach ($mapping as $key => $value) { + if ($value != null) { + $this->map[$key] = $value; + } + } + } + + /** + * Mappa una riga del CSV ai campi del database + */ + private function mapCsvLineToDb($line) + { + if (isset($line[$this->map['mov_data']])) { + $data = [ + 'mov_data' => $this->parseDate($line[$this->map['mov_data']]), + 'mov_descrizione' => $line[$this->map['mov_descrizione']] ?? null, + 'mov_importo_dare' => Movimenti::cleanImporto($line[$this->map['mov_importo_dare']]?? null) , + 'mov_importo_avere' => Movimenti::cleanImporto($line[$this->map['mov_importo_avere']] ?? null), + 'mov_fk_categoria' => Movimenti::setCategoriesFromCsv($line[$this->map['mov_descrizione']] ?? ''), + 'mov_fk_tags' => 1, + 'mov_inserito_da' => Auth::id(), + 'conto_id_da' => 1, + 'conto_id_a' => 1, + ]; + return $data; + } + return null; // Se non c'è la data, non importa la riga + + + } + + /** + * Converte la data dal formato d/m/Y a Y-m-d + */ + private function parseDate($dateString) + { + $date = DateTime::createFromFormat('d/m/Y', $dateString); + return $date ? $date->format('Y-m-d') : null; + } + public function importFile() { return view('conti.import'); @@ -345,6 +448,13 @@ class MovimentiController extends Controller return view('conti.importCR'); } + public function importFileGen() + { + return view('conti.importGen'); + } + + + /* public function test() { Movimenti::getYearsFromMovimenti(); @@ -360,4 +470,5 @@ class MovimentiController extends Controller $mov=Movimenti::getMovimentoById($id); return json_encode($mov); } + } diff --git a/app/Models/ImportRule.php b/app/Models/ImportRule.php index 0f04a2b..e83c528 100644 --- a/app/Models/ImportRule.php +++ b/app/Models/ImportRule.php @@ -8,4 +8,14 @@ use Illuminate\Database\Eloquent\Model; class ImportRule extends Model { use HasFactory; + protected $fillable = [ + 'category_id', + 'pattern', + 'description', + 'is_active', + 'created_by', + ]; + +// In MovimentiController o direttamente nel model Movimenti + } diff --git a/app/Models/Movimenti.php b/app/Models/Movimenti.php index 2a43767..0dc3c7b 100644 --- a/app/Models/Movimenti.php +++ b/app/Models/Movimenti.php @@ -5,10 +5,13 @@ namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Storage; use Rap2hpoutre\FastExcel\FastExcel; use App\Models\Categorie; use App\Models\Conto; use App\Models\User; +use App\Models\ImportRule; + class Movimenti extends Model { @@ -16,10 +19,24 @@ class Movimenti extends Model protected $dates = ['mov_data']; protected $casts = [ 'mov_data'=>'datetime']; + protected $fillable = [ + 'mov_data', + 'mov_fk_categoria', + 'mov_descrizione', + 'mov_importo_dare', + 'mov_importo_avere', + 'mov_inserito_da', + 'mov_fk_tags', + 'conto_id_da', + 'conto_id_a', + 'import_hash', + ]; + public static $query= 'SELECT a.id, a.mov_data, - a.mov_importo, + a.mov_importo_dare, + a.mov_importo_avere, a.mov_descrizione, c.cat_name, t.tag_name, @@ -28,10 +45,15 @@ FROM movimentis as a JOIN tags as t ON a.mov_fk_tags=t.id JOIN categories as c ON a.mov_fk_categoria=c.id'; - public function Conto() - { - return $this->belongsTo(Conto::class); - } + public function ContoDa() +{ + return $this->belongsTo(Conto::class, 'conto_id_da'); +} + +public function ContoA() +{ + return $this->belongsTo(Conto::class, 'conto_id_a'); +} public function User() { @@ -40,35 +62,20 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; public function Categorie() { - return $this->belongsTo(Categorie::class); + return $this->belongsTo(Categorie::class, 'mov_fk_categoria'); } public function Tags() { - return $this->belongsTo(Tags::class); + return $this->belongsTo(tag::class); } public static function getList() { + // ISSUE #3 - Aggiunta visualizzazione conto da e conto a nella lista dei movimenti + // e risoluzione duplicazione movimenti. - $expression=DB::raw( - 'SELECT - a.id, - a.mov_data, - a.mov_importo, - a.mov_descrizione, - c.cat_name, - t.tag_name, - co.nomeConto, - (SELECT Count(entity_id) as quanti FROM gen_docs WHERE entity=0 AND entity_id = a.id) as quanti - FROM movimentis as a - JOIN tags as t ON a.mov_fk_tags=t.id - JOIN categories as c ON a.mov_fk_categoria=c.id - JOIN contos as co ON a.conto_id=co.id' - ); - - $query = $expression->getValue(DB::connection()->getQueryGrammar()); - return DB::select($query); + return self::with(['Tags', 'Categorie', 'ContoDa', 'ContoA'])->orderBy('mov_data','desc')->get(); } public static function getSaldo($date) { @@ -89,6 +96,9 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; 'mov_fk_tags'=>$request->mov_fk_tags, 'mov_inserito_da'=>$request->userid, 'conto_id'=>$request->conto_id, + + // 'conto_id_da'=>$request->conto_id_da, + // 'conto_id_a'=>$request->conto_id_a, ]); } @@ -165,16 +175,17 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; } public static function updateMovimenti($request) { - DB::table('movimentis') - ->where('id','=', $request['id']) - ->update([ - 'mov_data' => $request['mov_data'], - 'mov_fk_categoria'=>$request['mov_fk_categoria'], - 'mov_descrizione'=>$request['mov_descrizione'], - 'mov_importo'=>$request['mov_importo'], - 'mov_fk_tags'=>$request['mov_fk_tags'], - 'mov_inserito_da'=>$request['userid'], - ]); + $updateData = []; + if (isset($request['mov_data'])) $updateData['mov_data'] = $request['mov_data']; + if (isset($request['mov_fk_categoria'])) $updateData['mov_fk_categoria'] = $request['mov_fk_categoria']; + if (isset($request['mov_descrizione'])) $updateData['mov_descrizione'] = $request['mov_descrizione']; + if (isset($request['mov_importo_dare'])) $updateData['mov_importo_dare'] = $request['mov_importo_dare']; + if (isset($request['mov_importo_avere'])) $updateData['mov_importo_avere'] = $request['mov_importo_avere']; + if (isset($request['mov_fk_tags'])) $updateData['mov_fk_tags'] = $request['mov_fk_tags']; + if (isset($request['userid'])) $updateData['mov_inserito_da'] = $request['userid']; + + self::where('id', $request['id'])->update($updateData); + } public static function deleteMovimento($id) { @@ -185,48 +196,90 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; public static function listByCatMonth($month,$cat,$year) { - $expression= DB::raw('SELECT - a.id, - a.mov_data, - a.mov_importo, - a.mov_descrizione, - c.cat_name, - t.tag_name, - (SELECT Count(entity_id) as quanti FROM gen_docs WHERE entity=0 AND entity_id = a.id) as quanti - FROM movimentis as a - JOIN tags as t ON a.mov_fk_tags=t.id - JOIN categories as c ON a.mov_fk_categoria=c.id - WHERE Month(a.mov_data)='.$month.' AND Year(a.mov_data)='.$year.' AND a.mov_fk_categoria='.$cat - ); - $query = $expression->getValue(DB::connection()->getQueryGrammar()); - return DB::select($query); - + // $expression= DB::raw('SELECT + // a.id, + // a.mov_data, + // a.mov_importo_dare, + // a.mov_importo_avere, + // a.mov_descrizione, + // c.cat_name, + // t.tag_name, + // (SELECT Count(entity_id) as quanti FROM gen_docs WHERE entity=0 AND entity_id = a.id) as quanti + // FROM movimentis as a + // JOIN tags as t ON a.mov_fk_tags=t.id + // JOIN categories as c ON a.mov_fk_categoria=c.id + // WHERE Month(a.mov_data)='.$month.' AND Year(a.mov_data)='.$year.' AND a.mov_fk_categoria='.$cat + // ); + // $query = $expression->getValue(DB::connection()->getQueryGrammar()); + // return DB::select($query); + return self::with(['Tags', 'Categorie']) + ->whereMonth('mov_data', $month) + ->whereYear('mov_data', $year) + ->where('mov_fk_categoria', $cat) + ->get(); } public static function listByCategory($cat) { - $expression=DB::raw(' SELECT a.id, - a.mov_data, - a.mov_importo, - a.mov_descrizione, - c.cat_name, - t.tag_name, - (SELECT Count(entity_id) as quanti FROM gen_docs WHERE entity=0 AND entity_id = a.id) as quanti - FROM movimentis as a - JOIN tags as t ON a.mov_fk_tags=t.id - JOIN categories as c ON a.mov_fk_categoria=c.id - WHERE a.mov_fk_categoria = '.$cat ); + // $expression=DB::raw(' SELECT a.id, + // a.mov_data, + // a.mov_importo_dare, + // a.mov_importo_avere, + // a.mov_descrizione, + // c.cat_name, + // t.tag_name, + // (SELECT Count(entity_id) as quanti FROM gen_docs WHERE entity=0 AND entity_id = a.id) as quanti + // FROM movimentis as a + // JOIN tags as t ON a.mov_fk_tags=t.id + // JOIN categories as c ON a.mov_fk_categoria=c.id + // WHERE a.mov_fk_categoria = '.$cat ); - $query = $expression->getValue(DB::connection()->getQueryGrammar()); - return DB::select($query); + // $query = $expression->getValue(DB::connection()->getQueryGrammar()); + // return DB::select($query); + return self::with(['Tags', 'Categorie']) + ->where('mov_fk_categoria', $cat) + ->get(); } + public static function makeHash($data,$movimento_dare, $movimento_avere, $descrizione) + { + // crea l'hash (serve per evitare duplicati nei movimenti) + return md5($data.$movimento_dare.$movimento_avere.$descrizione); + } + + public static function importHashExists($hash) + { + return self::where('import_hash', $hash)->exists(); + } + + public static function importNoDuplicate($data) + { + $hash = Movimenti::makeHash($data['mov_data'], $data['mov_importo_dare'], $data['mov_importo_avere'], $data['mov_descrizione']); + $exists = self::where('import_hash', $hash)->exists(); + if (!$exists) { + self::create([ + // TODO: ...altri campi... + 'mov_data' => $data['mov_data'], + 'mov_fk_categoria' => $data['mov_fk_categoria'], + 'mov_descrizione' => $data['mov_descrizione'], + 'mov_importo_dare' => $data['mov_importo_dare'], + 'mov_importo_avere' => $data['mov_importo_avere'], + 'mov_inserito_da' => 1, + 'conto_id_da' => 1, + 'conto_id_a' => 1, + 'mov_fk_tags' => 1, + 'import_hash' => $hash, + ]); + } + } + public static function getByTag($tag) { $expression=DB::raw('SELECT a.id, a.mov_data, - a.mov_importo, + a.mov_importo_dare, + a.mov_importo_avere, a.mov_descrizione, c.cat_name, t.tag_name, @@ -242,7 +295,7 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; public static function importEstrattoIng($filename) { - $inputPath='/var/www/html/gestionale_mt/public/storage/tenant'.tenant('id').'/'.$filename; + $inputPath='/var/www/html/gestionale2025/storage/app/public/'.$filename; // $outputPath='/var/www/html/gestionale_mt/public/tenant'.tenant('id').'/import/'.$filename.'.csv'; $outputPath = $inputPath.'.csv'; rename($inputPath,$outputPath); @@ -275,7 +328,7 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; public static function importEstrattoCR($filename) { - $inputPath='/var/www/html/gestionale_mt/public/storage/tenant'.tenant('id').'/'.$filename; + $inputPath='/var/www/html/gestionale2025/storage/app/public/'.$filename; // $outputPath='/var/www/html/gestionale_mt/public/'.tenant('id')."/app/".$filename; $outputPath = $inputPath.'.csv'; rename($inputPath,$outputPath); @@ -317,46 +370,72 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; } // Test filtri categoria - public function mapFieldByName($name) + public static function retrieveHeaders($filename) { - // definisce lo schema per rigenerare il file CSV secondo standard di importazione - $fields = Illuminate\Support\Facade\Schema::getColumnListing('movimentis')->mapFieldByName; - foreach ($fields as $field) - { - echo $column . "\n"; - } + $inputPath= Storage::path($filename); + $outputPath = $inputPath.'.csv'; + rename($inputPath,$outputPath); + $rows = (new FastExcel)->configureCsv(';')->import($outputPath); + $headers = array_keys($rows->first()); + return $headers; } - // Test applicazione regole - public function setCategoriaMovimento($movimento) + public static function getDbFields() { - $rules= \App\Models\ImportRule::all(); + return [ + "Data movimento"=>"mov_data", + "Descrizione"=>"mov_descrizione", + "Importo Dare"=>"mov_importo_dare", + "Importo Avere"=>"mov_importo_avere", + "Categoria"=>"mov_fk_categoria", + "Tag"=>"mov_fk_tags", + "Conto prelievo"=>"conto_id_da", + "Conto versamento"=>"conto_id_a", + ]; + } - foreach ($rules as $role) - { - if (preg_match("/$role->parola/i","$movimento->descrizione")) - { - $movimento->catemov_fk_categoria=$role->categoria_id; - } - else - { - $movimento->catemov_fk_categoria=1; + + + // Ritorna la categoria suggerita in base alla descrizione del movimento da utilizzare sul db + public static function getSuggestedCategory($descrizione) + { + $rule = ImportRule::whereRaw('? LIKE CONCAT("%", pattern, "%")', [$descrizione])->first(); + return $rule ? $rule->category_id : 1; + } + + public static function setCategoriesFromCsv($descrizione) + { + $rules = ImportRule::all(); + $categoria = 1; // Default category + + foreach ($rules as $rule) { + if (preg_match("/$rule->pattern/i", $descrizione)) { + $categoria = $rule->category_id; + break; } } + return $categoria; } - - + // Ritorna gli anni presenti nei movimenti public static function getYearsFromMovimenti() { - $anni=DB::table('movimentis')->select(DB::raw('DISTINCT YEAR(mov_data) as anno'))->get(); - // dd($anni); // for test purposes - return $anni; + if (env('DB_CONNECTION')=='mysql') { + return self::selectRaw('DISTINCT YEAR(mov_data) as anno') + ->orderBy('anno', 'desc') + ->get(); + } else + { + return self::selectRaw("strftime('%Y', mov_data) as anno") + ->distinct() + ->orderBy('anno', 'desc') + ->get(); + } } @@ -375,24 +454,27 @@ JOIN categories as c ON a.mov_fk_categoria=c.id'; } } + // Ritorna la somma delle entrate per un anno specifico public static function getEntrate($year) { - $entrate_anno=DB::table('movimentis') - ->where('mov_importo','>',0) - ->whereYear('mov_data', '=' , $year) - ->sum('mov_importo'); - //->get(); - return $entrate_anno; + return self::whereYear('mov_data', $year) + ->sum('mov_importo_avere'); } + // Ritorna la somma delle uscite per un anno specifico public static function getUscite($year) { - $uscite_anno=DB::table('movimentis') - ->where('mov_importo','<',0) - ->whereYear('mov_data', '=' , $year) - ->sum('mov_importo'); - //->get(); - return ($uscite_anno); + return self::whereYear('mov_data', $year) + ->sum('mov_importo_dare'); + } + + public static function cleanImporto($importo){ + // Rimuove i punti e sostituisce la virgola con un punto + $importo = str_replace('.', '', $importo); + $importo = str_replace(',', '.', $importo); + $importo = str_replace('-', '', $importo); + $importo = str_replace('+', '', $importo); + return $importo; } } diff --git a/config/adminlte.php b/config/adminlte.php index 27f2416..7a8a6d3 100644 --- a/config/adminlte.php +++ b/config/adminlte.php @@ -383,6 +383,16 @@ return [ 'text' => 'Importa Estratto conto Cassa Rurale', 'route' => 'importCR', ], + [ + 'text' => 'Importa Generic CSV', + 'route' => 'importGen', + ], + [ + 'text' => 'Regole importazione', + 'route' => 'import_rules.index', + // 'can' => ['import_rules'], + ], + ], ], ], diff --git a/config/logging.php b/config/logging.php index d526b64..f078a43 100644 --- a/config/logging.php +++ b/config/logging.php @@ -65,6 +65,14 @@ return [ 'replace_placeholders' => true, ], + 'app' => [ + 'driver' => 'single', + 'path' => storage_path('logs/gestionale2025.log'), + 'level' => env('LOG_LEVEL', 'debug'), + 'days' => env('LOG_DAILY_DAYS', 14), + 'replace_placeholders' => true, + ], + 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), diff --git a/database/migrations/2022_02_04_134245_create_movimentis_table.php b/database/migrations/2022_02_04_134245_create_movimentis_table.php index 5954ae3..9228e59 100644 --- a/database/migrations/2022_02_04_134245_create_movimentis_table.php +++ b/database/migrations/2022_02_04_134245_create_movimentis_table.php @@ -20,12 +20,15 @@ class CreateMovimentisTable extends Migration $table->unsignedBigInteger('mov_fk_categoria'); $table->foreign('mov_fk_categoria')->references('id')->on('categories'); $table->longText('mov_descrizione'); - $table->decimal('mov_importo',8,2); + $table->decimal('mov_importo_dare',8,2)->nullable(); + $table->decimal('mov_importo_avere',8,2)->nullable(); $table->unsignedBigInteger('mov_inserito_da'); $table->foreign('mov_inserito_da')->references('id')->on('users'); $table->unsignedBigInteger('mov_fk_tags'); $table->foreign('mov_fk_tags')->references('id')->on('tags'); - $table->foreignId('conto_id')->constrained('contos'); + $table->foreignId('conto_id_da')->constrained('contos')->nullable(); + $table->foreignId('conto_id_a')->constrained('contos')->nullable(); + $table->string('import_hash')->nullable()->index(); }); } diff --git a/database/migrations/2025_08_05_071946_create_import_rules_table.php b/database/migrations/2025_08_05_071946_create_import_rules_table.php index 3717306..e2d0ff5 100644 --- a/database/migrations/2025_08_05_071946_create_import_rules_table.php +++ b/database/migrations/2025_08_05_071946_create_import_rules_table.php @@ -14,6 +14,13 @@ return new class extends Migration Schema::create('import_rules', function (Blueprint $table) { $table->id(); $table->timestamps(); + $table->string('pattern'); + $table->unsignedBigInteger('category_id'); + $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); + // $table->unique(['pattern', 'category_id'], 'unique_import_rule'); + $table->string('description')->nullable(); // Optional description for the rule + $table->boolean('is_active')->default(true); // Flag to enable/disable the rule + $table->string('created_by')->nullable(); // User who created the rule }); } diff --git a/database/seeders/CategorieSeeder.php b/database/seeders/CategorieSeeder.php index 049cd6a..61f6afc 100644 --- a/database/seeders/CategorieSeeder.php +++ b/database/seeders/CategorieSeeder.php @@ -17,9 +17,9 @@ class CategorieSeeder extends Seeder // Inserisce le categorie necessarie DB::table('categories')->insert( [ - 'cat_name'=>'Automobili', + 'cat_name'=>'Da Selezionare', 'cat_uscita'=>1, - 'cat_entrata'=>0, + 'cat_entrata'=>1, ] ); DB::table('categories')->insert( @@ -30,9 +30,23 @@ class CategorieSeeder extends Seeder ); DB::table('categories')->insert( [ - 'cat_name'=>'Utenze', + 'cat_name'=>'Automobili', 'cat_uscita'=>1, 'cat_entrata'=>0] ); + DB::table('categories')->insert( + [ + 'cat_name'=>'Alimentari', + 'cat_uscita'=>1, + 'cat_entrata'=>0, + ] + ); + DB::table('categories')->insert( + [ + 'cat_name'=>'Utenze', + 'cat_uscita'=>1, + 'cat_entrata'=>0, + ] + ); } } diff --git a/public/js/app/import_rules.js b/public/js/app/import_rules.js new file mode 100644 index 0000000..429d0a9 --- /dev/null +++ b/public/js/app/import_rules.js @@ -0,0 +1,31 @@ +$(document).ready(function() { + $('#category_id').change(function() { + if ($(this).val() === 'nuovo') { + $('#nuovo_valore').show(); + $('#nuovo_aggiungi').show(); + } else { + $('#nuovo_valore').hide(); + $('#nuovo_aggiungi').hide(); + } + }); + + $('#nuovo_aggiungi').click(function() { + var selectedValue = $('#category_id').val(); + var nuovoValore = $('#nuovo_valore').val().trim(); + + if (selectedValue === 'nuovo' && nuovoValore !== '') { + $.post('/api/categorie', { cat_name: nuovoValore,cat_entrata: 1,cat_uscita: 1, _token: $('meta[name="csrf-token"]').attr('content') }, function(data) { + if (data.success) { + // Aggiungi la nuova categoria alla select e selezionala + $('#category_id').append(new Option(nuovoValore, data.id, true, true)).trigger('change'); + $('#nuovo_valore').val('').hide(); + $('#nuovo_aggiungi').hide(); + } else { + alert('Errore durante l\'aggiunta della categoria: ' + data.message); + } + }, 'json'); + } else { + alert('Per favore, inserisci un nome valido per la nuova categoria.'); + } + }); +}); diff --git a/public/js/app/movimenti.js b/public/js/app/movimenti.js index 6ee803a..87f30d4 100644 --- a/public/js/app/movimenti.js +++ b/public/js/app/movimenti.js @@ -1,161 +1,87 @@ + $(document).ready(function() { $('#listamovimenti').DataTable({ - "responsive": true, - columnDefs: [ - { - target: 0, - render: DataTable.render.date(), - } - ], - "order": [[0, "desc"]] + responsive: true, + columnDefs: [{ + target: 0, + render: DataTable.render.date(), + }], + order: [[0, "desc"]] }); - // $('.select2').select2(); }); - $(".draggable").draggable(); var d = new Date(); -var month = d.getMonth()+1; +var month = d.getMonth() + 1; var day = d.getDate(); -var strDate = d.getFullYear() + '-' + - (month<10 ? '0' : '') + month + '-' + - (day<10 ? '0' : '') + day; +var strDate = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day; + +function fillSelect(url, selectName, selectedValue) { + $(selectName).empty(); + $.getJSON(url, {}, function(items) { + $.each(items, function(i, item) { + var label = item.cat_name || item.tag_name || item.nomeConto; + $(selectName).append(new Option(label, item.id)); + }); + if (selectedValue) { + $(selectName).val(selectedValue).trigger('change'); + } + }); +} + +function resetForm(formSelector, dateValue) { + $(formSelector).find('input[type="text"], textarea, input[type="number"], input[type="date"], option').val(''); + $(formSelector).find('input[type="date"]').val(dateValue); +} + +function openModal(tipo, actionUrl, catUrl, tagUrl, contoUrl, modalTitle) { + resetForm('#form', strDate); + $('#myModal').modal('show'); + $('.modal-title').text(modalTitle); + $('#form').attr('action', actionUrl); + fillSelect(catUrl, "select[name='mov_fk_categoria']"); + fillSelect(tagUrl, "select[name='mov_fk_tags']"); + fillSelect(contoUrl, "select[name='conto_id']"); +} $(document).on('click', '.open_modal_spesa', function() { - console.log(strDate); - $("#categoria").empty(); - $("#tags").empty(); - $('#form').find('input[type="text"], textarea, input[type="number"],input[type="date"],option').val(""); - $('#form').find('input[type="date"]').val(strDate); - $('#myModal').modal('show'); - $('.modal-title').text(' Nuovo movimento in uscita'); - $('#form').attr('action', '/admin/movimenti/spesa'); - $.getJSON("/admin/service/catlistSpesa", {}, function(cats) { - $.each(cats, function(i, cat) { - $("select[name='mov_fk_categoria']").append( - new Option(cat.cat_name, cat.id) - ) - } - ); - }); - $.getJSON("/admin/service/taglist", {}, function(tags) { - $.each(tags, function(i, tag) { - $("select[name='mov_fk_tags']").append( - new Option(tag.tag_name, tag.id) - ) - }); -}); -$.getJSON("/admin/service/contolist", {}, function(contis) { - $.each(contis, function(i, conto) { - $("select[name='conto_id']").append( - new Option(conto.nomeConto, conto.id) - ) - } - ); -}); + openModal('spesa', '/admin/movimenti/spesa', '/admin/service/catlistSpesa', '/admin/service/taglist', '/admin/service/contolist', 'Nuovo movimento in uscita'); + $('#importo').attr('name', 'mov_importo_dare'); }); + $(document).on('click', '.open_modal_entrata', function() { - console.log(strDate); - $("#categoria").empty(); - $("#tags").empty(); - $('#form').find('input[type="text"], textarea, input[type="number"],option').val(""); - $('#form').find('input[type="date"]').val(strDate); - $('#myModal').modal('show'); - $('.modal-title').text('Nuovo movimento in entrata'); - $('#form').attr('action', '/admin/movimenti/entrata'); - $.getJSON("/admin/service/catlistEntrata", {}, function(data) { - $.each(data, function(i, item) { - $("select[name='mov_fk_categoria']").append( - new Option(item.cat_name, item.id) - ) - } - ); - }); - $.getJSON("/admin/service/taglist", {}, function(data) { - $.each(data, function(i, item) { - $("select[name='mov_fk_tags']").append( - new Option(item.tag_name, item.id) - ) - }); -}); -$.getJSON("/admin/service/contolist", {}, function(contis) { - $.each(contis, function(i, conto) { - $("select[name='conto_id']").append( - new Option(conto.nomeConto, conto.id) - ) - } - ); -}); + openModal('entrata', '/admin/movimenti/entrata', '/admin/service/catlistEntrata', '/admin/service/taglist', '/admin/service/contolist', 'Nuovo movimento in entrata'); + $('#importo').attr('name', 'mov_importo_avere'); }); + $(document).on('click', '.open_modal_modifica', function() { - var url = "/admin/movimenti/modify"; var riga_id = $(this).val(); - $("#categoria").empty(); - $("#tags").empty(); - $.getJSON(url + '/' + riga_id, function(data) { - // success data - console.log(data[0]); - $.getJSON("/admin/service/taglist", {}, function(tags) { - $.each(tags, function(i, tag) { - $("select[name='mov_fk_tags']").append( - new Option(tag.tag_name, tag.id) - ) - $('#tags') - .find('option:contains(' + data[0].tag_name + ')') - .prop('selected', true) - .trigger('change'); - }); - }); - $.getJSON("/admin/service/catlist", {}, function(cats) { - $.each(cats, function(i, cat) { - $("select[name='mov_fk_categoria']").append( - new Option(cat.cat_name, cat.id) - ) - $('#categoria') - .find('option:contains(' + data[0].cat_name + ')') - .prop('selected', true) - .trigger('change'); - } - ); - }); - $.getJSON("/admin/service/contolist", {}, function(contis) { - $.each(contis, function(i, conto) { - $("select[name='conto_id']").append( - new Option(conto.nomeConto, conto.id) - ) - $('#conto_id') - .find('option:contains(' + data[0].nomeConto + ')') - .prop('selected', true) - .trigger('change'); - } - ); - }); - $('.modal-title').text('Modifica movimento'); - $('#data').val(data[0].mov_data); + $.getJSON('/admin/movimenti/modify/' + riga_id, function(data) { + resetForm('#form', data[0].mov_data.substring(0, 10)); + fillSelect('/admin/service/catlist', "select[name='mov_fk_categoria']", data[0].cat_name); + fillSelect('/admin/service/taglist', "select[name='mov_fk_tags']", data[0].tag_name); + fillSelect('/admin/service/contolist', "select[name='conto_id']", data[0].nomeConto); $('#descrizione').val(data[0].mov_descrizione); - $('#importo').val(data[0].mov_importo); - $('#myModal').modal('show'); - // $('.panel-heading').text('Modifica movimento'); + // Imposta importo e name in base a DARE/AVERE + if (data[0].mov_importo_dare && parseFloat(data[0].mov_importo_dare) !== 0) { + $('#importo').val(data[0].mov_importo_dare); + $('#importo').attr('name', 'mov_importo_dare'); + } else if (data[0].mov_importo_avere && parseFloat(data[0].mov_importo_avere) !== 0) { + $('#importo').val(data[0].mov_importo_avere); + $('#importo').attr('name', 'mov_importo_avere'); + } else { + $('#importo').val(''); + $('#importo').attr('name', 'mov_importo'); + } + + $('.modal-title').text('Modifica movimento'); $('#form').attr('action', '/admin/movimenti/modify'); $('#form').append(''); - - }); - -}); - -/* - -$.getJSON("/admin/service/taglist", {}, function(data) { - $.each(data, function(i, item) { - $("select[name='mov_fk_tags']").append( - new Option(item.tag_name, item.id) - ) + $('#myModal').modal('show'); }); }); - -*/ diff --git a/resources/views/conti/importGen.blade.php b/resources/views/conti/importGen.blade.php new file mode 100644 index 0000000..8c46167 --- /dev/null +++ b/resources/views/conti/importGen.blade.php @@ -0,0 +1,27 @@ +@extends('adminlte::page') + +@section('content_header') +