@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Exports only the already authorised projection, without reading other sources. */
|
||||
class ProcurementReviewCsv
|
||||
{
|
||||
/** @param array<string,mixed> $report */
|
||||
public function render(array $report): string
|
||||
{
|
||||
$file = fopen('php://temp', 'w+');
|
||||
if ($file === false) {
|
||||
throw new \RuntimeException('Não foi possível preparar a exportação.');
|
||||
}
|
||||
$write = static function (array $cells) use ($file): void {
|
||||
$safe = array_map(static function (mixed $value): string {
|
||||
$text = $value === null ? 'Não disponível' : (is_bool($value) ? ($value ? 'Sim' : 'Não') : (string) $value);
|
||||
|
||||
return preg_match('/^[\s\x00-\x1F]*[=+\-@]/u', $text) ? "'".$text : $text;
|
||||
}, $cells);
|
||||
if (fputcsv($file, $safe, ';', '"', '') === false) {
|
||||
throw new \RuntimeException('Não foi possível escrever a exportação.');
|
||||
}
|
||||
};
|
||||
$fields = static function (string $section, string $reference, array $source, array $labels) use ($write): void {
|
||||
foreach ($labels as $key => $label) {
|
||||
$write([$section, $reference, $label, $source[$key] ?? null]);
|
||||
}
|
||||
};
|
||||
try {
|
||||
fwrite($file, "\xEF\xBB\xBF");
|
||||
$write(['Secção', 'Registo', 'Campo', 'Valor']);
|
||||
$fields('Consulta', '', $report, ['company' => 'Empresa', 'generated_at' => 'Consultado em', 'generated_by' => 'Consultado por']);
|
||||
$write(['Consulta', '', 'Natureza', 'Consulta actual; não constitui decisão, assinatura ou autorização financeira.']);
|
||||
$fields('Pedido', '', $report['requisition'], ['id' => 'Identificador', 'number' => 'Referência', 'status' => 'Estado', 'justification' => 'Fundamentação', 'department' => 'Departamento', 'requester' => 'Solicitante']);
|
||||
$comparison = $report['comparison'];
|
||||
$fields('Comparação actual', '', $comparison, ['ready' => 'Comparação completa', 'top_count' => 'Propostas com maior pontuação']);
|
||||
$fields('Regra de comparação', '', $comparison['policy'], ['revision' => 'Versão', 'configured' => 'Configuração explícita', 'minimum_proposals' => 'Mínimo de propostas', 'minimum_evaluators' => 'Mínimo de avaliadores']);
|
||||
$criteria = ['price' => 'Preço', 'quality' => 'Qualidade', 'delivery' => 'Entrega', 'history' => 'Histórico', 'payment' => 'Pagamento'];
|
||||
$fields('Ponderações da regra (%)', '', $comparison['policy']['weights'], $criteria);
|
||||
foreach ($comparison['rows'] as $row) {
|
||||
$ref = (string) $row['id'];
|
||||
$fields('Proposta actual', $ref, $row, ['reference' => 'Referência', 'supplier' => 'Fornecedor', 'currency' => 'Moeda', 'subtotal_minor' => 'Subtotal (centavos)', 'tax_minor' => 'IVA (centavos)', 'total_minor' => 'Total (centavos)', 'delivery_days' => 'Prazo de entrega (dias)', 'valid_until' => 'Válida até', 'eligible' => 'Elegível na consulta', 'evaluation_count' => 'Avaliações elegíveis', 'score_minor' => 'Pontuação (centésimos de 10)', 'is_top' => 'Maior pontuação numa comparação completa']);
|
||||
$fields('Ponderações da proposta (%)', $ref, $row['weights'], $criteria);
|
||||
if (isset($row['exchange_basis'])) {
|
||||
$fields('Taxa congelada da proposta', $ref, $row['exchange_basis'], ['id' => 'Registo da taxa', 'currency' => 'Moeda original', 'rate' => 'MZN por unidade original', 'quoted_on' => 'Data da taxa', 'source' => 'Fonte', 'recorded_by' => 'Registada por (utilizador)', 'rounding' => 'Arredondamento']);
|
||||
if ($row['reference_amounts'] !== null) {
|
||||
$fields('Referência em MZN', $ref, $row['reference_amounts'], ['subtotal_minor' => 'Subtotal (centavos MZN)', 'tax_minor' => 'IVA (centavos MZN)', 'total_minor' => 'Total (centavos MZN)']);
|
||||
}
|
||||
}
|
||||
foreach ($row['ineligibility_reasons'] as $reason) {
|
||||
$write(['Proposta actual', $ref, 'Motivo de inelegibilidade', $reason]);
|
||||
}
|
||||
if ($row['commercial_terms'] !== null) {
|
||||
$terms = $row['commercial_terms'];
|
||||
$fields('Condições económicas', $ref, $terms, ['version' => 'Versão', 'discount_basis' => 'Base do desconto', 'rounding' => 'Arredondamento']);
|
||||
foreach ($terms['lines'] as $line) {
|
||||
$fields('Desconto por linha', $ref.':'.$line['requisition_item_id'], $line, ['gross_unit_minor' => 'Preço unitário antes do desconto (centavos)', 'discount_type' => 'Tipo', 'discount_value' => 'Valor informado', 'net_unit_minor' => 'Preço unitário líquido (centavos)']);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['admission' => 'Regime de admissão', 'recommendation' => 'Regime de recomendação'] as $key => $section) {
|
||||
$record = $report[$key];
|
||||
$write([$section, '', 'Adopção registada', $record !== null]);
|
||||
if ($record !== null) {
|
||||
$fields($section, (string) $record['id'], $record, ['revision' => 'Versão', 'reason' => 'Fundamentação']);
|
||||
$fields($section, (string) $record['id'], $record['snapshot'], ['policy_revision' => 'Versão da política', 'required_count' => 'Confirmações independentes']);
|
||||
foreach ($record['snapshot']['roles'] as $role) {
|
||||
$write([$section, (string) $record['id'], 'Função prevista', $role]);
|
||||
}
|
||||
}
|
||||
}
|
||||
$qualification = $report['qualification'];
|
||||
$write(['Qualificação documental', '', 'Versão registada', $qualification !== null]);
|
||||
if ($qualification !== null) {
|
||||
$ref = (string) $qualification['id'];
|
||||
$fields('Qualificação documental', $ref, $qualification, ['revision' => 'Versão', 'created_at' => 'Registada em', 'author' => 'Autor', 'reason' => 'Fundamentação', 'is_current' => 'Base corresponde às propostas actuais']);
|
||||
foreach ($qualification['criteria'] as $criterion) {
|
||||
$fields('Requisito documental', $ref.':'.$criterion['id'], $criterion, ['label' => 'Requisito', 'category' => 'Categoria', 'required' => 'Obrigatório']);
|
||||
}
|
||||
foreach ($qualification['proposals'] as $proposal) {
|
||||
$fields('Proposta na qualificação', (string) $proposal['id'], $proposal, ['reference' => 'Referência preservada', 'supplier' => 'Fornecedor preservado']);
|
||||
foreach ($proposal['analyses'] as $analysis) {
|
||||
$ref = $proposal['id'].':'.$analysis['id'];
|
||||
$fields('Análise documental', $ref, $analysis, ['revision' => 'Versão', 'created_at' => 'Registada em', 'reason' => 'Fundamentação']);
|
||||
$fields('Analista preservado', $ref, $analysis['analyst'], ['name' => 'Nome', 'profile_label' => 'Perfil', 'purchasing_role' => 'Função']);
|
||||
foreach ($analysis['answers'] as $answer) {
|
||||
$fields('Resposta documental', $ref.':'.$answer['criterion_id'], $answer, ['result' => 'Resultado', 'evidence' => 'Evidência', 'reason' => 'Fundamentação']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['opening' => 'Abertura', 'award' => 'Adjudicação', 'order' => 'Ordem'] as $key => $section) {
|
||||
$record = $report[$key];
|
||||
$write([$section, '', 'Registo disponível', $record !== null]);
|
||||
if ($record !== null) {
|
||||
$fields($section, (string) $record['id'], $record, match ($key) {
|
||||
'opening' => ['revision' => 'Versão', 'reference' => 'Referência', 'source_changed' => 'Base difere das propostas actuais'],
|
||||
'award' => ['status' => 'Estado', 'total_minor' => 'Total (centavos)'],
|
||||
default => ['number' => 'Referência', 'currency' => 'Moeda', 'total_minor' => 'Total (centavos)'],
|
||||
});
|
||||
}
|
||||
}
|
||||
$fulfilment = $report['fulfilment'];
|
||||
$write(['Recepções', '', 'Registos disponíveis', count($fulfilment['receipts'])]);
|
||||
foreach ($fulfilment['receipts'] as $receipt) {
|
||||
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia']);
|
||||
}
|
||||
$write(['Execução financeira', '', 'Consulta autorizada', $fulfilment['finance_visible']]);
|
||||
if ($fulfilment['finance_visible']) {
|
||||
foreach (['invoices' => 'Factura', 'payments' => 'Pagamento externo'] as $key => $section) {
|
||||
$write([$section, '', 'Registos disponíveis', count($fulfilment[$key])]);
|
||||
foreach ($fulfilment[$key] as $record) {
|
||||
$fields($section, (string) $record['id'], $record, $key === 'invoices'
|
||||
? ['number' => 'Referência', 'status' => 'Estado', 'issued_on' => 'Emitida em', 'total_minor' => 'Total (centavos)', 'currency' => 'Moeda']
|
||||
: ['invoice_id' => 'Factura de origem', 'status' => 'Estado', 'paid_on' => 'Data informada', 'amount_minor' => 'Montante (centavos)', 'currency' => 'Moeda']);
|
||||
}
|
||||
}
|
||||
}
|
||||
rewind($file);
|
||||
$content = stream_get_contents($file);
|
||||
if ($content === false) {
|
||||
throw new \RuntimeException('Não foi possível ler a exportação.');
|
||||
}
|
||||
|
||||
return $content;
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user