diff --git a/src/auth/application/messages/password-change.ts b/src/auth/application/messages/password-change.ts new file mode 100644 index 00000000..a97c3f15 --- /dev/null +++ b/src/auth/application/messages/password-change.ts @@ -0,0 +1,51 @@ +import { Message } from 'src/common/application/events/message/message'; +import { ISession } from '../model/session.interface'; + +export class AccountRegistered extends Message { + serialize(): string { + let data= { + id: this.id, + password: this.password + } + return JSON.stringify(data) + } + static create( + sessions: ISession[], + id: string, + email: string, + password: string, + created_at: Date, + isConfirmed:boolean, + code: null, + code_created_at:null, + idUser:string, + idStripe:string + ){ + return new AccountRegistered( + sessions, + id, + email, + password, + created_at, + isConfirmed, + code, + code_created_at, + idUser, + idStripe + ) + } + constructor( + public sessions: ISession[], + public id: string, + public email: string, + public password: string, + public created_at: Date, + public isConfirmed:boolean, + public code: null, + public code_created_at:null, + public idUser:string, + public idStripe:string + ){ + super() + } +} \ No newline at end of file diff --git a/src/auth/application/messages/session-registered.ts b/src/auth/application/messages/session-registered.ts index 824e6186..a0335036 100644 --- a/src/auth/application/messages/session-registered.ts +++ b/src/auth/application/messages/session-registered.ts @@ -1,33 +1,31 @@ import { Message } from 'src/common/application/events/message/message'; +import { ISession } from '../model/session.interface'; export class SessionRegistered extends Message { serialize(): string { let data= { id: this.id, - expired_at: this.expired_at, - push_token: this.push_token, - accountId:this.accountId + session:{ + id: this.id, + expired_at: this.session.expired_at, + push_token: this.session.push_token, + accountId:this.session.accountId + } } return JSON.stringify(data) } static create( - id: string, - expired_at: Date, - push_token: string, - accountId:string + id:string, + session:ISession ){ return new SessionRegistered( id, - expired_at, - push_token, - accountId + session ) } constructor( public id: string, - public expired_at: Date, - public push_token: string, - public accountId:string + public session:ISession ){ super() } diff --git a/src/auth/application/services/command/log-in-user-application.service.ts b/src/auth/application/services/command/log-in-user-application.service.ts index b6a3e32d..9d2af886 100644 --- a/src/auth/application/services/command/log-in-user-application.service.ts +++ b/src/auth/application/services/command/log-in-user-application.service.ts @@ -16,6 +16,8 @@ import { IQueryUserRepository } from "src/user/application/repository/user.query import { UserId } from "src/user/domain/value-object/user-id"; import { ErrorRegisteringSessionApplicationException } from "../../application-exception/error-registering-session-application-exception"; import { AccountNotFoundApplicationException } from "../../application-exception/account-not-found-application-exception"; +import { IMessagesPublisher } from "src/common/application/messages/messages-publisher/messages-publisher.interface"; +import { SessionRegistered } from "../../messages/session-registered"; export class LogInUserApplicationService extends IApplicationService { @@ -27,7 +29,8 @@ export class LogInUserApplicationService extends IApplicationService private readonly encryptor: IEncryptor, private readonly idGen:IIdGen, private readonly jwtGen:IJwtGenerator, - private readonly dateHandler:IDateHandler + private readonly dateHandler:IDateHandler, + private readonly messagePublisher:IMessagesPublisher ){ super() } @@ -56,18 +59,26 @@ export class LogInUserApplicationService extends IApplicationService const idSession = await this.idGen.genId() const jwt = this.jwtGen.generateJwt( idSession ) - - let sessionResponse=await this.commandTokenSessionRepository.createSession( - { + + const session={ expired_at: this.dateHandler.getExpiry(), id: idSession, push_token: null, accountId: account.id - }) + } + + let sessionResponse=await this.commandTokenSessionRepository.createSession(session) if (!sessionResponse.isSuccess()) return Result.fail(new ErrorRegisteringSessionApplicationException()) + this.messagePublisher.publish([ + SessionRegistered.create( + account.id, + session + ) + ]) + return Result.success({ id: user.getId().Value, email: account.email, diff --git a/src/auth/infraestructure/controller/auth.controller.ts b/src/auth/infraestructure/controller/auth.controller.ts index 155b3ce2..d103c1df 100644 --- a/src/auth/infraestructure/controller/auth.controller.ts +++ b/src/auth/infraestructure/controller/auth.controller.ts @@ -68,6 +68,8 @@ import { AuthQueues } from "../queues/auth.queues" import { IAccountRegistered } from "../interface/account-registered.interface" import { AccountRegisteredSyncroniceService } from "../services/syncronice/account-registered-syncronice.service" import mongoose, { Mongoose } from "mongoose" +import { IAccountLogIn } from "../interface/account-log-in.interface" +import { AccountLogInSyncroniceService } from "../services/syncronice/account-log-in-syncronice.service" @ApiTags('Auth') @Controller('auth') @@ -136,7 +138,15 @@ export class AuthController { this.syncAccountRegistered(data) return } - ) + ) + + this.messageSuscriber.consume( + { name: 'Messages/SessionRegistered' }, + (data):Promise=>{ + this.syncAccountLogIn(data) + return + } + ) } async syncAccountRegistered(data:IAccountRegistered){ @@ -144,6 +154,11 @@ export class AuthController { await service.execute(data) } + async syncAccountLogIn(data:IAccountLogIn){ + let service = new AccountLogInSyncroniceService(mongoose) + await service.execute({...data}) + } + @Post('register') @ApiResponse({ status: 200, @@ -197,7 +212,8 @@ export class AuthController { this.encryptor, this.idGen, this.jwtGen, - this.dateHandler + this.dateHandler, + this.messagePubliser ), new NestTimer(), new NestLogger(new Logger()) // ),new NestLogger(new Logger()) ),this.auditRepository,this.dateHandler diff --git a/src/auth/infraestructure/interface/account-log-in.interface.ts b/src/auth/infraestructure/interface/account-log-in.interface.ts new file mode 100644 index 00000000..b70c4bfe --- /dev/null +++ b/src/auth/infraestructure/interface/account-log-in.interface.ts @@ -0,0 +1,9 @@ +export interface IAccountLogIn { + id:string + session: { + id: string; + expired_at: Date; + push_token: string; + accountId: string; + } +} \ No newline at end of file diff --git a/src/auth/infraestructure/queues/auth.queues.ts b/src/auth/infraestructure/queues/auth.queues.ts index 743dd784..de4f6969 100644 --- a/src/auth/infraestructure/queues/auth.queues.ts +++ b/src/auth/infraestructure/queues/auth.queues.ts @@ -1,3 +1,4 @@ export const AuthQueues = [ { name: 'Messages/AccountRegistered', pattern: 'AccountRegistered' }, + { name: 'Messages/SessionRegistered', pattern: 'SessionRegistered' }, ] \ No newline at end of file diff --git a/src/auth/infraestructure/repositories/odm-repository/odm-account-query-repository.ts b/src/auth/infraestructure/repositories/odm-repository/odm-account-query-repository.ts index f76c8a43..2d45f343 100644 --- a/src/auth/infraestructure/repositories/odm-repository/odm-account-query-repository.ts +++ b/src/auth/infraestructure/repositories/odm-repository/odm-account-query-repository.ts @@ -1,30 +1,82 @@ import { IQueryAccountRepository } from "src/auth/application/repository/query-account-repository.interface" -import { OrmAccountEntity } from "../../account/orm-entities/orm-account-entity" -import { DataSource, Repository } from "typeorm" import { IAccount } from "src/auth/application/model/account.interface" import { Result } from "src/common/utils/result-handler/result" import { NotFoundException } from "src/common/infraestructure/infraestructure-exception" +import { OdmAccount, OdmAccountSchema } from "../../account/odm-entities/odm-account-entity" +import { Model, Mongoose } from "mongoose" export class OdmAccountQueryRepository implements IQueryAccountRepository{ - constructor(dataSource:DataSource){} - - findAccountByEmail(email: string): Promise> { - throw new Error("Method not implemented.") + private readonly model: Model; + + constructor( mongoose: Mongoose ) { + this.model = mongoose.model('odmaccount', OdmAccountSchema) + } + + async findAccountByEmail(email: string): Promise> { + try{ + let odm=await this.model.findOne({email}) + + if(!odm) + return Result.fail( new NotFoundException('Find account by email unsucssessfully')) + + return Result.success(odm) + } + catch(e){ + return Result.fail( new NotFoundException('Find account by email unsucssessfully')) + } } - findAccountById(id: string): Promise> { - throw new Error("Method not implemented.") + async findAccountById(id: string): Promise> { + try{ + let odm=await this.model.findOne({id}) + + if(!odm) + return Result.fail( new NotFoundException('Find account by id unsucssessfully')) + + return Result.success(odm) + } + catch(e){ + return Result.fail( new NotFoundException('Find account by id unsucssessfully')) + } } - findAccountByUserId(userId: string): Promise> { - throw new Error("Method not implemented.") + async findAccountByUserId(userId: string): Promise> { + try{ + let odm=await this.model.findOne({idUser:userId}) + + if(!odm) + return Result.fail( new NotFoundException('Find account by user id unsucssessfully')) + + return Result.success(odm) + } + catch(e){ + return Result.fail( new NotFoundException('Find account by user id unsucssessfully')) + } } - verifyAccountExistanceByEmail(email: string): Promise> { - throw new Error("Method not implemented.") + async verifyAccountExistanceByEmail(email: string): Promise> { + try{ + let odm=await this.model.findOne({email}) + if(!odm) + return Result.success(false) + return Result.success(true) + } + catch(e){ + return Result.fail( new NotFoundException('Verify account by email unsucssessfully')) + } } - findAllEmails(): Promise> { - throw new Error("Method not implemented.") + async findAllEmails(): Promise> { + try{ + let odm=await this.model.find() + if(!odm) + return Result.success(odm + ? odm.map(o=>o.email) + : [] + ) + } + catch(e){ + return Result.fail( new NotFoundException('Find all emails unsucssessfully')) + } } } \ No newline at end of file diff --git a/src/auth/infraestructure/repositories/odm-repository/odm-token-query-session-repository.ts b/src/auth/infraestructure/repositories/odm-repository/odm-token-query-session-repository.ts index 4913f595..e7d8dc09 100644 --- a/src/auth/infraestructure/repositories/odm-repository/odm-token-query-session-repository.ts +++ b/src/auth/infraestructure/repositories/odm-repository/odm-token-query-session-repository.ts @@ -1,23 +1,43 @@ +import { Model, Mongoose } from "mongoose"; import { ISession } from "src/auth/application/model/session.interface" import { IQueryTokenSessionRepository } from "src/auth/application/repository/query-token-session-repository.interface" import { Result } from "src/common/utils/result-handler/result" import { UserId } from "src/user/domain/value-object/user-id" +import { OdmAccount, OdmAccountSchema } from "../../account/odm-entities/odm-account-entity"; +import { NotFoundException } from "src/common/infraestructure/infraestructure-exception"; export class OrmTokenQueryRepository implements IQueryTokenSessionRepository{ + + private readonly model: Model; + + constructor( mongoose: Mongoose ) { + this.model = mongoose.model('odmaccount', OdmAccountSchema) + } findAllLastTokenSessions(): Promise> { throw new Error("Method not implemented.") } - findSessionById(id: string): Promise> { - throw new Error("Method not implemented.") + async findSessionById(id: string): Promise> { + try{ + //TODO + let odm=await this.model.find({"sessions.id":id}) + } + catch(e){ + return Result.fail( new NotFoundException('Find session unsucssessfully')) + } } findAllTokenSessions(): Promise> { throw new Error("Method not implemented.") } - findSessionLastSessionByUserId(id: UserId): Promise> { - throw new Error("Method not implemented.") + async findSessionLastSessionByUserId(id: UserId): Promise> { + try{ + let odm=await this.model.find({idUser:id.Value}) + } + catch(e){ + return Result.fail( new NotFoundException('Find all emails unsucssessfully')) + } } } \ No newline at end of file diff --git a/src/auth/infraestructure/repositories/orm-repository/orm-token-query-session-repository.ts b/src/auth/infraestructure/repositories/orm-repository/orm-token-query-session-repository.ts index ec07c167..70bff028 100644 --- a/src/auth/infraestructure/repositories/orm-repository/orm-token-query-session-repository.ts +++ b/src/auth/infraestructure/repositories/orm-repository/orm-token-query-session-repository.ts @@ -27,13 +27,15 @@ export class OrmTokenQueryRepository extends Repository implem try{ const sessions = await this.createQueryBuilder("session") .select("session.push_token") - .orderBy("session.created_at", "DESC") + .orderBy("session.expired_at", "DESC") .limit(1) .getMany() - const tokens = sessions.map(session => session.push_token) - return Result.success(tokens) + return Result.success(sessions + ? sessions.map(session => session.push_token) + : [] + ) }catch(e){ - return Result.fail( new NotFoundException('Error finding all emails')) + return Result.fail( new NotFoundException('Error finding all tokens')) } } diff --git a/src/auth/infraestructure/services/dto/request/account-log-in-infraestructure-request-dto.ts b/src/auth/infraestructure/services/dto/request/account-log-in-infraestructure-request-dto.ts index a4081407..f894b3e3 100644 --- a/src/auth/infraestructure/services/dto/request/account-log-in-infraestructure-request-dto.ts +++ b/src/auth/infraestructure/services/dto/request/account-log-in-infraestructure-request-dto.ts @@ -1,8 +1,9 @@ export interface AccountLogInInfraestructureRequestDTO { - sessions: { - id: string - expired_at: Date - push_token: null - accountId:string + id:string + session: { + id: string; + expired_at: Date; + push_token: string; + accountId: string; } } \ No newline at end of file diff --git a/src/auth/infraestructure/services/syncronice/account-log-in-syncronice.service.ts b/src/auth/infraestructure/services/syncronice/account-log-in-syncronice.service.ts new file mode 100644 index 00000000..a1e49b77 --- /dev/null +++ b/src/auth/infraestructure/services/syncronice/account-log-in-syncronice.service.ts @@ -0,0 +1,24 @@ +import { Result } from 'src/common/utils/result-handler/result'; +import { ISycnchronizeService } from 'src/common/infraestructure/synchronize-service/synchronize.service.interface'; +import { Model, Mongoose } from 'mongoose'; +import { OdmAccount, OdmAccountSchema } from '../../account/odm-entities/odm-account-entity'; +import { AccountLogInInfraestructureRequestDTO } from '../dto/request/account-log-in-infraestructure-request-dto'; + +export class AccountLogInSyncroniceService implements +ISycnchronizeService{ + + private readonly model: Model + + + constructor( mongoose: Mongoose ) { + this.model = mongoose.model('odmaccount', OdmAccountSchema) + } + + async execute(event: AccountLogInInfraestructureRequestDTO): Promise> { + + const account = await this.model.findOne({id:event.id}) + account.sessions.push(event.session) + await account.save() + return Result.success(undefined) + } +} \ No newline at end of file diff --git a/src/bundle/infraestructure/entities/odm-entities/odm-bundle-entity.ts b/src/bundle/infraestructure/entities/odm-entities/odm-bundle-entity.ts index 26eee225..df350162 100644 --- a/src/bundle/infraestructure/entities/odm-entities/odm-bundle-entity.ts +++ b/src/bundle/infraestructure/entities/odm-entities/odm-bundle-entity.ts @@ -1,8 +1,6 @@ import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose" import mongoose, { Document, SchemaTypes } from "mongoose" -import { OdmCategory } from "src/category/infraestructure/entities/odm-entities/odm-category.entity" import { IOdmBundle } from "../../model-entity/odm-model-entity/odm-bundle-interface" -import { OdmProduct } from "src/product/infraestructure/entities/odm-entities/odm-product-entity" @Schema({ collection: 'odmbundle' }) export class OdmBundle extends Document implements IOdmBundle { @@ -69,15 +67,6 @@ export class OdmBundle extends Document implements IOdmBundle { id:string, name:string }[] - - // @Prop({ type: [Object], unique: false, required: false }) - // category?: OdmCategory[] - - - // @Prop({ type: [Object], unique: false, required: true }) - // products: OdmProduct[] - - } export const OdmBundleSchema = SchemaFactory.createForClass( OdmBundle ) diff --git a/src/bundle/infraestructure/repositories/odm-repository/odm-bundle-query-repository.ts b/src/bundle/infraestructure/repositories/odm-repository/odm-bundle-query-repository.ts index 4b287322..bf8dde3f 100644 --- a/src/bundle/infraestructure/repositories/odm-repository/odm-bundle-query-repository.ts +++ b/src/bundle/infraestructure/repositories/odm-repository/odm-bundle-query-repository.ts @@ -14,6 +14,8 @@ import { IProductModel } from "src/product/application/model/product.model.inter import { NotFoundException } from "src/common/infraestructure/infraestructure-exception"; import { OdmBundleMapper } from "../../mapper/odm-mapper/odm-bundle-mapper"; import { OdmPromotionEntity, OdmPromotionSchema } from "src/promotion/infraestructure/entities/odm-entities/odm-promotion-entity"; +import { IPromotion } from "src/promotion/application/model/promotion.interface"; +import { IOdmModelPromotion } from "src/promotion/infraestructure/model-entity/odm-model-entity/odm-promotion-interface"; export class OdmBundleQueryRepository implements IQueryBundleRepository{ @@ -62,13 +64,6 @@ export class OdmBundleQueryRepository implements IQueryBundleRepository{ discount:p.discount })) : [], - // odm.promotions - // ? odm.promotions.map(promotion=>({ - // id:promotion.id, - // name:promotion.name, - // discount:Number(promotion.discount) - // })) - // : [] products: odm.products ? odm.products.map(p=>({ id:p.id, @@ -84,7 +79,7 @@ export class OdmBundleQueryRepository implements IQueryBundleRepository{ try { const query: any = {}; - const model:IBundleModel[]=[] + let model:IBundleModel[]=[] if (criteria.name) query.name = { $regex: criteria.name, $options: 'i' } @@ -93,10 +88,9 @@ export class OdmBundleQueryRepository implements IQueryBundleRepository{ query.category = { $elemMatch: { name: { $in: criteria.category.map((c: string) => new RegExp(c, 'i')) } } }; if (criteria.price) - query.price = { ...query.price, $lte: criteria.price } + query.price = { ...query.price, $lt: criteria.price } + - if (criteria.discount) - query.discount = { $gt: 0 }; const bundles = await this.model.find(query) .skip(criteria.page) @@ -107,6 +101,10 @@ export class OdmBundleQueryRepository implements IQueryBundleRepository{ model.push(await this.trasnformtoDataModel(b)) } + if (criteria.discount){ + model=model.filter(p=>p.promotion.length!==0) + } + return Result.success(model) } catch (error) { diff --git a/src/cupon/infraestructure/controller/cupon.controller.ts b/src/cupon/infraestructure/controller/cupon.controller.ts index b883a51f..665bcf3c 100644 --- a/src/cupon/infraestructure/controller/cupon.controller.ts +++ b/src/cupon/infraestructure/controller/cupon.controller.ts @@ -138,12 +138,12 @@ export class CuponController { @Query() entry: FindAllCuponsInfraestructureRequestDTO) { if (!entry.page) entry.page = 1; - if (!entry.perPage) entry.perPage = 10; + if (!entry.perpage) entry.perpage = 10; const pagination: PaginationRequestDTO = { userId: credential.account.idUser, page: entry.page, - perPage: entry.perPage + perPage: entry.perpage }; let service = new ExceptionDecorator( diff --git a/src/cupon/infraestructure/dto-request/find-all-cupons-infraestructure-request.ts b/src/cupon/infraestructure/dto-request/find-all-cupons-infraestructure-request.ts index 3df439d7..d3fc1586 100644 --- a/src/cupon/infraestructure/dto-request/find-all-cupons-infraestructure-request.ts +++ b/src/cupon/infraestructure/dto-request/find-all-cupons-infraestructure-request.ts @@ -1,17 +1,5 @@ -import { ApiProperty } from "@nestjs/swagger"; -import { Transform, Type } from "class-transformer"; -import { IsOptional, IsPositive } from "class-validator"; +import { PaginationDto } from "src/common/infraestructure/dto/entry/pagination.dto"; -export class FindAllCuponsInfraestructureRequestDTO { - @ApiProperty({ required: false, default: 1, minimum: 1 }) - @IsOptional() - @IsPositive() - @Transform(({ value }) => { return Number(value); }) - page?: number; +export class FindAllCuponsInfraestructureRequestDTO extends PaginationDto{ - @ApiProperty({ required: false, default: 10, minimum: 1 }) - @IsOptional() - @IsPositive() - @Transform(({ value }) => { return Number(value); }) - perPage?: number; } diff --git a/src/payment-methods/infraestructure/controller/payment-method.controller.ts b/src/payment-methods/infraestructure/controller/payment-method.controller.ts index 0fb9e7f2..d96632e5 100644 --- a/src/payment-methods/infraestructure/controller/payment-method.controller.ts +++ b/src/payment-methods/infraestructure/controller/payment-method.controller.ts @@ -217,6 +217,9 @@ export class PaymentMethodController { userId: credential.account.idUser, ...data } + if (!values.page) values.page = 1; + if (!values.perPage) values.perPage = 10; + if (!values.page) values.page = 1; if (!values.perPage) values.perPage = 10; diff --git a/src/product/infraestructure/repositories/odm-repository/odm-product-query-repository.ts b/src/product/infraestructure/repositories/odm-repository/odm-product-query-repository.ts index d2f352c4..5ba64c56 100644 --- a/src/product/infraestructure/repositories/odm-repository/odm-product-query-repository.ts +++ b/src/product/infraestructure/repositories/odm-repository/odm-product-query-repository.ts @@ -70,7 +70,7 @@ export class OdmProductQueryRepository implements IQueryProductRepository { async findAllProducts(criteria: FindAllProductsApplicationRequestDTO): Promise> { try { const query: any = {}; - const model:IProductModel[]=[] + let model:IProductModel[]=[] if (criteria.name) query.name = { $regex: criteria.name, $options: 'i' } @@ -79,11 +79,8 @@ export class OdmProductQueryRepository implements IQueryProductRepository { query.category = { $elemMatch: { name: { $in: criteria.category.map((c: string) => new RegExp(c, 'i')) } } }; if (criteria.price) - query.price = { ...query.price, $gte: criteria.price } - - if (criteria.discount) - query.discount = { $gt: 0 }; - + query.price = { ...query.price, $lt: criteria.price } + const products = await this.model.find(query) .skip(criteria.page) .limit(criteria.perPage) @@ -93,6 +90,11 @@ export class OdmProductQueryRepository implements IQueryProductRepository { model.push(await this.trasnformtoDataModel(p)) } + if (criteria.discount){ + model=model.filter(p=>p.promotion.length!==0) + } + + return Result.success(model) } catch (error) { diff --git a/src/user/domain/aggregate/user.aggregate.ts b/src/user/domain/aggregate/user.aggregate.ts index d9e9981e..e85f51cd 100644 --- a/src/user/domain/aggregate/user.aggregate.ts +++ b/src/user/domain/aggregate/user.aggregate.ts @@ -146,7 +146,8 @@ export class User extends AggregateRoot { userPhone, userImage, wallet, - userCoupon + userCoupon, + userRole ) ) return user diff --git a/src/user/domain/domain-events/user-direction-added.ts b/src/user/domain/domain-events/user-direction-added.ts index 9e860290..8657093a 100644 --- a/src/user/domain/domain-events/user-direction-added.ts +++ b/src/user/domain/domain-events/user-direction-added.ts @@ -9,10 +9,10 @@ export class UserDirectionAdded extends DomainEvent { userId:this.userId.Value, userDirection:{ id: this.userDirection.getId().Value, - name: this.userDirection.DirectionName, - favorite: this.userDirection.DirectionFavorite, - lat: this.userDirection.DirectionLat, - lng: this.userDirection.DirectionLng + name: this.userDirection.DirectionName.Value, + favorite: this.userDirection.DirectionFavorite.Value, + lat: this.userDirection.DirectionLat.Value, + lng: this.userDirection.DirectionLng.Value } } return JSON.stringify(data) diff --git a/src/user/domain/domain-events/user-direction-updated.ts b/src/user/domain/domain-events/user-direction-updated.ts index f6722b38..3142dd8c 100644 --- a/src/user/domain/domain-events/user-direction-updated.ts +++ b/src/user/domain/domain-events/user-direction-updated.ts @@ -9,10 +9,10 @@ export class UserDirectionUpdated extends DomainEvent { userId:this.userId.Value, userDirection:{ id: this.userDirection.getId().Value, - name: this.userDirection.DirectionName, - favorite: this.userDirection.DirectionFavorite, - lat: this.userDirection.DirectionLat, - lng: this.userDirection.DirectionLng + name: this.userDirection.DirectionName.Value, + favorite: this.userDirection.DirectionFavorite.Value, + lat: this.userDirection.DirectionLat.Value, + lng: this.userDirection.DirectionLng.Value } } return JSON.stringify(data) diff --git a/src/user/domain/domain-events/user-registered.ts b/src/user/domain/domain-events/user-registered.ts index 67047e7c..e331c0d0 100644 --- a/src/user/domain/domain-events/user-registered.ts +++ b/src/user/domain/domain-events/user-registered.ts @@ -1,11 +1,11 @@ import { DomainEvent } from '../../../common/domain/domain-event/domain-event'; import { UserCoupon } from '../entities/coupon/user-coupon.entity'; import { Wallet } from '../entities/wallet/wallet.entity'; -import { UserEmail } from '../value-object/user-email'; import { UserId } from '../value-object/user-id'; import { UserImage } from '../value-object/user-image'; import { UserName } from '../value-object/user-name'; import { UserPhone } from '../value-object/user-phone'; +import { UserRole } from '../value-object/user-role'; export class UserRegistered extends DomainEvent { serialize(): string { @@ -26,7 +26,8 @@ export class UserRegistered extends DomainEvent { state:c.CuponState.Value })) : [], - userImage: this.userImage ? this.userImage.Value : undefined + userImage: this.userImage ? this.userImage.Value : undefined, + userRole: this.userRole.Value } return JSON.stringify(data) } @@ -36,7 +37,8 @@ export class UserRegistered extends DomainEvent { userPhone:UserPhone, userImage:UserImage, wallet:Wallet, - userCoupon:UserCoupon[] + userCoupon:UserCoupon[], + userRole:UserRole ){ return new UserRegistered( userId, @@ -44,7 +46,8 @@ export class UserRegistered extends DomainEvent { userPhone, userImage, wallet, - userCoupon + userCoupon, + userRole ) } constructor( @@ -53,7 +56,9 @@ export class UserRegistered extends DomainEvent { public userPhone:UserPhone, public userImage:UserImage, public Wallet:Wallet, - public userCoupon:UserCoupon[] + public userCoupon:UserCoupon[], + public userRole:UserRole, + ){ super() } diff --git a/src/user/infraestructure/controller/user.controller.ts b/src/user/infraestructure/controller/user.controller.ts index 43ff7983..1a707d11 100644 --- a/src/user/infraestructure/controller/user.controller.ts +++ b/src/user/infraestructure/controller/user.controller.ts @@ -62,6 +62,21 @@ import { FileInterceptor } from '@nestjs/platform-express'; import { UpdateProfileApplicationRequestDTO } from "src/user/application/dto/request/update-profile-application-request-dto" import { UpdateProfileApplicationResponseDTO } from "src/user/application/dto/response/update-profile-application-response-dto" import { OdmCuponQueryRepository } from "src/cupon/infraestructure/repository/odm-repository/odm-query-coupon-repository" +import { IUserRegistered } from "../interfaces/user-registered.interface" +import { UserRegisteredSyncroniceService } from "../services/syncronice/user-registered-syncronice.service" +import { UserUpdatedInfraestructureRequestDTO } from "../services/dto/request/user-updated-infraestructure-request-dto" +import { UserUpdatedSyncroniceService } from "../services/syncronice/user-updated-syncronice.service" +import { IUserBalanceAmountAdded } from "../interfaces/user-balance-amount-added.interface" +import { IUserBalanceAmountDecremented } from "../interfaces/user-balance-amount-decremented.interface" +import { IUserCouponAplied } from "../interfaces/user-coupon-aplied.interface" +import { IUserDirectionAdded } from "../interfaces/user-direction-added.interface" +import { IUserDirectionDeleted } from "../interfaces/user-direction-deleted.interface" +import { IUserDirectionUpdated } from "../interfaces/user-direction-updated.interface" +import { IUserImageUpdated } from "../interfaces/user-image-updated.interface" +import { IUserNameUpdated } from "../interfaces/user-name-updated.interface" +import { IUserPhoneUpdated } from "../interfaces/user-phone-updated.interface" +import { OdmUserQueryRepository } from '../repositories/odm-repository/odm-user-query-repository'; +import { OdmAccountQueryRepository } from "src/auth/infraestructure/repositories/odm-repository/odm-account-query-repository" @ApiBearerAuth() @UseGuards(JwtAuthGuard) @@ -81,6 +96,10 @@ export class UserController { private readonly hereMapsSingelton: HereMapsSingelton; private readonly ormCuponQueryRepo: IQueryCuponRepository; private readonly subscriber: RabbitMQSubscriber; + private readonly odmUserQueryRepository:IQueryUserRepository + private readonly odmAccountQueryRepo:IQueryAccountRepository + private readonly odmCuponQueryRepo: IQueryCuponRepository; + private initializeQueues():void{ UserQueues.forEach(queue => this.buildQueue(queue.name, queue.pattern)) @@ -116,6 +135,9 @@ export class UserController { this.geocodification= new GeocodificationOpenStreeMapsDomainService() this.ormCuponQueryRepo = new OdmCuponQueryRepository(mongoose); this.subscriber= new RabbitMQSubscriber(this.channel); + this.odmAccountQueryRepo= new OdmAccountQueryRepository(mongoose) + this.odmUserQueryRepository= new OdmUserQueryRepository(mongoose), + this.odmCuponQueryRepo= new OdmCuponQueryRepository(mongoose) this.initializeQueues(); @@ -126,6 +148,95 @@ export class UserController { return } ) + + this.subscriber.consume( + { name: 'UserSync/UserBalanceAmountAdded'}, + (data):Promise=>{ + this.userupdatedsync(data) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserBalanceAmountDecremented'}, + (data):Promise=>{ + this.userupdatedsync(data) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserCouponAplied'}, + (data):Promise=>{ + this.userupdatedsync({...data,coupons:[{...data.coupons}]}) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserDirectionAdded'}, + (data):Promise=>{ + this.userupdatedsync({...data}) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserDirectionDeleted'}, + (data):Promise=>{ + this.userupdatedsync({userId:data.userId, userDirectionDelete:{id:data.userDirection.id}}) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserDirectionUpdated'}, + (data):Promise=>{ + this.userupdatedsync({...data}) + return + } + ) + this.subscriber.consume( + { name: 'UserSync/UserImageUpdated'}, + (data):Promise=>{ + this.userupdatedsync({...data}) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserNameUpdated' }, + (data):Promise=>{ + this.userupdatedsync({...data}) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserPhoneUpdated'}, + (data):Promise=>{ + this.userupdatedsync({...data}) + return + } + ) + + this.subscriber.consume( + { name: 'UserSync/UserRegistered'}, + (data):Promise=>{ + this.userregisteredsync(data) + return + } + ) + } + + async userregisteredsync(data:IUserRegistered){ + let service=new UserRegisteredSyncroniceService(this.mongoose) + await service.execute(data) + } + + async userupdatedsync(data:UserUpdatedInfraestructureRequestDTO){ + let service=new UserUpdatedSyncroniceService(this.mongoose) + await service.execute(data) } @Patch('update/profile') diff --git a/src/user/infraestructure/entities/odm-entities/odm-user-entity.ts b/src/user/infraestructure/entities/odm-entities/odm-user-entity.ts new file mode 100644 index 00000000..298eab09 --- /dev/null +++ b/src/user/infraestructure/entities/odm-entities/odm-user-entity.ts @@ -0,0 +1,83 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { Document, SchemaTypes } from 'mongoose'; +import { UserRoles } from 'src/user/domain/value-object/enum/user.roles'; +import { IOdmUser } from '../../model-entity/odm-model-entity/odm-user-interface'; + +@Schema({ collection: 'odmuser' }) +export class OdmUserEntity extends Document implements IOdmUser{ + + @Prop({ type: String, unique: true, required: true }) + id: string + + @Prop({ type: String, unique: false, required: true }) + name: string; + + @Prop({ type: String, unique: true, required: true }) + phone: string; + + @Prop({ type: String, unique: true, required: false }) + image: string; + + @Prop({ type: String, enum: UserRoles, required: true }) + type: UserRoles + + + @Prop({ + type: [ + { + _id:false, + id: SchemaTypes.String, + favorite: SchemaTypes.Boolean, + lat: SchemaTypes.Number, + lng: SchemaTypes.Number, + name: SchemaTypes.String + } + ], + unique: false, + required: false + }) + direction: { + id: string; + favorite: boolean; + lat: number; + lng: number; + name: string; + }[]; + + @Prop({ + type: + { + _id:false, + id: SchemaTypes.String, + currency: SchemaTypes.String, + amount: SchemaTypes.String + } + , + unique: false, + required: false + }) + wallet:{ + id:string, + currency:string, + amount:number + } + + @Prop({ + type: [ + { + _id:false, + id: SchemaTypes.String, + state: SchemaTypes.String, + } + ] + , + unique: false, + required: false + }) + coupon:{ + id:string, + state:string, + }[] + +} +export const OdmUserSchema = SchemaFactory.createForClass(OdmUserEntity); diff --git a/src/user/infraestructure/interfaces/user-balance-amount-added.interface.ts b/src/user/infraestructure/interfaces/user-balance-amount-added.interface.ts new file mode 100644 index 00000000..d51b285e --- /dev/null +++ b/src/user/infraestructure/interfaces/user-balance-amount-added.interface.ts @@ -0,0 +1,8 @@ + +export interface IUserBalanceAmountAdded { + userId:string + userWallet: { + amount: number; + currency: string; + } +} diff --git a/src/user/infraestructure/interfaces/user-balance-amount-decremented.interface.ts b/src/user/infraestructure/interfaces/user-balance-amount-decremented.interface.ts new file mode 100644 index 00000000..6804cf13 --- /dev/null +++ b/src/user/infraestructure/interfaces/user-balance-amount-decremented.interface.ts @@ -0,0 +1,7 @@ +export interface IUserBalanceAmountDecremented { + userId:string + userWallet: { + amount: number; + currency: string; + } +} diff --git a/src/user/infraestructure/interfaces/user-coupon-aplied.interface.ts b/src/user/infraestructure/interfaces/user-coupon-aplied.interface.ts new file mode 100644 index 00000000..341744e7 --- /dev/null +++ b/src/user/infraestructure/interfaces/user-coupon-aplied.interface.ts @@ -0,0 +1,7 @@ +export interface IUserCouponAplied { + userId:string, + coupons: { + id: string; + state: string; + } +} \ No newline at end of file diff --git a/src/user/infraestructure/interfaces/user-direction-added.interface.ts b/src/user/infraestructure/interfaces/user-direction-added.interface.ts new file mode 100644 index 00000000..0d29dfe2 --- /dev/null +++ b/src/user/infraestructure/interfaces/user-direction-added.interface.ts @@ -0,0 +1,10 @@ +export interface IUserDirectionAdded { + userId: string + userDirection: { + id: string; + name: string; + favorite: boolean; + lat: number; + lng: number; + } +} \ No newline at end of file diff --git a/src/user/infraestructure/interfaces/user-direction-deleted.interface.ts b/src/user/infraestructure/interfaces/user-direction-deleted.interface.ts new file mode 100644 index 00000000..67e976f0 --- /dev/null +++ b/src/user/infraestructure/interfaces/user-direction-deleted.interface.ts @@ -0,0 +1,7 @@ + +export interface IUserDirectionDeleted { + userId: string + userDirection: { + id: string; + } +} \ No newline at end of file diff --git a/src/user/infraestructure/interfaces/user-direction-updated.interface.ts b/src/user/infraestructure/interfaces/user-direction-updated.interface.ts new file mode 100644 index 00000000..c4f615c7 --- /dev/null +++ b/src/user/infraestructure/interfaces/user-direction-updated.interface.ts @@ -0,0 +1,10 @@ +export interface IUserDirectionUpdated { + userId: string + userDirection: { + id: string; + name: string; + favorite: boolean; + lat: number; + lng: number; + } +} \ No newline at end of file diff --git a/src/user/infraestructure/interfaces/user-image-updated.interface.ts b/src/user/infraestructure/interfaces/user-image-updated.interface.ts new file mode 100644 index 00000000..9ba6974b --- /dev/null +++ b/src/user/infraestructure/interfaces/user-image-updated.interface.ts @@ -0,0 +1,4 @@ +export interface IUserImageUpdated{ + userId: string; + userImage: string; +} diff --git a/src/user/infraestructure/interfaces/user-name-updated.interface.ts b/src/user/infraestructure/interfaces/user-name-updated.interface.ts new file mode 100644 index 00000000..51d01cd2 --- /dev/null +++ b/src/user/infraestructure/interfaces/user-name-updated.interface.ts @@ -0,0 +1,4 @@ +export interface IUserNameUpdated{ + userId: string; + userName: string; +} diff --git a/src/user/infraestructure/interfaces/user-phone-updated.interface.ts b/src/user/infraestructure/interfaces/user-phone-updated.interface.ts new file mode 100644 index 00000000..2d834052 --- /dev/null +++ b/src/user/infraestructure/interfaces/user-phone-updated.interface.ts @@ -0,0 +1,4 @@ +export interface IUserPhoneUpdated{ + userId: string; + userPhone: string; +} diff --git a/src/user/infraestructure/interfaces/user-registered.interface.ts b/src/user/infraestructure/interfaces/user-registered.interface.ts new file mode 100644 index 00000000..cb73287c --- /dev/null +++ b/src/user/infraestructure/interfaces/user-registered.interface.ts @@ -0,0 +1,18 @@ +export interface IUserRegistered{ + userId: string; + userName: string; + userPhone: string; + wallet: { + walletId: string; + ballance: { + currency: string; + amount: number; + }; + }; + coupons: { + id: string; + state: string; + }[]; + userImage: string; + userRole: string +} diff --git a/src/user/infraestructure/mapper/odm-mapper/odm-user-mapper.ts b/src/user/infraestructure/mapper/odm-mapper/odm-user-mapper.ts new file mode 100644 index 00000000..cda8334d --- /dev/null +++ b/src/user/infraestructure/mapper/odm-mapper/odm-user-mapper.ts @@ -0,0 +1,73 @@ +import { IMapper } from "src/common/application/mappers/mapper.interface" +import { User } from "src/user/domain/aggregate/user.aggregate" +import { UserId } from "src/user/domain/value-object/user-id" +import { UserImage } from "src/user/domain/value-object/user-image" +import { UserName } from "src/user/domain/value-object/user-name" +import { UserPhone } from "src/user/domain/value-object/user-phone" +import { UserRole } from "src/user/domain/value-object/user-role" +import { UserRoles } from "src/user/domain/value-object/enum/user.roles" +import { IIdGen } from "src/common/application/id-gen/id-gen.interface" +import { IQueryUserRepository } from 'src/user/application/repository/user.query.repository.interface'; +import { Wallet } from 'src/user/domain/entities/wallet/wallet.entity'; +import { WalletId } from 'src/user/domain/entities/wallet/value-objects/wallet-id'; +import { Ballance } from 'src/user/domain/entities/wallet/value-objects/balance'; +import { OrmWalletEntity } from '../../entities/orm-entities/orm-wallet-entity'; +import { UserDirection } from 'src/user/domain/entities/directions/direction.entity'; +import { DirectionId } from 'src/user/domain/entities/directions/value-objects/direction-id';import { DirectionFavorite } from 'src/user/domain/entities/directions/value-objects/direction-favorite'; +import { DirectionLat } from 'src/user/domain/entities/directions/value-objects/direction-lat'; +import { DirectionLng } from 'src/user/domain/entities/directions/value-objects/direction-lng'; +import { DirectionName } from 'src/user/domain/entities/directions/value-objects/direction-name'; +import { UserCoupon } from "src/user/domain/entities/coupon/user-coupon.entity" +import { CuponId } from "src/cupon/domain/value-object/cupon-id" +import { CuponState } from "src/user/domain/entities/coupon/value-objects/cupon-state" +import { OrmCuponEntity } from "src/cupon/infraestructure/entities/orm-entities/orm-cupon-entity" +import { OrmCuponUserEntity } from "../../entities/orm-entities/orm-coupon-user-entity" +import { OdmUserEntity } from "../../entities/odm-entities/odm-user-entity" + + +export class OdmUserMapper implements IMapper { + + constructor(){} + + async fromDomaintoPersistence(domainEntity: User): Promise { + throw new Error('') + } + async fromPersistencetoDomain(infraEstructure: OdmUserEntity): Promise { + + + let user=User.initializeAggregate( + UserId.create(infraEstructure.id), + UserName.create(infraEstructure.name), + UserPhone.create(infraEstructure.phone), + UserRole.create(infraEstructure.type), + infraEstructure.direction + ? infraEstructure.direction.map(odmdirection=> + UserDirection.create( + DirectionId.create(odmdirection.id), + DirectionFavorite.create(odmdirection.favorite), + DirectionLat.create(odmdirection.lat), + DirectionLng.create(odmdirection.lng), + DirectionName.create(odmdirection.name) + )) + : [], + Wallet.create( + WalletId.create(infraEstructure.wallet.id), + Ballance.create( + infraEstructure.wallet.id + ? Number(Number(infraEstructure.wallet.amount).toFixed(2)) + : 0 + , infraEstructure.wallet.currency, + ) + ), + infraEstructure.coupon + ? infraEstructure.coupon.map(c=> + UserCoupon.create( + CuponId.create(c.id), + CuponState.create(c.state) + )) + : [], + infraEstructure.image ? UserImage.create(infraEstructure.image) : undefined + ) + return user + } +} \ No newline at end of file diff --git a/src/user/infraestructure/model-entity/odm-model-entity/odm-user-interface.ts b/src/user/infraestructure/model-entity/odm-model-entity/odm-user-interface.ts new file mode 100644 index 00000000..07a0b328 --- /dev/null +++ b/src/user/infraestructure/model-entity/odm-model-entity/odm-user-interface.ts @@ -0,0 +1,21 @@ +import { UserRoles } from "src/user/domain/value-object/enum/user.roles" + +export interface IOdmUser{ + id:string, + name:string, + phone:string, + image:string + type: UserRoles + direction:{ + id: string, + favorite:boolean, + lat:number, + lng: number + name:string + }[] + wallet:{ + id:string, + currency:string, + amount:number + } +} \ No newline at end of file diff --git a/src/user/infraestructure/queues/user.queues.ts b/src/user/infraestructure/queues/user.queues.ts index 17038fe3..9e75a2d3 100644 --- a/src/user/infraestructure/queues/user.queues.ts +++ b/src/user/infraestructure/queues/user.queues.ts @@ -1,3 +1,13 @@ export const UserQueues = [ { name: 'ApplyCoupon/OrderRegistered', pattern: 'OrderRegistered' }, -] \ No newline at end of file + { name: 'UserSync/UserBalanceAmountAdded', pattern: 'UserBalanceAmountAdded' }, + { name: 'UserSync/UserBalanceAmountDecremented', pattern: 'UserBalanceAmountDecremented' }, + { name: 'UserSync/UserCouponAplied', pattern: 'UserCouponAplied' }, + { name: 'UserSync/UserDirectionAdded', pattern: 'UserDirectionAdded' }, + { name: 'UserSync/UserDirectionDeleted', pattern: 'UserDirectionDeleted' }, + { name: 'UserSync/UserDirectionUpdated', pattern: 'UserDirectionUpdated' }, + { name: 'UserSync/UserImageUpdated', pattern: 'UserImageUpdated' }, + { name: 'UserSync/UserNameUpdated', pattern: 'UserNameUpdated' }, + { name: 'UserSync/UserPhoneUpdated', pattern: 'UserPhoneUpdated' }, + { name: 'UserSync/UserRegistered', pattern: 'UserRegistered' }, +] diff --git a/src/user/infraestructure/repositories/odm-repository/odm-transaction-query-repository.ts b/src/user/infraestructure/repositories/odm-repository/odm-transaction-query-repository.ts new file mode 100644 index 00000000..69190ee5 --- /dev/null +++ b/src/user/infraestructure/repositories/odm-repository/odm-transaction-query-repository.ts @@ -0,0 +1,15 @@ +import { Result } from "src/common/utils/result-handler/result" +import { ITransaction } from "src/user/application/model/transaction-interface" +import { IQueryTransactionRepository } from "src/user/application/repository/wallet-transaction/transaction-query-repository.interface" + + +export class OdmTransactionQueryRepository implements IQueryTransactionRepository{ + + getAllTransactionsByWalletId(walletId: string, page: number, perPage: number): Promise> { + throw new Error("Method not implemented.") + } + getTransactionById(id: string): Promise> { + throw new Error("Method not implemented.") + } + +} \ No newline at end of file diff --git a/src/user/infraestructure/repositories/odm-repository/odm-user-query-repository.ts b/src/user/infraestructure/repositories/odm-repository/odm-user-query-repository.ts new file mode 100644 index 00000000..020b89a5 --- /dev/null +++ b/src/user/infraestructure/repositories/odm-repository/odm-user-query-repository.ts @@ -0,0 +1,99 @@ +import { Result } from "src/common/utils/result-handler/result"; +import { IDirection } from "src/user/application/model/direction-interface"; +import { IUserDirection } from "src/user/application/model/user.direction.interface"; +import { IQueryUserRepository } from "src/user/application/repository/user.query.repository.interface"; +import { User } from "src/user/domain/aggregate/user.aggregate"; +import { UserDirection } from "src/user/domain/entities/directions/direction.entity"; +import { DirectionId } from "src/user/domain/entities/directions/value-objects/direction-id"; +import { UserId } from "src/user/domain/value-object/user-id"; +import { UserPhone } from "src/user/domain/value-object/user-phone"; +import { OdmUserEntity, OdmUserSchema } from "../../entities/odm-entities/odm-user-entity"; +import { OdmUserMapper } from "../../mapper/odm-mapper/odm-user-mapper"; +import { Model, Mongoose } from "mongoose"; +import { OdmPromotionEntity, OdmPromotionSchema } from "src/promotion/infraestructure/entities/odm-entities/odm-promotion-entity"; +import { NotFoundException } from "src/common/infraestructure/infraestructure-exception"; + + +export class OdmUserQueryRepository implements IQueryUserRepository{ + + private readonly model: Model; + private readonly odmMapper: OdmUserMapper + + constructor( mongoose: Mongoose ) { + this.model = mongoose.model('odmuser', OdmUserSchema) + this.odmMapper= new OdmUserMapper() + } + + async findUserById(id: UserId): Promise> { + try{ + let odm=await this.model.findOne({id:id.Value}) + + if(!odm) + return Result.fail( new NotFoundException('Find User unsucssessfully')) + + return Result.success(await this.odmMapper.fromPersistencetoDomain(odm)) + } + catch(e){ + return Result.fail( new NotFoundException('Find User unsucssessfully')) + } + } + async findUserByPhoneNumber(phoneNumber: UserPhone): Promise> { + try{ + let odm=await this.model.findOne({phone:phoneNumber.Value}) + + if(!odm) + return Result.fail( new NotFoundException('Find User unsucssessfully')) + + return Result.success(await this.odmMapper.fromPersistencetoDomain(odm)) + } + catch(e){ + return Result.fail( new NotFoundException('Find User unsucssessfully')) + } + } + async verifyUserExistenceByPhoneNumber(phoneNumber: UserPhone): Promise> { + try{ + let odm=await this.model.findOne({phone:phoneNumber.Value}) + if(!odm) + return Result.success(false) + return Result.success(true) + } + catch(e){ + return Result.fail( new NotFoundException('Find User unsucssessfully')) + } + } + async findUserDirectionsByUserId(id: UserId): Promise> { + try{ + let odm=await this.model.findOne({id:id.Value}) + if(!odm) + return Result.fail( new NotFoundException('Find User unsucssessfully')) + let domain=await this.odmMapper.fromPersistencetoDomain(odm) + return Result.success(domain.UserDirections.map(d=>({ + id:d.getId().Value, + name: d.DirectionName.Value, + isFavorite: d.DirectionFavorite.Value, + lat: Number(d.DirectionLat.Value), + lng: Number(d.DirectionLng.Value) + }))) + } + catch(e){ + return Result.fail( new NotFoundException('Find User unsucssessfully')) + } + } + findDirectionsByLatAndLng(userDirection: UserDirection[]): Promise> { + throw new Error("Method not implemented."); + } + async findDirectionById(id: DirectionId, userId: UserId): Promise> { + try{ + let odm=await this.model.findOne({id:userId.Value, + "direction.id": id.Value + }) + if(!odm) + return Result.fail( new NotFoundException('Find User unsucssessfully')) + let domain=await this.odmMapper.fromPersistencetoDomain(odm) + } + catch(e){ + return Result.fail( new NotFoundException('Find User unsucssessfully')) + } + } + +} \ No newline at end of file diff --git a/src/user/infraestructure/services/dto/request/user-registered-infraestructure-request-dto.ts b/src/user/infraestructure/services/dto/request/user-registered-infraestructure-request-dto.ts new file mode 100644 index 00000000..00796436 --- /dev/null +++ b/src/user/infraestructure/services/dto/request/user-registered-infraestructure-request-dto.ts @@ -0,0 +1,18 @@ +export interface UserRegistredInfraestructureRequestDTO { + userId: string; + userName: string; + userPhone: string; + wallet: { + walletId: string; + ballance: { + currency: string; + amount: number; + }; + }; + coupons: { + id: string; + state: string; + }[]; + userImage: string; + userRole: string +} \ No newline at end of file diff --git a/src/user/infraestructure/services/dto/request/user-updated-infraestructure-request-dto.ts b/src/user/infraestructure/services/dto/request/user-updated-infraestructure-request-dto.ts new file mode 100644 index 00000000..bb8fffdd --- /dev/null +++ b/src/user/infraestructure/services/dto/request/user-updated-infraestructure-request-dto.ts @@ -0,0 +1,29 @@ +export interface UserUpdatedInfraestructureRequestDTO { + userId: string; + userName?: string; + userPhone?: string; + wallet?: { + walletId: string; + ballance: { + currency: string; + amount: number; + }; + }; + coupons?: { + id: string; + state: string; + }[]; + userImage?: string; + + userDirection?: { + id: string; + name: string; + favorite: boolean; + lat: number; + lng: number; + } + + userDirectionDelete?:{ + id:string + } +} \ No newline at end of file diff --git a/src/user/infraestructure/services/syncronice/user-registered-syncronice.service.ts b/src/user/infraestructure/services/syncronice/user-registered-syncronice.service.ts new file mode 100644 index 00000000..c41e4e1f --- /dev/null +++ b/src/user/infraestructure/services/syncronice/user-registered-syncronice.service.ts @@ -0,0 +1,37 @@ +import { Result } from 'src/common/utils/result-handler/result'; +import { ISycnchronizeService } from 'src/common/infraestructure/synchronize-service/synchronize.service.interface'; +import { Model, Mongoose } from 'mongoose'; +import { OdmUserEntity, OdmUserSchema } from '../../entities/odm-entities/odm-user-entity'; +import { UserRegistredInfraestructureRequestDTO } from '../dto/request/user-registered-infraestructure-request-dto'; +import { UserRoles } from 'src/user/domain/value-object/enum/user.roles'; + +export class UserRegisteredSyncroniceService +implements ISycnchronizeService{ + + private readonly model: Model + + + constructor( mongoose: Mongoose ) { + this.model = mongoose.model('odmuser', OdmUserSchema) + } + + async execute(event: UserRegistredInfraestructureRequestDTO): Promise> { + + const user = new this.model({ + id:event.userId, + name:event.userName, + phone:event.userPhone, + image:event.userImage, + type:event.userRole as UserRoles, + direction:[], + wallet:{ + id:event.wallet.walletId, + currency:event.wallet.ballance.currency, + amount: event.wallet.ballance.amount + }, + coupon:[] + }) + await this.model.create(user) + return Result.success(undefined) + } +} \ No newline at end of file diff --git a/src/user/infraestructure/services/syncronice/user-updated-syncronice.service.ts b/src/user/infraestructure/services/syncronice/user-updated-syncronice.service.ts new file mode 100644 index 00000000..5545a0c1 --- /dev/null +++ b/src/user/infraestructure/services/syncronice/user-updated-syncronice.service.ts @@ -0,0 +1,69 @@ +import { Result } from 'src/common/utils/result-handler/result'; +import { ISycnchronizeService } from 'src/common/infraestructure/synchronize-service/synchronize.service.interface'; +import { Model, Mongoose } from 'mongoose'; +import { OdmUserEntity, OdmUserSchema } from '../../entities/odm-entities/odm-user-entity'; +import { UserUpdatedInfraestructureRequestDTO } from '../dto/request/user-updated-infraestructure-request-dto'; + +export class UserUpdatedSyncroniceService +implements ISycnchronizeService{ + + private readonly model: Model + + + constructor( mongoose: Mongoose ) { + this.model = mongoose.model('odmuser', OdmUserSchema) + } + + async execute(event: UserUpdatedInfraestructureRequestDTO): Promise> { + + let user= await this.model.findOne({id:event.userId}) + + console.log(event) + + if(event.userImage) + await this.model.updateOne({ id: event.userId }, {$set: {image: event.userImage}}) + + if(event.userName) + await this.model.updateOne({ id: event.userId }, {$set: {name: event.userName}}) + + if(event.userPhone) + await this.model.updateOne({ id: event.userId }, {$set: {phone: event.userPhone}}) + + if(event.wallet) + await this.model.updateOne({ id: event.userId }, {$set: {wallet: { + id:event.wallet.walletId, + currency:event.wallet.ballance.currency, + amount:event.wallet.ballance.amount + }}}) + + if (event.coupons) { + for (const newCoupon of event.coupons) { + let coupon = user.coupon.find(c => c.id === newCoupon.id); + if (!coupon) { + user.coupon.push(newCoupon) + } else { + user.coupon = user.coupon.filter(c => c.id !== newCoupon.id) + user.coupon.unshift(newCoupon) + } + } + await user.save() + } + if (event.userDirectionDelete){ + user.direction.filter(d=>d.id!==event.userDirectionDelete.id) + await user.save() + } + + if (event.userDirection){ + let direction = user.direction.find(d=>d.id==event.userDirection.id); + if (!direction) { + user.direction.push(event.userDirection) + } else { + user.direction = user.direction.filter(d => d.id !== event.userDirection.id) + user.direction.unshift(direction) + } + await user.save() + } + + return Result.success(undefined) + } +} \ No newline at end of file