diff --git a/src/app/Console/Commands/Data/Reports/VatCommand.php b/src/app/Console/Commands/Data/Reports/VatCommand.php index 195f8dcb..7f5bdcdc 100644 --- a/src/app/Console/Commands/Data/Reports/VatCommand.php +++ b/src/app/Console/Commands/Data/Reports/VatCommand.php @@ -1,98 +1,120 @@ argument('email'); + $period = $this->argument('period'); + + // Note: Carbon constructor takes care of date, but startOfDay() takes care of time + + if (empty($period)) { + // By default, report for the last month + $start = (new Carbon('first day of last month'))->startOfDay(); + $end = $start->copy()->endOfMonth(); + $period = $start->format('Y-m'); + } elseif (preg_match('|^(\d{4})-(\d{2})$|', $period, $matches)) { + // Report for specific month (YYYY-MM) + $start = (new Carbon("{$period}-01"))->startOfDay(); + $end = $start->copy()->endOfMonth(); + } elseif (preg_match('|^(\d{4})$|', $period, $matches)) { + // Report for specific year (YYYY) + $start = (new Carbon("first day of January {$period}"))->startOfDay(); + $end = $start->copy()->endOfYear(); + } else { + $this->error("Invalid 'period' format"); + exit(1); + } - // Note: Constructor takes care of date, but startOfDay()/endOfDay() takes care of time - $start = (new Carbon('first day of last month'))->startOfDay(); - $end = (new Carbon('last day of last month'))->endOfDay(); + $this->period = $period; $result = DB::select( <<= ? AND p.created_at <= ? ORDER BY timestamp, country SQL, [$start->toDateTimeString(), $end->toDateTimeString()] ); $fp = fopen('php://memory', 'w'); foreach ($result as $record) { fputcsv($fp, (array) $record); } rewind($fp); $csv = stream_get_contents($fp); fclose($fp); $this->sendMail($recipient, $csv); } /** * Sends an email message with csv file attached */ protected function sendMail($recipient, $csv) { $plainBody = 'See the attached report!'; + $filename = "Report-{$this->period}.csv"; - $attachment = Attachment::fromData(fn () => $csv, 'Report.csv')->withMime('text/csv'); + $attachment = Attachment::fromData(fn () => $csv, $filename)->withMime('text/csv'); $mail = new \App\Mail\Mailable(); $mail->subject('VAT Report') // This hack allows as to use plain text body instead of a Laravel view ->text(new \Illuminate\Support\HtmlString($plainBody)) ->to($recipient) ->attach($attachment); \App\Mail\Helper::sendMail($mail); } }