Record.php 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. use DateInterval;
  5. use DatePeriod;
  6. use DateTime;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  9. use Illuminate\Support\Facades\Storage;
  10. use Illuminate\Support\Facades\Log;
  11. use Illuminate\Support\Facades\Mail;
  12. use App\Mail\ExportNotification;
  13. use App\Jobs\ExportPrimaNota;
  14. use App\Http\Middleware\TenantMiddleware;
  15. class Record extends Component
  16. {
  17. public $records, $dataId, $totals;
  18. public $in;
  19. public $out;
  20. public $payments = [];
  21. public $origins = [];
  22. public $destinations = [];
  23. public $fromDate;
  24. public $toDate;
  25. public $appliedFromDate;
  26. public $appliedToDate;
  27. public $exportFromDate;
  28. public $exportToDate;
  29. public $isExporting = false;
  30. public $selectedPeriod = 'OGGI';
  31. public $filterCausals = null;
  32. public $filterPaymentMethods = null;
  33. public $filterOrigins = null;
  34. public $filterDestinations = null;
  35. public $filterMember = null;
  36. public $isFiltering = false;
  37. public array $recordDatas = [];
  38. public array $labels = [];
  39. public array $causals = [];
  40. public $members = array();
  41. public $sendViaEmail = false;
  42. public $exportEmailAddress = '';
  43. public $exportEmailSubject = 'Prima Nota - Export';
  44. private $causalAmounts = [];
  45. public $selectedMonth;
  46. public $showMonthPicker = false;
  47. public $selectedDay;
  48. public $showDayPicker = false;
  49. public $selectedYear;
  50. protected $rules = [
  51. 'exportEmailAddress' => 'required_if:sendViaEmail,true|email',
  52. 'exportEmailSubject' => 'required_if:sendViaEmail,true|string|max:255',
  53. ];
  54. public $total_in = 0;
  55. public $total_out = 0;
  56. protected $messages = [
  57. 'exportEmailAddress.required_if' => 'L\'indirizzo email è obbligatorio quando si sceglie di inviare via email.',
  58. 'exportEmailAddress.email' => 'Inserisci un indirizzo email valido.',
  59. 'exportEmailSubject.required_if' => 'L\'oggetto dell\'email è obbligatorio.',
  60. 'exportEmailSubject.max' => 'L\'oggetto dell\'email non può superare i 255 caratteri.',
  61. ];
  62. public function hydrate()
  63. {
  64. $this->emit('load-select');
  65. }
  66. public function boot()
  67. {
  68. app(TenantMiddleware::class)->setupTenantConnection();
  69. }
  70. public function mount()
  71. {
  72. $this->fromDate = date("Y-m-d");
  73. $this->toDate = date("Y-m-d");
  74. $this->appliedFromDate = date("Y-m-d");
  75. $this->appliedToDate = date("Y-m-d");
  76. $this->exportFromDate = date("Y-m-d");
  77. $this->exportToDate = date("Y-m-d");
  78. $this->exportEmailSubject = 'Prima Nota - Export del ' . date('d/m/Y');
  79. $this->getCausals(\App\Models\Causal::select('id', 'name')->where('parent_id', null)->get(), 0);
  80. $this->members = \App\Models\Member::select(['id', 'first_name', 'last_name', 'fiscal_code'])
  81. ->where(function ($query) {
  82. $query->where('is_archived', false)
  83. ->orWhereNull('is_archived');
  84. })
  85. ->where(function ($query) {
  86. $query->where('is_deleted', false)
  87. ->orWhereNull('is_deleted');
  88. })->orderBy('last_name')->orderBy('first_name')->get();
  89. $this->payments = \App\Models\PaymentMethod::select('id', 'name', 'type')->where('enabled', true)->where('money', false)->orderBy('name', 'asc')->get();
  90. $this->origins = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', ['OUT', 'ALL'])->orderBy('name', 'asc')->get();
  91. $this->destinations = \App\Models\Bank::select('id', 'name')->where('enabled', true)->whereIn('visibility', ['IN', 'ALL'])->orderBy('name', 'asc')->get();
  92. $this->selectedMonth = date('Y-m');
  93. $this->selectedDay = date('Y-m-d');
  94. $this->selectedYear = date('Y');
  95. }
  96. private function generateExportDataAndTotals($fromDate, $toDate)
  97. {
  98. Log::info('generateExportDataAndTotals: Start (combined method)', [
  99. 'from_date' => $fromDate,
  100. 'to_date' => $toDate,
  101. 'memory_before' => memory_get_usage(true)
  102. ]);
  103. $exportRecords = array();
  104. $exportTotals = array();
  105. Log::info('generateExportDataAndTotals: Getting excluded members');
  106. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  107. Log::info('generateExportDataAndTotals: Excluded members retrieved', ['count' => count($exclude_from_records)]);
  108. Log::info('generateExportDataAndTotals: Building main query');
  109. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  110. ->select(
  111. 'records.*',
  112. 'records_rows.id as row_id',
  113. 'records_rows.record_id',
  114. 'records_rows.causal_id',
  115. 'records_rows.amount',
  116. 'records_rows.note',
  117. 'records_rows.when',
  118. 'records_rows.vat_id',
  119. 'records_rows.created_at as row_created_at',
  120. 'records_rows.updated_at as row_updated_at'
  121. )
  122. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  123. //->where('records.deleted', false)
  124. ->where(function ($query) {
  125. $query->where('records.deleted', false)->orWhereNull('records.deleted');
  126. })
  127. ->whereBetween('date', [$fromDate, $toDate])
  128. ->where(function ($query) {
  129. $query->where('type', 'OUT')
  130. ->orWhere(function ($query) {
  131. $query->where('records.corrispettivo_fiscale', true)
  132. ->orWhere('records.commercial', false);
  133. });
  134. })
  135. ->where(function ($query) use ($exclude_from_records) {
  136. $query->where('type', 'OUT')
  137. ->orWhere(function ($subquery) use ($exclude_from_records) {
  138. $subquery->whereNotIn('member_id', $exclude_from_records);
  139. });
  140. });
  141. Log::info('generateExportDataAndTotals: Applying causal filters');
  142. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  143. $causals = array();
  144. foreach ($this->filterCausals as $z) {
  145. $causals[] = $z;
  146. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  147. foreach ($childs as $c) {
  148. $causals[] = $c->id;
  149. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  150. foreach ($childsX as $cX) {
  151. $causals[] = $cX->id;
  152. }
  153. }
  154. }
  155. $datas->whereIn('causal_id', $causals);
  156. Log::info('generateExportDataAndTotals: Causal filters applied', ['causal_count' => count($causals)]);
  157. }
  158. if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
  159. $datas->whereIn('payment_method_id', $this->filterPaymentMethods);
  160. Log::info('generateExportDataAndTotals: Payment method filters applied', ['payment_method_count' => count($this->filterPaymentMethods)]);
  161. }
  162. if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
  163. $datas->whereIn('origin_id', $this->filterOrigins);
  164. Log::info('generateExportDataAndTotals: Origin filters applied', ['origins_count' => count($this->filterOrigins)]);
  165. }
  166. if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
  167. $datas->whereIn('destination_id', $this->filterDestinations);
  168. Log::info('generateExportDataAndTotals: Destination filters applied', ['destinations_count' => count($this->filterDestinations)]);
  169. }
  170. if ($this->filterMember != null && $this->filterMember > 0) {
  171. $datas->where('member_id', $this->filterMember);
  172. Log::info('generateExportDataAndTotals: Member filter applied', ['member_id' => $this->filterMember]);
  173. }
  174. Log::info('generateExportDataAndTotals: Executing query');
  175. $queryStart = microtime(true);
  176. $datas = $datas->orderBy('date', 'ASC')
  177. ->orderBy('records.created_at', 'ASC')
  178. ->orderBy('records_rows.id', 'ASC')
  179. ->get();
  180. $queryTime = microtime(true) - $queryStart;
  181. Log::info('generateExportDataAndTotals: Query executed', [
  182. 'record_count' => $datas->count(),
  183. 'query_time' => $queryTime,
  184. 'memory_after_query' => memory_get_usage(true)
  185. ]);
  186. $groupedData = [];
  187. $causalsCount = [];
  188. $processedCount = 0;
  189. // Initialize totals array
  190. foreach ($this->payments as $p) {
  191. $exportTotals[$p->name] = ["IN" => 0, "OUT" => 0];
  192. }
  193. Log::info('generateExportDataAndTotals: Starting combined data processing loop');
  194. $loopStart = microtime(true);
  195. foreach ($datas as $idx => $data) {
  196. if ($processedCount % 100 == 0) {
  197. Log::info('generateExportDataAndTotals: Processing progress', [
  198. 'processed' => $processedCount,
  199. 'total' => $datas->count(),
  200. 'memory_current' => memory_get_usage(true),
  201. 'memory_peak' => memory_get_peak_usage(true)
  202. ]);
  203. }
  204. try {
  205. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  206. $paymentCheck = $data->payment_method->money;
  207. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  208. if (!$data->deleted) {
  209. $amount = $data->amount;
  210. $amount += getVatValue($amount, $data->vat_id);
  211. } else {
  212. $amount = $data->amount;
  213. }
  214. // CALCULATE TOTALS HERE (in the same loop)
  215. /*if (!$data->deleted) {
  216. $exportTotals[$data->payment_method->name][$data->type] += $amount;
  217. }*/
  218. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  219. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  220. $nominativo = '';
  221. if ($data->type == "IN") {
  222. if ($data->member) {
  223. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  224. }
  225. } else {
  226. if ($data->supplier) {
  227. $nominativo = $data->supplier->name;
  228. }
  229. }
  230. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  231. if (!isset($groupedData[$groupKey])) {
  232. $groupedData[$groupKey] = [
  233. 'date' => $data->date,
  234. 'type_label' => $typeLabel,
  235. 'payment_method' => $data->payment_method->name,
  236. 'transaction_type' => $data->type,
  237. 'nominativo' => $nominativo,
  238. 'amount' => 0,
  239. 'deleted' => false,
  240. 'causals' => [],
  241. 'notes' => []
  242. ];
  243. $causalsCount[$groupKey] = [];
  244. }
  245. $groupedData[$groupKey]['amount'] += $amount;
  246. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  247. if (!empty($data->note)) {
  248. $groupedData[$groupKey]['notes'][] = $data->note;
  249. }
  250. if ($data->deleted) {
  251. $groupedData[$groupKey]['deleted'] = true;
  252. }
  253. }
  254. $processedCount++;
  255. } catch (\Exception $e) {
  256. Log::error('generateExportDataAndTotals: Error processing individual record', [
  257. 'record_id' => $data->id ?? 'unknown',
  258. 'error' => $e->getMessage(),
  259. 'processed_so_far' => $processedCount
  260. ]);
  261. throw $e;
  262. }
  263. }
  264. $loopTime = microtime(true) - $loopStart;
  265. Log::info('generateExportDataAndTotals: Combined processing loop completed', [
  266. 'total_processed' => $processedCount,
  267. 'grouped_records' => count($groupedData),
  268. 'loop_time' => $loopTime,
  269. 'memory_after_loop' => memory_get_usage(true)
  270. ]);
  271. Log::info('generateExportDataAndTotals: Building final export records');
  272. $finalStart = microtime(true);
  273. $tot = 0;
  274. $count = 0;
  275. foreach ($groupedData as $groupKey => $group) {
  276. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  277. $causalDisplay = $group['type_label'];
  278. if (count($causalsInGroup) > 1) {
  279. $detailDisplay = 'Varie|' . implode('|', $causalsInGroup);
  280. } else {
  281. $detailDisplay = $causalsInGroup[0];
  282. }
  283. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  284. if (!isset($exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  285. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  286. }
  287. $exportRecords[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  288. if (!$group['deleted'])
  289. $exportTotals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  290. }
  291. $finalTime = microtime(true) - $finalStart;
  292. Log::info('generateExportDataAndTotals: Final processing completed', [
  293. 'final_export_records' => count($exportRecords),
  294. 'final_export_totals' => count($exportTotals),
  295. 'final_time' => $finalTime,
  296. 'total_time' => microtime(true) - $loopStart + $queryTime,
  297. 'memory_final' => memory_get_usage(true),
  298. 'memory_peak' => memory_get_peak_usage(true)
  299. ]);
  300. // Cleanup
  301. unset($datas, $groupedData, $causalsCount);
  302. gc_collect_cycles();
  303. Log::info('generateExportDataAndTotals: Completed with cleanup', [
  304. 'memory_after_cleanup' => memory_get_usage(true)
  305. ]);
  306. return ['records' => $exportRecords, 'totals' => $exportTotals];
  307. }
  308. private function generateExportTotals($fromDate, $toDate)
  309. {
  310. $exportTotals = array();
  311. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  312. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  313. ->select(
  314. 'records.*',
  315. 'records_rows.id as row_id',
  316. 'records_rows.record_id',
  317. 'records_rows.causal_id',
  318. 'records_rows.amount',
  319. 'records_rows.note',
  320. 'records_rows.when',
  321. 'records_rows.vat_id',
  322. )
  323. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  324. //->where('records.deleted', false)
  325. ->where(function ($query) {
  326. $query->where('records.deleted', false)->orWhereNull('records.deleted');
  327. })
  328. ->whereBetween('date', [$fromDate, $toDate])
  329. ->where(function ($query) {
  330. $query->where('type', 'OUT')
  331. ->orWhere(function ($query) {
  332. $query->where('records.corrispettivo_fiscale', true)
  333. ->orWhere('records.commercial', false);
  334. });
  335. })
  336. ->where(function ($query) use ($exclude_from_records) {
  337. $query->where('type', 'OUT')
  338. ->orWhere(function ($subquery) use ($exclude_from_records) {
  339. $subquery->whereNotIn('member_id', $exclude_from_records);
  340. });
  341. });
  342. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  343. $causals = array();
  344. foreach ($this->filterCausals as $z) {
  345. $causals[] = $z;
  346. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  347. foreach ($childs as $c) {
  348. $causals[] = $c->id;
  349. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  350. foreach ($childsX as $cX) {
  351. $causals[] = $cX->id;
  352. }
  353. }
  354. }
  355. $datas->whereIn('causal_id', $causals);
  356. }
  357. if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
  358. $datas->whereIn('payment_method_id', $this->filterPaymentMethods);
  359. }
  360. if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
  361. $datas->whereIn('origin_id', $this->filterOrigins);
  362. }
  363. if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
  364. $datas->whereIn('destination_id', $this->filterDestinations);
  365. }
  366. if ($this->filterMember != null && $this->filterMember > 0) {
  367. $datas->where('member_id', $this->filterMember);
  368. }
  369. $datas = $datas->orderBy('date', 'ASC')
  370. ->orderBy('records.created_at', 'ASC')
  371. ->orderBy('records_rows.id', 'ASC')
  372. ->get();
  373. foreach ($datas as $data) {
  374. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  375. $paymentCheck = $data->payment_method->money;
  376. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  377. if (!$data->deleted) {
  378. $amount = $data->amount;
  379. $amount += getVatValue($amount, $data->vat_id);
  380. } else {
  381. $amount = $data->amount;
  382. }
  383. if (!isset($exportTotals[$data->payment_method->name])) {
  384. $exportTotals[$data->payment_method->name]["IN"] = 0;
  385. $exportTotals[$data->payment_method->name]["OUT"] = 0;
  386. }
  387. if (!$data->deleted)
  388. $exportTotals[$data->payment_method->name][$data->type] += $amount;
  389. }
  390. }
  391. return $exportTotals;
  392. }
  393. public function resetFilters()
  394. {
  395. $this->selectedPeriod = 'OGGI';
  396. $this->selectedMonth = date('Y-m');
  397. $this->selectedDay = date('Y-m-d');
  398. $this->selectedYear = date('Y');
  399. $this->showMonthPicker = false;
  400. $this->showDayPicker = false;
  401. $this->filterCausals = [];
  402. $this->filterPaymentMethods = [];
  403. $this->filterOrigins = [];
  404. $this->filterDestinations = [];
  405. $this->filterMember = null;
  406. $today = date("Y-m-d");
  407. $this->fromDate = $today;
  408. $this->toDate = $today;
  409. $this->appliedFromDate = $today;
  410. $this->appliedToDate = $today;
  411. $this->emit('filters-reset');
  412. }
  413. public function applyFilters()
  414. {
  415. $this->isFiltering = true;
  416. $this->setPeriodDates();
  417. $this->appliedFromDate = $this->fromDate;
  418. $this->appliedToDate = $this->toDate;
  419. $this->render();
  420. $this->isFiltering = false;
  421. $this->emit('filters-applied');
  422. }
  423. private function setPeriodDates()
  424. {
  425. $today = now();
  426. switch ($this->selectedPeriod) {
  427. case 'OGGI':
  428. $this->fromDate = $today->format('Y-m-d');
  429. $this->toDate = $today->format('Y-m-d');
  430. break;
  431. case 'IERI':
  432. $yesterday = $today->copy()->subDay();
  433. $this->fromDate = $yesterday->format('Y-m-d');
  434. $this->toDate = $yesterday->format('Y-m-d');
  435. break;
  436. case 'MESE CORRENTE':
  437. $this->fromDate = $today->copy()->startOfMonth()->format('Y-m-d');
  438. $this->toDate = $today->copy()->endOfMonth()->format('Y-m-d');
  439. break;
  440. case 'MESE PRECEDENTE':
  441. $lastMonth = $today->copy()->subMonth();
  442. $this->fromDate = $lastMonth->startOfMonth()->format('Y-m-d');
  443. $this->toDate = $lastMonth->endOfMonth()->format('Y-m-d');
  444. break;
  445. case 'MESE_PERSONALIZZATO':
  446. if (!empty($this->selectedMonth)) {
  447. $firstDay = date('Y-m-01', strtotime($this->selectedMonth . '-01'));
  448. $lastDay = date('Y-m-t', strtotime($this->selectedMonth . '-01'));
  449. $this->fromDate = $firstDay;
  450. $this->toDate = $lastDay;
  451. }
  452. break;
  453. case 'GIORNO_PERSONALIZZATO':
  454. if (!empty($this->selectedDay)) {
  455. $this->fromDate = $this->selectedDay;
  456. $this->toDate = $this->selectedDay;
  457. }
  458. break;
  459. case 'ULTIMO TRIMESTRE':
  460. $this->fromDate = $today->copy()->subMonths(3)->format('Y-m-d');
  461. $this->toDate = $today->format('Y-m-d');
  462. break;
  463. case 'ULTIMO QUADRIMESTRE':
  464. $this->fromDate = $today->copy()->subMonths(4)->format('Y-m-d');
  465. $this->toDate = $today->format('Y-m-d');
  466. break;
  467. }
  468. }
  469. public function getCausals($records, $indentation)
  470. {
  471. foreach ($records as $record) {
  472. $this->causals[] = array('id' => $record->id, 'name' => $record->getTree(), 'text' => $record->getTree(), 'level' => $indentation);
  473. if (count($record->childs))
  474. $this->getCausals($record->childs, $indentation + 1);
  475. }
  476. }
  477. public function getMonth($m)
  478. {
  479. $ret = '';
  480. switch ($m) {
  481. case 1:
  482. $ret = 'Gennaio';
  483. break;
  484. case 2:
  485. $ret = 'Febbraio';
  486. break;
  487. case 3:
  488. $ret = 'Marzo';
  489. break;
  490. case 4:
  491. $ret = 'Aprile';
  492. break;
  493. case 5:
  494. $ret = 'Maggio';
  495. break;
  496. case 6:
  497. $ret = 'Giugno';
  498. break;
  499. case 7:
  500. $ret = 'Luglio';
  501. break;
  502. case 8:
  503. $ret = 'Agosto';
  504. break;
  505. case 9:
  506. $ret = 'Settembre';
  507. break;
  508. case 10:
  509. $ret = 'Ottobre';
  510. break;
  511. case 11:
  512. $ret = 'Novembre';
  513. break;
  514. case 12:
  515. $ret = 'Dicembre';
  516. break;
  517. default:
  518. $ret = '';
  519. break;
  520. }
  521. return $ret;
  522. }
  523. public function loadData($from, $to)
  524. {
  525. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  526. $f = $from != '' ? $from : $this->appliedFromDate;
  527. $t = $to != '' ? $to : $this->appliedToDate;
  528. $datas = \App\Models\Record::with('member', 'supplier', 'payment_method')
  529. ->select(
  530. 'records.*',
  531. 'records_rows.id as row_id',
  532. 'records_rows.record_id',
  533. 'records_rows.causal_id',
  534. 'records_rows.amount',
  535. 'records_rows.note',
  536. 'records_rows.when',
  537. 'records_rows.vat_id',
  538. //'causals.name as causal_name',
  539. 'd.name as destination',
  540. 'o.name as origin',
  541. )
  542. ->join('records_rows', 'records.id', '=', 'records_rows.record_id')
  543. ->join('causals', 'records_rows.causal_id', '=', 'causals.id')
  544. ->leftJoin('banks as d', 'records.destination_id', '=', 'd.id')
  545. ->leftJoin('banks as o', 'records.origin_id', '=', 'o.id')
  546. //->where('records.deleted', false)
  547. /*->where(function ($query) {
  548. $query->where('records.deleted', false)->orWhereNull('records.deleted');
  549. })*/
  550. ->whereBetween('date', [$f . " 00:00:00", $t . " 23:59:59"])
  551. ->where(function ($query) {
  552. $query->where('records.type', 'OUT')
  553. ->orWhere(function ($query) {
  554. $query->where('records.corrispettivo_fiscale', true)
  555. ->orWhere('records.commercial', false);
  556. });
  557. })
  558. ->where(function ($query) use ($exclude_from_records) {
  559. $query->where('records.type', 'OUT')
  560. ->orWhere(function ($subquery) use ($exclude_from_records) {
  561. $subquery->whereNotIn('member_id', $exclude_from_records);
  562. });
  563. });
  564. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  565. $causals = array();
  566. foreach ($this->filterCausals as $z) {
  567. $causals[] = $z;
  568. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  569. foreach ($childs as $c) {
  570. $causals[] = $c->id;
  571. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  572. foreach ($childsX as $cX) {
  573. $causals[] = $cX->id;
  574. }
  575. }
  576. }
  577. $datas->whereIn('causal_id', $causals);
  578. }
  579. if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
  580. $datas->whereIn('payment_method_id', $this->filterPaymentMethods);
  581. }
  582. if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
  583. $datas->whereIn('origin_id', $this->filterOrigins);
  584. }
  585. if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
  586. $datas->whereIn('destination_id', $this->filterDestinations);
  587. }
  588. if ($this->filterMember != null && $this->filterMember > 0) {
  589. $datas->where('member_id', $this->filterMember);
  590. }
  591. $datas = $datas->orderBy('date', 'ASC')
  592. ->orderBy('records.created_at', 'ASC')
  593. ->orderBy('records_rows.id', 'ASC')
  594. ->get();
  595. $ret = array();
  596. $this->total_in = 0;
  597. $this->total_out = 0;
  598. foreach ($datas as $data) {
  599. $causal = \App\Models\Causal::findOrFail($data->causal_id);
  600. $paymentCheck = $data->payment_method->money;
  601. if (!$paymentCheck && ($causal->no_first == null || !$causal->no_first)) {
  602. $data->causal_name = $causal->getTree();
  603. $ret[] = $data;
  604. if ($data->type == 'IN')
  605. $this->total_in += $data->amount;
  606. if ($data->type == 'OUT')
  607. $this->total_out += $data->amount;
  608. }
  609. }
  610. if ($this->total_in > 0 || $this->total_out > 0) {
  611. $ret[] = (object) array("date" => "", "total_in" => $this->total_in, "total_out" => $this->total_out);
  612. }
  613. return $ret;
  614. }
  615. public function render()
  616. {
  617. $month = 0;
  618. $year = 0;
  619. $this->records = array();
  620. $this->totals = array();
  621. $this->causalAmounts = array();
  622. $this->records = $this->loadData('', '');
  623. /*
  624. foreach ($datas as $idx => $data) {
  625. $causalCheck = \App\Models\Causal::findOrFail($data->causal_id);
  626. $paymentCheck = $data->payment_method->money;
  627. if (!$paymentCheck && ($causalCheck->no_first == null || !$causalCheck->no_first)) {
  628. if (!$data->deleted) {
  629. $amount = $data->amount;
  630. if ($data->vat_id > 0)
  631. $amount += getVatValue($amount, $data->vat_id);
  632. } else {
  633. $amount = $data->amount;
  634. }
  635. $isCommercial = ($data->commercial == 1 || $data->commercial === '1' || $data->commercial === true);
  636. $typeLabel = $isCommercial ? 'Commerciale' : 'Non Commerciale';
  637. $nominativo = '';
  638. if ($data->type == "IN") {
  639. if ($data->member) {
  640. $nominativo = $data->member->last_name . " " . $data->member->first_name;
  641. }
  642. if ($data->payment_method_id == 7)
  643. $values[] = array('id' => $data->record_id, 'amount' => $amount);
  644. } else {
  645. if ($data->supplier) {
  646. $nominativo = $data->supplier->name;
  647. }
  648. }
  649. $groupKey = $data->date . '|' . $typeLabel . '|' . $data->payment_method->name . '|' . $data->type . '|' . $nominativo;
  650. if (!isset($groupedData[$groupKey])) {
  651. $groupedData[$groupKey] = [
  652. 'date' => $data->date,
  653. 'type_label' => $typeLabel,
  654. 'payment_method' => $data->payment_method->name,
  655. 'transaction_type' => $data->type,
  656. 'nominativo' => $nominativo,
  657. 'amount' => 0,
  658. 'deleted' => false,
  659. 'causals' => [],
  660. 'notes' => []
  661. ];
  662. $causalsCount[$groupKey] = [];
  663. $causalsAmounts[$groupKey] = []; // Initialize causal amounts for this group
  664. $nominativi[$groupKey] = $nominativo;
  665. }
  666. $groupedData[$groupKey]['amount'] += $amount;
  667. $causalsCount[$groupKey][$causalCheck->getTree()] = true;
  668. $causalName = $causalCheck->getTree();
  669. if (!isset($causalsAmounts[$groupKey][$causalName])) {
  670. $causalsAmounts[$groupKey][$causalName] = 0;
  671. }
  672. $causalsAmounts[$groupKey][$causalName] += $amount;
  673. if (!empty($data->note)) {
  674. $groupedData[$groupKey]['notes'][] = $data->note;
  675. }
  676. if ($data->deleted) {
  677. $groupedData[$groupKey]['deleted'] = true;
  678. }
  679. }
  680. }
  681. Log::info('values', [$values]);
  682. foreach ($groupedData as $groupKey => $group) {
  683. $causalsInGroup = array_keys($causalsCount[$groupKey]);
  684. $causalDisplay = $group['type_label'];
  685. if (count($causalsInGroup) > 1) {
  686. $causalAmountsForJs = [];
  687. foreach ($causalsInGroup as $causalName) {
  688. $causalAmountsForJs[] = $causalName . ':::' . formatPrice($causalsAmounts[$groupKey][$causalName]);
  689. }
  690. $detailDisplay = 'Varie|' . implode('|', $causalAmountsForJs);
  691. } else {
  692. $detailDisplay = $causalsInGroup[0];
  693. }
  694. $recordKey = $group['date'] . "§" . $causalDisplay . "§" . $group['nominativo'] . "§" . $detailDisplay . "§" . ($group['deleted'] ? 'DELETED' : '') . "§";
  695. if (!isset($this->records[$recordKey][$group['payment_method']][$group['transaction_type']])) {
  696. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] = 0;
  697. }
  698. $this->records[$recordKey][$group['payment_method']][$group['transaction_type']] += $group['amount'];
  699. if (!isset($this->totals[$group['payment_method']])) {
  700. $this->totals[$group['payment_method']]["IN"] = 0;
  701. $this->totals[$group['payment_method']]["OUT"] = 0;
  702. }
  703. if (!$group['deleted'])
  704. $this->totals[$group['payment_method']][$group['transaction_type']] += $group['amount'];
  705. }
  706. */
  707. return view('livewire.records');
  708. }
  709. private function getLabels($fromDate, $toDate)
  710. {
  711. $begin = new DateTime($fromDate);
  712. $end = new DateTime($toDate);
  713. $interval = DateInterval::createFromDateString('1 day');
  714. $date_range = new DatePeriod($begin, $interval, $end);
  715. foreach ($date_range as $date) {
  716. $labels[] = $date->format('d/M');
  717. }
  718. return $labels;
  719. }
  720. private function getRecordData($type, $fromDate, $toDate)
  721. {
  722. $data = [];
  723. $begin = new DateTime($fromDate);
  724. $end = new DateTime($toDate);
  725. $interval = DateInterval::createFromDateString('1 day');
  726. $date_range = new DatePeriod($begin, $interval, $end);
  727. foreach ($date_range as $date) {
  728. if ($type == 'IN') {
  729. $found = false;
  730. foreach ($this->in as $in) {
  731. if (date("Y-m-d", strtotime($in->date)) == $date->format('Y-m-d')) {
  732. $data[] = number_format($in->total, 0, "", "");
  733. $found = true;
  734. }
  735. }
  736. if (!$found)
  737. $data[] = 0;
  738. }
  739. if ($type == 'OUT') {
  740. $found = false;
  741. foreach ($this->out as $out) {
  742. if (date("Y-m-d", strtotime($out->date)) == $date->format('Y-m-d')) {
  743. $data[] = number_format($out->total, 0, "", "");
  744. $found = true;
  745. }
  746. }
  747. if (!$found)
  748. $data[] = 0;
  749. }
  750. }
  751. return $data;
  752. }
  753. public function openExportModal()
  754. {
  755. $this->exportFromDate = $this->appliedFromDate;
  756. $this->exportToDate = $this->appliedToDate;
  757. // Reset email options
  758. $this->sendViaEmail = false;
  759. $this->exportEmailAddress = $this->getPreferredEmail();
  760. $this->updateEmailSubject();
  761. $this->emit('show-export-modal');
  762. }
  763. public function exportWithDateRange()
  764. {
  765. Log::info('=== EXPORT START ===', [
  766. 'user_id' => auth()->id(),
  767. 'from_date' => $this->exportFromDate,
  768. 'to_date' => $this->exportToDate,
  769. 'send_via_email' => $this->sendViaEmail,
  770. 'memory_usage' => memory_get_usage(true),
  771. 'memory_peak' => memory_get_peak_usage(true),
  772. 'time_limit' => ini_get('max_execution_time')
  773. ]);
  774. $this->isExporting = true;
  775. $this->emit('$refresh');
  776. usleep(100000);
  777. if ($this->sendViaEmail) {
  778. Log::info('Export: Validating email fields');
  779. $this->validate([
  780. 'exportEmailAddress' => 'required|email',
  781. 'exportEmailSubject' => 'required|string|max:255',
  782. ]);
  783. Log::info('Export: Email validation passed');
  784. }
  785. $this->isExporting = true;
  786. try {
  787. Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
  788. $startTime = microtime(true);
  789. // *** THIS IS THE KEY CHANGE - USE ONLY THE COMBINED METHOD ***
  790. $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
  791. $exportRecords = $result['records'];
  792. $exportTotals = $result['totals'];
  793. Log::info('TOTALS', [$exportTotals]);
  794. $dataGenTime = microtime(true) - $startTime;
  795. Log::info('Export: COMBINED data generation completed (NO SEPARATE TOTALS CALL)', [
  796. 'records_count' => count($exportRecords),
  797. 'totals_count' => count($exportTotals),
  798. 'generation_time' => $dataGenTime,
  799. 'memory_usage' => memory_get_usage(true),
  800. 'memory_peak' => memory_get_peak_usage(true)
  801. ]);
  802. if ($this->sendViaEmail) {
  803. Log::info('Export: Dispatching to background job');
  804. //$this->dispatchExportJob($exportRecords, $exportTotals);
  805. Log::info('Export: Job dispatched successfully');
  806. } else {
  807. Log::info('Export: Starting direct download export');
  808. $exportStartTime = microtime(true);
  809. $result = $this->exportWithData($exportRecords, $exportTotals);
  810. $exportTime = microtime(true) - $exportStartTime;
  811. Log::info('Export: Direct export completed', [
  812. 'export_time' => $exportTime,
  813. 'total_time' => microtime(true) - $startTime,
  814. 'memory_usage' => memory_get_usage(true),
  815. 'memory_peak' => memory_get_peak_usage(true)
  816. ]);
  817. return $result;
  818. }
  819. } catch (\Illuminate\Validation\ValidationException $e) {
  820. Log::error('Export: Validation error', [
  821. 'error' => $e->getMessage(),
  822. 'errors' => $e->errors()
  823. ]);
  824. $this->isExporting = false;
  825. throw $e;
  826. } catch (\Exception $e) {
  827. Log::error('Export: General error', [
  828. 'error' => $e->getMessage(),
  829. 'trace' => $e->getTraceAsString(),
  830. 'memory_usage' => memory_get_usage(true),
  831. 'memory_peak' => memory_get_peak_usage(true),
  832. 'execution_time' => microtime(true) - ($startTime ?? 0)
  833. ]);
  834. $this->isExporting = false;
  835. if ($this->sendViaEmail) {
  836. $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
  837. } else {
  838. session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
  839. }
  840. } finally {
  841. Log::info('Export: Cleanup phase');
  842. $this->isExporting = false;
  843. $this->emit('export-complete');
  844. $this->emit('hide-export-modal');
  845. Log::info('=== EXPORT END ===');
  846. }
  847. }
  848. public function exportData()
  849. {
  850. $this->isExporting = true;
  851. $this->emit('$refresh');
  852. usleep(100000);
  853. if ($this->sendViaEmail) {
  854. Log::info('Export: Validating email fields');
  855. $this->validate([
  856. 'exportEmailAddress' => 'required|email',
  857. 'exportEmailSubject' => 'required|string|max:255',
  858. ]);
  859. Log::info('Export: Email validation passed');
  860. }
  861. $this->isExporting = true;
  862. try {
  863. Log::info('Export: Starting COMBINED data generation phase (NO SEPARATE CALLS)');
  864. $startTime = microtime(true);
  865. $records = $this->loadData($this->exportFromDate, $this->exportToDate);
  866. $dataGenTime = microtime(true) - $startTime;
  867. if ($this->sendViaEmail) {
  868. Log::info('Export: Dispatching to background job');
  869. // Invio mail
  870. $this->dispatchExportJob($records);
  871. Log::info('Export: Job dispatched successfully');
  872. } else {
  873. Log::info('Export: Starting direct download export');
  874. $exportStartTime = microtime(true);
  875. // Creo excel e scarico
  876. $result = $this->exportExcel($records);
  877. $exportTime = microtime(true) - $exportStartTime;
  878. return $result;
  879. }
  880. } catch (\Illuminate\Validation\ValidationException $e) {
  881. Log::error('Export: Validation error', [
  882. 'error' => $e->getMessage(),
  883. 'errors' => $e->errors()
  884. ]);
  885. $this->isExporting = false;
  886. throw $e;
  887. } catch (\Exception $e) {
  888. Log::error('Export: General error', [
  889. 'error' => $e->getMessage(),
  890. 'trace' => $e->getTraceAsString(),
  891. 'memory_usage' => memory_get_usage(true),
  892. 'memory_peak' => memory_get_peak_usage(true),
  893. 'execution_time' => microtime(true) - ($startTime ?? 0)
  894. ]);
  895. $this->isExporting = false;
  896. if ($this->sendViaEmail) {
  897. $this->emit('export-email-error', 'Errore durante l\'invio dell\'email: ' . $e->getMessage());
  898. } else {
  899. session()->flash('error', 'Errore durante l\'export: ' . $e->getMessage());
  900. }
  901. } finally {
  902. Log::info('Export: Cleanup phase');
  903. $this->isExporting = false;
  904. $this->emit('export-complete');
  905. $this->emit('hide-export-modal');
  906. Log::info('=== EXPORT END ===');
  907. }
  908. }
  909. private function getEstimatedRecordCount($fromDate, $toDate)
  910. {
  911. $exclude_from_records = \App\Models\Member::where('exclude_from_records', true)->pluck('id')->toArray();
  912. $query = \App\Models\Record::join('records_rows', 'records.id', '=', 'records_rows.record_id')
  913. ->whereBetween('date', [$fromDate, $toDate])
  914. ->where(function ($query) {
  915. $query->where('type', 'OUT')
  916. ->orWhere(function ($query) {
  917. $query->where('records.corrispettivo_fiscale', true)
  918. ->orWhere('records.commercial', false);
  919. });
  920. })
  921. ->where(function ($query) use ($exclude_from_records) {
  922. $query->where('type', 'OUT')
  923. ->orWhere(function ($subquery) use ($exclude_from_records) {
  924. $subquery->whereNotIn('member_id', $exclude_from_records);
  925. });
  926. });
  927. if ($this->filterCausals != null && sizeof($this->filterCausals) > 0) {
  928. $causals = array();
  929. foreach ($this->filterCausals as $z) {
  930. $causals[] = $z;
  931. $childs = \App\Models\Causal::where('parent_id', $z)->get();
  932. foreach ($childs as $c) {
  933. $causals[] = $c->id;
  934. $childsX = \App\Models\Causal::where('parent_id', $c->id)->get();
  935. foreach ($childsX as $cX) {
  936. $causals[] = $cX->id;
  937. }
  938. }
  939. }
  940. $query->whereIn('causal_id', $causals);
  941. }
  942. if ($this->filterPaymentMethods != null && sizeof($this->filterPaymentMethods) > 0) {
  943. $query->whereIn('payment_method_id', $this->filterPaymentMethods);
  944. }
  945. if ($this->filterOrigins != null && sizeof($this->filterOrigins) > 0) {
  946. $query->whereIn('origin_id', $this->filterOrigins);
  947. }
  948. if ($this->filterDestinations != null && sizeof($this->filterDestinations) > 0) {
  949. $query->whereIn('destination_id', $this->filterDestinations);
  950. }
  951. if ($this->filterMember != null && $this->filterMember > 0) {
  952. $query->where('member_id', $this->filterMember);
  953. }
  954. return $query->count();
  955. }
  956. private function getMemberName($memberId)
  957. {
  958. $member = \App\Models\Member::find($memberId);
  959. return $member ? $member->last_name . ' ' . $member->first_name : 'Sconosciuto';
  960. }
  961. private function getCausalsNames($causalIds)
  962. {
  963. if (!is_array($causalIds)) {
  964. return null;
  965. }
  966. $causals = \App\Models\Causal::whereIn('id', $causalIds)->pluck('name')->toArray();
  967. return implode(', ', $causals);
  968. }
  969. private function getPaymentMethodsNames($paymentMethodIds)
  970. {
  971. if (!is_array($paymentMethodIds)) {
  972. return null;
  973. }
  974. $payment_methods = \App\Models\PaymentMethod::whereIn('id', $paymentMethodIds)->pluck('name')->toArray();
  975. return implode(', ', $payment_methods);
  976. }
  977. private function getOriginsNames($originIds)
  978. {
  979. if (!is_array($originIds)) {
  980. return null;
  981. }
  982. $origins = \App\Models\Bank::whereIn('id', $originIds)->pluck('name')->toArray();
  983. return implode(', ', $origins);
  984. }
  985. private function getDestinationsNames($destinationIds)
  986. {
  987. if (!is_array($destinationIds)) {
  988. return null;
  989. }
  990. $destinations = \App\Models\Bank::whereIn('id', $destinationIds)->pluck('name')->toArray();
  991. return implode(', ', $destinations);
  992. }
  993. public function updatedExportFromDate()
  994. {
  995. $this->updateEmailSubject();
  996. }
  997. public function updatedExportToDate()
  998. {
  999. $this->updateEmailSubject();
  1000. }
  1001. public function updatedSendViaEmail($value)
  1002. {
  1003. if ($value && empty($this->exportEmailAddress)) {
  1004. $this->exportEmailAddress = $this->getPreferredEmail();
  1005. }
  1006. }
  1007. public function resetEmailForm()
  1008. {
  1009. $this->sendViaEmail = false;
  1010. $this->exportEmailAddress = $this->getPreferredEmail();
  1011. $this->updateEmailSubject();
  1012. }
  1013. private function updateEmailSubject()
  1014. {
  1015. if (!empty($this->exportFromDate) && !empty($this->exportToDate)) {
  1016. $fromFormatted = date('d/m/Y', strtotime($this->exportFromDate));
  1017. $toFormatted = date('d/m/Y', strtotime($this->exportToDate));
  1018. if ($this->exportFromDate === $this->exportToDate) {
  1019. $this->exportEmailSubject = "Prima Nota - Export del {$fromFormatted}";
  1020. } else {
  1021. $this->exportEmailSubject = "Prima Nota - Export dal {$fromFormatted} al {$toFormatted}";
  1022. }
  1023. }
  1024. }
  1025. /**
  1026. * Dispatch export job to queue
  1027. */
  1028. //private function dispatchExportJob($exportRecords, $exportTotals)
  1029. private function dispatchExportJob($records)
  1030. {
  1031. try {
  1032. // Prepare filter descriptions for the job
  1033. $filterDescriptions = [
  1034. 'member' => $this->filterMember ? $this->getMemberName($this->filterMember) : null,
  1035. 'causals' => $this->filterCausals ? $this->getCausalsNames($this->filterCausals) : null,
  1036. 'payment_methods' => $this->filterPaymentMethods ? $this->getPaymentMethodsNames($this->filterPaymentMethods) : null,
  1037. 'origins' => $this->filterOrigins ? $this->getOriginsNames($this->filterOrigins) : null,
  1038. 'destinations' => $this->filterDestinations ? $this->getDestinationsNames($this->filterDestinations) : null,
  1039. ];
  1040. $paymentsArray = $this->payments->map(function ($payment) {
  1041. return [
  1042. 'id' => $payment->id,
  1043. 'name' => $payment->name,
  1044. 'type' => $payment->type
  1045. ];
  1046. })->toArray();
  1047. // Dispatch job to background queue
  1048. ExportPrimaNota::dispatch(
  1049. /*$exportRecords,
  1050. $exportTotals,*/
  1051. $records,
  1052. $this->exportEmailAddress,
  1053. $this->exportEmailSubject,
  1054. [
  1055. 'from' => date('d/m/Y', strtotime($this->exportFromDate)),
  1056. 'to' => date('d/m/Y', strtotime($this->exportToDate))
  1057. ],
  1058. auth()->id(),
  1059. $paymentsArray,
  1060. $filterDescriptions
  1061. );
  1062. $this->emit('export-email-queued');
  1063. session()->flash('success', 'Export in corso! Riceverai l\'email a breve alla casella: ' . $this->exportEmailAddress);
  1064. Log::info('Export job dispatched', [
  1065. 'user_id' => auth()->id(),
  1066. 'email' => $this->exportEmailAddress,
  1067. 'date_range' => [$this->exportFromDate, $this->exportToDate],
  1068. 'total_records' => count($this->records)
  1069. ]);
  1070. } catch (\Exception $e) {
  1071. Log::error('Failed to dispatch export job', [
  1072. 'user_id' => auth()->id(),
  1073. 'email' => $this->exportEmailAddress,
  1074. 'error' => $e->getMessage()
  1075. ]);
  1076. throw new \Exception('Errore nell\'avvio dell\'export: ' . $e->getMessage());
  1077. }
  1078. }
  1079. function export()
  1080. {
  1081. $result = $this->generateExportDataAndTotals($this->exportFromDate, $this->exportToDate);
  1082. $exportRecords = $result['records'];
  1083. $exportTotals = $result['totals'];
  1084. return $this->exportWithData($exportRecords, $exportTotals);
  1085. }
  1086. private function exportWithData($exportRecords, $exportTotals)
  1087. {
  1088. Log::info('exportWithData: Starting Excel generation', [
  1089. 'records_count' => count($exportRecords),
  1090. 'totals_count' => count($exportTotals),
  1091. 'memory_before' => memory_get_usage(true)
  1092. ]);
  1093. $startTime = microtime(true);
  1094. Log::info('exportWithData: Setting memory and GC');
  1095. ini_set('memory_limit', '512M');
  1096. gc_enable();
  1097. Log::info('exportWithData: Preparing column letters');
  1098. $letters = array('F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA');
  1099. Log::info('exportWithData: Creating spreadsheet object');
  1100. $spreadsheet = new Spreadsheet();
  1101. $activeWorksheet = $spreadsheet->getActiveSheet();
  1102. Log::info('exportWithData: Setting basic headers');
  1103. $activeWorksheet->setCellValue('A1', "Data");
  1104. $activeWorksheet->setCellValue('B1', "Tipologia");
  1105. $activeWorksheet->setCellValue('C1', "Causale");
  1106. $activeWorksheet->setCellValue('D1', "Nominativo");
  1107. $activeWorksheet->setCellValue('E1', "Stato");
  1108. $activeWorksheet->getStyle('A1:Q1')->getFill()
  1109. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1110. ->getStartColor()->setARGB('FF0C6197');
  1111. $activeWorksheet->getStyle('A1:Q1')->getFont()->getColor()->setARGB('FFFFFFFF');
  1112. Log::info('exportWithData: Setting payment method headers');
  1113. $idx = 0;
  1114. foreach ($this->payments as $p) {
  1115. if ($idx >= count($letters)) {
  1116. Log::warning('exportWithData: Reached letter limit', ['payment_index' => $idx]);
  1117. break;
  1118. }
  1119. Log::debug('exportWithData: Setting payment header', [
  1120. 'payment_name' => $p->name,
  1121. 'column_index' => $idx,
  1122. 'column_letter' => $letters[$idx]
  1123. ]);
  1124. $activeWorksheet->setCellValue($letters[$idx] . '1', $p->name);
  1125. $idx++;
  1126. if ($idx >= count($letters)) {
  1127. break;
  1128. }
  1129. $activeWorksheet->mergeCells($letters[$idx] . '1:' . $letters[$idx] . '1');
  1130. $idx++;
  1131. }
  1132. Log::info('exportWithData: Setting sub-headers');
  1133. $idx = 0;
  1134. $activeWorksheet->setCellValue('A2', "");
  1135. $activeWorksheet->setCellValue('B2', "");
  1136. $activeWorksheet->setCellValue('C2', "");
  1137. $activeWorksheet->setCellValue('D2', "");
  1138. $activeWorksheet->setCellValue('E2', "");
  1139. foreach ($this->payments as $p) {
  1140. if ($p->type == 'ALL') {
  1141. if ($idx >= count($letters)) {
  1142. break;
  1143. }
  1144. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  1145. $idx++;
  1146. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  1147. $idx++;
  1148. } elseif ($p->type == 'IN') {
  1149. if ($idx >= count($letters)) {
  1150. break;
  1151. }
  1152. $activeWorksheet->setCellValue($letters[$idx] . '2', "Entrate");
  1153. $idx++;
  1154. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  1155. $idx++;
  1156. } elseif ($p->type == 'OUT') {
  1157. if ($idx >= count($letters)) {
  1158. break;
  1159. }
  1160. $activeWorksheet->setCellValue($letters[$idx] . '2', "");
  1161. $idx++;
  1162. $activeWorksheet->setCellValue($letters[$idx] . '2', "Uscite");
  1163. $idx++;
  1164. }
  1165. }
  1166. Log::info('exportWithData: Applying header styles');
  1167. $activeWorksheet->getStyle('A1:Q1')->getFont()->setBold(true);
  1168. $activeWorksheet->getStyle('A2:Q2')->getFont()->setBold(true);
  1169. Log::info('exportWithData: Starting data row processing');
  1170. $count = 3;
  1171. $batchSize = 1000;
  1172. $recordsProcessed = 0;
  1173. $totalRecords = count($exportRecords);
  1174. Log::info('exportWithData: Processing records in batches', [
  1175. 'total_records' => $totalRecords,
  1176. 'batch_size' => $batchSize
  1177. ]);
  1178. $recordsArray = array_chunk($exportRecords, $batchSize, true);
  1179. Log::info('exportWithData: Created batches', ['batch_count' => count($recordsArray)]);
  1180. foreach ($recordsArray as $batchIndex => $recordsBatch) {
  1181. Log::info('exportWithData: Processing batch', [
  1182. 'batch_index' => $batchIndex,
  1183. 'batch_size' => count($recordsBatch),
  1184. 'memory_current' => memory_get_usage(true),
  1185. 'time_elapsed' => microtime(true) - $startTime
  1186. ]);
  1187. foreach ($recordsBatch as $causal => $record) {
  1188. if ($recordsProcessed % 250 == 0) {
  1189. Log::info('exportWithData: Record processing progress', [
  1190. 'processed' => $recordsProcessed,
  1191. 'total' => $totalRecords,
  1192. 'current_row' => $count,
  1193. 'memory_usage' => memory_get_usage(true),
  1194. 'time_elapsed' => microtime(true) - $startTime
  1195. ]);
  1196. }
  1197. try {
  1198. $check = $causal;
  1199. $parts = explode("§", $check);
  1200. $d = $parts[0] ?? '';
  1201. $c = $parts[1] ?? '';
  1202. $j = $parts[2] ?? '';
  1203. $det = $parts[3] ?? '';
  1204. $deleted = $parts[4] ?? '';
  1205. $detailParts = explode('|', $det);
  1206. $exportDetail = count($detailParts) > 1 ? implode(', ', array_slice($detailParts, 1)) : $det;
  1207. Log::debug('exportWithData: Setting row cells', ['row' => $count]);
  1208. $activeWorksheet->setCellValue('A' . $count, !empty($d) ? date("d/m/Y", strtotime($d)) : '');
  1209. $activeWorksheet->setCellValue('B' . $count, $c);
  1210. $activeWorksheet->setCellValue('C' . $count, $exportDetail);
  1211. $activeWorksheet->setCellValue('D' . $count, $j);
  1212. $stato = ($deleted === 'DELETED') ? 'ANNULLATA' : '';
  1213. $activeWorksheet->setCellValue('E' . $count, $stato);
  1214. if ($stato === 'ANNULLATA') {
  1215. $activeWorksheet->getStyle('E' . $count)->getFont()->getColor()->setARGB('FFFF0000');
  1216. }
  1217. $idx = 0;
  1218. foreach ($this->payments as $p) {
  1219. if ($idx >= count($letters) - 1) {
  1220. break;
  1221. }
  1222. if (isset($record[$p->name])) {
  1223. $inValue = isset($record[$p->name]["IN"]) ? formatPrice($record[$p->name]["IN"]) : "";
  1224. $outValue = isset($record[$p->name]["OUT"]) ? formatPrice($record[$p->name]["OUT"]) : "";
  1225. $activeWorksheet->setCellValue($letters[$idx] . $count, $inValue);
  1226. $idx++;
  1227. $activeWorksheet->setCellValue($letters[$idx] . $count, $outValue);
  1228. $idx++;
  1229. } else {
  1230. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1231. $idx++;
  1232. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1233. $idx++;
  1234. }
  1235. }
  1236. $count++;
  1237. $recordsProcessed++;
  1238. if ($recordsProcessed % 500 === 0) {
  1239. Log::debug('exportWithData: Garbage collection');
  1240. gc_collect_cycles();
  1241. }
  1242. } catch (\Exception $e) {
  1243. Log::error('exportWithData: Error processing record row', [
  1244. 'row' => $count,
  1245. 'causal' => $causal,
  1246. 'error' => $e->getMessage(),
  1247. 'processed_so_far' => $recordsProcessed
  1248. ]);
  1249. throw $e;
  1250. }
  1251. }
  1252. Log::info('exportWithData: Batch completed', [
  1253. 'batch_index' => $batchIndex,
  1254. 'records_in_batch' => count($recordsBatch),
  1255. 'total_processed' => $recordsProcessed
  1256. ]);
  1257. unset($recordsBatch);
  1258. gc_collect_cycles();
  1259. }
  1260. Log::info('exportWithData: Adding totals row');
  1261. $count++;
  1262. $idx = 0;
  1263. $activeWorksheet->setCellValue('A' . $count, 'Totale');
  1264. $activeWorksheet->setCellValue('B' . $count, '');
  1265. $activeWorksheet->setCellValue('C' . $count, '');
  1266. $activeWorksheet->setCellValue('D' . $count, '');
  1267. $activeWorksheet->setCellValue('E' . $count, '');
  1268. foreach ($this->payments as $p) {
  1269. if ($idx >= count($letters) - 1) {
  1270. break;
  1271. }
  1272. if (isset($exportTotals[$p->name])) {
  1273. if ($p->type == 'ALL') {
  1274. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  1275. $idx++;
  1276. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  1277. $idx++;
  1278. } elseif ($p->type == 'IN') {
  1279. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["IN"] ?? 0));
  1280. $idx++;
  1281. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1282. $idx++;
  1283. } elseif ($p->type == 'OUT') {
  1284. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1285. $idx++;
  1286. $activeWorksheet->setCellValue($letters[$idx] . $count, formatPrice($exportTotals[$p->name]["OUT"] ?? 0));
  1287. $idx++;
  1288. }
  1289. } else {
  1290. if ($p->type == 'ALL') {
  1291. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1292. $idx++;
  1293. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1294. $idx++;
  1295. } elseif ($p->type == 'IN') {
  1296. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1297. $idx++;
  1298. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1299. $idx++;
  1300. } elseif ($p->type == 'OUT') {
  1301. $activeWorksheet->setCellValue($letters[$idx] . $count, "");
  1302. $idx++;
  1303. $activeWorksheet->setCellValue($letters[$idx] . $count, "0");
  1304. $idx++;
  1305. }
  1306. }
  1307. }
  1308. Log::info('exportWithData: Applying final styles');
  1309. $activeWorksheet->getStyle('A' . $count . ':Q' . $count)->getFont()->setBold(true);
  1310. Log::info('exportWithData: Setting column dimensions');
  1311. $activeWorksheet->getColumnDimension('A')->setWidth(20);
  1312. $activeWorksheet->getColumnDimension('B')->setWidth(40);
  1313. $activeWorksheet->getColumnDimension('C')->setWidth(40);
  1314. $activeWorksheet->getColumnDimension('D')->setWidth(40);
  1315. $activeWorksheet->getColumnDimension('E')->setWidth(20);
  1316. foreach ($letters as $l) {
  1317. $activeWorksheet->getColumnDimension($l)->setWidth(20);
  1318. }
  1319. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  1320. Log::info('exportWithData: Preparing to save file', [
  1321. 'filename' => $filename,
  1322. 'total_processing_time' => microtime(true) - $startTime,
  1323. 'memory_before_save' => memory_get_usage(true)
  1324. ]);
  1325. try {
  1326. $currentClient = session('currentClient', 'default');
  1327. $tempPath = sys_get_temp_dir() . '/' . $filename;
  1328. Log::info('exportWithData: Creating Excel writer');
  1329. $writer = new Xlsx($spreadsheet);
  1330. Log::info('exportWithData: Saving to temp path', ['temp_path' => $tempPath]);
  1331. $writerStart = microtime(true);
  1332. $writer->save($tempPath);
  1333. $writerTime = microtime(true) - $writerStart;
  1334. Log::info('exportWithData: File saved to temp', [
  1335. 'writer_time' => $writerTime,
  1336. 'file_size' => file_exists($tempPath) ? filesize($tempPath) : 'unknown',
  1337. 'memory_after_save' => memory_get_usage(true)
  1338. ]);
  1339. unset($spreadsheet, $activeWorksheet, $writer);
  1340. gc_collect_cycles();
  1341. Log::info('exportWithData: Uploading to S3');
  1342. $disk = Storage::disk('s3');
  1343. $s3Path = $currentClient . '/prima_nota/' . $filename;
  1344. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  1345. if (!$disk->exists($primaNotaFolderPath)) {
  1346. $disk->put($primaNotaFolderPath, '');
  1347. Log::info("Created prima_nota folder for client: {$currentClient}");
  1348. }
  1349. $uploadStart = microtime(true);
  1350. $fileContent = file_get_contents($tempPath);
  1351. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  1352. $uploadTime = microtime(true) - $uploadStart;
  1353. if (!$uploaded) {
  1354. throw new \Exception('Failed to upload file to Wasabi S3');
  1355. }
  1356. Log::info("Export completed successfully", [
  1357. 'client' => $currentClient,
  1358. 'path' => $s3Path,
  1359. 'file_size' => filesize($tempPath),
  1360. 'records_processed' => $recordsProcessed,
  1361. 'upload_time' => $uploadTime,
  1362. 'total_time' => microtime(true) - $startTime,
  1363. 'memory_peak' => memory_get_peak_usage(true)
  1364. ]);
  1365. if (file_exists($tempPath)) {
  1366. unlink($tempPath);
  1367. }
  1368. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  1369. return redirect($downloadUrl);
  1370. } catch (\Exception $e) {
  1371. Log::error('Export S3 error - falling back to local', [
  1372. 'error' => $e->getMessage(),
  1373. 'trace' => $e->getTraceAsString(),
  1374. 'client' => session('currentClient', 'unknown'),
  1375. 'filename' => $filename,
  1376. 'records_processed' => $recordsProcessed ?? 0,
  1377. 'time_elapsed' => microtime(true) - $startTime
  1378. ]);
  1379. // Fallback logic remains the same...
  1380. $currentClient = session('currentClient', 'default');
  1381. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  1382. if (!is_dir($clientFolder)) {
  1383. mkdir($clientFolder, 0755, true);
  1384. Log::info("Created local client prima_nota folder: {$clientFolder}");
  1385. }
  1386. $localPath = $clientFolder . '/' . $filename;
  1387. if (isset($tempPath) && file_exists($tempPath)) {
  1388. rename($tempPath, $localPath);
  1389. } else {
  1390. $writer = new Xlsx($spreadsheet);
  1391. $writer->save($localPath);
  1392. unset($spreadsheet, $activeWorksheet, $writer);
  1393. }
  1394. gc_collect_cycles();
  1395. Log::warning("Export saved locally due to S3 error", [
  1396. 'client' => $currentClient,
  1397. 'local_path' => $localPath,
  1398. 'error' => $e->getMessage()
  1399. ]);
  1400. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  1401. return response()->download($localPath)->deleteFileAfterSend();
  1402. }
  1403. }
  1404. private function getPreferredEmail()
  1405. {
  1406. $email = auth()->user()->email ?? null;
  1407. if (empty($email)) {
  1408. $email = session('user_email', null);
  1409. }
  1410. if (empty($email)) {
  1411. $member = \App\Models\Member::where('user_id', auth()->id())->first();
  1412. $email = $member ? $member->email : null;
  1413. }
  1414. if (empty($email)) {
  1415. $email = config('mail.default_recipient', '');
  1416. }
  1417. return $email;
  1418. }
  1419. public function updatedSelectedPeriod($value)
  1420. {
  1421. $this->setPeriodDates();
  1422. $this->applyFilters();
  1423. }
  1424. public function updatedSelectedDay($value)
  1425. {
  1426. if (!empty($value)) {
  1427. $this->selectedPeriod = 'GIORNO_PERSONALIZZATO';
  1428. $this->fromDate = $value;
  1429. $this->toDate = $value;
  1430. $this->applyFilters();
  1431. }
  1432. }
  1433. public function selectDay($day)
  1434. {
  1435. $this->selectedDay = $day;
  1436. $this->showDayPicker = false;
  1437. $this->updatedSelectedDay($day);
  1438. }
  1439. public function toggleDayPicker()
  1440. {
  1441. $this->showDayPicker = !$this->showDayPicker;
  1442. }
  1443. public function selectToday()
  1444. {
  1445. $today = date('Y-m-d');
  1446. $this->selectDay($today);
  1447. }
  1448. public function selectYesterday()
  1449. {
  1450. $yesterday = date('Y-m-d', strtotime('-1 day'));
  1451. $this->selectDay($yesterday);
  1452. }
  1453. // Updated month methods to work with both custom month and day
  1454. public function updatedSelectedMonth($value)
  1455. {
  1456. if (!empty($value)) {
  1457. $this->selectedPeriod = 'MESE_PERSONALIZZATO';
  1458. $firstDay = date('Y-m-01', strtotime($value . '-01'));
  1459. $lastDay = date('Y-m-t', strtotime($value . '-01'));
  1460. $this->fromDate = $firstDay;
  1461. $this->toDate = $lastDay;
  1462. $this->applyFilters();
  1463. }
  1464. }
  1465. public function selectMonth($month)
  1466. {
  1467. $this->selectedMonth = $month;
  1468. $this->showMonthPicker = false;
  1469. $this->updatedSelectedMonth($month);
  1470. }
  1471. public function toggleMonthPicker()
  1472. {
  1473. $this->showMonthPicker = !$this->showMonthPicker;
  1474. }
  1475. private function exportExcel($records)
  1476. {
  1477. $startTime = microtime(true);
  1478. $spreadsheet = new Spreadsheet();
  1479. $activeWorksheet = $spreadsheet->getActiveSheet();
  1480. $activeWorksheet->setCellValue('A1', "Data");
  1481. $activeWorksheet->setCellValue('B1', "Tipologia");
  1482. $activeWorksheet->setCellValue('C1', "Causale");
  1483. $activeWorksheet->setCellValue('D1', "Nominativo");
  1484. $activeWorksheet->setCellValue('E1', "Stato");
  1485. $activeWorksheet->setCellValue('F1', "Entrata");
  1486. $activeWorksheet->setCellValue('G1', "Uscita");
  1487. $activeWorksheet->setCellValue('H1', "Origine");
  1488. $activeWorksheet->setCellValue('I1', "Destinazione");
  1489. $activeWorksheet->setCellValue('J1', "Metodo di pagamento");
  1490. $activeWorksheet->getStyle('A1:J1')->getFill()
  1491. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1492. ->getStartColor()->setARGB('FF0C6197');
  1493. $activeWorksheet->getStyle('A1:J1')->getFont()->getColor()->setARGB('FFFFFFFF');
  1494. $idx = 2;
  1495. foreach ($records as $record) {
  1496. if ($record->date != '') {
  1497. $activeWorksheet->setCellValue('A' . $idx, date("d/m/Y", strtotime($record->date)));
  1498. $activeWorksheet->setCellValue('B' . $idx, $record->commercial ? 'Commerciale' : 'Non commerciale');
  1499. $activeWorksheet->setCellValue('C' . $idx, $record->causal_name);
  1500. $activeWorksheet->setCellValue('D' . $idx, $record->type == 'IN' ? ($record->member->first_name . " " . $record->member->last_name) : @$record->supplier->name);
  1501. $activeWorksheet->setCellValue('E' . $idx, $record->deleted ? 'Annullata' : '');
  1502. $activeWorksheet->setCellValue('F' . $idx, $record->type == 'IN' ? formatPrice($record->amount) : '');
  1503. $activeWorksheet->setCellValue('G' . $idx, $record->type == 'OUT' ? formatPrice($record->amount) : '');
  1504. $activeWorksheet->setCellValue('H' . $idx, $record->type == 'OUT' ? $record->origin : '');
  1505. $activeWorksheet->setCellValue('I' . $idx, $record->type == 'IN' ? $record->destination : '');
  1506. $activeWorksheet->setCellValue('J' . $idx, $record->payment_method->name);
  1507. } else {
  1508. $activeWorksheet->setCellValue('A' . $idx, "Totali");
  1509. $activeWorksheet->setCellValue('B' . $idx, "");
  1510. $activeWorksheet->setCellValue('C' . $idx, "");
  1511. $activeWorksheet->setCellValue('D' . $idx, "");
  1512. $activeWorksheet->setCellValue('E' . $idx, "");
  1513. $activeWorksheet->setCellValue('F' . $idx, formatPrice($record->total_in));
  1514. $activeWorksheet->setCellValue('G' . $idx, formatPrice($record->total_out));
  1515. $activeWorksheet->setCellValue('H' . $idx, "");
  1516. $activeWorksheet->setCellValue('I' . $idx, "");
  1517. $activeWorksheet->setCellValue('J' . $idx, "");
  1518. }
  1519. $idx++;
  1520. }
  1521. $activeWorksheet->getColumnDimension('A')->setWidth(10);
  1522. $activeWorksheet->getColumnDimension('B')->setWidth(30);
  1523. $activeWorksheet->getColumnDimension('C')->setWidth(30);
  1524. $activeWorksheet->getColumnDimension('D')->setWidth(30);
  1525. $activeWorksheet->getColumnDimension('E')->setWidth(10);
  1526. $activeWorksheet->getColumnDimension('F')->setWidth(10);
  1527. $activeWorksheet->getColumnDimension('G')->setWidth(10);
  1528. $activeWorksheet->getColumnDimension('H')->setWidth(20);
  1529. $activeWorksheet->getColumnDimension('I')->setWidth(20);
  1530. $activeWorksheet->getColumnDimension('J')->setWidth(30);
  1531. $activeWorksheet->getStyle('A' . ($idx - 1) . ':J' . ($idx - 1))->getFont()->setBold(true);
  1532. $filename = 'prima_nota_' . date("YmdHis") . '.xlsx';
  1533. Log::info('exportWithData: Preparing to save file', [
  1534. 'filename' => $filename,
  1535. //'total_processing_time' => microtime(true) - $startTime,
  1536. 'memory_before_save' => memory_get_usage(true)
  1537. ]);
  1538. try {
  1539. $currentClient = session('currentClient', 'default');
  1540. $tempPath = sys_get_temp_dir() . '/' . $filename;
  1541. $writer = new Xlsx($spreadsheet);
  1542. $writer->save($tempPath);
  1543. unset($spreadsheet, $activeWorksheet, $writer);
  1544. gc_collect_cycles();
  1545. Log::info('exportWithData: Uploading to S3');
  1546. $disk = Storage::disk('s3');
  1547. $s3Path = $currentClient . '/prima_nota/' . $filename;
  1548. $primaNotaFolderPath = $currentClient . '/prima_nota/.gitkeep';
  1549. if (!$disk->exists($primaNotaFolderPath)) {
  1550. $disk->put($primaNotaFolderPath, '');
  1551. }
  1552. $uploadStart = microtime(true);
  1553. $fileContent = file_get_contents($tempPath);
  1554. $uploaded = $disk->put($s3Path, $fileContent, 'private');
  1555. $uploadTime = microtime(true) - $uploadStart;
  1556. if (!$uploaded) {
  1557. throw new \Exception('Failed to upload file to Wasabi S3');
  1558. }
  1559. Log::info("Export completed successfully", [
  1560. 'client' => $currentClient,
  1561. 'path' => $s3Path,
  1562. 'file_size' => filesize($tempPath),
  1563. 'records_processed' => $recordsProcessed,
  1564. 'upload_time' => $uploadTime,
  1565. 'total_time' => microtime(true) - $startTime,
  1566. 'memory_peak' => memory_get_peak_usage(true)
  1567. ]);
  1568. if (file_exists($tempPath)) {
  1569. unlink($tempPath);
  1570. }
  1571. $downloadUrl = $disk->temporaryUrl($s3Path, now()->addHour());
  1572. return redirect($downloadUrl);
  1573. } catch (\Exception $e) {
  1574. Log::error('Export S3 error - falling back to local', [
  1575. 'error' => $e->getMessage(),
  1576. 'trace' => $e->getTraceAsString(),
  1577. 'client' => session('currentClient', 'unknown'),
  1578. 'filename' => $filename,
  1579. 'records_processed' => $recordsProcessed ?? 0,
  1580. 'time_elapsed' => microtime(true) - $startTime
  1581. ]);
  1582. // Fallback logic remains the same...
  1583. $currentClient = session('currentClient', 'default');
  1584. $clientFolder = storage_path('app/prima_nota/' . $currentClient);
  1585. if (!is_dir($clientFolder)) {
  1586. mkdir($clientFolder, 0755, true);
  1587. Log::info("Created local client prima_nota folder: {$clientFolder}");
  1588. }
  1589. $localPath = $clientFolder . '/' . $filename;
  1590. if (isset($tempPath) && file_exists($tempPath)) {
  1591. rename($tempPath, $localPath);
  1592. } else {
  1593. $writer = new Xlsx($spreadsheet);
  1594. $writer->save($localPath);
  1595. unset($spreadsheet, $activeWorksheet, $writer);
  1596. }
  1597. gc_collect_cycles();
  1598. Log::warning("Export saved locally due to S3 error", [
  1599. 'client' => $currentClient,
  1600. 'local_path' => $localPath,
  1601. 'error' => $e->getMessage()
  1602. ]);
  1603. session()->flash('warning', 'File salvato localmente a causa di un errore del cloud storage.');
  1604. return response()->download($localPath)->deleteFileAfterSend();
  1605. }
  1606. }
  1607. }