Commit 4d5d769e authored by Rafael's avatar Rafael

Adiciona retomada de edição de propostas.

parent b3dd6675
Pipeline #8008 passed with stage
in 9 minutes and 45 seconds
...@@ -116,7 +116,7 @@ const makeCommonPlugins = (env) => [ ...@@ -116,7 +116,7 @@ const makeCommonPlugins = (env) => [
}), }),
new HtmlWebpackPlugin({ new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.ejs'), template: path.join(__dirname, 'public', 'index.ejs'),
favicon: path.join(PUBLIC, 'images', 'favicon.png'), favicon: path.join(PUBLIC, 'images', 'pdcase.png'),
title: 'Agiliza - Agente', title: 'Agiliza - Agente',
inject: false, inject: false,
}), }),
......
--registry "https://nexus.dev.evologica.com.br/repository/npm" --registry "https://nexus.dev.evologica.com.br/repository/npm/"
"@curio:registry" "https://nexus.dev.evologica.com.br/repository/npm" "@curio:registry" "https://nexus.dev.evologica.com.br/repository/npm"
"@dynamo:registry" "https://nexus.dev.evologica.com.br/repository/npm" "@dynamo:registry" "https://nexus.dev.evologica.com.br/repository/npm"
\ No newline at end of file
...@@ -51,8 +51,8 @@ ...@@ -51,8 +51,8 @@
"@types/webpack": "5.28.0", "@types/webpack": "5.28.0",
"@types/webpack-bundle-analyzer": "4.4.0", "@types/webpack-bundle-analyzer": "4.4.0",
"@types/webpack-dev-server": "3.11.4", "@types/webpack-dev-server": "3.11.4",
"@typescript-eslint/eslint-plugin": "^4.25.0", "@typescript-eslint/eslint-plugin": "^4.31.0",
"@typescript-eslint/parser": "^4.25.0", "@typescript-eslint/parser": "^4.29.2",
"autoprefixer": "^10.2.5", "autoprefixer": "^10.2.5",
"babel-eslint": "^10.1.0", "babel-eslint": "^10.1.0",
"babel-loader": "8.2.2", "babel-loader": "8.2.2",
...@@ -90,7 +90,7 @@ ...@@ -90,7 +90,7 @@
"@material-ui/icons": "^4.11.2", "@material-ui/icons": "^4.11.2",
"@material-ui/lab": "4.0.0-alpha.58", "@material-ui/lab": "4.0.0-alpha.58",
"@material-ui/pickers": "^3.3.10", "@material-ui/pickers": "^3.3.10",
"@microcredito/client": "^0.7.22", "@microcredito/client": "^0.7.26",
"@reduxjs/toolkit": "^1.2.5", "@reduxjs/toolkit": "^1.2.5",
"@types/react-swipeable-views": "^0.13.1", "@types/react-swipeable-views": "^0.13.1",
"@types/react-swipeable-views-utils": "^0.13.3", "@types/react-swipeable-views-utils": "^0.13.3",
......
{ {
"API_URL": "https://microcredito.dev.evologica.com.br", "API_URL": "http://192.168.0.65:8080",
"APP_NAME_BROKER": "@microcredito/agente", "APP_NAME_BROKER": "@agiliza-dev/agente",
"APP_NAME_CUSTOMER": "@microcredito/cliente", "APP_NAME_CUSTOMER": "@agiliza-dev/cliente",
"SESSION_KEY_BROKER": "@microcredito/agente", "SESSION_KEY_BROKER": "@agiliza-dev/agente",
"SESSION_KEY_CUSTOMER": "@microcredito/cliente" "SESSION_KEY_CUSTOMER": "@agiliza-dev/cliente"
} }
\ No newline at end of file
import { Entity } from '@agiliza/utils/method'
export interface Event extends Entity {
date: Date
title: string
description: string
}
...@@ -5,6 +5,9 @@ export * from './context' ...@@ -5,6 +5,9 @@ export * from './context'
export * from './error' export * from './error'
export * from './simulation' export * from './simulation'
export * from './authentication' export * from './authentication'
export * from './schedule'
export * from './project'
export * from './event'
export interface Customer { export interface Customer {
name: string name: string
...@@ -38,3 +41,19 @@ export interface Document { ...@@ -38,3 +41,19 @@ export interface Document {
extraInformations: string extraInformations: string
url: string url: string
} }
export interface UserClient {
cpfcnpj: string
name: string
}
export interface UserCustomer {
name: string
email: string
ownerName?: string
ownerCPF?: string
cpfcnpj: string
phone: string
avatarUrl?: string
address?: Partial<Address>
}
...@@ -13,7 +13,7 @@ export interface Project extends Entity { ...@@ -13,7 +13,7 @@ export interface Project extends Entity {
documents?: Document[] documents?: Document[]
processNumber: string processNumber: string
permissions?: ProjectPermissions permissions?: ProjectPermissions
schedules: Schedule[] schedules?: Schedule[]
// customer: UserCustomer // customer: UserCustomer
// involvedPeople?: InvolvedPerson[] // involvedPeople?: InvolvedPerson[]
// businessData?: BusinessData // businessData?: BusinessData
...@@ -56,10 +56,10 @@ interface InputGetProjects { ...@@ -56,10 +56,10 @@ interface InputGetProjects {
statuses?: number[] statuses?: number[]
} }
export interface GetProjects { // export interface GetProjects {
Input: InputGetProjects // Input: InputGetProjects
Output: Project[] // Output: Project[]
} // }
interface InputSubmitProjects { interface InputSubmitProjects {
ids: string[] ids: string[]
...@@ -69,3 +69,8 @@ export interface SubmitProjects { ...@@ -69,3 +69,8 @@ export interface SubmitProjects {
Input: InputSubmitProjects Input: InputSubmitProjects
Output: void Output: void
} }
export interface GetProjects {
Input: void
Output: Project[]
}
import type { BDIdentification } from './identification' import type { BDIdentification } from './identification'
import type { BDAddress } from './address' import type { BDAddress } from './address'
import type { StockSalesCosts } from './stockSalesCosts' import type { BDStockSalesCosts } from './stockSalesCosts'
import type { BDProductService } from './productService' import type { BDProductService } from './productService'
export interface BusinessData { export interface BusinessData {
identification?: BDIdentification identification?: BDIdentification
address?: BDAddress address?: BDAddress
stockSalesCosts?: StockSalesCosts stockSalesCosts?: BDStockSalesCosts
productsServices?: BDProductService[] productsServices?: BDProductService[]
} }
...@@ -14,3 +14,19 @@ export * from './address' ...@@ -14,3 +14,19 @@ export * from './address'
export * from './identification' export * from './identification'
export * from './productService' export * from './productService'
export * from './stockSalesCosts' export * from './stockSalesCosts'
// interface OutputGetBusinessData {
// identification: BDIdentification
// address: BDAddress
// productService: BDProductService
// stockSalesCosts: BDStockSalesCosts
// }
interface InputGetBusinessData {
projectId: string
}
export interface GetBusinessData {
Input: InputGetBusinessData
Output: BusinessData
}
import { Document } from '../../../domain/project' import { Document } from '../../../domain/project'
export interface StockSalesCosts { export interface BDStockSalesCosts {
document?: Document document?: Document
monthYearReference: string monthYearReference: string
salesCommission: string salesCommission: string
...@@ -9,10 +9,10 @@ export interface StockSalesCosts { ...@@ -9,10 +9,10 @@ export interface StockSalesCosts {
interface InputUpdateBDStockSalesCosts { interface InputUpdateBDStockSalesCosts {
projectId: string projectId: string
stockSalesCosts: StockSalesCosts stockSalesCosts: BDStockSalesCosts
} }
export interface UpdateBDStockSalesCosts { export interface UpdateBDStockSalesCosts {
Input: InputUpdateBDStockSalesCosts Input: InputUpdateBDStockSalesCosts
Output: StockSalesCosts Output: BDStockSalesCosts
} }
...@@ -7,9 +7,9 @@ export interface InvolvedPerson { ...@@ -7,9 +7,9 @@ export interface InvolvedPerson {
sourceIncome?: SourceIncome sourceIncome?: SourceIncome
address?: InvolvedPersonAddress address?: InvolvedPersonAddress
home?: Home home?: Home
// spousePersonalData?: SpousePersonalData spousePersonalData?: SpousePersonalData
// vehicles?: Vehicle[] vehicles?: Vehicle[]
// references?: Reference[] references?: Reference[]
} }
export interface Identification { export interface Identification {
...@@ -45,3 +45,23 @@ export interface AddCDIdentification { ...@@ -45,3 +45,23 @@ export interface AddCDIdentification {
Input: InputAddCDIdentification Input: InputAddCDIdentification
Output: Identification Output: Identification
} }
interface InputUpdateCDIdentification {
identification: Identification
projectId: string
personId: string
}
export interface UpdateCDIdentification {
Input: InputUpdateCDIdentification
Output: Identification
}
interface InputGetCDIdentification {
projectId: string
}
export interface GetCDIdentification {
Input: InputGetCDIdentification
Output?: Identification
}
import type { IPAddress } from './address' import type { IPAddress } from './address'
import type { InvolvedPerson } from './identification'
export * from './identification' export * from './identification'
export * from './personalData' export * from './personalData'
...@@ -15,3 +16,13 @@ export interface RG { ...@@ -15,3 +16,13 @@ export interface RG {
number: string number: string
dispatcherAgency: string dispatcherAgency: string
} }
interface InputGetCustomerData {
projectId: string
personId: string
}
export interface GetCustomerData {
Input: InputGetCustomerData
Output: InvolvedPerson
}
import { Entity } from '@agiliza/utils/method'
import { Document, Operation } from './project'
export interface Schedule extends Entity {
status: ScheduleStatus
events: string[]
documents?: Document[]
number: string
date: Date
// user: UserClient
// complement?: ScheduleVisitComplement
// details?: ScheduleDetails
idProject?: string
}
interface ScheduleDetails {
rescheduleDate?: Date
reason: string
justification: string
}
export interface SchedulePermissions {
requestCancel?: boolean
requestReschedule?: boolean
confirmReschedule?: boolean
confirmRequest?: boolean
goToProject?: boolean
cancelVisit?: boolean
confirmCancel?: boolean
}
export interface ScheduleCancellationReason extends Entity {
description: string
}
export interface RescheduleReason extends Entity {
description: string
}
export interface ScheduleStatus extends Entity {
description: string
operations: Operation[]
}
interface ScheduleVisitComplement {
address: VisitAddress
interestCredit: CreditInformation
}
export interface VisitAddress {
id: string
street: string
number: string
cep: string
complement: string
city: string
district: string
state: string
}
export interface CreditInformation {
creditValue: number
creditObjective: string
creditInstallment: number
creditGracePeriod: string
}
export interface ScheduleCancellation {
scheduleId: string
reason: string
justification: string
}
export interface Reschedule {
scheduleId: string
dateTime: Date
reason: string
justification: string
}
export interface ScheduleContext {
gracePeriods: CreditGracePeriod[]
installments: CreditInstallment[]
}
export interface CreditInstallment extends Entity {
description: string
}
// Carência
export interface CreditGracePeriod extends Entity {
description: string
}
...@@ -7,6 +7,15 @@ export interface SubProduct extends Entity { ...@@ -7,6 +7,15 @@ export interface SubProduct extends Entity {
maxAmountInstallment?: number maxAmountInstallment?: number
installementOptions: InstallmentOption[] installementOptions: InstallmentOption[]
TAC?: number TAC?: number
monthlyCET?: number
yearlyCET?: number
totalLiberateLiquidValue?: number
loanValue?: number
baseCalcDate?: Date
amortization?: number
graceInstallementAmount?: number
totalCalcValue?: number
feeTotalValue?: number
} }
export interface GetSubProducts { export interface GetSubProducts {
......
...@@ -2,10 +2,10 @@ import { ...@@ -2,10 +2,10 @@ import {
AddBDProductService, AddBDProductService,
BDAddress, BDAddress,
BDProductService, BDProductService,
BDStockSalesCosts,
BusinessData, BusinessData,
CreateProposal, CreateProposal,
Document, Document,
StockSalesCosts,
UpdateBDAddress, UpdateBDAddress,
UpdateBDIdentification, UpdateBDIdentification,
UpdateBDProductService, UpdateBDProductService,
...@@ -150,12 +150,12 @@ export class BDUpdateAddressApiMapper implements ApiAdapter<UpdateBDAddress['Inp ...@@ -150,12 +150,12 @@ export class BDUpdateAddressApiMapper implements ApiAdapter<UpdateBDAddress['Inp
}) })
} }
export class BDStockSalesCostsApiAdapter implements ApiAdapter<StockSalesCosts, DadosNegocioEstoqueVendasCustosApiModel> { export class BDStockSalesCostsApiAdapter implements ApiAdapter<BDStockSalesCosts, DadosNegocioEstoqueVendasCustosApiModel> {
private documentApiAdapter: DocumentApiMapper private documentApiAdapter: DocumentApiMapper
constructor() { constructor() {
this.documentApiAdapter = new DocumentApiMapper() this.documentApiAdapter = new DocumentApiMapper()
} }
public mapDomainToApiModel = (sSC: StockSalesCosts): DadosNegocioEstoqueVendasCustosApiModel => ({ public mapDomainToApiModel = (sSC: BDStockSalesCosts): DadosNegocioEstoqueVendasCustosApiModel => ({
classificacaoMes: sSC.monthRating, classificacaoMes: sSC.monthRating,
comissaoVendas: Number(sSC.salesCommission), comissaoVendas: Number(sSC.salesCommission),
documento: sSC.document && this.documentApiAdapter.mapDomainToApiModel(sSC.document), documento: sSC.document && this.documentApiAdapter.mapDomainToApiModel(sSC.document),
......
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
SpousePersonalData, SpousePersonalData,
UpdateCDAddress, UpdateCDAddress,
UpdateCDHome, UpdateCDHome,
UpdateCDIdentification,
UpdateCDPersonalData, UpdateCDPersonalData,
UpdateCDReference, UpdateCDReference,
UpdateCDSourceIncome, UpdateCDSourceIncome,
...@@ -18,6 +19,7 @@ import { ...@@ -18,6 +19,7 @@ import {
UpdateCDVehicle, UpdateCDVehicle,
Vehicle Vehicle
} from '@agiliza/api/domain' } from '@agiliza/api/domain'
import { INVOLVED_PERSON_NAMES, INVOLVED_PERSON_TYPES } from '@agiliza/constants/involvedPeople'
import { extractNumbers } from '@agiliza/utils/method' import { extractNumbers } from '@agiliza/utils/method'
import { import {
EnderecoApiModel, EnderecoApiModel,
...@@ -37,6 +39,7 @@ import { ...@@ -37,6 +39,7 @@ import {
AtualizarDadosPessoaisPessoaEnvolvidaRequest, AtualizarDadosPessoaisPessoaEnvolvidaRequest,
AtualizarEnderecoPessoaEnvolvidaRequest, AtualizarEnderecoPessoaEnvolvidaRequest,
AtualizarFonteRendaPessoaEnvolvidaRequest, AtualizarFonteRendaPessoaEnvolvidaRequest,
AtualizarIdentificacaoPessoaEnvolvidaRequest,
AtualizarVeiculoPessoaEnvolvidaRequest, AtualizarVeiculoPessoaEnvolvidaRequest,
CriarReferenciaPessoaEnvolvidaRequest, CriarReferenciaPessoaEnvolvidaRequest,
CriarVeiculoPessoaEnvolvidaRequest, CriarVeiculoPessoaEnvolvidaRequest,
...@@ -65,7 +68,7 @@ export class AddInvolvedPersonIdentification implements ApiAdapter<InvolvedPerso ...@@ -65,7 +68,7 @@ export class AddInvolvedPersonIdentification implements ApiAdapter<InvolvedPerso
nome: domain.name, nome: domain.name,
cpfcnpj: extractNumbers(domain.cpfcnpj), cpfcnpj: extractNumbers(domain.cpfcnpj),
sexo: domain.gender, sexo: domain.gender,
tipo: domain.type, tipo: domain.type === INVOLVED_PERSON_NAMES['2'] ? INVOLVED_PERSON_TYPES['CUSTOMER'] : '',
contaBanestes: domain.account ? this.mapBanestesAccountToApi(domain.account) : undefined, contaBanestes: domain.account ? this.mapBanestesAccountToApi(domain.account) : undefined,
dadosTipo: domain.dataType ? this.mapDateTypeToApi(domain.dataType) : undefined, dadosTipo: domain.dataType ? this.mapDateTypeToApi(domain.dataType) : undefined,
}) })
...@@ -83,6 +86,19 @@ export class CDAddIdentificationMapper implements ApiAdapter<AddCDIdentification ...@@ -83,6 +86,19 @@ export class CDAddIdentificationMapper implements ApiAdapter<AddCDIdentification
}, },
}) })
} }
export class CDUpdateIdentificationMapper implements ApiAdapter<UpdateCDIdentification['Input'], AtualizarIdentificacaoPessoaEnvolvidaRequest> {
private identificationApiMapper: AddInvolvedPersonIdentification
constructor() {
this.identificationApiMapper = new AddInvolvedPersonIdentification()
}
public mapDomainToApiModel = (input: UpdateCDIdentification['Input']): AtualizarIdentificacaoPessoaEnvolvidaRequest => ({
projetoId: input.projectId,
pessoaId: input.personId,
pessoaEnvolvidaIdentificacaoRequestApiModel: {
identificacao: this.identificationApiMapper.mapDomainToApiModel(input.identification),
},
})
}
export class RGApiAdapter implements ApiAdapter<RG, ProjetoPessoaEnvolvidaRGApiModel> { export class RGApiAdapter implements ApiAdapter<RG, ProjetoPessoaEnvolvidaRGApiModel> {
public mapDomainToApiModel = (rg: RG): ProjetoPessoaEnvolvidaRGApiModel => ({ public mapDomainToApiModel = (rg: RG): ProjetoPessoaEnvolvidaRGApiModel => ({
......
...@@ -2,10 +2,20 @@ import * as AuthenticationMappers from './authentication' ...@@ -2,10 +2,20 @@ import * as AuthenticationMappers from './authentication'
import * as ContextMappers from './context' import * as ContextMappers from './context'
import * as CustomerMappers from './customer' import * as CustomerMappers from './customer'
import * as ErrorMappers from './error' import * as ErrorMappers from './error'
import * as ProjectMappers from './project'
import * as ProposalDataMappers from './proposalData' import * as ProposalDataMappers from './proposalData'
import * as SessionAdapters from './session' import * as SessionAdapters from './session'
import * as SimulationMappers from './simulation' import * as SimulationMappers from './simulation'
export { ContextMappers, ErrorMappers, SessionAdapters, SimulationMappers, AuthenticationMappers, CustomerMappers, ProposalDataMappers } export {
ContextMappers,
ErrorMappers,
SessionAdapters,
SimulationMappers,
AuthenticationMappers,
CustomerMappers,
ProposalDataMappers,
ProjectMappers,
}
export * from './shared' export * from './shared'
import { Document, Operation, Project, ProjectStatus } from '@agiliza/api/domain/project'
import {
DocumentoApiModel,
ProjetoClienteApiModel,
ProjetoOperacaoApiModel,
ProjetoSituacaoApiModel,
ProjetoSituacaoCompletoApiModel
} from '@microcredito/client'
import { ScheduleAdapter } from './schedule'
import { DomainAdapter } from './shared'
export class ProjectMapper implements DomainAdapter<ProjetoClienteApiModel, Project> {
private statusAdapter: ProjectStatusAdapter
private scheduleAdapter: ScheduleAdapter
private documentAdapter: ProjectDocumentMapper
// private userCustomerAdapter: UserCustomerMapper
constructor() {
this.scheduleAdapter = new ScheduleAdapter()
this.statusAdapter = new ProjectStatusAdapter()
this.documentAdapter = new ProjectDocumentMapper()
// this.userCustomerAdapter = new UserCustomerMapper()
}
public mapApiModelToDomain = (apimodel: ProjetoClienteApiModel) => {
const result: Project = {
// customer: this.userCustomerAdapter.mapApiModelToDomain(apimodel.cliente),
processNumber: apimodel.numeroProcesso,
events: apimodel.eventos ?? [],
id: apimodel.id,
status: this.statusAdapter.mapApiModelToDomain(apimodel.situacao),
schedules: apimodel?.agendamentos?.map(this.scheduleAdapter.mapApiModelToDomain),
documents: apimodel.documentos.map(this.documentAdapter.mapApiModelToDomain),
}
return result
}
}
// TODO: mudar spec para corrigir status de Visita e Projeto
export class ProjectStatusAdapter implements DomainAdapter<ProjetoSituacaoCompletoApiModel, ProjectStatus> {
public mapOperacaoToDomain = (oprt: ProjetoOperacaoApiModel): Operation => ({
id: oprt.codigo,
description: oprt.descricao,
descriptionTransition: oprt.descricaoTransicao,
permission: oprt.permissao === 'cliente' ? 'customer' : 'broker',
})
public mapApiModelToDomain = (apimodel: ProjetoSituacaoCompletoApiModel) => {
const result: ProjectStatus = {
id: apimodel.codigo,
description: apimodel.descricao,
operations: apimodel.operacoes?.map(this.mapOperacaoToDomain),
}
return result
}
}
export class ProjectDocumentMapper implements DomainAdapter<DocumentoApiModel, Document> {
public mapTipoDocumentoApiToDomain = (tipo: DocumentoApiModel['tipoDocumento']): Document['type'] => ({
id: tipo.codigo,
description: tipo.descricao,
})
public mapApiModelToDomain = (apimodel: DocumentoApiModel): Document => ({
id: apimodel.id,
url: apimodel.imagem,
type: this.mapTipoDocumentoApiToDomain(apimodel.tipoDocumento),
extraInformations: apimodel.informacoesComplementares || '',
})
}
export class ProjectContextStatusMapper implements DomainAdapter<ProjetoSituacaoApiModel, ProjectStatus> {
public mapApiModelToDomain = (situacao: ProjetoSituacaoApiModel): ProjectStatus => ({
id: situacao.codigo,
description: situacao.descricao,
})
}
import { import {
BDIdentification, BDIdentification,
BDProductService, BDProductService,
BDStockSalesCosts,
BusinessData,
Document, Document,
StockSalesCosts,
UpdateBDAddress UpdateBDAddress
} from '@agiliza/api/domain' } from '@agiliza/api/domain'
import { import {
...@@ -80,16 +81,41 @@ export class BDUpdateAddressMapper implements DomainAdapter<DadosNegocioEndereco ...@@ -80,16 +81,41 @@ export class BDUpdateAddressMapper implements DomainAdapter<DadosNegocioEndereco
}) })
} }
export class BDUpdateStockSalesCostsMapper implements DomainAdapter<DadosNegocioEstoqueVendasCustosApiModel, StockSalesCosts> { export class BDUpdateStockSalesCostsMapper implements DomainAdapter<DadosNegocioEstoqueVendasCustosApiModel, BDStockSalesCosts> {
private documentMapper: ProjectDocumentMapper private documentMapper: ProjectDocumentMapper
constructor() { constructor() {
this.documentMapper = new ProjectDocumentMapper() this.documentMapper = new ProjectDocumentMapper()
} }
public mapApiModelToDomain = (sSC: DadosNegocioEstoqueVendasCustosApiModel): StockSalesCosts => ({ public mapApiModelToDomain = (sSC: DadosNegocioEstoqueVendasCustosApiModel): BDStockSalesCosts => ({
document: sSC.documento && this.documentMapper.mapApiModelToDomain(sSC.documento), document: sSC.documento && this.documentMapper.mapApiModelToDomain(sSC.documento),
monthRating: sSC.classificacaoMes || '', monthRating: sSC.classificacaoMes || '',
monthYearReference: sSC.mesAnoReferencia || '', monthYearReference: sSC.mesAnoReferencia || '',
salesCommission: sSC.comissaoVendas?.toString() || '', salesCommission: sSC.comissaoVendas?.toString() || '',
}) })
} }
export interface DadosNegocio {
identificacao?: DadosNegocioIdentificacaoApiModel
endereco?: DadosNegocioEnderecoApiModel
estoqueVendasCustos?: DadosNegocioEstoqueVendasCustosApiModel
produtosServicos?: DadosNegocioProdutoServicoApiModel[]
}
export class BDGetBusinessDataMapper implements DomainAdapter<DadosNegocio, BusinessData> {
private identificationMapper: BDIdentificationMapper
private addressMapper: BDUpdateAddressMapper
private productServicesMapper: BDProductsServicesMapper
private stockSalesCostsMapper: BDUpdateStockSalesCostsMapper
constructor() {
this.identificationMapper = new BDIdentificationMapper()
this.addressMapper = new BDUpdateAddressMapper()
this.productServicesMapper = new BDProductsServicesMapper()
this.stockSalesCostsMapper = new BDUpdateStockSalesCostsMapper()
}
public mapApiModelToDomain = (dN: DadosNegocio): BusinessData => ({
identification: dN.identificacao && this.identificationMapper.mapApiModelToDomain(dN.identificacao),
address: dN.endereco && this.addressMapper.mapApiModelToDomain(dN.endereco),
productsServices: dN.produtosServicos && dN.produtosServicos.map(this.productServicesMapper.mapApiModelToDomain),
stockSalesCosts: dN.estoqueVendasCustos && this.stockSalesCostsMapper.mapApiModelToDomain(dN.estoqueVendasCustos),
})
}
...@@ -221,3 +221,58 @@ export class VehicleMapper implements DomainAdapter<ProjetoPessoaEnvolvidaVeicul ...@@ -221,3 +221,58 @@ export class VehicleMapper implements DomainAdapter<ProjetoPessoaEnvolvidaVeicul
year: vcl.ano ? vcl.ano.toString() : '', year: vcl.ano ? vcl.ano.toString() : '',
}) })
} }
// export interface InvolvedPerson {
// id: string
// identification: Identification
// personalData?: PersonalData
// sourceIncome?: SourceIncome
// address?: InvolvedPersonAddress
// home?: Home
// spousePersonalData?: SpousePersonalData
// vehicles?: Vehicle[]
// references?: Reference[]
// }
export interface DadosCliente {
identificacao: ProjetoPessoaEnvolvidaIdentificacaoApiModel
dadosPessoais: ProjetoPessoaEnvolvidaDadosPessoaisApiModel
fonteRenda: ProjetoPessoaEnvolvidaFonteRendaApiModel
endereco: ProjetoPessoaEnvolvidaEnderecoApiModel
dadosMoradia: ProjetoPessoaEnvolvidaDadosMoradiaApiModel
conjuge: ProjetoPessoaEnvolvidaConjugeApiModel & ProjetoPessoaEnvolvidaConjugeDadosAdicionaisApiModel
veiculos: ProjetoPessoaEnvolvidaVeiculoApiModel[]
referencias: ProjetoPessoaEnvolvidaReferenciaApiModel[]
}
export class GetCustomerDataMapper implements DomainAdapter<DadosCliente, InvolvedPerson> {
private identificationMapper: CDIdentificationAdapter
private personalDataMapper: CDPersonalDataMapper
private sourceIncomeMapper: CDSourceIncomeAdapter
private addresseMapper: CDUpdateAddressMapper
private homeMapper: CDUpdateHomeMapper
private referenceMapper: ReferenceMapper
private spouseMapper: CDUpdateSpouseDataMapper
private vehicleMapper: VehicleMapper
constructor() {
this.identificationMapper = new CDIdentificationAdapter()
this.personalDataMapper = new CDPersonalDataMapper()
this.sourceIncomeMapper = new CDSourceIncomeAdapter()
this.addresseMapper = new CDUpdateAddressMapper()
this.homeMapper = new CDUpdateHomeMapper()
this.referenceMapper = new ReferenceMapper()
this.spouseMapper = new CDUpdateSpouseDataMapper()
this.vehicleMapper = new VehicleMapper()
}
public mapApiModelToDomain = (dC: DadosCliente): InvolvedPerson => ({
id: dC.identificacao.id || '',
identification: this.identificationMapper.mapApiModelToDomain(dC.identificacao),
personalData: this.personalDataMapper.mapApiModelToDomain(dC.dadosPessoais),
sourceIncome: this.sourceIncomeMapper.mapApiModelToDomain(dC.fonteRenda),
address: this.addresseMapper.mapApiModelToDomain(dC.endereco),
home: this.homeMapper.mapApiModelToDomain(dC.dadosMoradia),
spousePersonalData: this.spouseMapper.mapApiModelToDomain(dC.conjuge),
vehicles: dC.veiculos.map(this.vehicleMapper.mapApiModelToDomain),
references: dC.referencias.map(this.referenceMapper.mapApiModelToDomain),
})
}
import {
CreditGracePeriod,
CreditInformation,
CreditInstallment,
Event,
Operation,
RescheduleReason,
Schedule,
ScheduleCancellationReason,
ScheduleContext,
ScheduleStatus,
VisitAddress
} from '@agiliza/api/domain'
import {
AgendamentoDadosCreditoInteresseApiModel,
AgendamentoVisitaClienteApiModel,
AgendamentoVisitaOperacaoApiModel,
AgendamentoVisitaSituacaoApiModel,
AgendamentoVisitaSituacaoCompletoApiModel,
ContextoVisitaResponseApiModel,
CreditoCarenciaApiModel,
EnderecoApiModel,
EventoVisitaApiModel,
MotivoCancelamentoApiModel,
MotivoReagendamentoApiModel
} from '@microcredito/client'
import { ProjectDocumentMapper } from './project'
import { DomainAdapter } from './shared'
export class CreditInformationAdapter implements DomainAdapter<AgendamentoDadosCreditoInteresseApiModel, CreditInformation> {
public mapApiModelToDomain = (apimodel: AgendamentoDadosCreditoInteresseApiModel): CreditInformation => ({
creditValue: apimodel.valor,
creditInstallment: apimodel.numeroParcelas,
creditObjective: apimodel.objetivo,
creditGracePeriod: apimodel.carencia,
})
}
export class VisitAddressAdapter implements DomainAdapter<EnderecoApiModel, VisitAddress> {
public mapApiModelToDomain = (apimodel: EnderecoApiModel): VisitAddress => ({
id: apimodel.id || '',
cep: apimodel.cep,
city: apimodel.municipio,
state: apimodel.estado,
complement: apimodel.complemento || '',
district: apimodel.bairro,
number: apimodel.numero,
street: apimodel.logradouro,
})
}
type Agendamento = Omit<AgendamentoVisitaClienteApiModel, 'creditoInteresse' | 'enderecoVisita'>
export class ScheduleAdapter implements DomainAdapter<Agendamento, Schedule> {
// private userClientMapper: UserClientMapper
// private addressAdapter: VisitAddressAdapter
// private creditInformationAdapter: CreditInformationAdapter
private statusAdapter: ScheduleStatusAdapter
private documentAdapter: ProjectDocumentMapper
constructor() {
// this.userClientMapper = new UserClientMapper()
// this.addressAdapter = new VisitAddressAdapter()
// this.creditInformationAdapter = new CreditInformationAdapter()
this.statusAdapter = new ScheduleStatusAdapter()
this.documentAdapter = new ProjectDocumentMapper()
}
public mapApiModelToDomain = (agendamento: Agendamento): Schedule => {
const result: Schedule = {
id: agendamento.id || '',
number: agendamento.numero,
date: agendamento.data,
events: agendamento.eventos,
documents: agendamento.documentos.map(this.documentAdapter.mapApiModelToDomain),
status: this.statusAdapter.mapApiModelToDomain(agendamento.situacao),
// user: this.userClientMapper.mapApiModelToDomain(agendamento.cliente),
// complement: agendamento.enderecoVisita
// ? {
// address: this.addressAdapter.mapApiModelToDomain(agendamento.enderecoVisita),
// interestCredit: agendamento.creditoInteresse && this.creditInformationAdapter.mapApiModelToDomain(agendamento.creditoInteresse),
// }
// : ({} as any),
// details: agendamento.solicitacaoReagendamento
// ? {
// rescheduleDate: agendamento.solicitacaoReagendamento.dataReagendamento,
// reason: agendamento.solicitacaoReagendamento.codigoMotivo,
// justification: agendamento.solicitacaoReagendamento.justificativa,
// }
// : agendamento.solicitacaoCancelamento
// ? {
// reason: agendamento.solicitacaoCancelamento.codigoMotivo,
// justification: agendamento.solicitacaoCancelamento.justificativa,
// }
// : ({} as any),
}
return result
}
}
export class ScheduleStatusAdapter implements DomainAdapter<AgendamentoVisitaSituacaoApiModel, ScheduleStatus> {
private scheduleOperationAdapter: ScheduleOperationAdapter
constructor() {
this.scheduleOperationAdapter = new ScheduleOperationAdapter()
}
public mapApiModelToDomain = (apimodel: AgendamentoVisitaSituacaoApiModel): ScheduleStatus => {
const situacao = apimodel as AgendamentoVisitaSituacaoCompletoApiModel
const result: ScheduleStatus = {
id: situacao.codigo || '',
description: situacao.descricao,
operations: situacao.operacoes?.filter((op) => op.permissao !== 'cliente').map(this.scheduleOperationAdapter.mapApiModelToDomain) ?? [],
}
return result
}
}
export class ScheduleOperationAdapter implements DomainAdapter<AgendamentoVisitaOperacaoApiModel, Operation> {
public mapApiModelToDomain = (operacao: AgendamentoVisitaOperacaoApiModel): Operation => ({
id: operacao.codigo,
description: operacao.descricao,
descriptionTransition: operacao.descricaoTransicao,
permission: operacao.permissao === 'cliente' ? 'customer' : 'broker',
})
}
export class RescheduleReasonAdapter implements DomainAdapter<MotivoReagendamentoApiModel, RescheduleReason> {
public mapApiModelToDomain = (apimodel: MotivoReagendamentoApiModel): RescheduleReason => ({
id: apimodel.codigo,
description: apimodel.descricao,
})
}
export class ScheduleCancellationReasonAdapter implements DomainAdapter<MotivoCancelamentoApiModel, ScheduleCancellationReason> {
public mapApiModelToDomain = (apimodel: MotivoCancelamentoApiModel): ScheduleCancellationReason => ({
id: apimodel.codigo,
description: apimodel.descricao,
})
}
export class VisitEventAdapter implements DomainAdapter<EventoVisitaApiModel, Event> {
public mapApiModelToDomain = (apimodel: EventoVisitaApiModel): Event => ({
id: apimodel.id || '',
title: apimodel.titulo,
date: apimodel.data,
description: apimodel.descricao,
})
}
// Parcelas
export class CreditInstallmentAdapter implements DomainAdapter<number, CreditInstallment> {
public mapApiModelToDomain = (apimodel: number) => {
const result: CreditInstallment = {
id: apimodel.toString(),
description: apimodel.toString(),
}
return result
}
}
// Carência
export class CreditGracePeriodAdapter implements DomainAdapter<CreditoCarenciaApiModel, CreditGracePeriod> {
public mapApiModelToDomain = (apimodel: CreditoCarenciaApiModel) => {
const result: CreditGracePeriod = {
id: apimodel.codigo,
description: apimodel.descricao,
}
return result
}
}
export class ScheduleContextAdapter implements DomainAdapter<ContextoVisitaResponseApiModel, ScheduleContext> {
// private objectiveAdapter: CreditObjectiveAdapter
private gracePeriodAdapter: CreditGracePeriodAdapter
private installmentAdapter: CreditInstallmentAdapter
// private dueDateAdapter: CreditDueDateAdapter
// private productAdapter: CreditProductAdapter
constructor() {
// this.objectiveAdapter = new CreditObjectiveAdapter()
this.gracePeriodAdapter = new CreditGracePeriodAdapter()
this.installmentAdapter = new CreditInstallmentAdapter()
// this.dueDateAdapter = new CreditDueDateAdapter()
// this.productAdapter = new CreditProductAdapter()
}
public mapApiModelToDomain = (apimodel: ContextoVisitaResponseApiModel) => {
const result: ScheduleContext = {
gracePeriods: apimodel.carencias.map(this.gracePeriodAdapter.mapApiModelToDomain),
installments: apimodel.parcelas.map(this.installmentAdapter.mapApiModelToDomain),
}
return result
}
}
...@@ -14,10 +14,19 @@ export class SubProductMapper implements DomainAdapter<SubprodutoApiModel, SubPr ...@@ -14,10 +14,19 @@ export class SubProductMapper implements DomainAdapter<SubprodutoApiModel, SubPr
public mapApiModelToDomain = (subproduto: SubprodutoApiModel): SubProduct => ({ public mapApiModelToDomain = (subproduto: SubprodutoApiModel): SubProduct => ({
id: subproduto.id || '', id: subproduto.id || '',
description: subproduto.descricao, description: subproduto.descricao,
IOF: subproduto.iof, IOF: subproduto.valorTotalIOF,
TAC: subproduto.tac, TAC: subproduto.valorTarifadeAnaliseDeCredito,
fee: subproduto.taxa, monthlyCET: subproduto.taxaCETMensal,
yearlyCET: subproduto.taxaCETAnual,
fee: subproduto.taxaJuros,
installementOptions: subproduto.opcoesPrestacao?.map(this.mapInstallmentOption) || [], installementOptions: subproduto.opcoesPrestacao?.map(this.mapInstallmentOption) || [],
maxAmountInstallment: subproduto.qntMaxPrestacoes, maxAmountInstallment: subproduto.qtdeParcelas,
totalLiberateLiquidValue: subproduto.valorTotalLiberarLiquido,
loanValue: subproduto.valorEmprestimo,
baseCalcDate: subproduto.dataBaseCalc,
amortization: subproduto.sistemaAmortizacao,
graceInstallementAmount: subproduto.qtdeParcelasCarencia,
totalCalcValue: subproduto.valorTotalCalc,
feeTotalValue: subproduto.valorTotalJuros,
}) })
} }
import { UserClient, UserCustomer } from '@agiliza/api/domain'
import { AgendamentoDadosClienteApiModel, UsuarioClienteApiModel } from '@microcredito/client'
import { DomainAdapter } from './shared'
export class UserCustomerMapper implements DomainAdapter<UsuarioClienteApiModel, UserCustomer | undefined> {
public mapApiModelToDomain = (apimodel?: UsuarioClienteApiModel): UserCustomer | undefined => {
const result: UserCustomer | undefined = apimodel
? {
cpfcnpj: apimodel.cpfcnpj,
name: apimodel.nome,
phone: apimodel.celular,
ownerCPF: apimodel.cpfResponsavel,
ownerName: apimodel.nomeResponsavel,
address: apimodel.endereco
? {
additionalInfo: apimodel.endereco.complemento,
cep: apimodel.endereco.cep,
city: apimodel.endereco.municipio,
state: apimodel.endereco.estado,
district: apimodel.endereco.bairro,
number: apimodel.endereco.numero,
street: apimodel.endereco.logradouro,
id: apimodel.endereco.id,
}
: undefined,
email: apimodel.email,
}
: undefined
return result
}
}
export class UserClientMapper implements DomainAdapter<AgendamentoDadosClienteApiModel, UserClient> {
public mapApiModelToDomain = (apimodel: AgendamentoDadosClienteApiModel): UserClient => {
const result: UserClient = {
cpfcnpj: apimodel.cpfcnpj,
name: apimodel.nome,
}
return result
}
}
import { GetProjects } from '@agiliza/api/domain'
import { ClienteApi, Configuration } from '@microcredito/client'
import { ErrorMappers, ProjectMappers } from '../mappers'
import { API_URL, mapUserAgentToString, SESSION_KEY, UserAgent } from './shared'
export interface ProjectRepository {
getProjects(input: GetProjects['Input']): Promise<GetProjects['Output']>
}
export class ProjectRepositoryImpl implements ProjectRepository {
private api: ClienteApi
private errorAdapter: ErrorMappers.ResponseErrorAdapter
private projectMapper: ProjectMappers.ProjectMapper
constructor(userAgent: string, accessToken: string) {
this.errorAdapter = new ErrorMappers.ResponseErrorAdapter()
this.projectMapper = new ProjectMappers.ProjectMapper()
this.api = new ClienteApi(
new Configuration({
basePath: API_URL,
accessToken,
headers: {
'User-Agent': userAgent,
},
})
)
}
public getProjects = async (input: GetProjects['Input']): Promise<GetProjects['Output']> => {
try {
const projetos = await this.api.obterAcompanhamentos()
return projetos.map(this.projectMapper.mapApiModelToDomain)
} catch (e) {
const result = await this.errorAdapter.mapApiModelToDomain(e)
throw result
}
}
}
export class ProjectRepositoryImplFactory {
static create(userAgent: UserAgent) {
const accessToken = localStorage.getItem(SESSION_KEY) || ''
const repository = new ProjectRepositoryImpl(mapUserAgentToString(userAgent), accessToken)
return repository
}
}
import { import {
AddBDProductService, AddBDProductService,
GetBDProductsServices, GetBDProductsServices,
GetBusinessData,
UpdateBDAddress, UpdateBDAddress,
UpdateBDIdentification, UpdateBDIdentification,
UpdateBDProductService, UpdateBDProductService,
UpdateBDStockSalesCosts UpdateBDStockSalesCosts
} from '@agiliza/api/domain' } from '@agiliza/api/domain'
import { ErrorMappers } from '@agiliza/api/mappers' import { ErrorMappers } from '@agiliza/api/mappers'
import { DadosNegocio } from '@agiliza/api/mappers/domain/proposalData'
import { ClienteApi, Configuration } from '@microcredito/client' import { ClienteApi, Configuration } from '@microcredito/client'
import { ProposalDataApiMappers, ProposalDataMappers } from '../../mappers' import { ProposalDataApiMappers, ProposalDataMappers } from '../../mappers'
...@@ -19,6 +21,7 @@ export interface PDBusinessDataRepository { ...@@ -19,6 +21,7 @@ export interface PDBusinessDataRepository {
updateIdentification(input: UpdateBDIdentification['Input']): Promise<UpdateBDIdentification['Output']> updateIdentification(input: UpdateBDIdentification['Input']): Promise<UpdateBDIdentification['Output']>
updateAddress(input: UpdateBDAddress['Input']): Promise<UpdateBDAddress['Output']> updateAddress(input: UpdateBDAddress['Input']): Promise<UpdateBDAddress['Output']>
updateStockSalesCosts(input: UpdateBDStockSalesCosts['Input']): Promise<UpdateBDStockSalesCosts['Output']> updateStockSalesCosts(input: UpdateBDStockSalesCosts['Input']): Promise<UpdateBDStockSalesCosts['Output']>
getBusinessData(input: GetBusinessData['Input']): Promise<GetBusinessData['Output']>
} }
export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository { export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository {
...@@ -34,6 +37,8 @@ export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository { ...@@ -34,6 +37,8 @@ export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository {
private bdUpdateStockSalesCostsApiMapper: ProposalDataApiMappers.BDUpdateStockSalesCosts private bdUpdateStockSalesCostsApiMapper: ProposalDataApiMappers.BDUpdateStockSalesCosts
private bdUpdateStockSalesCostsMapper: ProposalDataMappers.BDUpdateStockSalesCostsMapper private bdUpdateStockSalesCostsMapper: ProposalDataMappers.BDUpdateStockSalesCostsMapper
private businessDataMapper: ProposalDataMappers.BDGetBusinessDataMapper
constructor(userAgent: string, accessToken: string) { constructor(userAgent: string, accessToken: string) {
this.errorAdapter = new ErrorMappers.ResponseErrorAdapter() this.errorAdapter = new ErrorMappers.ResponseErrorAdapter()
this.bdGetServicesProductsMapper = new ProposalDataMappers.BDProductsServicesMapper() this.bdGetServicesProductsMapper = new ProposalDataMappers.BDProductsServicesMapper()
...@@ -46,6 +51,7 @@ export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository { ...@@ -46,6 +51,7 @@ export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository {
this.bdUpdateStockSalesCostsApiMapper = new ProposalDataApiMappers.BDUpdateStockSalesCosts() this.bdUpdateStockSalesCostsApiMapper = new ProposalDataApiMappers.BDUpdateStockSalesCosts()
this.bdUpdateStockSalesCostsMapper = new ProposalDataMappers.BDUpdateStockSalesCostsMapper() this.bdUpdateStockSalesCostsMapper = new ProposalDataMappers.BDUpdateStockSalesCostsMapper()
this.businessDataMapper = new ProposalDataMappers.BDGetBusinessDataMapper()
this.api = new ClienteApi( this.api = new ClienteApi(
new Configuration({ new Configuration({
basePath: API_URL, basePath: API_URL,
...@@ -57,6 +63,22 @@ export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository { ...@@ -57,6 +63,22 @@ export class PDBusinessDataRepositoryImpl implements PDBusinessDataRepository {
) )
} }
public getBusinessData = async (input: GetBusinessData['Input']): Promise<GetBusinessData['Output']> => {
const { projectId } = input
try {
const result: DadosNegocio = {
identificacao: await this.api.obterIdentificacaoDadosNegocio({ projetoId: projectId }),
endereco: await this.api.obterEnderecoDadosNegocio({ projetoId: projectId }),
produtosServicos: await this.api.obterProdutosServicosDadosNegocio({ projetoId: projectId }),
estoqueVendasCustos: await this.api.obterEstoqueVendasCustosDadosNegocio({ projetoId: projectId }),
}
return this.businessDataMapper.mapApiModelToDomain(result)
} catch (e) {
const result = await this.errorAdapter.mapApiModelToDomain(e)
throw result
}
}
public getProductsServices = async (input: GetBDProductsServices['Input']): Promise<GetBDProductsServices['Output']> => { public getProductsServices = async (input: GetBDProductsServices['Input']): Promise<GetBDProductsServices['Output']> => {
try { try {
const response = await this.api.obterProdutosServicosDadosNegocio({ projetoId: input.projectId }) const response = await this.api.obterProdutosServicosDadosNegocio({ projetoId: input.projectId })
......
...@@ -3,16 +3,21 @@ import { ...@@ -3,16 +3,21 @@ import {
AddCDReference, AddCDReference,
AddCDVehicle, AddCDVehicle,
CreateProposal, CreateProposal,
GetCDIdentification,
GetCDReferences, GetCDReferences,
GetCDVehicles, GetCDVehicles,
GetCustomerData,
UpdateCDAddress, UpdateCDAddress,
UpdateCDHome, UpdateCDHome,
UpdateCDIdentification,
UpdateCDPersonalData, UpdateCDPersonalData,
UpdateCDReference, UpdateCDReference,
UpdateCDSourceIncome, UpdateCDSourceIncome,
UpdateCDSpouseData, UpdateCDSpouseData,
UpdateCDVehicle UpdateCDVehicle
} from '@agiliza/api/domain' } from '@agiliza/api/domain'
import { DadosCliente } from '@agiliza/api/mappers/domain/proposalData'
import { INVOLVED_PERSON_NAMES, INVOLVED_PERSON_TYPES } from '@agiliza/constants/involvedPeople'
import { ClienteApi, Configuration } from '@microcredito/client' import { ClienteApi, Configuration } from '@microcredito/client'
import { ErrorMappers, ProposalDataApiMappers, ProposalDataMappers } from '../../mappers' import { ErrorMappers, ProposalDataApiMappers, ProposalDataMappers } from '../../mappers'
...@@ -21,6 +26,7 @@ import { API_URL, mapUserAgentToString, SESSION_KEY, UserAgent } from '../shared ...@@ -21,6 +26,7 @@ import { API_URL, mapUserAgentToString, SESSION_KEY, UserAgent } from '../shared
export interface PDCustomerDataDataRepository { export interface PDCustomerDataDataRepository {
createProposal(input: CreateProposal['Input']): Promise<CreateProposal['Output']> createProposal(input: CreateProposal['Input']): Promise<CreateProposal['Output']>
addIdentification(input: AddCDIdentification['Input']): Promise<AddCDIdentification['Output']> addIdentification(input: AddCDIdentification['Input']): Promise<AddCDIdentification['Output']>
updateIdentification(input: UpdateCDIdentification['Input']): Promise<UpdateCDIdentification['Output']>
updatePersonalData(input: UpdateCDPersonalData['Input']): Promise<UpdateCDPersonalData['Output']> updatePersonalData(input: UpdateCDPersonalData['Input']): Promise<UpdateCDPersonalData['Output']>
updateAddress(input: UpdateCDAddress['Input']): Promise<UpdateCDAddress['Output']> updateAddress(input: UpdateCDAddress['Input']): Promise<UpdateCDAddress['Output']>
updateSourceIncome(input: UpdateCDSourceIncome['Input']): Promise<UpdateCDSourceIncome['Output']> updateSourceIncome(input: UpdateCDSourceIncome['Input']): Promise<UpdateCDSourceIncome['Output']>
...@@ -32,13 +38,16 @@ export interface PDCustomerDataDataRepository { ...@@ -32,13 +38,16 @@ export interface PDCustomerDataDataRepository {
getVehicles(input: GetCDVehicles['Input']): Promise<GetCDVehicles['Output']> getVehicles(input: GetCDVehicles['Input']): Promise<GetCDVehicles['Output']>
addVehicle(input: AddCDVehicle['Input']): Promise<AddCDVehicle['Output']> addVehicle(input: AddCDVehicle['Input']): Promise<AddCDVehicle['Output']>
updateVehicle(input: UpdateCDVehicle['Input']): Promise<UpdateCDVehicle['Output']> updateVehicle(input: UpdateCDVehicle['Input']): Promise<UpdateCDVehicle['Output']>
getCustomerData(input: GetCustomerData['Input']): Promise<GetCustomerData['Output']>
getIdentification(input: GetCDIdentification['Input']): Promise<GetCDIdentification['Output']>
} }
export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepository { export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepository {
private api: ClienteApi private api: ClienteApi
private errorAdapter: ErrorMappers.ResponseErrorAdapter private errorAdapter: ErrorMappers.ResponseErrorAdapter
private createProposalApiMapper: ProposalDataApiMappers.CreateProposalApiMapper private createProposalApiMapper: ProposalDataApiMappers.CreateProposalApiMapper
private cdUpdateIdentificationApiMapper: ProposalDataApiMappers.CDAddIdentificationMapper private cdAddIdentificationApiMapper: ProposalDataApiMappers.CDAddIdentificationMapper
private cdUpdateIdentificationApiMapper: ProposalDataApiMappers.CDUpdateIdentificationMapper
private cdUpdatePersonalDataApiMapper: ProposalDataApiMappers.CDUpdatePersonalDataMapper private cdUpdatePersonalDataApiMapper: ProposalDataApiMappers.CDUpdatePersonalDataMapper
private cdIdentificationMapper: ProposalDataMappers.CDIdentificationAdapter private cdIdentificationMapper: ProposalDataMappers.CDIdentificationAdapter
private cdPersonalDataMapper: ProposalDataMappers.CDPersonalDataMapper private cdPersonalDataMapper: ProposalDataMappers.CDPersonalDataMapper
...@@ -56,12 +65,14 @@ export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepositor ...@@ -56,12 +65,14 @@ export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepositor
private cdVehicleMapper: ProposalDataMappers.VehicleMapper private cdVehicleMapper: ProposalDataMappers.VehicleMapper
private cdAddVehicleApiMapper: ProposalDataApiMappers.CDAddVehicleApiMapper private cdAddVehicleApiMapper: ProposalDataApiMappers.CDAddVehicleApiMapper
private cdUpdateVehicleApiMapper: ProposalDataApiMappers.CDUpdateVehicleApiMapper private cdUpdateVehicleApiMapper: ProposalDataApiMappers.CDUpdateVehicleApiMapper
private cdGetCustomerDataMapper: ProposalDataMappers.GetCustomerDataMapper
constructor(userAgent: string, accessToken: string) { constructor(userAgent: string, accessToken: string) {
this.errorAdapter = new ErrorMappers.ResponseErrorAdapter() this.errorAdapter = new ErrorMappers.ResponseErrorAdapter()
this.createProposalApiMapper = new ProposalDataApiMappers.CreateProposalApiMapper() this.createProposalApiMapper = new ProposalDataApiMappers.CreateProposalApiMapper()
this.cdIdentificationMapper = new ProposalDataMappers.CDIdentificationAdapter() this.cdIdentificationMapper = new ProposalDataMappers.CDIdentificationAdapter()
this.cdUpdateIdentificationApiMapper = new ProposalDataApiMappers.CDAddIdentificationMapper() this.cdAddIdentificationApiMapper = new ProposalDataApiMappers.CDAddIdentificationMapper()
this.cdUpdateIdentificationApiMapper = new ProposalDataApiMappers.CDUpdateIdentificationMapper()
this.cdUpdatePersonalDataApiMapper = new ProposalDataApiMappers.CDUpdatePersonalDataMapper() this.cdUpdatePersonalDataApiMapper = new ProposalDataApiMappers.CDUpdatePersonalDataMapper()
this.cdPersonalDataMapper = new ProposalDataMappers.CDPersonalDataMapper() this.cdPersonalDataMapper = new ProposalDataMappers.CDPersonalDataMapper()
this.cdUpdateAddressApiMapper = new ProposalDataApiMappers.CDUpdateAddressApiMapper() this.cdUpdateAddressApiMapper = new ProposalDataApiMappers.CDUpdateAddressApiMapper()
...@@ -78,6 +89,7 @@ export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepositor ...@@ -78,6 +89,7 @@ export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepositor
this.cdVehicleMapper = new ProposalDataMappers.VehicleMapper() this.cdVehicleMapper = new ProposalDataMappers.VehicleMapper()
this.cdAddVehicleApiMapper = new ProposalDataApiMappers.CDAddVehicleApiMapper() this.cdAddVehicleApiMapper = new ProposalDataApiMappers.CDAddVehicleApiMapper()
this.cdUpdateVehicleApiMapper = new ProposalDataApiMappers.CDUpdateVehicleApiMapper() this.cdUpdateVehicleApiMapper = new ProposalDataApiMappers.CDUpdateVehicleApiMapper()
this.cdGetCustomerDataMapper = new ProposalDataMappers.GetCustomerDataMapper()
this.api = new ClienteApi( this.api = new ClienteApi(
new Configuration({ new Configuration({
...@@ -90,9 +102,56 @@ export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepositor ...@@ -90,9 +102,56 @@ export class PDCustomerDataRepositoryImpl implements PDCustomerDataDataRepositor
) )
} }
public getIdentification = async (input: GetCDIdentification['Input']): Promise<GetCDIdentification['Output']> => {
try {
const pessoasEnvolvidas = await this.api.obterPessoasEnvolvidas({ projetoId: input.projectId })
const involvedPeople = pessoasEnvolvidas.map(this.cdIdentificationMapper.mapApiModelToDomain)
console.log(involvedPeople)
const identification = involvedPeople.find((pE) => pE.type === INVOLVED_PERSON_NAMES[INVOLVED_PERSON_TYPES['CUSTOMER']])
return identification
} catch (e) {
const result = await this.errorAdapter.mapApiModelToDomain(e)
throw result
}
}
public getCustomerData = async (input: GetCustomerData['Input']): Promise<GetCustomerData['Output']> => {
try {
const pessoasEnvolvidas = await this.api.obterPessoasEnvolvidas({ projetoId: input.projectId })
const identificacao = pessoasEnvolvidas.find((pE) => pE.id === input.personId)!
const result: DadosCliente = {
identificacao,
dadosPessoais: await this.api.obterDadosPessoaisPessoaEnvolvida({ projetoId: input.projectId, pessoaId: input.personId }),
fonteRenda: await this.api.obterFonteRendaPessoaEnvolvida({ projetoId: input.projectId, pessoaId: input.personId }),
endereco: await this.api.obterEnderecoPessoaEnvolvida({ projetoId: input.projectId, pessoaId: input.personId }),
dadosMoradia: await this.api.obterDadosPessoaEnvolvidaMoradia({ projetoId: input.projectId, pessoaId: input.personId }),
conjuge: {
...(await this.api.obterConjugePessoaEnvolvida({ projetoId: input.projectId, pessoaId: input.personId })),
...(await this.api.obterConjugeDadosAdicionaisPessoaEnvolvida({ projetoId: input.projectId, pessoaId: input.personId })),
},
veiculos: await this.api.obterVeiculosPessoaEnvolvida({ projetoId: input.projectId, pessoaId: input.personId }),
referencias: await this.api.obterReferenciasPessoaEnvolvida({ projetoId: input.projectId, pessoaId: input.personId }),
}
return this.cdGetCustomerDataMapper.mapApiModelToDomain(result)
} catch (e) {
const result = await this.errorAdapter.mapApiModelToDomain(e)
throw result
}
}
public updateIdentification = async (input: UpdateCDIdentification['Input']): Promise<UpdateCDIdentification['Output']> => {
try {
const response = await this.api.atualizarIdentificacaoPessoaEnvolvida(this.cdUpdateIdentificationApiMapper.mapDomainToApiModel(input))
return this.cdIdentificationMapper.mapApiModelToDomain(response)
} catch (e) {
const result = await this.errorAdapter.mapApiModelToDomain(e)
throw result
}
}
public addIdentification = async (input: AddCDIdentification['Input']): Promise<AddCDIdentification['Output']> => { public addIdentification = async (input: AddCDIdentification['Input']): Promise<AddCDIdentification['Output']> => {
try { try {
const response = await this.api.incluirPessoaEnvolvida(this.cdUpdateIdentificationApiMapper.mapDomainToApiModel(input)) const response = await this.api.incluirPessoaEnvolvida(this.cdAddIdentificationApiMapper.mapDomainToApiModel(input))
return this.cdIdentificationMapper.mapApiModelToDomain(response) return this.cdIdentificationMapper.mapApiModelToDomain(response)
} catch (e) { } catch (e) {
const result = await this.errorAdapter.mapApiModelToDomain(e) const result = await this.errorAdapter.mapApiModelToDomain(e)
......
...@@ -7,10 +7,11 @@ import { isAuthenticated } from '@agiliza/redux/session/selectors' ...@@ -7,10 +7,11 @@ import { isAuthenticated } from '@agiliza/redux/session/selectors'
interface Props extends RouteProps { interface Props extends RouteProps {
authenticated: boolean authenticated: boolean
redirectTo?: string
} }
function AuthRoute({ authenticated, ...props }: Props) { function AuthRoute({ authenticated, redirectTo, ...props }: Props) {
return authenticated ? <Route {...props} /> : <Redirect to="/login" /> return authenticated ? <Route {...props} /> : <Redirect to={redirectTo || '/login'} />
} }
const mapStateToProps = (state: StoreState) => ({ const mapStateToProps = (state: StoreState) => ({
......
...@@ -16,7 +16,7 @@ interface Props extends ExtendedProps { ...@@ -16,7 +16,7 @@ interface Props extends ExtendedProps {
const PhoneField = (props: Props) => { const PhoneField = (props: Props) => {
const { label, value, onChange } = props const { label, value, onChange } = props
return <TextField variant="outlined" label="Telefone" value={label || maskPhone(value)} onChange={onChange} inputProps={{ maxLength: 15 }} /> return <TextField variant="outlined" label={label || 'Telefone'} value={maskPhone(value)} onChange={onChange} inputProps={{ maxLength: 15 }} />
} }
export default withStyles(styles)(PhoneField) export default withStyles(styles)(PhoneField)
export const AMORTIZATIONS = {
1: 'Price',
2: 'SAC',
3: 'Livre',
} as const
...@@ -2,6 +2,7 @@ import authentication, { ...@@ -2,6 +2,7 @@ import authentication, {
initialState as authenticationInitState, initialState as authenticationInitState,
Store as AuthenticationState Store as AuthenticationState
} from './authentication' } from './authentication'
import project, { initialState as projectInitState, Store as ProjectState } from './project'
import proposalData, { import proposalData, {
initialState as proposalDataInitState, initialState as proposalDataInitState,
State as ProposalDataState State as ProposalDataState
...@@ -17,6 +18,7 @@ export interface EntitiesState { ...@@ -17,6 +18,7 @@ export interface EntitiesState {
simulation: SimulationState simulation: SimulationState
authentication: AuthenticationState authentication: AuthenticationState
proposalData: ProposalDataState proposalData: ProposalDataState
project: ProjectState
} }
export const initialState: EntitiesState = { export const initialState: EntitiesState = {
...@@ -24,6 +26,7 @@ export const initialState: EntitiesState = { ...@@ -24,6 +26,7 @@ export const initialState: EntitiesState = {
system: systemInitState, system: systemInitState,
authentication: authenticationInitState, authentication: authenticationInitState,
proposalData: proposalDataInitState, proposalData: proposalDataInitState,
project: projectInitState,
} }
const reducers = { const reducers = {
...@@ -31,6 +34,7 @@ const reducers = { ...@@ -31,6 +34,7 @@ const reducers = {
system, system,
authentication, authentication,
proposalData, proposalData,
project,
} }
export default reducers export default reducers
import { getActionTypes } from '@agiliza/utils/method'
import * as selectors from './selectors'
import slice from './slice'
export * from './slice'
const actions = slice.actions
const reducer = slice.reducer
const types = getActionTypes(slice.actions)
export { actions, types, selectors }
export default reducer
import { createSelector } from '@reduxjs/toolkit'
import { Store } from './slice'
export const getAllIds = (key: keyof Store) => (state: Store) => {
return state[key].allIds
}
export const getById = (key: keyof Store) => (state: Store) => {
return state[key].byId
}
export const getProjects = createSelector(getById('projects'), getAllIds('projects'), (byId, allIds) => allIds.map((id) => byId[id]))
import { normalize, schema } from 'normalizr'
import { Project } from '@agiliza/api/domain'
import { NormalizedEntity } from '@agiliza/utils/method'
export const PROJECT_PREFIX = 'entities/project'
export interface NormalizedProjects {
projects: NormalizedEntity<Project>
}
const project = new schema.Array(new schema.Entity('projects'))
export const normalizeProjects = (sCs: Project[]) => {
const { entities } = normalize(sCs, project)
const normalizedEntities = entities as unknown as NormalizedProjects
return normalizedEntities
}
import { GetProjects, Project } from '@agiliza/api/domain'
import { types as fetchTypes } from '@agiliza/redux/useCases/project'
import { EntityStore, syncAllIds, syncById } from '@agiliza/utils/method'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { PREFIX } from '../shared'
import { normalizeProjects } from './shared'
export interface Store {
projects: EntityStore<Project>
}
export const initialState: Store = {
projects: { byId: {}, allIds: [] },
}
export default createSlice({
name: `${PREFIX}/project`,
initialState,
reducers: {},
extraReducers: {
[fetchTypes.getProjects.fulfilled]: (state, action: PayloadAction<GetProjects['Output']>) => {
const normalized = normalizeProjects(action.payload)
state.projects.byId = syncById(state.projects, normalized.projects)
state.projects.allIds = syncAllIds(state.projects, normalized.projects)
},
},
})
import { getActionTypes } from '@agiliza/utils/method'
import * as selectors from './selectors'
import slice from './slice'
export * from './slice'
const actions = slice.actions
const reducer = slice.reducer
const types = getActionTypes(slice.actions)
export { actions, types, selectors }
export default reducer
import { BusinessData } from '@agiliza/api/domain'
import { createSelector } from '@reduxjs/toolkit'
import { Store } from './slice'
export const getAllIds = (key: keyof Pick<Store, 'productsServices'>) => (state: Store) => {
return state[key].allIds
}
export const getById = (key: keyof Pick<Store, 'productsServices'>) => (state: Store) => {
return state[key].byId
}
export const getIdentification = (state: Store) => state.identification
export const getAddress = (state: Store) => state.address
export const getStockSalesCosts = (state: Store) => state.stockSalesCosts
export const getProductsServices = createSelector(getById('productsServices'), getAllIds('productsServices'), (byId, allIds) =>
allIds.map((id) => byId[id])
)
export const getBusinessData = (state: Store): BusinessData => ({
identification: getIdentification(state),
address: getAddress(state),
stockSalesCosts: getStockSalesCosts(state),
productsServices: getProductsServices(state),
})
import { normalize, schema } from 'normalizr'
import { BDProductService } from '@agiliza/api/domain'
import { NormalizedEntity } from '@agiliza/utils/method'
export const PROJECT_PREFIX = 'entities/project'
export interface NormalizedProjects {
productsServices: NormalizedEntity<BDProductService>
}
const productsServices = new schema.Array(new schema.Entity('productsServices'))
export const normalizeProductsServices = (pS: BDProductService[]) => {
const { entities } = normalize(pS, productsServices)
const normalizedEntities = entities as unknown as NormalizedProjects
return normalizedEntities
}
import {
AddBDProductService,
BDProductService,
BusinessData,
GetBDProductsServices,
GetBusinessData,
UpdateBDProductService
} from '@agiliza/api/domain'
import { types as businessDataTypes } from '@agiliza/redux/useCases/proposalData/businessData'
import { keys, WithEntityStore } from '@agiliza/utils/method'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { PROPOSAL_DATA_PREFIX } from '../shared'
import { normalizeProductsServices } from './shared'
type ExtendedStore = Omit<BusinessData, 'productsServices'> & WithEntityStore<Required<Pick<BusinessData, 'productsServices'>>>
export interface Store extends ExtendedStore {}
export const initialState: Store = {
identification: undefined,
address: undefined,
stockSalesCosts: undefined,
productsServices: { byId: {}, allIds: [] },
}
const updateProductsServices = (state: Store, pds: BDProductService[]) => {
const { productsServices } = normalizeProductsServices(pds)
state.productsServices.byId = productsServices
state.productsServices.allIds = keys(productsServices)
}
export default createSlice({
name: `${PROPOSAL_DATA_PREFIX}/businessData`,
initialState,
reducers: {},
extraReducers: {
[businessDataTypes.getBusinessData.fulfilled]: (state, action: PayloadAction<GetBusinessData['Output']>) => {
const { payload } = action
state.identification = payload.identification
state.address = payload.address
state.stockSalesCosts = payload.stockSalesCosts
if (payload.productsServices) updateProductsServices(state, payload.productsServices)
},
[businessDataTypes.getProductsServices.fulfilled]: (state, action: PayloadAction<GetBDProductsServices['Output']>) => {
const { payload } = action
updateProductsServices(state, payload)
},
[businessDataTypes.addProductService.fulfilled]: (state, action: PayloadAction<AddBDProductService['Output']>) => {
const { payload } = action
updateProductsServices(state, payload)
},
[businessDataTypes.updateProductService.fulfilled]: (state, action: PayloadAction<UpdateBDProductService['Output']>) => {
const { payload } = action
updateProductsServices(state, payload)
},
},
})
import { getActionTypes } from '@agiliza/utils/method'
import * as selectors from './selectors'
import slice from './slice'
export * from './slice'
const actions = slice.actions
const reducer = slice.reducer
const types = getActionTypes(slice.actions)
export { actions, types, selectors }
export default reducer
import { InvolvedPerson } from '@agiliza/api/domain'
import { createSelector } from '@reduxjs/toolkit'
import { Store } from './slice'
export const getAllIds = (key: keyof Pick<Store, 'vehicles' | 'references'>) => (state: Store) => {
return state[key].allIds
}
export const getById = (key: keyof Pick<Store, 'vehicles' | 'references'>) => (state: Store) => {
return state[key].byId
}
export const getIdentification = (state: Store) => state.identification
export const getAddress = (state: Store) => state.address
export const getPersonalData = (state: Store) => state.personalData
export const getHome = (state: Store) => state.home
export const getSourceIncome = (state: Store) => state.sourceIncome
export const getSpousePersonalData = (state: Store) => state.spousePersonalData
export const getVehicles = createSelector(getById('vehicles'), getAllIds('vehicles'), (byId, allIds) => allIds.map((id) => byId[id]))
export const getReferences = createSelector(getById('references'), getAllIds('references'), (byId, allIds) => allIds.map((id) => byId[id]))
export const getCustomerData = (state: Store): Omit<InvolvedPerson, 'id'> => ({
identification: getIdentification(state),
address: getAddress(state),
personalData: getPersonalData(state),
home: getHome(state),
sourceIncome: getSourceIncome(state),
spousePersonalData: getSpousePersonalData(state),
references: getReferences(state),
vehicles: getVehicles(state),
})
import { normalize, schema } from 'normalizr'
import { Reference, Vehicle } from '@agiliza/api/domain'
import { NormalizedEntity } from '@agiliza/utils/method'
export const PROJECT_PREFIX = 'entities/project'
export interface NormalizedCustomerData {
vehicles: NormalizedEntity<Vehicle>
references: NormalizedEntity<Reference>
}
const schemas: Record<keyof NormalizedCustomerData, any> = {
references: new schema.Array(new schema.Entity('references')),
vehicles: new schema.Array(new schema.Entity('vehicles')),
}
export const normalizeCustomerData = (vehicles: Vehicle[], references: Reference[]) => {
const { entities } = normalize({ vehicles, references }, schemas)
const normalizedEntities = entities as unknown as NormalizedCustomerData
return normalizedEntities
}
import {
AddCDReference,
AddCDVehicle,
GetCDReferences,
GetCDVehicles,
GetCustomerData,
InvolvedPerson,
Reference,
UpdateCDReference,
UpdateCDVehicle,
Vehicle
} from '@agiliza/api/domain'
import { INVOLVED_PERSON_TYPES } from '@agiliza/constants/involvedPeople'
import { types as customerDataTypes } from '@agiliza/redux/useCases/proposalData/customerData'
import { keys, WithEntityStore } from '@agiliza/utils/method'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { PROPOSAL_DATA_PREFIX } from '../shared'
import { normalizeCustomerData } from './shared'
type ExtendedStore = Omit<InvolvedPerson, 'vehicles' | 'references' | 'id'> &
WithEntityStore<Required<Pick<InvolvedPerson, 'vehicles' | 'references'>>>
export interface Store extends ExtendedStore {}
export const initialState: Store = {
identification: {
id: '',
name: '',
cpfcnpj: '',
gender: '',
type: INVOLVED_PERSON_TYPES['CUSTOMER'],
account: { agencyNumber: '', number: '', cardPicture: '' },
dataType: { doesWithdrawal: false, framework: '' },
},
address: undefined,
personalData: undefined,
home: undefined,
sourceIncome: undefined,
spousePersonalData: undefined,
vehicles: { byId: {}, allIds: [] },
references: { byId: {}, allIds: [] },
}
const updateVehiclesReferences = (state: Store, pds: Vehicle[] = [], rfs: Reference[] = []) => {
const { vehicles, references } = normalizeCustomerData(pds, rfs)
state.vehicles.byId = vehicles
state.vehicles.allIds = keys(vehicles)
state.references.byId = references
state.references.allIds = keys(references)
}
export default createSlice({
name: `${PROPOSAL_DATA_PREFIX}/customerData`,
initialState,
reducers: {},
extraReducers: {
[customerDataTypes.getCustomerData.fulfilled]: (state, action: PayloadAction<GetCustomerData['Output']>) => {
const { payload } = action
state.identification = payload.identification
state.address = payload.address
state.home = payload.home
state.personalData = payload.personalData
state.sourceIncome = payload.sourceIncome
state.spousePersonalData = payload.spousePersonalData
updateVehiclesReferences(state, payload.vehicles, payload.references)
},
[customerDataTypes.getVehicles.fulfilled]: (state, action: PayloadAction<GetCDVehicles['Output']>) => {
const { payload } = action
updateVehiclesReferences(state, payload)
},
[customerDataTypes.updateReference.fulfilled]: (state, action: PayloadAction<UpdateCDVehicle['Output']>) => {
const { payload } = action
updateVehiclesReferences(state, payload)
},
[customerDataTypes.addReference.fulfilled]: (state, action: PayloadAction<AddCDVehicle['Output']>) => {
const { payload } = action
updateVehiclesReferences(state, payload)
},
[customerDataTypes.getReferences.fulfilled]: (state, action: PayloadAction<GetCDReferences['Output']>) => {
const { payload } = action
updateVehiclesReferences(state, [], payload)
},
[customerDataTypes.updateReference.fulfilled]: (state, action: PayloadAction<UpdateCDReference['Output']>) => {
const { payload } = action
updateVehiclesReferences(state, [], payload)
},
[customerDataTypes.addReference.fulfilled]: (state, action: PayloadAction<AddCDReference['Output']>) => {
const { payload } = action
updateVehiclesReferences(state, [], payload)
},
},
})
import { combineReducers } from 'redux' import { combineReducers } from 'redux'
import businessData, {
initialState as businessDataInitState,
Store as BusinessDataStore
} from './businessData'
import context, { initialState as contextInitState, Store as ContextStore } from './context' import context, { initialState as contextInitState, Store as ContextStore } from './context'
import customerData, {
initialState as customerDataInitState,
Store as CustomerDataStore
} from './customerData'
import proposal, { initialState as proposalInitState, Store as ProposalStore } from './proposal' import proposal, { initialState as proposalInitState, Store as ProposalStore } from './proposal'
export interface State { export interface State {
context: ContextStore context: ContextStore
proposal: ProposalStore proposal: ProposalStore
businessData: BusinessDataStore
customerData: CustomerDataStore
} }
export const initialState: State = { export const initialState: State = {
context: contextInitState, context: contextInitState,
proposal: proposalInitState, proposal: proposalInitState,
businessData: businessDataInitState,
customerData: customerDataInitState,
} }
export default combineReducers({ export default combineReducers<State>({
context, context,
proposal, proposal,
businessData,
customerData,
}) })
...@@ -2,6 +2,6 @@ import { Store } from './slice' ...@@ -2,6 +2,6 @@ import { Store } from './slice'
export const getProposalId = (state: Store) => state.proposalId export const getProposalId = (state: Store) => state.proposalId
export const getPersonlId = (state: Store) => state.personId export const getPersonlId = (state: Store) => state.personId
export const getReferences = (state: Store) => state.references // export const getReferences = (state: Store) => state.references
export const getVehicles = (state: Store) => state.vehicles // export const getVehicles = (state: Store) => state.vehicles
export const getProductsServices = (state: Store) => state.productsServices // export const getProductsServices = (state: Store) => state.productsServices
import { import { Identification } from '@agiliza/api/domain'
AddBDProductService, import { actions as uiSimulationActions } from '@agiliza/redux/ui/simulation'
AddCDReference,
AddCDVehicle,
BDProductService,
GetBDProductsServices,
GetCDReferences,
GetCDVehicles,
Identification,
Reference,
UpdateBDProductService,
UpdateCDReference,
UpdateCDVehicle,
Vehicle
} from '@agiliza/api/domain'
import { types as businessDataTypes } from '@agiliza/redux/useCases/proposalData/businessData'
import { types as customerDataTypes } from '@agiliza/redux/useCases/proposalData/customerData' import { types as customerDataTypes } from '@agiliza/redux/useCases/proposalData/customerData'
import { createSlice, PayloadAction } from '@reduxjs/toolkit' import { createSlice, PayloadAction } from '@reduxjs/toolkit'
...@@ -22,57 +8,38 @@ import { PROPOSAL_DATA_PREFIX } from '../shared' ...@@ -22,57 +8,38 @@ import { PROPOSAL_DATA_PREFIX } from '../shared'
export interface Store { export interface Store {
proposalId: string proposalId: string
personId: string personId: string
references: Reference[]
vehicles: Vehicle[]
productsServices: BDProductService[]
} }
export const initialState: Store = { export const initialState: Store = {
proposalId: '', proposalId: '',
personId: '', personId: '',
references: [],
vehicles: [],
productsServices: [],
} }
export default createSlice({ export default createSlice({
name: `${PROPOSAL_DATA_PREFIX}/proposal`, name: `${PROPOSAL_DATA_PREFIX}/proposal`,
initialState, initialState,
reducers: {}, reducers: {
// setProposalId: (state, action: PayloadAction<string>) => {
// console.log(action)
// state.proposalId = action.payload
// },
},
extraReducers: { extraReducers: {
[uiSimulationActions.setProposalId.toString()]: (state, action: PayloadAction<string>) => {
state.proposalId = action.payload
},
[customerDataTypes.createProposal.fulfilled]: (state, action: PayloadAction<string>) => { [customerDataTypes.createProposal.fulfilled]: (state, action: PayloadAction<string>) => {
state.proposalId = action.payload state.proposalId = action.payload
}, },
[customerDataTypes.addIndentification.fulfilled]: (state, action: PayloadAction<Identification>) => { [customerDataTypes.addIndentification.fulfilled]: (state, action: PayloadAction<Identification>) => {
console.log(action)
state.personId = action.payload.id state.personId = action.payload.id
}, },
[customerDataTypes.getReferences.fulfilled]: (state, action: PayloadAction<GetCDReferences['Output']>) => { [customerDataTypes.updateIdentification.fulfilled]: (state, action: PayloadAction<Identification>) => {
state.references = action.payload state.personId = action.payload.id
},
[customerDataTypes.addReference.fulfilled]: (state, action: PayloadAction<AddCDReference['Output']>) => {
state.references = action.payload
},
[customerDataTypes.updateReference.fulfilled]: (state, action: PayloadAction<UpdateCDReference['Output']>) => {
state.references = action.payload
},
[customerDataTypes.getVehicles.fulfilled]: (state, action: PayloadAction<GetCDVehicles['Output']>) => {
state.vehicles = action.payload
},
[customerDataTypes.addVehicle.fulfilled]: (state, action: PayloadAction<AddCDVehicle['Output']>) => {
state.vehicles = action.payload
},
[customerDataTypes.updateVehicle.fulfilled]: (state, action: PayloadAction<UpdateCDVehicle['Output']>) => {
state.vehicles = action.payload
},
[businessDataTypes.getProductsServices.fulfilled]: (state, action: PayloadAction<GetBDProductsServices['Output']>) => {
state.productsServices = action.payload
},
[businessDataTypes.addProductService.fulfilled]: (state, action: PayloadAction<AddBDProductService['Output']>) => {
state.productsServices = action.payload
}, },
[businessDataTypes.updateProductService.fulfilled]: (state, action: PayloadAction<UpdateBDProductService['Output']>) => { [customerDataTypes.getIdentification.fulfilled]: (state, action: PayloadAction<Identification>) => {
state.productsServices = action.payload console.log(action.payload)
state.personId = action.payload?.id
}, },
}, },
}) })
...@@ -25,7 +25,6 @@ const session = createSlice({ ...@@ -25,7 +25,6 @@ const session = createSlice({
[loginTypes.login.fulfilled]: (state, action: PayloadAction<Customer>) => { [loginTypes.login.fulfilled]: (state, action: PayloadAction<Customer>) => {
state.authenticated = true state.authenticated = true
state.customer = action.payload state.customer = action.payload
console.log(action.payload)
}, },
[loginTypes.logout.fulfilled]: (state) => { [loginTypes.logout.fulfilled]: (state) => {
state.authenticated = false state.authenticated = false
......
...@@ -35,9 +35,10 @@ export const actions = { ...@@ -35,9 +35,10 @@ export const actions = {
return thunkApi.rejectWithValue(e) return thunkApi.rejectWithValue(e)
} }
}), }),
logout: createAsyncThunk(`${prefix}/logout`, (_, thunkApi) => { logout: createAsyncThunk(`${prefix}/logout`, (input: { onSuccess?: () => void } | void, thunkApi) => {
const useCase = SessionRepositoryImplFactory.create(appPlatform) const useCase = SessionRepositoryImplFactory.create(appPlatform)
useCase.logout() useCase.logout()
input?.onSuccess && input?.onSuccess()
thunkApi.dispatch({ type: 'RESET_STORE' }) thunkApi.dispatch({ type: 'RESET_STORE' })
return return
}), }),
......
...@@ -15,6 +15,8 @@ const simulation = createSlice({ ...@@ -15,6 +15,8 @@ const simulation = createSlice({
setData: (state, action: PayloadAction<State['data']>) => { setData: (state, action: PayloadAction<State['data']>) => {
state.data = action.payload state.data = action.payload
}, },
setProposalId: (state: State, action: PayloadAction<string>) => {},
setPersonId: (state: State, action: PayloadAction<string>) => {},
}, },
}) })
......
...@@ -2,6 +2,7 @@ import authentication, { ...@@ -2,6 +2,7 @@ import authentication, {
initialState as authenticationInitialState, initialState as authenticationInitialState,
State as AuthenticationState State as AuthenticationState
} from './authentication' } from './authentication'
import project, { initialState as projectsInitialState, State as ProjectsState } from './project'
import proposalData, { import proposalData, {
initialState as proposalDataInitialState, initialState as proposalDataInitialState,
State as ProposalDataState State as ProposalDataState
...@@ -15,18 +16,21 @@ export interface UseCasesState { ...@@ -15,18 +16,21 @@ export interface UseCasesState {
simulation: SimulationState simulation: SimulationState
authentication: AuthenticationState authentication: AuthenticationState
proposalData: ProposalDataState proposalData: ProposalDataState
project: ProjectsState
} }
const reducers = { const reducers = {
simulation, simulation,
authentication, authentication,
proposalData, proposalData,
project,
} }
export const initialState: UseCasesState = { export const initialState: UseCasesState = {
simulation: simulationInitialState, simulation: simulationInitialState,
authentication: authenticationInitialState, authentication: authenticationInitialState,
proposalData: proposalDataInitialState, proposalData: proposalDataInitialState,
project: projectsInitialState,
} }
export default reducers export default reducers
import * as selectors from './selectors'
import slice from './slice'
export * from './slice'
export { selectors }
export default slice.reducer
import { State } from './slice'
export const isFetching = (state: State) => state.fetching
import { ProjectRepositoryImplFactory } from '@agiliza/api/useCases/project'
import { appPlatform } from '@agiliza/constants/platform'
import { createAsyncReducers, getTypesThunkActions, values } from '@agiliza/utils/method'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
const prefix = 'useCases/project'
export interface State {
fetching: boolean
}
export const initialState: State = {
fetching: false,
}
export const actions = {
getProjects: createAsyncThunk(`${prefix}/getProjects`, async (_, thunkApi) => {
const useCase = ProjectRepositoryImplFactory.create(appPlatform)
try {
return await useCase.getProjects()
} catch (e) {
return thunkApi.rejectWithValue(e)
}
}),
} as const
export const types = getTypesThunkActions(actions)
export default createSlice({
name: prefix,
initialState,
reducers: {},
extraReducers: {
...values(types).reduce((reducers, type) => ({ ...reducers, ...createAsyncReducers(type) }), {}),
},
})
import { State } from './slice' import { State } from './slice'
export const isFetching = (state: State) => state.fetching export const isFetching = (state: State) => state.fetching
export const isGettingBusinessData = (state: State) => state.gettingBusinessData
import { import {
AddBDProductService, AddBDProductService,
GetBDProductsServices, GetBDProductsServices,
GetBusinessData,
UpdateBDAddress, UpdateBDAddress,
UpdateBDIdentification, UpdateBDIdentification,
UpdateBDProductService, UpdateBDProductService,
...@@ -20,10 +21,12 @@ const prefix = 'useCases/businessData' ...@@ -20,10 +21,12 @@ const prefix = 'useCases/businessData'
export interface State { export interface State {
fetching: boolean fetching: boolean
gettingBusinessData
} }
export const initialState: State = { export const initialState: State = {
fetching: false, fetching: false,
gettingBusinessData: false,
} }
export const actions = { export const actions = {
...@@ -90,6 +93,16 @@ export const actions = { ...@@ -90,6 +93,16 @@ export const actions = {
} }
} }
), ),
getBusinessData: createAsyncThunk(`${prefix}/getBusinessData`, async (input: WithSuccess<GetBusinessData['Input']>, thunkApi) => {
const useCase = PDBusinessDataRepositoryImplFactory.create(appPlatform)
try {
const response = await useCase.getBusinessData(input)
input.onSuccess && input.onSuccess()
return response
} catch (e) {
return thunkApi.rejectWithValue(e)
}
}),
} as const } as const
export const types = getTypesThunkActions(actions) export const types = getTypesThunkActions(actions)
...@@ -99,6 +112,7 @@ const login = createSlice({ ...@@ -99,6 +112,7 @@ const login = createSlice({
reducers: {}, reducers: {},
extraReducers: { extraReducers: {
...values(types).reduce((reducers, type) => ({ ...reducers, ...createAsyncReducers(type) }), {}), ...values(types).reduce((reducers, type) => ({ ...reducers, ...createAsyncReducers(type) }), {}),
...createAsyncReducers(types.getBusinessData, 'gettingBusinessData'),
}, },
}) })
......
import { State } from './slice' import { State } from './slice'
export const isFetching = (state: State) => state.fetching export const isFetching = (state: State) => state.fetching
export const isGettingCustomerData = (state: State) => state.gettingCustomerData
...@@ -3,10 +3,13 @@ import { ...@@ -3,10 +3,13 @@ import {
AddCDReference, AddCDReference,
AddCDVehicle, AddCDVehicle,
CreateProposal, CreateProposal,
GetCDIdentification,
GetCDReferences, GetCDReferences,
GetCDVehicles, GetCDVehicles,
GetCustomerData,
UpdateCDAddress, UpdateCDAddress,
UpdateCDHome, UpdateCDHome,
UpdateCDIdentification,
UpdateCDPersonalData, UpdateCDPersonalData,
UpdateCDReference, UpdateCDReference,
UpdateCDSourceIncome, UpdateCDSourceIncome,
...@@ -29,18 +32,20 @@ const prefix = 'useCases/customerData' ...@@ -29,18 +32,20 @@ const prefix = 'useCases/customerData'
export interface State { export interface State {
fetching: boolean fetching: boolean
gettingCustomerData: boolean
} }
export const initialState: State = { export const initialState: State = {
fetching: false, fetching: false,
gettingCustomerData: false,
} }
export const actions = { export const actions = {
createProposal: createAsyncThunk(`${prefix}/createProposal`, async (input: WithSuccess<CreateProposal['Input']>, thunkApi) => { createProposal: createAsyncThunk(`${prefix}/createProposal`, async (input: WithSuccess<CreateProposal['Input'], string>, thunkApi) => {
const useCase = PDCustomerDataRepositoryImplFactory.create(appPlatform) const useCase = PDCustomerDataRepositoryImplFactory.create(appPlatform)
try { try {
const response = await useCase.createProposal(input) const response = await useCase.createProposal(input)
input.onSuccess && input.onSuccess() input.onSuccess && input.onSuccess(response)
return response return response
} catch (e) { } catch (e) {
return thunkApi.rejectWithValue(e) return thunkApi.rejectWithValue(e)
...@@ -49,9 +54,19 @@ export const actions = { ...@@ -49,9 +54,19 @@ export const actions = {
addIndentification: createAsyncThunk(`${prefix}/addIndentification`, async (input: WithSuccess<AddCDIdentification['Input']>, thunkApi) => { addIndentification: createAsyncThunk(`${prefix}/addIndentification`, async (input: WithSuccess<AddCDIdentification['Input']>, thunkApi) => {
const useCase = PDCustomerDataRepositoryImplFactory.create(appPlatform) const useCase = PDCustomerDataRepositoryImplFactory.create(appPlatform)
try { try {
const proposal = await useCase.addIdentification(input) const identification = await useCase.addIdentification(input)
input.onSuccess && input.onSuccess()
return identification
} catch (e) {
return thunkApi.rejectWithValue(e)
}
}),
updateIdentification: createAsyncThunk(`${prefix}/updateIdentification`, async (input: WithSuccess<UpdateCDIdentification['Input']>, thunkApi) => {
const useCase = PDCustomerDataRepositoryImplFactory.create(appPlatform)
try {
const identification = await useCase.updateIdentification(input)
input.onSuccess && input.onSuccess() input.onSuccess && input.onSuccess()
return proposal return identification
} catch (e) { } catch (e) {
return thunkApi.rejectWithValue(e) return thunkApi.rejectWithValue(e)
} }
...@@ -166,6 +181,26 @@ export const actions = { ...@@ -166,6 +181,26 @@ export const actions = {
return thunkApi.rejectWithValue(e) return thunkApi.rejectWithValue(e)
} }
}), }),
getCustomerData: createAsyncThunk(`${prefix}/getCustomerData`, async (input: WithSuccess<GetCustomerData['Input']>, thunkApi) => {
const useCase = PDCustomerDataRepositoryImplFactory.create(appPlatform)
try {
const response = await useCase.getCustomerData(input)
input.onSuccess && input.onSuccess()
return response
} catch (e) {
return thunkApi.rejectWithValue(e)
}
}),
getIdentification: createAsyncThunk(`${prefix}/getIdentification`, async (input: WithSuccess<GetCDIdentification['Input'], string>, thunkApi) => {
const useCase = PDCustomerDataRepositoryImplFactory.create(appPlatform)
try {
const response = await useCase.getIdentification(input)
input.onSuccess && input.onSuccess(response?.id || '')
return response
} catch (e) {
return thunkApi.rejectWithValue(e)
}
}),
} as const } as const
export const types = getTypesThunkActions(actions) export const types = getTypesThunkActions(actions)
...@@ -175,6 +210,7 @@ const login = createSlice({ ...@@ -175,6 +210,7 @@ const login = createSlice({
reducers: {}, reducers: {},
extraReducers: { extraReducers: {
...values(types).reduce((reducers, type) => ({ ...reducers, ...createAsyncReducers(type) }), {}), ...values(types).reduce((reducers, type) => ({ ...reducers, ...createAsyncReducers(type) }), {}),
...createAsyncReducers(types.getCustomerData, 'gettingCustomerData'),
}, },
}) })
......
...@@ -22,10 +22,11 @@ interface Props extends BaseProps { ...@@ -22,10 +22,11 @@ interface Props extends BaseProps {
authenticated: boolean authenticated: boolean
fetching: boolean fetching: boolean
loginRequest: typeof actions.login loginRequest: typeof actions.login
redirectTo?: string
} }
const Login = (props: Props) => { const Login = (props: Props) => {
const { loginRequest, authenticated, fetching } = props const { loginRequest, authenticated, fetching, redirectTo } = props
const classes = useStyles() const classes = useStyles()
...@@ -37,7 +38,7 @@ const Login = (props: Props) => { ...@@ -37,7 +38,7 @@ const Login = (props: Props) => {
} }
if (authenticated) { if (authenticated) {
return <Redirect to="/" /> return <Redirect to={redirectTo || '/'} />
} }
return ( return (
......
import React, { lazy, Suspense, useEffect } from 'react' import React, { lazy, Suspense, useEffect, useState } from 'react'
import { Redirect, Route, RouteComponentProps, Switch, useHistory } from 'react-router' import { Redirect, Route, RouteComponentProps, Switch, useHistory } from 'react-router'
import AppBar from '@agiliza/components/molecules/AppBar' import AppBar from '@agiliza/components/molecules/AppBar'
...@@ -6,8 +6,9 @@ import CircularProgress from '@agiliza/components/molecules/CircularProgress' ...@@ -6,8 +6,9 @@ import CircularProgress from '@agiliza/components/molecules/CircularProgress'
import { actions as drawerActions } from '@agiliza/redux/ui/drawer' import { actions as drawerActions } from '@agiliza/redux/ui/drawer'
import { actions as loginActions } from '@agiliza/redux/ui/login' import { actions as loginActions } from '@agiliza/redux/ui/login'
import { ProposalDataRouteState } from '@agiliza/views/ProposalData/pages/ProposalData' import { ProposalDataRouteState } from '@agiliza/views/ProposalData/pages/ProposalData'
import { Typography } from '@material-ui/core' import { Button, ListItem, ListItemIcon, ListItemText, Menu, Typography } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles' import { withStyles, WithStyles } from '@material-ui/core/styles'
import { AccountCircleOutlined as PersonIcon, MeetingRoom as LogoutIcon } from '@material-ui/icons'
import connect, { ConnectedProps } from './connect' import connect, { ConnectedProps } from './connect'
import { PATHS } from './DrawerItems' import { PATHS } from './DrawerItems'
...@@ -15,7 +16,7 @@ import styles from './styles' ...@@ -15,7 +16,7 @@ import styles from './styles'
const SimulationCreditLines = lazy(() => import('@agiliza/views/SimulationCreditLines/pages/router')) const SimulationCreditLines = lazy(() => import('@agiliza/views/SimulationCreditLines/pages/router'))
const ProposalData = lazy(() => import('@agiliza/views/ProposalData/pages/ProposalData')) const ProposalData = lazy(() => import('@agiliza/views/ProposalData/pages/ProposalData'))
const ListProjects = lazy(() => import('@agiliza/views/Projects/pages/ListProjects')) const Projects = lazy(() => import('@agiliza/views/Projects/pages/router'))
// const SecurityProfile = lazy(() => import('@curio/ui/dist/views/SecurityProfile')) // const SecurityProfile = lazy(() => import('@curio/ui/dist/views/SecurityProfile'))
type BaseProps = RouteComponentProps & ConnectedProps & WithStyles<typeof styles> type BaseProps = RouteComponentProps & ConnectedProps & WithStyles<typeof styles>
...@@ -26,41 +27,75 @@ interface Props extends BaseProps { ...@@ -26,41 +27,75 @@ interface Props extends BaseProps {
} }
const Main = (props: Props) => { const Main = (props: Props) => {
const { classes, toggleDrawer, fetchMenu } = props const { classes, toggleDrawer, fetchMenu, customer } = props
const history = useHistory() const history = useHistory()
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null)
useEffect(() => { useEffect(() => {
fetchMenu() fetchMenu()
}, []) }, [])
const handleProfileClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget)
}
const handleClose = () => {
setAnchorEl(null)
}
const handleLogout = () => {
props.logout({
onSuccess: () => {
history.push('/')
setAnchorEl(null)
},
})
}
return ( return (
<div className={classes.pageContainer}> <div className={classes.pageContainer}>
<AppBar <AppBar
onNavClick={toggleDrawer} onNavClick={toggleDrawer}
title={ title={
<div style={{ display: 'flex' }}>
<a onClick={() => history.push('/')} className={classes.titleAnchor}> <a onClick={() => history.push('/')} className={classes.titleAnchor}>
<Typography className={classes.appTitle}>Agiliza</Typography> <Typography className={classes.appTitle}>Agiliza</Typography>
</a> </a>
<div style={{ flex: 1 }} />
<Button color="inherit" variant="text" onClick={() => history.push(PATHS.proposals)}>
Retomar proposta
</Button>
{customer && <Button onClick={handleProfileClick} key="1" color="inherit" endIcon={<PersonIcon />} />}
</div>
} }
/> />
{/* <Drawer drawerOpen={drawerOpen} toggleDrawer={toggleDrawer} logout={logout} Items={DrawerItems} {...routeProps} /> */} {/* <Drawer drawerOpen={drawerOpen} toggleDrawer={toggleDrawer} logout={logout} Items={DrawerItems} {...routeProps} /> */}
<Suspense fallback={<CircularProgress />}> <Suspense fallback={<CircularProgress />}>
<Switch> <Switch>
<Route path={PATHS.proposals} render={(rProps) => <ListProjects {...rProps} />} /> <Route path={PATHS.proposals} render={(rProps) => <Projects {...rProps} />} />
<Route path={PATHS.simulation} render={(rProps) => <SimulationCreditLines {...rProps} />} /> <Route path={PATHS.simulation} render={(rProps) => <SimulationCreditLines {...rProps} />} />
<Route <Route
path={PATHS.proposalData} path={PATHS.proposalData}
render={(rProps) => { render={(rProps) => {
const { location } = rProps as RouteComponentProps<any, any, ProposalDataRouteState> const { location } = rProps as RouteComponentProps<any, any, ProposalDataRouteState>
// if (!location.state) location.state = { subproductId: '0' } // if (!location.state) location.state = { subproductId: '0' }
if (location.state?.subproductId) return <ProposalData {...rProps} /> if (location.state?.proposalId) return <ProposalData {...rProps} />
else return <Redirect from={PATHS.proposalData} to="/" /> else return <Redirect from={PATHS.proposalData} to="/" />
}} }}
/> />
<Redirect from="/" to={PATHS.simulation} /> <Redirect from="/" to={PATHS.simulation} />
</Switch> </Switch>
</Suspense> </Suspense>
<Menu id="long-menu" anchorEl={anchorEl} keepMounted open={Boolean(anchorEl)} onClose={handleClose}>
<ListItem button onClick={handleLogout}>
<ListItemIcon>
<LogoutIcon />
</ListItemIcon>
<ListItemText>Sair</ListItemText>
</ListItem>
</Menu>
</div> </div>
) )
} }
......
import { connect } from 'react-redux' import { connect } from 'react-redux'
import { bindActionCreators, Dispatch } from 'redux' import { bindActionCreators, Dispatch } from 'redux'
import { Customer } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux' import { StoreState } from '@agiliza/redux'
import * as session from '@agiliza/redux/session'
import { actions as drawerActions } from '@agiliza/redux/ui/drawer' import { actions as drawerActions } from '@agiliza/redux/ui/drawer'
import { isDrawerOpen } from '@agiliza/redux/ui/drawer/selectors' import { isDrawerOpen } from '@agiliza/redux/ui/drawer/selectors'
import { actions as loginActions } from '@agiliza/redux/ui/login' import { actions as loginActions } from '@agiliza/redux/ui/login'
...@@ -13,12 +15,14 @@ export interface ConnectedProps { ...@@ -13,12 +15,14 @@ export interface ConnectedProps {
fetchMenu: typeof systemActions.fetchMenu fetchMenu: typeof systemActions.fetchMenu
toggleDrawer: typeof drawerActions.toggleDrawer toggleDrawer: typeof drawerActions.toggleDrawer
logout: typeof loginActions.logout logout: typeof loginActions.logout
customer?: Customer
} }
const mapStateToProps = (state: StoreState) => ({ const mapStateToProps = (state: StoreState) => ({
drawerOpen: isDrawerOpen(state.ui.drawer), drawerOpen: isDrawerOpen(state.ui.drawer),
fetchMenu: systemActions.fetchMenu, fetchMenu: systemActions.fetchMenu,
fetchingMenu: systemSelectors.isFetching(state.ui.system), fetchingMenu: systemSelectors.isFetching(state.ui.system),
customer: session.selectors.getCustomer(state.session),
}) })
const mapDispatchToProps = (dispatch: Dispatch) => const mapDispatchToProps = (dispatch: Dispatch) =>
......
import React from 'react' import React, { useEffect } from 'react'
import { RouteComponentProps } from 'react-router' import { RouteComponentProps } from 'react-router'
import { Project } from '@agiliza/api/domain/project' import { Project } from '@agiliza/api/domain/project'
import { Avatar, List, ListItem, ListItemAvatar, ListItemText } from '@material-ui/core' import { PATHS } from '@agiliza/views/Main/DrawerItems'
import {
Avatar,
CircularProgress,
List,
ListItem,
ListItemAvatar,
ListItemText,
ListSubheader
} from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles' import { withStyles, WithStyles } from '@material-ui/core/styles'
import { Apps as AppsIcon } from '@material-ui/icons' import { Apps as AppsIcon } from '@material-ui/icons'
...@@ -14,13 +23,29 @@ type ExtendedProps = WithStyles<typeof styles> & ConnectedProps & RouteComponent ...@@ -14,13 +23,29 @@ type ExtendedProps = WithStyles<typeof styles> & ConnectedProps & RouteComponent
interface Props extends ExtendedProps {} interface Props extends ExtendedProps {}
const ListProjects = (props: Props) => { const ListProjects = (props: Props) => {
const { classes, proposals } = props const { classes, fetching, proposals, history } = props
const handleClickListItem = (proposal: Project) => () => {} useEffect(() => {
props.getProjects()
}, [])
const handleClickListItem = (proposal: Project) => () => {
props.setProposalId(proposal.id)
history.push({ pathname: PATHS.proposalData, state: { proposalId: proposal.id } })
}
if (fetching) return <CircularProgress />
return ( return (
<div className={classes.pageContent}> <div className={classes.pageContent}>
<List className={classes.list}> <List
className={classes.list}
subheader={
<ListSubheader component="div" id="nested-list-subheader">
Projetos
</ListSubheader>
}
>
{proposals.map((proposal, i) => ( {proposals.map((proposal, i) => (
<ListItem key={i} button onClick={handleClickListItem(proposal)}> <ListItem key={i} button onClick={handleClickListItem(proposal)}>
<ListItemAvatar> <ListItemAvatar>
......
import { connect } from 'react-redux' import { connect } from 'react-redux'
import { bindActionCreators, Dispatch } from 'redux'
import { Project } from '@agiliza/api/domain/project' import { Project } from '@agiliza/api/domain/project'
import { StoreState } from '@agiliza/redux' import { StoreState } from '@agiliza/redux'
import * as entProject from '@agiliza/redux/entities/project'
import * as uiSimulation from '@agiliza/redux/ui/simulation'
import * as ucProject from '@agiliza/redux/useCases/project'
export interface ConnectedProps { export interface ConnectedProps {
fetching: boolean fetching: boolean
proposals: Project[] proposals: Project[]
getProjects: typeof ucProject.actions.getProjects
setProposalId: typeof uiSimulation.actions.setProposalId
setPersonId: typeof uiSimulation.actions.setPersonId
} }
type StateProps = Pick<ConnectedProps, 'fetching' | 'proposals'> type StateProps = Pick<ConnectedProps, 'fetching' | 'proposals'>
// type DispatchProps = Pick<ConnectedProps, 'getContext'> type DispatchProps = Pick<ConnectedProps, 'getProjects' | 'setProposalId' | 'setPersonId'>
const mapStateToProps = (state: StoreState): StateProps => ({ const mapStateToProps = (state: StoreState): StateProps => ({
fetching: false, fetching: ucProject.selectors.isFetching(state.useCases.project),
proposals: [], proposals: entProject.selectors.getProjects(state.entities.project),
}) })
// const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
// bindActionCreators( bindActionCreators(
// { {
// }, getProjects: ucProject.actions.getProjects,
// dispatch setProposalId: uiSimulation.actions.setProposalId,
// ) setPersonId: uiSimulation.actions.setPersonId,
},
dispatch
)
export const connected = connect(mapStateToProps) export const connected = connect(mapStateToProps, mapDispatchToProps)
import React, { lazy, Suspense } from 'react'
import { Route, RouteComponentProps, Switch } from 'react-router'
import AuthRoute from '@agiliza/components/atoms/AuthRoute'
import { PATHS } from '@agiliza/views/Main/DrawerItems'
import { CircularProgress } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles'
import styles from './shared-styles'
export const PROJECTS_PATHS = {
login: PATHS.proposals + '/login',
}
const ListProjects = lazy(() => import('./ListProjects'))
const Login = lazy(() => import('@agiliza/views/Login'))
type ExtendedProps = WithStyles<typeof styles> & RouteComponentProps
interface Props extends ExtendedProps {}
const ProposalDataRouter = (props: Props) => {
const { classes } = props
return (
<div className={classes.pageContent}>
<Suspense fallback={<CircularProgress className={classes.circularProgress} />}>
<Switch>
<Route path={PROJECTS_PATHS.login} render={(renderProps) => <Login {...renderProps} redirectTo={PATHS.proposals} />} />
<AuthRoute path={PATHS.proposals} redirectTo={PROJECTS_PATHS.login} component={ListProjects} />
</Switch>
</Suspense>
</div>
)
}
export default withStyles(styles)(ProposalDataRouter)
import { file } from '@agiliza/__mocks__/files'
import { BDIdentification } from '@agiliza/api/domain' import { BDIdentification } from '@agiliza/api/domain'
type ExtendedState = BDIdentification type ExtendedState = BDIdentification
...@@ -8,23 +7,24 @@ export interface BDIdentificationState extends ExtendedState { ...@@ -8,23 +7,24 @@ export interface BDIdentificationState extends ExtendedState {
} }
export const initialState: BDIdentificationState = export const initialState: BDIdentificationState =
process.env.NODE_ENV === 'development' // process.env.NODE_ENV === 'development'
? { // ? {
cnpj: '81.867.778/0001-02', // cnpj: '81.867.778/0001-02',
activitySector: '1', // activitySector: '1',
cityRegistration: '123456', // cityRegistration: '123456',
codeCNAE: '123456', // codeCNAE: '123456',
companyName: 'TEST', // companyName: 'TEST',
document: { extraInformations: 'TEST', id: '1', url: file, type: { id: '1', description: '' } }, // document: { extraInformations: 'TEST', id: '1', url: file, type: { id: '1', description: '' } },
fantasyName: 'TEST', // fantasyName: 'TEST',
local: '1', // local: '1',
settledOP: '1', // settledOP: '1',
stateRegistration: '123456', // stateRegistration: '123456',
commercialRegistration: '123456', // commercialRegistration: '123456',
mainActivity: 'TEST', // mainActivity: 'TEST',
openingDate: new Date('2010-10-10'), // openingDate: new Date('2010-10-10'),
} // }
: { // :
{
cnpj: '', cnpj: '',
activitySector: '', activitySector: '',
cityRegistration: '', cityRegistration: '',
......
...@@ -3,8 +3,8 @@ import { bindActionCreators, Dispatch } from 'redux' ...@@ -3,8 +3,8 @@ import { bindActionCreators, Dispatch } from 'redux'
import { BDProductService, ProposalDataContext } from '@agiliza/api/domain' import { BDProductService, ProposalDataContext } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux' import { StoreState } from '@agiliza/redux'
import * as entBusinessData from '@agiliza/redux/entities/proposalData/businessData'
import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context' import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context'
import * as entProposalData from '@agiliza/redux/entities/proposalData/proposal'
import * as ucProposalData from '@agiliza/redux/useCases/proposalData/businessData' import * as ucProposalData from '@agiliza/redux/useCases/proposalData/businessData'
export interface ConnectedProps { export interface ConnectedProps {
...@@ -22,7 +22,7 @@ type DispatchProps = Pick<ConnectedProps, 'getProductsServices' | 'addProductSer ...@@ -22,7 +22,7 @@ type DispatchProps = Pick<ConnectedProps, 'getProductsServices' | 'addProductSer
const mapStateToProps = (state: StoreState): StateProps => ({ const mapStateToProps = (state: StoreState): StateProps => ({
fetching: ucProposalData.selectors.isFetching(state.useCases.proposalData.businessData), fetching: ucProposalData.selectors.isFetching(state.useCases.proposalData.businessData),
context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context), context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context),
productsServices: entProposalData.selectors.getProductsServices(state.entities.proposalData.proposal), productsServices: entBusinessData.selectors.getProductsServices(state.entities.proposalData.businessData),
}) })
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
......
...@@ -2,8 +2,8 @@ import { connect } from 'react-redux' ...@@ -2,8 +2,8 @@ import { connect } from 'react-redux'
import { BDProductService, ProposalDataContext } from '@agiliza/api/domain' import { BDProductService, ProposalDataContext } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux' import { StoreState } from '@agiliza/redux'
import * as entBusinessData from '@agiliza/redux/entities/proposalData/businessData'
import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context' import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context'
import * as entProposalData from '@agiliza/redux/entities/proposalData/proposal'
export interface ConnectedProps { export interface ConnectedProps {
context: ProposalDataContext context: ProposalDataContext
...@@ -15,7 +15,7 @@ type StateProps = Pick<ConnectedProps, 'context' | 'productsServices'> ...@@ -15,7 +15,7 @@ type StateProps = Pick<ConnectedProps, 'context' | 'productsServices'>
const mapStateToProps = (state: StoreState): StateProps => ({ const mapStateToProps = (state: StoreState): StateProps => ({
context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context), context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context),
productsServices: entProposalData.selectors.getProductsServices(state.entities.proposalData.proposal), productsServices: entBusinessData.selectors.getProductsServices(state.entities.proposalData.businessData),
}) })
// const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => // const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
......
import { StockSalesCosts } from '@agiliza/api/domain' import { BDStockSalesCosts } from '@agiliza/api/domain'
type ExtendedState = StockSalesCosts type ExtendedState = BDStockSalesCosts
export interface BDStockSalesCostsState extends ExtendedState { export interface BDStockSalesCostsState extends ExtendedState {
totalStock: string totalStock: string
......
...@@ -4,7 +4,7 @@ import { bindActionCreators, Dispatch } from 'redux' ...@@ -4,7 +4,7 @@ import { bindActionCreators, Dispatch } from 'redux'
import { ProposalDataContext, Reference } from '@agiliza/api/domain' import { ProposalDataContext, Reference } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux' import { StoreState } from '@agiliza/redux'
import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context' import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context'
import * as entProposalData from '@agiliza/redux/entities/proposalData/proposal' import * as entCustomerData from '@agiliza/redux/entities/proposalData/customerData'
import * as ucProposalData from '@agiliza/redux/useCases/proposalData/customerData' import * as ucProposalData from '@agiliza/redux/useCases/proposalData/customerData'
export interface ConnectedProps { export interface ConnectedProps {
...@@ -22,7 +22,7 @@ type DispatchProps = Pick<ConnectedProps, 'getReferences' | 'addReference' | 'up ...@@ -22,7 +22,7 @@ type DispatchProps = Pick<ConnectedProps, 'getReferences' | 'addReference' | 'up
const mapStateToProps = (state: StoreState): StateProps => ({ const mapStateToProps = (state: StoreState): StateProps => ({
fetching: ucProposalData.selectors.isFetching(state.useCases.proposalData.customerData), fetching: ucProposalData.selectors.isFetching(state.useCases.proposalData.customerData),
context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context), context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context),
references: entProposalData.selectors.getReferences(state.entities.proposalData.proposal), references: entCustomerData.selectors.getReferences(state.entities.proposalData.customerData),
}) })
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
......
...@@ -4,7 +4,7 @@ import { bindActionCreators, Dispatch } from 'redux' ...@@ -4,7 +4,7 @@ import { bindActionCreators, Dispatch } from 'redux'
import { ProposalDataContext, Vehicle } from '@agiliza/api/domain' import { ProposalDataContext, Vehicle } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux' import { StoreState } from '@agiliza/redux'
import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context' import * as entProposalDataContext from '@agiliza/redux/entities/proposalData/context'
import * as entProposalData from '@agiliza/redux/entities/proposalData/proposal' import * as entCustomerData from '@agiliza/redux/entities/proposalData/customerData'
import * as ucProposalData from '@agiliza/redux/useCases/proposalData/customerData' import * as ucProposalData from '@agiliza/redux/useCases/proposalData/customerData'
export interface ConnectedProps { export interface ConnectedProps {
...@@ -22,7 +22,7 @@ type DispatchProps = Pick<ConnectedProps, 'getVehicles' | 'addVehicle' | 'update ...@@ -22,7 +22,7 @@ type DispatchProps = Pick<ConnectedProps, 'getVehicles' | 'addVehicle' | 'update
const mapStateToProps = (state: StoreState): StateProps => ({ const mapStateToProps = (state: StoreState): StateProps => ({
fetching: ucProposalData.selectors.isFetching(state.useCases.proposalData.customerData), fetching: ucProposalData.selectors.isFetching(state.useCases.proposalData.customerData),
context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context), context: entProposalDataContext.selectors.getContext(state.entities.proposalData.context),
vehicles: entProposalData.selectors.getVehicles(state.entities.proposalData.proposal), vehicles: entCustomerData.selectors.getVehicles(state.entities.proposalData.customerData),
}) })
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
......
...@@ -3,8 +3,9 @@ import { RouteComponentProps } from 'react-router' ...@@ -3,8 +3,9 @@ import { RouteComponentProps } from 'react-router'
import ButtonWithProgress from '@agiliza/components/atoms/ButtonWithProgress' import ButtonWithProgress from '@agiliza/components/atoms/ButtonWithProgress'
import { useFormState } from '@agiliza/utils/hooks/state' import { useFormState } from '@agiliza/utils/hooks/state'
import { entries } from '@agiliza/utils/method'
import { CREDIT_LINES_PATHS } from '@agiliza/views/SimulationCreditLines/pages/router' import { CREDIT_LINES_PATHS } from '@agiliza/views/SimulationCreditLines/pages/router'
import { Button, MobileStepper, Typography } from '@material-ui/core' import { Button, CircularProgress, MobileStepper, Typography } from '@material-ui/core'
import { withStyles, WithStyles } from '@material-ui/core/styles' import { withStyles, WithStyles } from '@material-ui/core/styles'
import { import {
AccountBox as AccountBoxIcon, AccountBox as AccountBoxIcon,
...@@ -52,7 +53,7 @@ export const PROPOSAL_DATA_PATHS = { ...@@ -52,7 +53,7 @@ export const PROPOSAL_DATA_PATHS = {
} }
export interface ProposalDataRouteState { export interface ProposalDataRouteState {
subproductId: string proposalId: string
} }
type ExtendedProps = WithStyles<typeof styles> & RouteComponentProps & ConnectedProps type ExtendedProps = WithStyles<typeof styles> & RouteComponentProps & ConnectedProps
...@@ -60,7 +61,7 @@ type ExtendedProps = WithStyles<typeof styles> & RouteComponentProps & Connected ...@@ -60,7 +61,7 @@ type ExtendedProps = WithStyles<typeof styles> & RouteComponentProps & Connected
interface Props extends ExtendedProps {} interface Props extends ExtendedProps {}
const ProposalData = (props: Props) => { const ProposalData = (props: Props) => {
const { classes, history, fetching, proposalId, personId } = props const { classes, history, fetching, proposalId, personId, customerData, businessData } = props
const [activeStep, setActiveStep] = useState(0) const [activeStep, setActiveStep] = useState(0)
useEffect(() => { useEffect(() => {
...@@ -82,6 +83,87 @@ const ProposalData = (props: Props) => { ...@@ -82,6 +83,87 @@ const ProposalData = (props: Props) => {
const bdStockSalesCostsState = useFormState('bdStockSalesCostsState', bdStockSalesCostsInitState) const bdStockSalesCostsState = useFormState('bdStockSalesCostsState', bdStockSalesCostsInitState)
const bdProductServiceState = useFormState('bdProductServiceState', bdProductServiceInitState) const bdProductServiceState = useFormState('bdProductServiceState', bdProductServiceInitState)
useEffect(() => {
props.getBusinessData({ projectId: proposalId })
props.getCDIdentification({
projectId: proposalId,
onSuccess: (pID) => {
if (pID) props.getCustomerData({ projectId: proposalId, personId: pID })
},
})
}, [])
useEffect(() => {
const { identification, personalData, address, sourceIncome, spousePersonalData, home } = customerData
if (identification)
cdIdentification.actions.update(
entries(identification).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
if (personalData)
cdPersonalData.actions.update(
entries(personalData).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
if (address)
cdAddress.actions.update(
entries(address).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
if (sourceIncome)
cdSourceIncome.actions.update(
entries(sourceIncome).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
if (spousePersonalData)
cdSpouseData.actions.update(
entries(spousePersonalData).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
if (home)
cdHomeState.actions.update(
entries(home).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
}, [customerData])
useEffect(() => {
const { identification, address, stockSalesCosts } = businessData
if (identification)
bdIdentificationState.actions.update(
entries(identification).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
if (address)
bdAddressState.actions.update(
entries(address).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
if (stockSalesCosts)
bdStockSalesCostsState.actions.update(
entries(stockSalesCosts).reduce((idn, [k, v]) => {
if (v !== undefined) return { ...idn, [k]: v }
else return idn
}, {})
)
}, [businessData])
const customerDataItems = useMemo( const customerDataItems = useMemo(
() => [ () => [
{ {
...@@ -145,6 +227,13 @@ const ProposalData = (props: Props) => { ...@@ -145,6 +227,13 @@ const ProposalData = (props: Props) => {
const projectPersonIds = { projectId: proposalId, personId } const projectPersonIds = { projectId: proposalId, personId }
switch (activeStep) { switch (activeStep) {
case 0: case 0:
if (personId)
props.updateCDIndentification({
identification: { ...cdIdentification.state, account: cdIdentification.state.hasAccount ? cdIdentification.state.account : undefined },
...projectPersonIds,
onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
})
else
props.addIndentification({ props.addIndentification({
identification: { ...cdIdentification.state, account: cdIdentification.state.hasAccount ? cdIdentification.state.account : undefined }, identification: { ...cdIdentification.state, account: cdIdentification.state.hasAccount ? cdIdentification.state.account : undefined },
projectId: proposalId, projectId: proposalId,
...@@ -194,7 +283,7 @@ const ProposalData = (props: Props) => { ...@@ -194,7 +283,7 @@ const ProposalData = (props: Props) => {
}) })
break break
case 9: case 9:
props.updateIdentification({ props.updateBDIdentification({
projectId: proposalId, projectId: proposalId,
identification: bdIdentificationState.state, identification: bdIdentificationState.state,
onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1), onSuccess: () => setActiveStep((prevActiveStep) => prevActiveStep + 1),
...@@ -241,7 +330,9 @@ const ProposalData = (props: Props) => { ...@@ -241,7 +330,9 @@ const ProposalData = (props: Props) => {
{mapActiveStepToTitle()} {mapActiveStepToTitle()}
</Typography> </Typography>
<Typography className={classes.pageSubtitle}>{proposalDataItems[activeStep].label}</Typography> <Typography className={classes.pageSubtitle}>{proposalDataItems[activeStep].label}</Typography>
<div className={classes.stepContentContainer}>{proposalDataItems[activeStep].component}</div> <div className={classes.stepContentContainer}>
{fetching ? <CircularProgress className={classes.circularProgress} /> : proposalDataItems[activeStep].component}
</div>
<div className={classes.stepperContainer}> <div className={classes.stepperContainer}>
{/* <Stepper activeStep={activeStep} alternativeLabel className={classes.stepper}> */} {/* <Stepper activeStep={activeStep} alternativeLabel className={classes.stepper}> */}
{/* {propostalDataItems.map((iPI, i) => ( {/* {propostalDataItems.map((iPI, i) => (
......
import { connect } from 'react-redux' import { connect } from 'react-redux'
import { bindActionCreators, Dispatch } from 'redux' import { bindActionCreators, Dispatch } from 'redux'
import { BusinessData, InvolvedPerson } from '@agiliza/api/domain'
import { StoreState } from '@agiliza/redux' import { StoreState } from '@agiliza/redux'
import * as entBusinessData from '@agiliza/redux/entities/proposalData/businessData'
import * as entCustomerData from '@agiliza/redux/entities/proposalData/customerData'
import * as entProposal from '@agiliza/redux/entities/proposalData/proposal' import * as entProposal from '@agiliza/redux/entities/proposalData/proposal'
import * as ucAuthentication from '@agiliza/redux/useCases/authentication' import * as ucAuthentication from '@agiliza/redux/useCases/authentication'
import * as ucProposalDataBD from '@agiliza/redux/useCases/proposalData/businessData' import * as ucProposalDataBD from '@agiliza/redux/useCases/proposalData/businessData'
...@@ -15,25 +18,32 @@ export interface ConnectedProps { ...@@ -15,25 +18,32 @@ export interface ConnectedProps {
proposalId: string proposalId: string
personId: string personId: string
reset: () => void reset: () => void
customerData: Omit<InvolvedPerson, 'id'>
businessData: BusinessData
fetchContext: typeof ucProposalDataContext.actions.fetchContext fetchContext: typeof ucProposalDataContext.actions.fetchContext
getContextAddress: typeof ucAuthentication.actions.getContext getContextAddress: typeof ucAuthentication.actions.getContext
addIndentification: typeof ucProposalDataCD.actions.addIndentification addIndentification: typeof ucProposalDataCD.actions.addIndentification
updateCDIndentification: typeof ucProposalDataCD.actions.updateIdentification
updatePersonalData: typeof ucProposalDataCD.actions.updatePersonalData updatePersonalData: typeof ucProposalDataCD.actions.updatePersonalData
updateCDAddress: typeof ucProposalDataCD.actions.updateAddress updateCDAddress: typeof ucProposalDataCD.actions.updateAddress
updateSourceIncome: typeof ucProposalDataCD.actions.updateSourceIncome updateSourceIncome: typeof ucProposalDataCD.actions.updateSourceIncome
updateSpouseData: typeof ucProposalDataCD.actions.updateSpouseData updateSpouseData: typeof ucProposalDataCD.actions.updateSpouseData
updateHome: typeof ucProposalDataCD.actions.updateHome updateHome: typeof ucProposalDataCD.actions.updateHome
updateIdentification: typeof ucProposalDataBD.actions.updateIdentification updateBDIdentification: typeof ucProposalDataBD.actions.updateIdentification
updateBDAddress: typeof ucProposalDataBD.actions.updateAddress updateBDAddress: typeof ucProposalDataBD.actions.updateAddress
updateStockSalesCosts: typeof ucProposalDataBD.actions.updateStockSalesCosts updateStockSalesCosts: typeof ucProposalDataBD.actions.updateStockSalesCosts
sendProposal: typeof ucSimulation.actions.sendProposal sendProposal: typeof ucSimulation.actions.sendProposal
getCDIdentification: typeof ucProposalDataCD.actions.getIdentification
getCustomerData: typeof ucProposalDataCD.actions.getCustomerData
getBusinessData: typeof ucProposalDataBD.actions.getBusinessData
} }
type StateProps = Pick<ConnectedProps, 'fetching' | 'proposalId' | 'personId'> type StateProps = Pick<ConnectedProps, 'fetching' | 'proposalId' | 'personId' | 'businessData' | 'customerData'>
type DispatchProps = Pick< type DispatchProps = Pick<
ConnectedProps, ConnectedProps,
| 'reset' | 'reset'
| 'addIndentification' | 'addIndentification'
| 'updateCDIndentification'
| 'fetchContext' | 'fetchContext'
| 'updatePersonalData' | 'updatePersonalData'
| 'updateCDAddress' | 'updateCDAddress'
...@@ -41,17 +51,22 @@ type DispatchProps = Pick< ...@@ -41,17 +51,22 @@ type DispatchProps = Pick<
| 'updateSourceIncome' | 'updateSourceIncome'
| 'updateSpouseData' | 'updateSpouseData'
| 'updateHome' | 'updateHome'
| 'updateIdentification' | 'updateBDIdentification'
| 'updateBDAddress' | 'updateBDAddress'
| 'updateStockSalesCosts' | 'updateStockSalesCosts'
| 'sendProposal' | 'sendProposal'
| 'getCDIdentification'
| 'getCustomerData'
| 'getBusinessData'
> >
const isFetching = createSelector( const isFetching = createSelector(
(state: StoreState) => ucProposalDataContext.selectors.isFetching(state.ui.login), (state: StoreState) => ucProposalDataContext.selectors.isFetching(state.ui.login),
(state: StoreState) => ucAuthentication.selectors.isFetching(state.useCases.authentication), (state: StoreState) => ucAuthentication.selectors.isFetching(state.useCases.authentication),
(state: StoreState) => ucProposalDataCD.selectors.isFetching(state.useCases.proposalData.customerData), (state: StoreState) => ucProposalDataCD.selectors.isFetching(state.useCases.proposalData.customerData),
(state: StoreState) => ucProposalDataCD.selectors.isGettingCustomerData(state.useCases.proposalData.customerData),
(state: StoreState) => ucProposalDataBD.selectors.isFetching(state.useCases.proposalData.businessData), (state: StoreState) => ucProposalDataBD.selectors.isFetching(state.useCases.proposalData.businessData),
(state: StoreState) => ucProposalDataBD.selectors.isGettingBusinessData(state.useCases.proposalData.businessData),
(state: StoreState) => ucSimulation.selectors.isSendingProposal(state.useCases.simulation), (state: StoreState) => ucSimulation.selectors.isSendingProposal(state.useCases.simulation),
(...conditions) => conditions.some((c) => c) (...conditions) => conditions.some((c) => c)
) )
...@@ -60,6 +75,8 @@ const mapStateToProps = (state: StoreState): StateProps => ({ ...@@ -60,6 +75,8 @@ const mapStateToProps = (state: StoreState): StateProps => ({
fetching: isFetching(state), fetching: isFetching(state),
proposalId: entProposal.selectors.getProposalId(state.entities.proposalData.proposal), proposalId: entProposal.selectors.getProposalId(state.entities.proposalData.proposal),
personId: entProposal.selectors.getPersonlId(state.entities.proposalData.proposal), personId: entProposal.selectors.getPersonlId(state.entities.proposalData.proposal),
customerData: entCustomerData.selectors.getCustomerData(state.entities.proposalData.customerData),
businessData: entBusinessData.selectors.getBusinessData(state.entities.proposalData.businessData),
}) })
const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
...@@ -67,6 +84,7 @@ const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ...@@ -67,6 +84,7 @@ const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
{ {
reset: () => ({ type: 'RESET_STORE' }), reset: () => ({ type: 'RESET_STORE' }),
addIndentification: ucProposalDataCD.actions.addIndentification, addIndentification: ucProposalDataCD.actions.addIndentification,
updateCDIndentification: ucProposalDataCD.actions.updateIdentification,
fetchContext: ucProposalDataContext.actions.fetchContext, fetchContext: ucProposalDataContext.actions.fetchContext,
updatePersonalData: ucProposalDataCD.actions.updatePersonalData, updatePersonalData: ucProposalDataCD.actions.updatePersonalData,
updateCDAddress: ucProposalDataCD.actions.updateAddress, updateCDAddress: ucProposalDataCD.actions.updateAddress,
...@@ -75,9 +93,12 @@ const mapDispatchToProps = (dispatch: Dispatch): DispatchProps => ...@@ -75,9 +93,12 @@ const mapDispatchToProps = (dispatch: Dispatch): DispatchProps =>
updateSpouseData: ucProposalDataCD.actions.updateSpouseData, updateSpouseData: ucProposalDataCD.actions.updateSpouseData,
updateHome: ucProposalDataCD.actions.updateHome, updateHome: ucProposalDataCD.actions.updateHome,
updateBDAddress: ucProposalDataBD.actions.updateAddress, updateBDAddress: ucProposalDataBD.actions.updateAddress,
updateIdentification: ucProposalDataBD.actions.updateIdentification, updateBDIdentification: ucProposalDataBD.actions.updateIdentification,
updateStockSalesCosts: ucProposalDataBD.actions.updateStockSalesCosts, updateStockSalesCosts: ucProposalDataBD.actions.updateStockSalesCosts,
sendProposal: ucSimulation.actions.sendProposal, sendProposal: ucSimulation.actions.sendProposal,
getBusinessData: ucProposalDataBD.actions.getBusinessData,
getCustomerData: ucProposalDataCD.actions.getCustomerData,
getCDIdentification: ucProposalDataCD.actions.getIdentification,
}, },
dispatch dispatch
) )
......
import { lightFormat } from 'date-fns'
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { SubProduct } from '@agiliza/api/domain' import { SubProduct } from '@agiliza/api/domain'
import { AMORTIZATIONS } from '@agiliza/constants/amortization'
import { formatCurrency } from '@agiliza/utils/formatters' import { formatCurrency } from '@agiliza/utils/formatters'
import { SelectField } from '@curio/components' import { SelectField } from '@curio/components'
import { Button, Grid } from '@material-ui/core' import { Button, Grid } from '@material-ui/core'
...@@ -48,8 +50,16 @@ const CreditLinesInfo = (props: Props) => { ...@@ -48,8 +50,16 @@ const CreditLinesInfo = (props: Props) => {
{/* <GridLine label="Valor das parcelas" value={formatCurrency(subproduct?.amount.toFixed(2))} /> */} {/* <GridLine label="Valor das parcelas" value={formatCurrency(subproduct?.amount.toFixed(2))} /> */}
<GridLine label="Taxa de juros" value={subproduct?.fee ? `${subproduct?.fee} %` : ''} /> <GridLine label="Taxa de juros" value={subproduct?.fee ? `${subproduct?.fee} %` : ''} />
<GridLine label="Valor total IOF" value={formatCurrency(subproduct?.IOF?.toString() || '')} /> <GridLine label="Valor total IOF" value={formatCurrency(subproduct?.IOF?.toString() || '')} />
<GridLine label="Custo efetivo total (CET)" value={subproduct?.TAC !== undefined ? `${subproduct?.TAC.toFixed(2)} %` : ''} /> <GridLine label="Custo efetivo total mensal (CET)" value={`${subproduct?.monthlyCET?.toFixed(2) || ''} %`} />
{/* <GridLine label="Taxa abertura crédito (TAC)" value={formatCurrency(subproduct?.TAC?.toFixed(2))} /> */} <GridLine label="Custo efetivo total anual (CET)" value={`${subproduct?.yearlyCET?.toFixed(2) || ''} %`} />
<GridLine label="Taxa abertura crédito (TAC)" value={formatCurrency(subproduct?.TAC?.toFixed(2))} />
<GridLine label="Valor total liberado líquido" value={formatCurrency(subproduct?.totalLiberateLiquidValue?.toFixed(2))} />
<GridLine label="Valor do empréstimo" value={formatCurrency(subproduct?.feeTotalValue?.toFixed(2))} />
<GridLine label="Sistema de amortização" value={subproduct?.amortization ? AMORTIZATIONS[subproduct.amortization] : ''} />
<GridLine label="Quatidade de parcelas da carência" value={subproduct?.graceInstallementAmount?.toString() || ''} />
<GridLine label="Valor total calculado" value={formatCurrency(subproduct?.totalCalcValue?.toFixed(2) || '')} />
<GridLine label="Valor total juros" value={formatCurrency(subproduct?.feeTotalValue?.toFixed(2) || '')} />
<GridLine label="Data base de cálculo" value={subproduct?.baseCalcDate ? lightFormat(subproduct.baseCalcDate, 'dd/MM/yyyy') : ''} />
</Grid> </Grid>
<Button variant="text" onClick={() => setOpen(true)} disabled={!subproduct}> <Button variant="text" onClick={() => setOpen(true)} disabled={!subproduct}>
Exibir opções de parcelamento Exibir opções de parcelamento
......
...@@ -52,7 +52,7 @@ const Simulation = (props: Props) => { ...@@ -52,7 +52,7 @@ const Simulation = (props: Props) => {
gracePeriodId: graceMonths, gracePeriodId: graceMonths,
installmentsNumber: paymentMonths, installmentsNumber: paymentMonths,
subproductId: subproduct.id, subproductId: subproduct.id,
onSuccess: () => history.push({ pathname: PATHS.proposalData, state: { subproductId: subproduct?.id } }), onSuccess: (proposalId) => history.push({ pathname: PATHS.proposalData, state: { proposalId } }),
}) })
} }
} else setActiveStep((prevActiveStep) => prevActiveStep + 1) } else setActiveStep((prevActiveStep) => prevActiveStep + 1)
......
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
"@agiliza/public": ["public"], "@agiliza/public": ["public"],
"@agiliza/public/*": ["public/*"] "@agiliza/public/*": ["public/*"]
}, },
"useUnknownInCatchVariables": false,
"removeComments": true, "removeComments": true,
"preserveConstEnums": true, "preserveConstEnums": true,
"sourceMap": true, "sourceMap": true,
......
...@@ -118,7 +118,7 @@ const makeCommonPlugins = (env) => [ ...@@ -118,7 +118,7 @@ const makeCommonPlugins = (env) => [
}), }),
new HtmlWebpackPlugin({ new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.ejs'), template: path.join(__dirname, 'public', 'index.ejs'),
favicon: path.join(PUBLIC, 'images', 'favicon.png'), favicon: path.join(PUBLIC, 'images', 'pdcase.png'),
title: 'Agiliza - Cliente', title: 'Agiliza - Cliente',
inject: false, inject: false,
}), }),
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment