RprtCli/app/src/Commands/InvoiceCommand.php

374 lines
12 KiB
PHP
Raw Normal View History

<?php
2021-09-20 01:08:42 +02:00
declare(strict_types=1);
2022-05-11 19:43:05 +02:00
// src/Commands/InvoiceCommand.php;
namespace RprtCli\Commands;
use Exception;
2021-04-05 17:20:59 +02:00
use RprtCli\Utils\Configuration\ConfigurationInterface;
use RprtCli\Utils\CsvReport\ReportCsvInterface;
use RprtCli\Utils\Mailer\MailerInterface;
2021-09-21 01:13:15 +02:00
use RprtCli\Utils\PdfExport\PdfExportInterface;
2021-09-20 01:08:42 +02:00
use RprtCli\Utils\TimeTrackingServices\YoutrackInterface;
use RprtCli\ValueObjects\Expenses;
use RprtCli\ValueObjects\WorkInvoiceElement;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Helper\TableCell;
use Symfony\Component\Console\Helper\TableSeparator;
2021-09-20 01:08:42 +02:00
use Symfony\Component\Console\Input\InputInterface;
2021-04-05 16:23:06 +02:00
use Symfony\Component\Console\Input\InputOption;
2021-09-20 01:08:42 +02:00
use Symfony\Component\Console\Output\OutputInterface;
use function array_merge;
use function explode;
use function is_array;
use function is_null;
use function is_string;
use function readline;
use function strpos;
use function strtolower;
2023-01-02 22:03:59 +01:00
use function sys_get_temp_dir;
2021-09-20 01:08:42 +02:00
use function var_dump;
use function var_export;
// use Symfony\Contracts\Translation\TranslatorInterface;
2021-09-20 01:08:42 +02:00
/**
2022-05-11 19:43:05 +02:00
* Main file - invoice command.
2021-09-20 01:08:42 +02:00
*/
2023-01-02 15:18:52 +01:00
class InvoiceCommand extends Command
{
2023-01-01 23:41:40 +01:00
use SelectReportTrait;
protected ReportCsvInterface $csv;
2021-04-05 17:20:59 +02:00
protected ConfigurationInterface $config;
protected YoutrackInterface $trackingService;
protected PdfExportInterface $pdfExport;
protected MailerInterface $mailer;
2021-09-21 01:13:15 +02:00
2023-01-02 15:18:52 +01:00
protected const TYPE_WORK = 1;
protected const TYPE_EXPENSE = 2;
2021-09-20 01:08:42 +02:00
public function __construct(
ReportCsvInterface $csv,
2021-09-20 01:08:42 +02:00
ConfigurationInterface $configuration,
2023-01-01 23:41:40 +01:00
YoutrackInterface $trackingService,
2021-09-21 01:13:15 +02:00
PdfExportInterface $pdf_export,
MailerInterface $mailer,
2021-09-20 01:08:42 +02:00
?string $name = null
) {
2023-01-02 15:18:52 +01:00
$this->csv = $csv;
$this->config = $configuration;
$this->trackingService = $trackingService;
$this->pdfExport = $pdf_export;
$this->mailer = $mailer;
2021-09-20 01:08:42 +02:00
parent::__construct($name);
}
2021-04-05 16:23:06 +02:00
2021-09-20 01:08:42 +02:00
/**
* Get configuration.
*/
2023-01-02 22:03:59 +01:00
protected function configure() : void
2021-09-20 01:08:42 +02:00
{
2022-05-11 19:43:05 +02:00
$this->setName('invoice');
$this->setDescription('Generate an invoice from (monthly) report');
2021-09-20 01:08:42 +02:00
// @TODO $this->addUsage('');
// @TODO add sub options (config overrides)
2021-09-20 01:08:42 +02:00
$this->addOption(
'file',
'f',
InputOption::VALUE_REQUIRED,
'Specify the input csv file to generate report from.'
);
2023-01-01 23:41:40 +01:00
// $this->addOption(
// 'youtrack',
// 'y',
// InputOption::VALUE_NONE,
// 'Use youtrack api to get a report. If this option is used --file does not have any effect..'
// );
2021-09-20 01:08:42 +02:00
$this->addOption(
'pdf',
'p',
InputOption::VALUE_NONE,
'Create invoice pdf from template.'
);
$this->addOption(
'test',
2022-05-11 19:43:05 +02:00
'',
2021-09-20 01:08:42 +02:00
InputOption::VALUE_NONE,
'Test login into youtrack service. Prints out your name.'
2021-09-20 01:08:42 +02:00
);
$this->addOption(
'output',
'o',
InputOption::VALUE_REQUIRED,
'Provide output file path. This option overrides configuration.'
);
$this->addOption(
'send',
's',
InputOption::VALUE_NONE,
'Send pdf export via email to recipient.'
);
2021-10-03 16:45:40 +02:00
$this->addOption(
2022-05-02 13:42:41 +02:00
'recipients',
't',
2021-10-03 16:45:40 +02:00
InputOption::VALUE_REQUIRED,
'Comma separated list of recipients that should get the exported pdf.'
);
$this->addOption(
'expenses',
'e',
InputOption::VALUE_OPTIONAL,
2023-01-02 15:18:52 +01:00
// phpcs:ignore
'List of additional expenses in format expense1=value1;expenses2=value2... or empty for interactive output.',
false
);
$this->addOption(
'custom',
'c',
InputOption::VALUE_OPTIONAL,
2023-01-02 15:18:52 +01:00
// phpcs:ignore
'Additional custom work untracked in format: name1=time1;name2=time2... Project to assign work items to has to be configured in app config. Leave empty for interactive output.',
false
);
2022-05-02 13:42:41 +02:00
$this->addOption(
'list-reports',
'l',
InputOption::VALUE_NONE,
'List my reports'
);
$this->addOption(
'report',
'r',
2022-05-02 13:42:41 +02:00
InputOption::VALUE_OPTIONAL,
'Show time tracked for report.',
false
2022-05-02 13:42:41 +02:00
);
2021-04-05 16:23:06 +02:00
}
2023-01-02 22:03:59 +01:00
protected function execute(InputInterface $input, OutputInterface $output) : int
2021-09-20 01:08:42 +02:00
{
if ($input->getOption('test')) {
2023-01-01 23:41:40 +01:00
$test = $this->trackingService->testYoutrackapi();
2021-09-20 01:08:42 +02:00
$output->writeln($test);
}
2022-05-02 13:42:41 +02:00
if ($input->getOption('list-reports')) {
2023-01-01 23:41:40 +01:00
$list = $this->trackingService->listReports();
$output->writeln(var_export($list, true));
2022-05-15 13:04:50 +02:00
return Command::SUCCESS;
2022-05-02 13:42:41 +02:00
}
2023-01-01 23:41:40 +01:00
// Gets report parameter.
2023-01-02 15:18:52 +01:00
$file = $this->getReportCsvFilePath($input, $output, 'tracking_service.youtrack.invoice.report');
2023-01-01 23:41:40 +01:00
$report_name = $this->trackingService->getReportName();
2022-05-02 13:42:41 +02:00
if ($input->hasParameterOption('--expenses') || $input->hasParameterOption('-e')) {
$expenses = $this->getCustomWorkOrExpenses($input->getOption('expenses'), self::TYPE_EXPENSE);
}
2022-05-02 13:42:41 +02:00
if ($input->hasParameterOption('--custom') || $input->hasParameterOption('-c')) {
2023-01-01 23:41:40 +01:00
// @TODO Add option for custom time tracking data.
2022-05-02 13:42:41 +02:00
$custom = $this->getCustomWorkOrExpenses($input->getOption('custom'), self::TYPE_WORK);
}
2023-01-01 23:41:40 +01:00
$output->writeln("report: <info>{$report_name}</info>");
$data = $this->csv->getInvoiceData($file);
if (! empty($expenses)) {
$data = array_merge($data, $expenses);
}
$table = $this->getTable($output, $data);
$table->render();
if ($input->getOption('pdf')) {
$nice_data = $this->csv->arangeDataForDefaultPdfExport($data);
// @TODO method gatherTokens();
if ($out = $input->getOption('output')) {
$this->pdfExport->setOutput($out);
2021-09-21 01:13:15 +02:00
}
$output_path = $this->pdfExport->fromDefaultDataToPdf($nice_data) ?: sys_get_temp_dir();
2023-01-01 23:41:40 +01:00
// Notify the user where the file was generated to.
$output->writeln("The file was generated at <info>${output_path}</info>.");
}
if ($input->getOption('send') && isset($output_path)) {
// @TODO If no output path print an error.
// Send email to configured address.
if ($recipients = $input->getOption('recipients')) {
2021-10-03 16:45:40 +02:00
$this->mailer->setRecipients(explode(',', $recipients));
}
$this->mailer->sendDefaultMail($output_path);
2021-09-20 01:08:42 +02:00
}
// $this->dummyOutput($input, $output);
2021-09-20 01:08:42 +02:00
return Command::SUCCESS;
}
2023-01-02 22:03:59 +01:00
protected function getTable(OutputInterface $output, array $data) : Table
{
$rows = $this->csv->generateTable($data);
$table = new Table($output);
$table->setHeaders([
'Project',
'Hours',
'Rate',
'Price',
]);
foreach ($rows as $key => $row) {
if (! $row) {
$rows[$key] = new TableSeparator();
} elseif (is_array($row) && is_null($row[1]) && is_null($row[0])) {
// Check which elements in array are null.
$rows[$key] = [new TableCell($row[2], ['colspan' => 3]), $row[3]];
}
}
$table->setRows($rows);
return $table;
}
2021-04-08 19:23:19 +02:00
/**
* Create table from data that is already inline with configuration.
*
* @deprecated
* This method was almost exact copy of CsvReport::arangeDataForDefaultPdfExport
2021-04-08 19:23:19 +02:00
*/
2023-01-02 22:03:59 +01:00
protected function generateTable(OutputInterface $output, array $data) : Table
2021-09-20 01:08:42 +02:00
{
$table = new Table($output);
$table->setHeaders([
'Project',
'Hours',
'Rate',
'Price',
2021-09-20 01:08:42 +02:00
]);
[$rows, $totalHours, $totalPrice] = [[], 0, 0];
2023-01-01 23:41:40 +01:00
$projectsConfig = $this->config->get('projects');
2021-09-20 01:08:42 +02:00
foreach ($projectsConfig as $name => $config) {
if (! isset($data[$name])) {
// @TODO Proper error handling.
var_dump('Project ' . $name . ' is not set!');
continue;
}
$hours = $data[$name];
if ($config['time_format'] === 'm') {
$hours /= 60;
}
$price = $hours * (float) $config['price'];
2021-09-20 01:08:42 +02:00
$row = [
$config['name'],
$hours,
$config['price'],
$hours * $config['price'],
];
$rows[] = $row;
$totalHours += $hours;
$totalPrice += $price;
unset($data[$name]);
}
if (! empty($data)) {
foreach ($data as $name => $value) {
if (strpos(strtolower($name), 'expanses') !== false) {
}
}
2021-09-20 01:08:42 +02:00
}
2021-09-20 01:08:42 +02:00
$rows[] = new TableSeparator();
// @TODO Check rate in final result.
// $rows[] = [$this->translator->trans('Sum'), $totalHours, $config['price'], $totalPrice];
2023-01-02 22:03:59 +01:00
$rows[] = ['Sum', $totalHours, null, $totalPrice];
2021-09-20 01:08:42 +02:00
$table->setRows($rows);
return $table;
2021-04-05 16:23:06 +02:00
}
/**
* Dummy output for testing.
*/
2023-01-02 22:03:59 +01:00
protected function dummyOutput(InputInterface $input, OutputInterface $output) : void
2021-09-20 01:08:42 +02:00
{
// $txt = $this->translator->trans('From [start-date] to [end-date].', [], 'rprt', 'sl_SI');
// $output->writeln($txt);
$table = new Table($output);
$table->setHeaders(['Project', 'Hours', 'Price']);
$table->setRows([
['LDP', 100, 2600],
['WV', 50, 1300],
new TableSeparator(),
['Zusamen', 150, 3900],
]);
// $table->setStyle('borderless');
$table->render();
}
/**
* Gets the expenses array.
*
* @return Expenses[]
*/
protected function getExpenses($expenses)
{
$output = [];
if (is_string($expenses)) {
foreach (explode(';', $expenses) as $expense) {
[$name, $value] = explode('=', $expense);
$output[] = new Expenses($name, (float) $value);
}
} else {
$continue = true;
while ($continue) {
$name = readline('Enter expenses name or leave empty to stop: ');
$value = (float) readline('Enter expenses value: ');
if (! empty($name)) {
$output[] = new Expenses($name, $value);
} else {
$continue = false;
}
}
}
return $output;
}
protected function getCustomWorkOrExpenses(mixed $custom, int $type)
2023-01-02 15:18:52 +01:00
{
$output = [];
if (is_string($custom)) {
foreach (explode(';', $custom) as $item) {
[$name, $value] = explode('=', $item);
$output[] = $this->createInvoiceElement($name, (float) $value, $type);
}
} else {
$continue = true;
if ($type === self::TYPE_WORK) {
$message_name = 'Enter project name or leave empty to stop: ';
$message_value = 'Enter time spent of project: ';
} elseif ($type === self::TYPE_EXPENSE) {
$message_name = 'Enter expenses name or leave empty to stop: ';
$message_value = 'Enter expenses value: ';
2023-01-02 22:03:59 +01:00
} else {
throw new Exception('Unknown type of custom data.');
}
while ($continue) {
$name = readline($message_name);
$value = (float) readline($message_value);
if (! empty($name)) {
$output[] = $this->createInvoiceElement($name, $value, $type);
} else {
$continue = false;
}
}
}
return $output;
}
protected function createInvoiceElement(string $name, float $value, int $type)
{
if ($type === self::TYPE_WORK) {
return new WorkInvoiceElement($name, (float) $value);
} elseif ($type === self::TYPE_EXPENSE) {
return new Expenses($name, (float) $value);
}
throw new Exception('Unkown invoice element type.');
}
}