<?php
namespace App\Services;
use App\Line;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Storage;
class LinesCsv
{
const AUTO = '<AUTO>';
const DOCUMENT_TYPE = 20;
const DELIMITER = ';';
public function exportCSVFileToSftp($filename = 'export.csv')
{
$handle = fopen('php://temp', 'w');
$handle = $this->buildCsv($handle);
return Storage::disk('sftp')->put($filename, $handle);
}
public function exportCSVFileToResponse($filename = 'export.csv')
{
return new StreamedResponse(function () use ($filename) {
$handle = fopen('php://output', 'w');
$handle = $this->buildCsv($handle);
fclose($handle);
}, 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="' . $filename . '"',
]);
}
public function buildCsv($handle, $header = false)
{
if ($header) {
fputcsv(
$handle,
array_keys($this->lineMapping(Line::first())),
self::DELIMITER
);
}
Line::with(['invoice', 'invoice.customer', 'item'])
->whereHas('invoice', function ($query) {
$query->where('is_exportable', 1);
})
->chunk(200, function ($lines) use ($handle) {
foreach ($lines as $line) {
fputcsv(
$handle,
$this->lineMapping($line),
self::DELIMITER
);
}
});
return $handle;
}
protected function lineMapping(Line $line)
{
return [
'Invoice number' => $line->invoice->id ?? "<NEW>",
'Document type' => self::DOCUMENT_TYPE,
'Date' => $line->invoice->date,
];
}
}