Skip to content

Commit

Permalink
Merge pull request #328 from RJ-SMTR/feature-ajuste-remessa
Browse files Browse the repository at this point in the history
Criação de rotina para conferencia de envio remessa
  • Loading branch information
williamfl2007 committed Jul 3, 2024
2 parents 6bd8432 + ea3d0f0 commit c4e6bba
Show file tree
Hide file tree
Showing 20 changed files with 1,683 additions and 95 deletions.
23 changes: 15 additions & 8 deletions src/bigquery/services/bigquery-ordem-pagamento.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,26 @@ export class BigqueryOrdemPagamentoService {
/**
* Get data from current payment week (qui-qua). Also with older days.
*/
public async getFromWeek(daysBefore = 0): Promise<BigqueryOrdemPagamentoDTO[]> {
public async getFromWeek(daysBefore:number,dataPgto:Date | undefined): Promise<BigqueryOrdemPagamentoDTO[]> {
// Read
const today = new Date();
const friday = isFriday(today) ? today : nextFriday(today);
let startDate;
let endDate;

const sex = subDays(friday, 7 + daysBefore);
const qui = subDays(friday, 1);
const today = new Date();
if(dataPgto == undefined){
const friday = isFriday(today) ? today : nextFriday(today);
startDate = subDays(friday, 7 + daysBefore);
endDate = subDays(friday, 1);
}else{
startDate = dataPgto;
endDate = dataPgto;
}
const ordemPgto = (
await this.bigqueryOrdemPagamentoRepository.findMany({
startDate: sex,
endDate: qui,
startDate: startDate,
endDate: endDate
})
).map((i) => ({ ...i } as BigqueryOrdemPagamentoDTO));
return ordemPgto;
}
}
}
23 changes: 14 additions & 9 deletions src/bigquery/services/bigquery-transacao.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,24 @@ export class BigqueryTransacaoService {
*
* @param [daysBack=0] Pega a semana atual ou N dias atrás.
*/
public async getFromWeek(
daysBack = 0,
startDateOnly = false,
): Promise<BigqueryTransacao[]> {
public async getFromWeek(daysBack = 0,dataPgto: Date | undefined,startDateOnly = false): Promise<BigqueryTransacao[]> {
// Read
let startDate;
let endDate;

const today = new Date();
const friday = isFriday(today) ? today : nextFriday(today);
const qui = subDays(friday, 8 + daysBack);
const qua = subDays(friday, 2 + (startDateOnly ? 0 : daysBack));
if(dataPgto == undefined){
const friday = isFriday(today) ? today : nextFriday(today);
startDate = subDays(friday, 8 + daysBack);
endDate = subDays(friday, 2 + (startDateOnly ? 0 : daysBack));
}else{
startDate = subDays(dataPgto,1);
endDate = subDays(dataPgto,1);
}
const ordemPgto = (
await this.bigqueryTransacaoRepository.findMany({
startDate: qui,
endDate: qua,
startDate: startDate,
endDate: endDate,
})
).map((i) => ({ ...i } as BigqueryTransacao));
return ordemPgto;
Expand Down
36 changes: 36 additions & 0 deletions src/cnab/cnab.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,18 @@ import { PagadorService } from './service/pagamento/pagador.service';
import { RemessaRetornoService } from './service/pagamento/remessa-retorno.service';
import { TransacaoAgrupadoService } from './service/pagamento/transacao-agrupado.service';
import { TransacaoService } from './service/pagamento/transacao.service';
import { DetalheAConfRepository } from './repository/pagamento/detalhe-a-conf.repository';
import { DetalheBConfRepository } from './repository/pagamento/detalhe-b-conf.repository';
import { HeaderArquivoConfRepository } from './repository/pagamento/header-arquivo-conf.repository';
import { HeaderLoteConfRepository } from './repository/pagamento/header-lote-conf.repository';
import { DetalheAConfService } from './service/pagamento/detalhe-a-conf.service';
import { DetalheBConfService } from './service/pagamento/detalhe-b-conf.service';
import { HeaderArquivoConfService } from './service/pagamento/header-arquivo-conf.service';
import { HeaderLoteConfService } from './service/pagamento/header-lote-conf.service';
import { DetalheAConf } from './entity/conference/detalhe-a-conf.entity';
import { DetalheBConf } from './entity/conference/detalhe-b-conf.entity';
import { HeaderArquivoConf } from './entity/conference/header-arquivo-conf.entity';
import { HeaderLoteConf } from './entity/conference/header-lote-conf.entity';

@Module({
imports: [
Expand All @@ -66,6 +78,10 @@ import { TransacaoService } from './service/pagamento/transacao.service';
SettingsModule,
TransacaoViewModule,
TypeOrmModule.forFeature([
HeaderArquivoConf,
HeaderLoteConf,
DetalheAConf,
DetalheBConf,
HeaderArquivo,
HeaderLote,
DetalheA,
Expand Down Expand Up @@ -93,6 +109,16 @@ import { TransacaoService } from './service/pagamento/transacao.service';
DetalheAService,
DetalheBRepository,
DetalheBService,

HeaderArquivoConfRepository,
HeaderArquivoConfService,
HeaderLoteConfRepository,
HeaderLoteConfService,
DetalheAConfRepository,
DetalheAConfService,
DetalheBConfRepository,
DetalheBConfService,

ClienteFavorecidoRepository,
ClienteFavorecidoService,
PagadorRepository,
Expand Down Expand Up @@ -127,6 +153,16 @@ import { TransacaoService } from './service/pagamento/transacao.service';
DetalheAService,
DetalheBRepository,
DetalheBService,

HeaderArquivoConfRepository,
HeaderArquivoConfService,
HeaderLoteConfRepository,
HeaderLoteConfService,
DetalheAConfRepository,
DetalheAConfService,
DetalheBConfRepository,
DetalheBConfService,

ClienteFavorecidoRepository,
ClienteFavorecidoService,
PagadorRepository,
Expand Down
28 changes: 13 additions & 15 deletions src/cnab/cnab.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,17 @@ export class CnabService {
*
* Requirement: **Salvar novas transações Jaé** - {@link https://github.com/RJ-SMTR/api-cct/issues/207#issuecomment-1984421700 #207, items 3}
*/
public async saveTransacoesJae(daysBefore = 0,consorcio='Todos') {
public async saveTransacoesJae(daysBefore:number,consorcio:string,dataPgto: Date | undefined) {
const METHOD = this.saveTransacoesJae.name;

// 1. Update cliente favorecido
await this.updateAllFavorecidosFromUsers();

// 2. Update TransacaoView
await this.updateTransacaoViewBigquery(daysBefore);
await this.updateTransacaoViewBigquery(daysBefore,dataPgto);

// 3. Update ordens
const ordens = await this.bigqueryOrdemPagamentoService.getFromWeek(daysBefore);
const ordens = await this.bigqueryOrdemPagamentoService.getFromWeek(daysBefore,dataPgto);
await this.saveOrdens(ordens,consorcio);

//await this.compareTransacaoViewPublicacao();
Expand All @@ -123,11 +123,9 @@ export class CnabService {
/**
* Atualiza a tabela TransacaoView
*/
async updateTransacaoViewBigquery(daysBack = 0) {
const transacoesBq = await this.bigqueryTransacaoService.getFromWeek(
daysBack,
false,
);
async updateTransacaoViewBigquery(daysBack:number,dataPgto: Date | undefined) {
const transacoesBq =
await this.bigqueryTransacaoService.getFromWeek(daysBack,dataPgto,false);

forChunk(transacoesBq, 1000, async (chunk) => {
const transacoes = chunk.map((i) =>
Expand Down Expand Up @@ -505,7 +503,7 @@ export class CnabService {
*
* @throws `Error` if any subtask throws
*/
public async saveRemessa(tipo: PagadorContaEnum) {
public async saveRemessa(tipo: PagadorContaEnum, dataPgto: Date | undefined, isConference: boolean) {
const METHOD = this.sendRemessa.name;
const transacoesAg =
await this.transacaoAgService.findAllNewTransacao(tipo);
Expand All @@ -522,11 +520,10 @@ export class CnabService {

// Generate Remessas and send SFTP
for (const transacaoAg of transacoesAg) {

// Get headerArquivo
const headerArquivoDTO = await this.remessaRetornoService.saveHeaderArquivoDTO(transacaoAg);
const headerArquivoDTO = await this.remessaRetornoService.saveHeaderArquivoDTO(transacaoAg,isConference);

const lotes = await this.remessaRetornoService.getLotes(transacaoAg.pagador,headerArquivoDTO);
const lotes = await this.remessaRetornoService.getLotes(transacaoAg.pagador,headerArquivoDTO,dataPgto,isConference);

const cnab104 = this.remessaRetornoService.generateFile(headerArquivoDTO,lotes);

Expand All @@ -544,9 +541,10 @@ export class CnabService {
}

// Update
await this.remessaRetornoService.updateHeaderArquivoDTOFrom104(headerArquivoDTO,processedCnab104.headerArquivo);

await this.transacaoAgService.save({ id: transacaoAg.id, status: new TransacaoStatus(TransacaoStatusEnum.remessa) });
if(isConference){
await this.remessaRetornoService.updateHeaderArquivoDTOFrom104(headerArquivoDTO,processedCnab104.headerArquivo);
await this.transacaoAgService.save({ id: transacaoAg.id, status: new TransacaoStatus(TransacaoStatusEnum.remessa) });
}

if (!cnabStr) {
this.logger.warn(
Expand Down
174 changes: 174 additions & 0 deletions src/cnab/entity/conference/detalhe-a-conf.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { EntityHelper } from 'src/utils/entity-helper';
import {
asNullableStringOrNumber,
asStringOrNumber,
} from 'src/utils/pipe-utils';
import {
AfterLoad,
Column,
CreateDateColumn,
Entity,
JoinColumn,
ManyToOne,
OneToMany,
OneToOne,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
import { ClienteFavorecido } from '../cliente-favorecido.entity';
import { HeaderLoteConf } from './header-lote-conf.entity';
import { Ocorrencia } from '../pagamento/ocorrencia.entity';
import { ItemTransacaoAgrupado } from '../pagamento/item-transacao-agrupado.entity';

/**
* Pagamento.DetalheA
*/
@Entity()
export class DetalheAConf extends EntityHelper {
@PrimaryGeneratedColumn({ primaryKeyConstraintName: 'PK_DetalheAConf_id' })
id: number;

@ManyToOne(() => HeaderLoteConf, { eager: true })
@JoinColumn({ foreignKeyConstraintName: 'FK_DetalheAConf_headerLote_ManyToOne' })
headerLote: HeaderLoteConf;

@ManyToOne(() => ClienteFavorecido, { eager: true })
@JoinColumn({
foreignKeyConstraintName: 'FK_DetalheAConf_clienteFavorecido_ManyToOne',
})
clienteFavorecido: ClienteFavorecido;

@OneToMany(() => Ocorrencia, (ocorrencia) => ocorrencia.detalheA, {
eager: true,
})
@JoinColumn({
foreignKeyConstraintName: 'FK_DetalheAConf_ocorrencias_OneToMany',
})
ocorrencias: Ocorrencia[];

@Column({ type: String, unique: false, nullable: true, length: 30 })
ocorrenciasCnab: string | null;

@Column({ type: Number, unique: false, nullable: true })
loteServico: number;

@Column({ type: String, unique: false, nullable: true })
finalidadeDOC: string | null;

/** Atribuído pela empresa, sequencial */
@Column({ type: Number, unique: false, nullable: false })
numeroDocumentoEmpresa: number;

@Column({ type: Date, unique: false, nullable: true })
dataVencimento: Date;

@Column({ type: String, unique: false, nullable: true })
tipoMoeda: string | null;

@Column({
type: 'decimal',
unique: false,
nullable: true,
precision: 10,
scale: 5,
})
quantidadeMoeda: number | null;

@Column({
type: 'decimal',
unique: false,
nullable: true,
precision: 13,
scale: 2,
})
valorLancamento: number;

@Column({ type: String, unique: false, nullable: true })
numeroDocumentoBanco: string | null;

@Column({ type: Number, unique: false, nullable: true })
quantidadeParcelas: number | null;

@Column({ type: String, unique: false, nullable: true })
indicadorBloqueio: string | null;

@Column({ type: String, unique: false, nullable: true })
indicadorFormaParcelamento: string | null;

@Column({ type: Date, unique: false, nullable: true })
periodoVencimento: Date | null;

@Column({ type: Number, unique: false, nullable: true })
numeroParcela: number | null;

@Column({ type: Date, unique: false, nullable: true })
dataEfetivacao: Date | null;

@Column({
type: 'decimal',
unique: false,
nullable: true,
precision: 13,
scale: 2,
})
valorRealEfetivado: number;

/**
* Número Sequencial do Registro.
*
* Detalhe unique ID per lote
*/
@Column({ type: Number, unique: false, nullable: false })
nsr: number;

/** `UQ_DetalheA_itemTransacaoAgrupado` */
@OneToOne(() => ItemTransacaoAgrupado, { eager: true, nullable: false })
@JoinColumn({
foreignKeyConstraintName: 'FK_DetalheAConf_itemTransacaoAgrupado_OneToOne',
})
itemTransacaoAgrupado: ItemTransacaoAgrupado;

@CreateDateColumn()
createdAt: Date;

@UpdateDateColumn()
updatedAt: Date;

getOcorrenciasCnab() {
return (this.ocorrenciasCnab || '').trim();
}

@AfterLoad()
setReadValues() {
this.quantidadeMoeda = asNullableStringOrNumber(this.quantidadeMoeda);
this.valorLancamento = asStringOrNumber(this.valorLancamento);
this.valorRealEfetivado = asStringOrNumber(this.valorRealEfetivado);
}

public isPago() {
const errors = Ocorrencia.getErrorCodes(this.ocorrenciasCnab || '');
return errors.length === 0;
}

public static getOcorrenciaErrors(detalhes: DetalheAConf[]) {
return detalhes.reduce(
(l, i) => [
...l,
...i.ocorrencias.filter((j) => !['00', 'BD'].includes(j.code)),
],
[],
);
}

public static getItemTransacaoAgIds(detalhesA: DetalheAConf[]) {
return [...new Set(detalhesA.map((i) => i.itemTransacaoAgrupado.id))];
}

public static getTransacaoAgIds(detalhesA: DetalheAConf[]): number[] {
return [
...new Set(
detalhesA.map((i) => i.itemTransacaoAgrupado.transacaoAgrupado.id),
),
];
}
}
Loading

0 comments on commit c4e6bba

Please sign in to comment.