Skip to content

Commit

Permalink
Merge pull request #460 from RJ-SMTR/feat/234-lancamento
Browse files Browse the repository at this point in the history
fix: show VLT, sort by name
  • Loading branch information
yxuo authored Sep 10, 2024
2 parents 312d756 + 7b0bf6c commit 92b0ae8
Show file tree
Hide file tree
Showing 142 changed files with 3,163 additions and 2,546 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/cd.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ on:
push:
branches:
- "main"
paths-ignore:
- 'README.md'
- 'docs'

env:
PROJECT_ID: ${{ secrets.GKE_PROJECT }}
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/cd_stag.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ on:
- "release/*"
- "devops"
- "develop"
paths-ignore:
- 'README.md'
- 'docs'

env:
PROJECT_ID: ${{ secrets.GKE_PROJECT }}
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ on:
branches: [develop]
pull_request:
branches: [develop]
paths-ignore:
- 'README.md'
- 'docs'

jobs:
lint:
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/docker-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ on:
branches: [main]
pull_request:
branches: [main]
paths-ignore:
- 'README.md'
- 'docs'

jobs:
build:
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "api-cct",
"version": "0.12.6",
"version": "0.13.1",
"description": "",
"author": "",
"private": true,
Expand Down
4 changes: 2 additions & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ import { SftpModule } from './sftp/sftp.module';
import { TestModule } from './test/test.module';
import { TicketRevenuesModule } from './ticket-revenues/ticket-revenues.module';
import { UsersModule } from './users/users.module';
import { TransacaoViewService } from './transacao-bq/transacao-view.service';
import { TransacaoViewModule } from './transacao-bq/transacao-view.module';
import { TransacaoViewService } from './transacao-view/transacao-view.service';
import { TransacaoViewModule } from './transacao-view/transacao-view.module';
import { AppLoggerMiddleware } from './utils/logger-middleware';
import { RelatorioModule } from './relatorio/relatorio.module';
import { AppService } from './app.service';
Expand Down
12 changes: 5 additions & 7 deletions src/bank-statements/bank-statements.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { TimeIntervalEnum } from 'src/utils/enums/time-interval.enum';
import { getPagination } from 'src/utils/get-pagination';
import { IRequest } from 'src/utils/interfaces/request.interface';
import { ParseNumberPipe } from 'src/utils/pipes/parse-number.pipe';
import { ValidateEnumPipe } from 'src/utils/pipes/validate-enum.pipe';
import { ParseEnumPipe } from 'src/utils/pipes/parse-enum.pipe';
import { DateQueryParams } from 'src/utils/query-param/date.query-param';
import { PaginationQueryParams } from 'src/utils/query-param/pagination.query-param';
import { getRequestLog } from 'src/utils/request-utils';
Expand Down Expand Up @@ -60,12 +60,10 @@ export class BankStatementsController {
@ApiQuery(CommonApiParams.userId)
@HttpCode(HttpStatus.OK)
async getMe(
@Request() request: IRequest,
@Request() request: IRequest, //
@Query(...DateQueryParams.yearMonth) yearMonth: string,
@Query('timeInterval', new ValidateEnumPipe(BSMeTimeIntervalEnum, false, BSMeTimeIntervalEnum.LAST_MONTH))
timeInterval?: BSMeTimeIntervalEnum | undefined,
@Query('userId', new ParseNumberPipe({ min: 1, optional: true }))
userId?: number | null,
@Query('timeInterval', new ParseEnumPipe(BSMeTimeIntervalEnum, { optional: true, defaultValue: BSMeTimeIntervalEnum.LAST_MONTH })) timeInterval: BSMeTimeIntervalEnum | undefined,
@Query('userId', new ParseNumberPipe({ min: 1, optional: true })) userId?: number | null,
): Promise<IBSGetMeResponse> {
this.logger.log(getRequestLog(request));

Expand Down Expand Up @@ -118,7 +116,7 @@ export class BankStatementsController {
@Query(...PaginationQueryParams.page) page: number,
@Query(...PaginationQueryParams.limit) limit: number,
@Query('endDate', new ParseDatePipe()) endDate: string,
@Query('timeInterval', new ValidateEnumPipe(BSMePrevDaysTimeIntervalEnum, true)) timeInterval: BSMePrevDaysTimeIntervalEnum,
@Query('timeInterval', new ParseEnumPipe(BSMePrevDaysTimeIntervalEnum)) timeInterval: BSMePrevDaysTimeIntervalEnum,
@Query('userId', new ParseNumberPipe({ min: 1, optional: true })) userId?: number | null,
): Promise<Pagination<IBSGetMePreviousDaysResponse>> {
const isUserIdParam = userId !== null && !isNaN(Number(userId));
Expand Down
2 changes: 1 addition & 1 deletion src/bank-statements/bank-statements.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { BankStatementsRepositoryService } from './bank-statements.repository';
import { BankStatementsController } from './bank-statements.controller';
import { BankStatementsService } from './bank-statements.service';
import { CnabModule } from 'src/cnab/cnab.module';
import { TransacaoViewModule } from 'src/transacao-bq/transacao-view.module';
import { TransacaoViewModule } from 'src/transacao-view/transacao-view.module';

@Module({
providers: [BankStatementsService, BankStatementsRepositoryService],
Expand Down
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
3 changes: 1 addition & 2 deletions src/bigquery/bigquery.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,13 @@ export class BigqueryService {
* @throws `HttpException`
*/
public async query(source: BigquerySource, query: string) {
this.logger.debug('Query fetch started');
const _query = compactQuery(query);
console.log(`${formatSqlTitle('bigquery:')} ${formatSqlQuery(query)}`);
try {
const [rows] = await this.getBqInstance(source).query({
query: _query,
});
this.logger.debug(`Query fetch finished. Count: ${rows.length}`);
this.logger.debug(`Query finished. Count: ${rows.length}`);
return rows;
} catch (error) {
console.log(`${formatSqlTitleFailed('bigquery failed:')} ${_query}`);
Expand Down
23 changes: 4 additions & 19 deletions src/bigquery/dtos/bigquery-ordem-pagamento.dto.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
import {
IsDateString,
IsNotEmpty,
IsNumber,
IsNumberString,
IsString,
ValidateIf,
} from 'class-validator';
import { IsDateString, IsNotEmpty, IsNumber, IsNumberString, IsString, ValidateIf } from 'class-validator';
import { isSameDay, nextFriday } from 'date-fns';
import { TipoFavorecidoEnum } from 'src/tipo-favorecido/tipo-favorecido.enum';
import { TipoFavorecidoEnum } from 'src/cnab/enums/tipo-favorecido.enum';
import { DeepPartial } from 'typeorm';

/**
Expand Down Expand Up @@ -158,16 +151,8 @@ export class BigqueryOrdemPagamentoDTO {

tipoFavorecido: TipoFavorecidoEnum | null;

public static findAgrupado(
ordemAgs: BigqueryOrdemPagamentoDTO[],
ordem: BigqueryOrdemPagamentoDTO,
newDataOrdem = nextFriday(new Date()),
) {
const filtered = ordemAgs.filter(
(i) =>
isSameDay(new Date(i.dataOrdem), newDataOrdem) &&
i.idConsorcio === ordem.idConsorcio,
)[0];
public static findAgrupado(ordemAgs: BigqueryOrdemPagamentoDTO[], ordem: BigqueryOrdemPagamentoDTO, newDataOrdem = nextFriday(new Date())) {
const filtered = ordemAgs.filter((i) => isSameDay(new Date(i.dataOrdem), newDataOrdem) && i.idConsorcio === ordem.idConsorcio)[0];
return filtered ? filtered : null;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { TipoFavorecidoEnum } from 'src/tipo-favorecido/tipo-favorecido.enum';
import { TipoFavorecidoEnum } from 'src/cnab/enums/tipo-favorecido.enum';

export interface IBigqueryFindOrdemPagamento {
operadorCpfs?: string[];
Expand Down
12 changes: 0 additions & 12 deletions src/bigquery/interfaces/bq-find-transacao-by.interface.ts

This file was deleted.

25 changes: 0 additions & 25 deletions src/bigquery/maps/bq-transacao-tipo-transacao.map.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
import { Injectable, Logger } from '@nestjs/common';
import { SettingsService } from 'src/settings/settings.service';
import { Injectable } from '@nestjs/common';
import { CustomLogger } from 'src/utils/custom-logger';
import { bigToNumber } from 'src/utils/pipe-utils';
import { BigquerySource, BigqueryService } from '../bigquery.service';
import { BigqueryService, BigquerySource } from '../bigquery.service';
import { BigqueryOrdemPagamento } from '../entities/ordem-pagamento.bigquery-entity';
import { IBigqueryFindOrdemPagamento } from '../interfaces/bigquery-find-ordem-pagamento.interface';
import { CustomLogger } from 'src/utils/custom-logger';

@Injectable()
export class BigqueryOrdemPagamentoRepository {
private logger = new CustomLogger('BigqueryOrdemPagamentoRepository', { timestamp: true });

constructor(
private readonly bigqueryService: BigqueryService,
private readonly settingsService: SettingsService,
) {}

public async findMany(
Expand Down Expand Up @@ -87,6 +85,7 @@ export class BigqueryOrdemPagamentoRepository {
const select = `
SELECT
CAST(t.data_ordem AS STRING) AS dataOrdem,
CAST(t.data_pagamento AS STRING) AS dataPagamento,
t.id_consorcio AS idConsorcio,
t.consorcio,
t.id_operadora AS idOperadora,
Expand Down
29 changes: 21 additions & 8 deletions src/bigquery/repositories/bigquery-transacao.repository.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { appSettings } from 'src/settings/app.settings';
import { BigqueryEnvironment } from 'src/settings/enums/bigquery-env.enum';
import { SettingsService } from 'src/settings/settings.service';
import { TRIntegrationTypeMap } from 'src/ticket-revenues/maps/ticket-revenues.map';
import { isCpfOrCnpj } from 'src/utils/cpf-cnpj';
import { CustomLogger } from 'src/utils/custom-logger';
import { logWarn } from 'src/utils/log-utils';
import { QueryBuilder } from 'src/utils/query-builder/query-builder';
import { BigquerySource, BigqueryService } from '../bigquery.service';
import { BigqueryService, BigquerySource } from '../bigquery.service';
import { BigqueryTransacao } from '../entities/transacao.bigquery-entity';
import { IBqFindTransacao } from '../interfaces/bq-find-transacao-by.interface';
import { BqTsansacaoTipoIntegracaoMap } from '../maps/bq-transacao-tipo-integracao.map';
import { BqTransacaoTipoPagamentoMap } from '../maps/bq-transacao-tipo-pagamento.map';
import { BqTransacaoTipoTransacaoMap } from '../maps/bq-transacao-tipo-transacao.map';
import { logWarn } from 'src/utils/log-utils';
import { CustomLogger } from 'src/utils/custom-logger';
import { isArray } from 'class-validator';

export interface IBqFindTransacao {
cpfCnpj?: string;
manyCpfCnpj?: string[];
startDate?: Date;
endDate?: Date;
limit?: number;
offset?: number;
getToday?: boolean;
previousDaysOnly?: boolean;
valor_pagamento?: number[] | null | ['>=' | '<=' | '>' | '<', number] | 'NOT NULL';
id_transacao?: string[] | null;
id_operadora?: string[];
}

@Injectable()
export class BigqueryTransacaoRepository {
Expand Down Expand Up @@ -149,6 +160,9 @@ export class BigqueryTransacaoRepository {
}
queryBuilder.pushAND(`t.id_transacao ${value}`);
}
if (args?.id_operadora?.length) {
queryBuilder.pushAND(`t.id_operadora IN('${args.id_operadora.join("','")}')`);
}

queryBuilder.pushOR([]);
if (args?.getToday) {
Expand Down Expand Up @@ -219,7 +233,6 @@ export class BigqueryTransacaoRepository {
valor_transacao: item.valor_transacao || 0,
paymentMediaType: tipo_pagamento !== null ? BqTransacaoTipoPagamentoMap?.[tipo_pagamento] || tipo_pagamento : tipo_pagamento,
transportIntegrationType: tipo_integracao !== null ? BqTsansacaoTipoIntegracaoMap?.[tipo_integracao] || tipo_integracao : tipo_integracao,
transactionType: tipo_transacao !== null ? BqTransacaoTipoTransacaoMap?.[tipo_transacao] || tipo_transacao : tipo_transacao,
};
});
}
Expand Down
3 changes: 1 addition & 2 deletions src/bigquery/services/bigquery-transacao.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Injectable } from '@nestjs/common';
import { CustomLogger } from 'src/utils/custom-logger';
import { BigqueryTransacao } from '../entities/transacao.bigquery-entity';
import { BigqueryTransacaoRepository } from '../repositories/bigquery-transacao.repository';
import { IBqFindTransacao } from '../interfaces/bq-find-transacao-by.interface';
import { BigqueryTransacaoRepository, IBqFindTransacao } from '../repositories/bigquery-transacao.repository';

@Injectable()
export class BigqueryTransacaoService {
Expand Down
Loading

0 comments on commit 92b0ae8

Please sign in to comment.