Skip to content

Commit

Permalink
Merge pull request #453 from RJ-SMTR/hotfix/385-financeiro-refatorar
Browse files Browse the repository at this point in the history
(prod) Hotfix/385-financeiro-refatorar
  • Loading branch information
williamfl2007 authored Sep 6, 2024
2 parents da0adc2 + 6497fc6 commit 91bc4d5
Show file tree
Hide file tree
Showing 17 changed files with 522 additions and 687 deletions.
49 changes: 15 additions & 34 deletions src/bank-statements/bank-statements.repository.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import { Injectable } from '@nestjs/common';
import { endOfDay, isFriday, nextFriday, nextThursday, startOfDay, subDays } from 'date-fns';
import { DetalheA } from 'src/cnab/entity/pagamento/detalhe-a.entity';
import { ArquivoPublicacaoService } from 'src/cnab/service/arquivo-publicacao.service';
import { DetalheAService } from 'src/cnab/service/pagamento/detalhe-a.service';
import { TransacaoViewService } from 'src/transacao-bq/transacao-view.service';
import { Ocorrencia } from 'src/cnab/entity/pagamento/ocorrencia.entity';
import { TicketRevenuesService } from 'src/ticket-revenues/ticket-revenues.service';
import { User } from 'src/users/entities/user.entity';
import { formatDateYMD } from 'src/utils/date-utils';
import { TimeIntervalEnum } from 'src/utils/enums/time-interval.enum';
import { getPagination } from 'src/utils/get-pagination';
import { PaginationOptions } from 'src/utils/types/pagination-options';
import { Pagination } from 'src/utils/types/pagination.type';
import { In } from 'typeorm';
import { BankStatementPreviousDaysDTO } from './dtos/bank-statement-previous-days.dto';
import { BankStatementDTO } from './dtos/bank-statement.dto';
import { IBSCounts } from './interfaces/bs-counts.interface';
Expand All @@ -22,11 +19,7 @@ import { IBSGetMePreviousDaysResponse } from './interfaces/bs-get-me-previous-da
*/
@Injectable()
export class BankStatementsRepositoryService {
constructor(
private readonly transacaoViewService: TransacaoViewService, //
private readonly detalheAService: DetalheAService,
private arquivoPublicacaoService: ArquivoPublicacaoService,
) {}
constructor(private readonly ticketRevenuesService: TicketRevenuesService) {}

/**
* Parâmetros validados:
Expand Down Expand Up @@ -78,7 +71,6 @@ export class BankStatementsRepositoryService {
*
* Requisitos:
* - Mostra sempre as transações individuais
* -
*/
private async buildPreviousDays(validArgs: {
user: User; //
Expand All @@ -105,37 +97,26 @@ export class BankStatementsRepositoryService {
endDate = qua;
}

const transacoes = await this.transacaoViewService.findPreviousDays({
startDate: startDate,
endDate: endDate,
cpfCnpjs: [validArgs.user.getCpfCnpj()],
});
const publicacoes = await this.arquivoPublicacaoService.findMany({ where: { itemTransacao: { itemTransacaoAgrupado: { id: In(transacoes.map((t) => t.itemTransacaoAgrupadoId)) } } } });
const revenues = transacoes.map((i) => i.toTicketRevenue(publicacoes));
const detalhesA = await this.detalheAService.findMany({
itemTransacaoAgrupado: {
id: In(revenues.map((i) => i.arquivoPublicacao?.itemTransacao.itemTransacaoAgrupado.id)),
},
});
const revenues = await this.ticketRevenuesService.findManyIndividual({ startDate, endDate, cpfCnpj: [validArgs.user.getCpfCnpj()], previousDays: true });

// Gerar BankStatements
const statements = revenues.map((item, index) => {
const isPago = item.arquivoPublicacao?.isPago;
const amount = Number((item.transactionValue || 0).toFixed(2));
const paidAmount = Number(item.paidValue.toFixed(2));
const statements = revenues.map((revenue, index) => {
const isPago = revenue.isPago;
const amount = Number((revenue.transactionValue || 0).toFixed(2));
const paidAmount = Number(revenue.paidValue.toFixed(2));
const ticketCount = 1;
const foundDetalhesA = detalhesA.filter((i) => i.itemTransacaoAgrupado.id === item.arquivoPublicacao?.itemTransacao.itemTransacaoAgrupado.id);
const errors = DetalheA.getOcorrenciaErrors(foundDetalhesA);
const orderDate = nextThursday(startOfDay(new Date(item.processingDateTime)));
// const foundDetalhesA = detalhesA.filter((i) => i.itemTransacaoAgrupado.id === item.arquivoPublicacao?.itemTransacao.itemTransacaoAgrupado.id);
const errors = Ocorrencia.getErrors(revenue.ocorrencias);
const orderDate = nextThursday(startOfDay(new Date(revenue.processingDateTime)));
const status = !errors.length ? (amount ? (isPago ? 'Pago' : 'A pagar') : null) : 'Pendente';
const dataEfetivacao = item.arquivoPublicacao?.dataEfetivacao;
const dataEfetivacao = revenue.dataEfetivacao;
return new BankStatementPreviousDaysDTO({
id: index + 1,
date: formatDateYMD(new Date(String(item.processingDateTime))),
date: formatDateYMD(new Date(String(revenue.processingDateTime))),
effectivePaymentDate: isPago && dataEfetivacao ? formatDateYMD(new Date(dataEfetivacao)) : null,
paymentOrderDate: formatDateYMD(orderDate),
transactionDate: formatDateYMD(new Date(item.transactionDateTime)),
processingDate: formatDateYMD(new Date(item.processingDateTime)),
transactionDate: formatDateYMD(new Date(revenue.transactionDateTime)),
processingDate: formatDateYMD(new Date(revenue.processingDateTime)),
cpfCnpj: validArgs.user.getCpfCnpj(),
permitCode: validArgs.user.getPermitCode(),
amount: amount,
Expand Down
2 changes: 1 addition & 1 deletion src/bank-statements/bank-statements.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Provider } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { BigqueryService } from 'src/bigquery/bigquery.service';
import { TicketRevenuesGroupDto } from 'src/ticket-revenues/dtos/ticket-revenues-group.dto';
import { TicketRevenuesRepositoryService } from 'src/ticket-revenues/ticket-revenues-repository';
import { TicketRevenuesRepositoryService } from 'src/ticket-revenues/ticket-revenues.repository';
import { TicketRevenuesService } from 'src/ticket-revenues/ticket-revenues.service';
import { User } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
Expand Down
2 changes: 1 addition & 1 deletion src/cnab/cnab.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ export class CnabService {

async updateTransacaoViewBigqueryLimit(trsBq: BigqueryTransacao[], queryRunner: QueryRunner, idTransacao: string[] = []) {
const trsFilter = idTransacao.length ? trsBq.filter((i) => idTransacao.includes(i.id_transacao)) : trsBq;
const existings = await this.transacaoViewService.findRaw({ idTransacao: trsFilter.map((tv) => tv.id_transacao) });
const existings = await this.transacaoViewService.findRaw({ where: {idTransacao: trsFilter.map((tv) => tv.id_transacao)} });
const response = { updated: 0, created: 0, deduplicated: 0 };
for (const trBq of trsFilter) {
const transacaoViewBq = TransacaoView.fromBigqueryTransacao(trBq);
Expand Down
6 changes: 5 additions & 1 deletion src/cnab/entity/pagamento/ocorrencia.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export class Ocorrencia extends EntityHelper {
return ocorrencias;
}

public static getErrorCodes(ocorrencias: Ocorrencia[]) {
public static getErrorCodes(ocorrencias: Ocorrencia[]): string[] {
const codesList = ocorrencias.map((o) => o.code);
const errors = codesList.filter((c) => !['00', 'BD'].includes(c));
return errors;
Expand Down Expand Up @@ -121,4 +121,8 @@ export class Ocorrencia extends EntityHelper {
const code = ocorrencia?.code;
return code && !['BD', '00'].includes(code);
}

public static getErrors(ocorrencias: Ocorrencia[]) {
return ocorrencias.filter(o => Ocorrencia.isError(o));
}
}
151 changes: 28 additions & 123 deletions src/ticket-revenues/dtos/ticket-revenue.dto.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
// @Exclude({ toPlainOnly: true })

import { Exclude } from 'class-transformer';
import { ArquivoPublicacao } from 'src/cnab/entity/arquivo-publicacao.entity';
import { ItemTransacaoAgrupado } from 'src/cnab/entity/pagamento/item-transacao-agrupado.entity';
import { Ocorrencia } from 'src/cnab/entity/pagamento/ocorrencia.entity';

/**
* Internal representation of `IBqApiTicketRevenues`
Expand All @@ -15,14 +14,17 @@ export class TicketRevenueDTO {
constructor(dto?: TicketRevenueDTO) {
if (dto) {
Object.assign(this, dto);
this.isPago = Boolean(this.arquivoPublicacao?.isPago || this.isPago || this.paidValue === 0);
this.isPago = Boolean(this.isPago);
if (this.ocorrencias.length) {
this.ocorrencias = this.ocorrencias.map((o) => new Ocorrencia(o));
}
}
}

/**
* Para o frontend exibir o número de passagens arrecadadas - individual é sempre 1
*/
count: number;
count: number = 1;

/**
* Represents `data`
Expand Down Expand Up @@ -73,51 +75,15 @@ export class TicketRevenueDTO {
* @description Timestamp de captura em GMT-3 (formato YYYY-MM-dd HH:mm:ssTZD)
* @example '2023-09-12 14:49:00-03:00'
*/
captureDateTime: string | null;
captureDateTime: string | null = null;

/**
* Represents `modo`
*
* @description Tipo de transporte
* @options 'BRT', 'Ônibus', 'Van', 'VLT'
*/
transportType: string | null;

/**
* Represents `servico`
*
* @description Nome curto da linha operada pelo veículo com variação de serviço (ex: 010, 011SN, ...)
* @example '010', '011SN'
*/
vehicleService: string | null;

/**
* Represents `sentido`
*
* GTFS `direction_id`
*
* @description Sentido de operação do serviço (0 = ida, 1 = volta)
* @example '0', '1'
*/
directionId: number | null;

/**
* **Important field**
*
* Represents `id_veiculo`
*
* @description Identificador único do veículo
*/
vehicleId: string | null;

/**
* Represents `id_cliente`
*
* @description Identificador único do cliente
* @example '3'
*/
clientId: string | null;

transportType: string | null = null;
/**
* **Important field**
*
Expand Down Expand Up @@ -160,95 +126,34 @@ export class TicketRevenueDTO {
*/
transportIntegrationType: string | null;

/**
* [WIP] **Dont use it!** Currently in progress by bigquery team
*
* Represents `id_integracao`
*
* @description Tipo da integração realizada (identificador relacionado à matriz de integração)
* @type `string | null`
*/
integrationId: string | null;

/**
* **Important field**
*
* Represents `latitude`
*
* @description Latitude da transação (WGS84)
* @type `float | null`
*/
transactionLat: number | null;

/**
* **Important field**
*
* Represents `longitude`
*
* @description Longitude da transação (WGS84)
* @type `float | null`
*/
transactionLon: number | null;

/**
* **Important field**
*
* Represents `stop_id`
*
* @description Código identificador do ponto de embarque (GTFS)
* @type `float | null`
*/
stopId: number | null;

/**
* **Important field**
*
* Represents `stop_lat`
*
* @description Latitude do ponto de embarque (GTFS)
* @type `float | null`
*/
stopLat: number | null;

/**
* **Important field**
*
* Represents `stop_lon`
*
* @description Longitude do ponto de embarque (GTFS)
* @type `float | null`
*/
stopLon: number | null;

/**
* Valor bruto.
*
* Represents `valor_transacao`
*
* @description Valor debitado na transação atual (R$)
* @type `float | null`
*/
/** Valor bruto debitado na transação atual (R$) */
transactionValue: number | null;

/** Valor a ser pago - valor líquido calculado
* Não significa que foi pago
/**
* Valor a ser pago - valor líquido calculado.
*
* Se não houve pagamento o valor também é zero.
*/
paidValue: number;

/**
* Represents `versao`
*
* @description Código de controle de versão do dado (SHA Github)
* @example
*/
@Exclude()
bqDataVersion: string | null;

/** arquivoPublicacao.isPago */
isPago = false;

/** arquivoPublicacao.dataEfetivacao */
dataEfetivacao: Date;

/** DetalheA.ocorrenciasCnab */
@Exclude()
arquivoPublicacao?: ArquivoPublicacao;
ocorrenciasCnab?: string;

/** DetalheA->Ocorrencias */
@Exclude()
itemTransacaoAgrupadoId?: number;
ocorrencias: Ocorrencia[] = [];

/**
* Apenas soma se status = pago
*/
public static getAmountSum<T extends TicketRevenueDTO>(data: T[]): number {
return +data.reduce((sum, i) => sum + (i.transactionValue || 0), 0).toFixed(2);
}
}
Loading

0 comments on commit 91bc4d5

Please sign in to comment.