te dare contexto tengo la siguiente clase "import {… · The Chat Archive
Explore / Programming te dare contexto tengo la siguiente clase "import { Location } from '@angular/common';… Save Share Download ▾ Reportte dare contexto tengo la siguiente clase "import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatCheckboxChange } from '@angular/material/checkbox';
import { ActivatedRoute, Router } from '@angular/router';
import { finalize } from 'rxjs/operators';
import { VehicleType } from 'src/app/models/catalog.models';
import { CompaniesService } from 'src/app/services/companies/companies.service';
import { HeaderService } from 'src/app/services/header/header.service';
import { NotificationsService } from 'src/app/services/notifications/notifications.service';
import { VehicleService } from 'src/app/services/vehicle/vehicle.service';
@Component({
selector: 'impulsa-edit-services-aditionals',
templateUrl: './edit-services-aditionals.component.html',
styleUrls: ['./edit-services-aditionals.component.scss']
})
export class EditServicesAditionalsComponent implements OnInit {
loading: Boolean = false;
contractId : string = '';
formServices = this.formBuilder.group({});
respVehicles : any[]=[];
listVehiclesTypesServices: any = {};
listBrand: any[] = [];
listModel: any[] = [];
listModelServices: any[] = [];
listaditionalsService: any = {Moto: [], Patineta:[], Bicicleta:[], Carro:[]};
listInfoResumen: any[] = [];
total: number = 0;
totalAux: number = 0;
listVehicleTypes: any[] = [];
listServices = {
basic: { services: [] },
check: { services: [] },
};
constructor(private companiesService: CompaniesService,
private vehiclesService: VehicleService,
private activateRoute: ActivatedRoute,
private formBuilder: FormBuilder,
private location: Location,
private notification: NotificationsService,
private headerService: HeaderService
) {
this.contractId = this.activateRoute.snapshot.params.contractId;
this.getServicesAditionalsInfo();
this.getContractServices();
}
ngOnInit(): void {
this.headerService.updateSubtitle(Empresas / Detalle / Anexo ${this.contractId});
}
getContractServices(){
this.loading = true;
this.companiesService.getServicesAdittionalsByContract(this.contractId)
.pipe(finalize( () => this.loading = false))
.subscribe((res)=>{
console.log('servicios aditcionales', res);
this.respVehicles = res.data;
this.fillServicesForm();
});
}
public valueControlServicesForm(nameForm: string, contrl: string): any {
return this.formServices.get(${nameForm}.${contrl}).value;
}
getVehiclesServicesForm(nameFormGroup: string): FormArray {
return this.formServices.get(${nameFormGroup}.vehicles) as FormArray;
}
getnameBrand(vehicleType: number, id: number): string {
let brand: any;
brand = this.listBrand[vehicleType].find(
(item: { name: string; brand: number }) => {
return item.brand === id;
}
);
return brand.name;
}
getNameModel(vehicleType: number, id: number): string {
let model: any;
model = this.listModelServices[vehicleType].find((item) => {
return item.id === id;
});
return model.reference;
}
changeServicesTelemetry(
event: MatCheckboxChange,
value: number,
id: number,
index: number,
type: string
): void {
console.log(value, index, type);
Assistant2024-11-05 15:38 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Nov 5, 2024
Added to archive Nov 16, 2026
ID 01m7h424gzwkmwtxz8v98ctag3Source & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 4b46540ba03023ab1844626e28c587e7
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
const formArray = this.getVehiclesServicesForm(type);
const formGroup = formArray.at(index) as FormGroup;
if (event.checked) {
if (formGroup) {
if (!formGroup.contains('price')) {
formGroup.addControl('price', this.formBuilder.control('', Validators.required));
}
} else {
console.error(No se encontró el FormGroup en el índice ${index});
}
}else{
if (formGroup.contains('price')) {
formGroup.removeControl('price');
}
this.listaditionalsService[type][index][value] = [];
this.sumAditionals();
}
console.log(this.formServices.value);
sumAditionals(){
this.total = this.totalAux;
console.log(this.total, 'total');
this.listInfoResumen[1].items[0].subdesc = [];
this.listInfoResumen[1].items[1].subdesc = [];
Object.keys(this.listaditionalsService).forEach((key) => {
this.listaditionalsService[key].forEach((value) => {
value.forEach((value2, i ) => {
console.log(JSON.stringify(value2)+ "index "+i);
if (i== 0 && value2 != '') {
this.listInfoResumen[1].items[0].subdesc.push({subtitle : value2.desc, value: value2.value});
this.total += value2.value > 0 ? +value2.value : 0;
}else{
this.listInfoResumen[1].items[1].subdesc.push({subtitle : value2.desc, value: value2.value});
this.total += value2.value > 0 ? +value2.value : 0;
}
});
});
});
bort(index, indexType,type){
const formArray = this.getVehiclesServicesForm(type);
const formGroup = formArray.at(index) as FormGroup;
if (!this.listaditionalsService[type]) {
this.listaditionalsService[type] = [];
}
if (!this.listaditionalsService[type][index]) {
this.listaditionalsService[type][index] = [];
}
if (!this.listaditionalsService[type][index][indexType]) {
this.listaditionalsService[type][index][indexType] = { value: 0, desc: '' };
}
const price = formGroup.get('price').value;
const quantity = this.getVehiclesServicesForm(type).value[index].quanty;
this.listaditionalsService[type][index][indexType] = {desc : `$ ${price} x ${quantity}`, value: price * quantity};
this.sumAditionals();
public goBack(): void {
this.location.back();
}
resetForm1() {
this.goBack();
}
editContract(){
const result = [];
Object.keys(this.formServices.value).forEach(groupname => {
const group = this.formServices.get(groupname);
this.getVehiclesServicesForm(groupname).value.forEach((vehicle) => {
const vehicleData = {
id: vehicle.id,
contractId: this.contractId,
vehicleTypeId: group.get('id').value,
vehicleTypeName: groupname,
vehicleBrandName: vehicle.brand,
vehicleModelName: vehicle.model,
cityName: vehicle.city,
listServiceAdditional: []
};
console.log(vehicle.telemetryBasic);
let service = this.respVehicles.find(x => x.id === vehicle.id).listServiceAdditional;
if (vehicle.telemetryBasic !== undefined) {
let action = this.determineAction(vehicle.id, 'Telemetría básica', vehicle.telemetryBasic, vehicle.price);
console.log(action);
if (action) {
console.log(action);
vehicleData.listServiceAdditional.push({
id: action === 'EDIT' || action === 'DELETED' ? service[0].id : null,
serviceId: action === 'EDIT' || action === 'DELETED' ? service[0].serviceId : this.getServiceIdOfVehicleType(vehicle.vehicleTypeId, 0),
name: 'Telemetría básica',
quantity: vehicle.quanty,
price: vehicle.price || 0,
action: action
});
console.log(vehicleData);
}
}
if (vehicle.telemetryPreo !== undefined) {
let action = this.determineAction(vehicle.id, 'Telemetría + Chequeo preoperacional', vehicle.telemetryPreo, vehicle.price );
if (action) {
vehicleData.listServiceAdditional.push({
id: action === 'EDIT' || action === 'DELETED' ? service[0].id : null,
serviceId: action === 'EDIT' || action === 'DELETED' ? service[0].serviceId : this.getServiceIdOfVehicleType(vehicle.vehicleTypeId, 1),
name:'Telemetría + Chequeo preoperacional',
quantity:vehicle.quanty,
price: vehicle.price || 0,
action:action
})
}
}
if (vehicleData.listServiceAdditional.length === 0) {
vehicleData.listServiceAdditional = (service) || [];
}
result.push(vehicleData);
});
});
console.log(result);
this.sendDatatoEdit(result);
}
fillServicesForm(){
this.respVehicles.forEach(element => {
if(!this.listVehiclesTypesServices[element.vehicleTypeName]){
this.listVehiclesTypesServices[element.vehicleTypeName] = {
name: element.vehicleTypeName,
id: element.vehicleTypeId
};
}
if (!this.listVehiclesTypesServices[element.vehicleTypeName].vehicles) {
this.listVehiclesTypesServices[element.vehicleTypeName].vehicles = [];
}
this.listVehiclesTypesServices[element.vehicleTypeName].vehicles.push({
brand: element.vehicleBrandName,
model: element.vehicleModelName,
price: element.valuePlan,
quanty: element.quantity,
listServiceAdditional: element.listServiceAdditional,
city: element.cityName,
id:element.id,
vehicleTypeId: element.vehicleTypeId
} ) ;
});
console.log(this.listVehiclesTypesServices);
console.log(this.listVehicleTypes);
Object.keys(this.listVehiclesTypesServices).forEach((type) => {
console.log(type);
this.listVehicleTypes.push(this.listVehiclesTypesServices[type]);
this.formServices.addControl(
type,
this.formBuilder.group({
id: [this.listVehiclesTypesServices[type].id],
active: [this.hasAdditionalServices(this.listVehiclesTypesServices[type].vehicles)],
vehicles: this.formBuilder.array([])
})
);
});
console.log(this.formServices.value);
this.formServices.updateValueAndValidity();
this.fillInfoVehiclesToEdit();
}
fillInfoVehiclesToEdit(){
this.total = 0;
this.listInfoResumen.push({ name: 'Vehiculos', items: [] });
this.listInfoResumen.push({
name: 'Servicios adicionales',
items: [
{ name: 'Telemetría básica', value: 0 },
{ name: 'Telemetría + Chequeo preoperacional', value: 0},
],
});
Object.keys(this.listVehiclesTypesServices).forEach((type) => {
if (this.listVehiclesTypesServices[type].vehicles.length > 0) {
this.listVehiclesTypesServices[type].vehicles.forEach((vehicle, index) => {
const value = vehicle.price * vehicle.quanty;
this.total += value;
this.listInfoResumen[0].items.push({
name: ${vehicle.brand} ${vehicle.model},
desc: `$ ${vehicle.price} x ${vehicle.quanty}`,
value: value,
});
this.addVehiclesServices(type, vehicle, index);
} ) ;
}
} );
this.totalAux = this.total;
this.sumAditionals();
console.log(this.formServices.value, this.total);
addVehiclesServices(nameFormGroup: string, vehicle: any, index:number) {
let telemetryBasic = false;
let checkPreOperacional = false;
if (vehicle.listServiceAdditional.length > 0) {
telemetryBasic = vehicle.listServiceAdditional.some(service => service.name === 'Telemetría básica');
checkPreOperacional = vehicle.listServiceAdditional.some(service => service.name === 'Telemetría + Chequeo preoperacional');
}
const newformVehicle = this.formBuilder.group({
id:vehicle.id,
vehicleTypeId: vehicle.vehicleTypeId,
quanty: vehicle.quanty,
brand: vehicle.brand,
model: vehicle.model,
city: vehicle.city,
telemetryBasic: telemetryBasic,
telemetryPreo: checkPreOperacional,
});
if (telemetryBasic || checkPreOperacional) {
newformVehicle.addControl('price', this.formBuilder.control(vehicle.listServiceAdditional[0].price, Validators.required));
if (!this.listaditionalsService[nameFormGroup]) {
this.listaditionalsService[nameFormGroup] = [];
}
if (!this.listaditionalsService[nameFormGroup][index]) {
this.listaditionalsService[nameFormGroup][index] = [];
}
if (!this.listaditionalsService[nameFormGroup][index][telemetryBasic ? 0 :1]) {
this.listaditionalsService[nameFormGroup][index][telemetryBasic ? 0 :1] = { value: 0, desc: '' };
}
this.listaditionalsService[nameFormGroup][index][telemetryBasic ? 0 :1] = { value: vehicle.quanty * vehicle.price, desc: `$ ${vehicle.price} x ${vehicle.quanty}` };
console.log(this.listaditionalsService);
}
this.getVehiclesServicesForm(nameFormGroup).push(newformVehicle);
hasAdditionalServices(vehicles) {
return vehicles.some(vehicle =>
vehicle.listServiceAdditional && vehicle.listServiceAdditional.length > 0
);
}
determineAction(vehicleId: number, serviceName: string, isChecked: boolean, price: number) {
const originalData = this.respVehicles;
const vehicleOriginal = originalData.find(v => v.id === vehicleId);
const serviceOriginal = vehicleOriginal?.listServiceAdditional.find(s => s.name === serviceName);
if (!serviceOriginal && isChecked) {
return 'NEW';
}
if (serviceOriginal && !isChecked) {
return 'DELETED';
}
if (serviceOriginal && (serviceOriginal.price !== price)) {
return 'EDIT';
}
if (serviceOriginal && (serviceOriginal.name != serviceName)) {
return 'EDIT';
}
return null;
getServicesAditionalsInfo() {
this.loading = true;
this.vehiclesService
.getServicesKeyService('SERVICE_ADDITIONAL_FO')
.pipe(finalize(() => (this.loading = false)))
.subscribe({
next: (res) => {
this.listServices.basic.services = res.data.slice(0, 4);
this.listServices.check.services = res.data.slice(4, 8);
},
});
}
getServiceIdOfVehicleType(vehicleType, serviceType) {
console.log(vehicleType, serviceType, this.listServices);
return this.listServices[serviceType == 0 ? 'basic' : 'check'].services[vehicleType-1].id;
sendDatatoEdit(data:any){
this.companiesService.editServicesAdittionalsToContract(data).subscribe({
next:(res)=>{
this.notification.showSuccessMessage('Servicios actualizados correctamente');
this.location.back();
},
error:(err)=>{
this.notification.showErrorMessage(err.error.message);
console.log(err);
this.location.back();
}
}
" y tengo su clase de test unitarios "import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
import { MatCheckboxChange } from '@angular/material/checkbox';
import { CommonModule, Location } from '@angular/common';
import { of, throwError } from 'rxjs';
import { CompaniesService } from 'src/app/services/companies/companies.service';
import { VehicleService } from 'src/app/services/vehicle/vehicle.service';
import { ActivatedRoute } from '@angular/router';
import { EditServicesAditionalsComponent } from './edit-services-aditionals.component';
import { SharedModule } from 'src/app/shared/shared.module';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HeaderService } from 'src/app/services/header/header.service';
import { NotificationsService } from 'src/app/services/notifications/notifications.service';
describe('EditServicesAditionalsComponent', () => {
let component: EditServicesAditionalsComponent;
let fixture: ComponentFixture;
let companiesService: CompaniesService;
let headerService: HeaderService;
let vehicleService: VehicleService;
let notificationService: NotificationsService;
let location: Location;
let activatedRouteSpy: any;
let formBuilder: FormBuilder;
class MockHeaderService {
updateSubtitle(){
class MockCompaniesService {
getServicesAdittionalsByContract() {
return of({
message: "Consulta realizada con éxito.",
data: [
{
"id": 122,
"contractId": 98,
"vehicleTypeId": 1,
"vehicleTypeName": "Moto",
"vehicleModelName": "N GT",
"vehicleBrandName": "Niu",
"cityName": "MEDELLÍN",
"valuePlan": 60000.0,
"quantity": 1,
"listServiceAdditional": [
{
"id": 5,
"serviceId": 561,
"name": "Telemetría básica",
"quantity": 1,
"price": 70000.0,
"action": "NO_ACTION"
}
]
},
{
"id": 123,
"contractId": 98,
"vehicleTypeId": 1,
"vehicleTypeName": "Moto",
"vehicleModelName": "N GT",
"vehicleBrandName": "Niu",
"cityName": "MEDELLÍN",
"valuePlan": 90000.0,
"quantity": 1,
"listServiceAdditional": []
}
]
});
}
editServicesAdittionalsToContract(){
return of({});
}
}
class MockVehiclesSerivce {
getServicesKeyService(){
return of({
message: "Proceso realizado correctamente",
data: [
{
"id": 561,
"name": "Telemetría básica",
"vehicleTypeId": 1,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría básica",
"extraInfo": "",
"price": 70000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
},
{
"id": 562,
"name": "Telemetría básica",
"vehicleTypeId": 2,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría básica",
"extraInfo": "",
"price": 70000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
},
{
"id": 563,
"name": "Telemetría básica",
"vehicleTypeId": 3,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría básica",
"extraInfo": "",
"price": 70000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
},
{
"id": 564,
"name": "Telemetría básica",
"vehicleTypeId": 4,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría básica",
"extraInfo": "",
"price": 70000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
},
{
"id": 565,
"name": "Telemetría + Chequeo preoperacional",
"vehicleTypeId": 1,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría + Chequeo preoperacional",
"extraInfo": "",
"price": 78000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
},
{
"id": 566,
"name": "Telemetría + Chequeo preoperacional",
"vehicleTypeId": 2,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría + Chequeo preoperacional",
"extraInfo": "",
"price": 78000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
},
{
"id": 567,
"name": "Telemetría + Chequeo preoperacional",
"vehicleTypeId": 3,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría + Chequeo preoperacional",
"extraInfo": "",
"price": 78000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
},
{
"id": 568,
"name": "Telemetría + Chequeo preoperacional",
"vehicleTypeId": 4,
"keyService": "SERVICE_ADDITIONAL_FO",
"description": "Telemetría + Chequeo preoperacional",
"extraInfo": "",
"price": 78000.0,
"accessory": "N",
"customized": "Y",
"status": "ACTIVE",
"listServiceImages": [],
"listServiceAttributes": []
}
]
}
beforeEach(async () => {
activatedRouteSpy = {
snapshot: {
params: { contractId: '12345' }
}
};
await TestBed.configureTestingModule({
declarations: [EditServicesAditionalsComponent],
imports:[SharedModule,
CommonModule,
HttpClientTestingModule,
BrowserAnimationsModule
] ,
providers: [
FormBuilder,
{ provide: CompaniesService, useClass: MockCompaniesService },
{ provide: VehicleService, useClass: MockVehiclesSerivce },
{ provide: HeaderService, useClass: MockHeaderService},
{ provide: Location, useValue: {back : jasmine.createSpy('back')} },
{ provide: ActivatedRoute, useValue: activatedRouteSpy },
{ provide: FormBuilder },
{ provide: NotificationsService },
]
}).compileComponents();
beforeEach(() => {
fixture = TestBed.createComponent(EditServicesAditionalsComponent);
component = fixture.componentInstance;
companiesService = TestBed.inject(CompaniesService);
vehicleService = TestBed.inject(VehicleService);
location = TestBed.inject(Location) as jasmine.SpyObj;
formBuilder = TestBed.inject(FormBuilder);
headerService = TestBed.inject(HeaderService);
notificationService = TestBed.inject(NotificationsService);
fixture.detectChanges();
})
it('should create', () => {
expect(component).toBeTruthy();
});
it('should load contract services and fill the form correctly', () => {
component.getContractServices();
expect(component.loading).toBe(false);
expect(component.formServices.get('Carro')).toBeNull();
it('should go back on resetForm1', () => {
component.resetForm1();
expect(location.back).toHaveBeenCalled();
});
it('should handle checkbox change and update form correctly', () => {
component.listServices = {
basic: {
services: [
{ price: 10 },
{ price: 20 },
],
},
check: {
services: [
{ price: 30 },
{ price: 40 },
],
},
};
component.listInfoResumen = [];
component.listInfoResumen.push({ name: 'Vehiculos', items: [] });
component.listInfoResumen.push({
name: 'Servicios adicionales',
items: [
{ name: 'Telemetría básica', value: 0, subdesc: [] },
{ name: 'Telemetría + Chequeo preoperacional', value: 0, subdesc: [] },
],
});
component.listaditionalsService = {
Carro: [
[
{ desc: 'Adicional 1', value: 100 },
{ desc: 'Adicional 2', value: 200 },
],
[
{ desc: 'Adicional 3', value: 300 },
],
],
Moto: [
[
{ desc: 'Adicional 4', value: 400 },
],
],
};
const event = { checked: true } as MatCheckboxChange;
const type = 'Carro';
const index = 0;
const id = 1;
const value = 0;
const mockForm = { value: [{ quanty: 2 }] };
component.formServices = new FormBuilder().group({});
component.formServices.addControl(
type,
formBuilder.group({
id: [1],
active: [true],
vehicles: formBuilder.array([
formBuilder.group({
price: [null],
quanty: [2],
}),
]),
})
);
component.changeServicesTelemetry(event, value, id, index, type);
expect(component.listInfoResumen[1].items[0].value).toBe(0);
expect(component.listInfoResumen[1].items[0].value).toBe(0);
event.checked = false;
component.changeServicesTelemetry(event, value, id, index, type);
expect(component.listInfoResumen[1].items[0].value).toBe(0);
it('should sum additionals correctly', () => {
component.totalAux = 100;
component.listaditionalsService = {
Carro: [
[
{ value: 50, desc: 'desc1' },
{ value: 30, desc: 'desc2' },
],
],
};
component.sumAditionals();
expect(component.total).toBe(180);
it('should determine action new', () => {
component.respVehicles = [
{
"id": 124,
"contractId": 99,
"vehicleTypeId": 2,
"vehicleTypeName": "Bicicleta",
"vehicleModelName": "Kuo plus",
"vehicleBrandName": "A2B",
"cityName": "CALI",
"valuePlan": 15000.0,
"quantity": 1,
"listServiceAdditional": []
}
];
const vehicleId = 124;
const serviceName = 'Servicio 1';
const price = 3000;
const action = component.determineAction(vehicleId, serviceName,true, price);
expect(action).toBe('NEW');
it('should determine action deleted', () => {
component.respVehicles = [
{
"id": 122,
"contractId": 98,
"vehicleTypeId": 1,
"vehicleTypeName": "Moto",
"vehicleModelName": "N GT",
"vehicleBrandName": "Niu",
"cityName": "MEDELLÍN",
"valuePlan": 60000.0,
"quantity": 1,
"listServiceAdditional": []
},
{
"id": 123,
"contractId": 98,
"vehicleTypeId": 1,
"vehicleTypeName": "Moto",
"vehicleModelName": "N GT",
"vehicleBrandName": "Niu",
"cityName": "MEDELLÍN",
"valuePlan": 90000.0,
"quantity": 1,
"listServiceAdditional": [
{
"id": 22,
"serviceId": 561,
"name": "Telemetría básica",
"quantity": 1,
"price": 85000.0,
"action": "NO_ACTION"
}
]
}
];
const vehicleId = 123;
const serviceName = 'Telemetría básica';
const price = 3000;
const action = component.determineAction(vehicleId, serviceName,false, price);
expect(action).toBe('DELETED');
it('should determine action EDIT', () => {
component.respVehicles = [
{
"id": 122,
"contractId": 98,
"vehicleTypeId": 1,
"vehicleTypeName": "Moto",
"vehicleModelName": "N GT",
"vehicleBrandName": "Niu",
"cityName": "MEDELLÍN",
"valuePlan": 60000.0,
"quantity": 1,
"listServiceAdditional": []
},
{
"id": 123,
"contractId": 98,
"vehicleTypeId": 1,
"vehicleTypeName": "Moto",
"vehicleModelName": "N GT",
"vehicleBrandName": "Niu",
"cityName": "MEDELLÍN",
"valuePlan": 90000.0,
"quantity": 1,
"listServiceAdditional": [
{
"id": 22,
"serviceId": 561,
"name": "Telemetría básica",
"quantity": 1,
"price": 85000.0,
"action": "NO_ACTION"
}
]
}
];
const vehicleId = 123;
const serviceName = 'Telemetría básica';
const price = 3000;
const action = component.determineAction(vehicleId, serviceName,true, price);
expect(action).toBe('EDIT');
it('should return correct service ID for basic service', () => {
component.listServices = {
basic: {
services: [
{
id: 561,
name: 'Telemetría básica',
vehicleTypeId: 1,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 562,
name: 'Telemetría básica',
vehicleTypeId: 2,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 563,
name: 'Telemetría básica',
vehicleTypeId: 3,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 564,
name: 'Telemetría básica',
vehicleTypeId: 4,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
}
]
},
check: {
services: [
{
id: 565,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 1,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 566,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 2,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 567,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 3,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 568,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 4,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
}
]
}
}
const vehicleType = 1;
const serviceType = 0;
const result = component.getServiceIdOfVehicleType(vehicleType, serviceType);
expect(result).toBe(561);
it('should return correct service ID for check service', () => {
component.listServices = {
basic: {
services: [
{
id: 561,
name: 'Telemetría básica',
vehicleTypeId: 1,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 562,
name: 'Telemetría básica',
vehicleTypeId: 2,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 563,
name: 'Telemetría básica',
vehicleTypeId: 3,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 564,
name: 'Telemetría básica',
vehicleTypeId: 4,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría básica',
extraInfo: '',
price: 70000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
}
]
},
check: {
services: [
{
id: 565,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 1,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 566,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 2,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 567,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 3,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
},
{
id: 568,
name: 'Telemetría + Chequeo preoperacional',
vehicleTypeId: 4,
keyService: 'SERVICE_ADDITIONAL_FO',
description: 'Telemetría + Chequeo preoperacional',
extraInfo: '',
price: 78000,
accessory: 'N',
customized: 'Y',
status: 'ACTIVE',
listServiceImages: [],
listServiceAttributes: []
}
]
}
}
const vehicleType = 4;
const serviceType = 1;
const result = component.getServiceIdOfVehicleType(vehicleType, serviceType);
expect(result).toBe(568);
it('should make successful request to edit services', () => {
const data = {};
spyOn(companiesService, 'editServicesAdittionalsToContract').and.returnValue(of({}));
spyOn(notificationService, 'showSuccessMessage').and.callFake(() => {});
component.sendDatatoEdit(data);
expect(companiesService.editServicesAdittionalsToContract).toHaveBeenCalledTimes(1);
expect(notificationService.showSuccessMessage).toHaveBeenCalledTimes(1);
it('should show error message and log error on failed request', () => {
const data = {};
spyOn(companiesService, 'editServicesAdittionalsToContract').and.returnValue(throwError({ error: { message: 'Error message' } }));
spyOn(notificationService, 'showErrorMessage').and.callFake(() => {});
component.sendDatatoEdit(data);
expect(notificationService.showErrorMessage).toHaveBeenCalledTimes(1);
});
" puedes por favor basado en esta informacion generar los test para el metodo "editContract"
Claro, a continuación se presentan varios casos de prueba unitarios para el método editContract del componente EditServicesAditionalsComponent. Estos tests verifican que el método prepare correctamente los datos y llame a sendDatatoEdit con la estructura esperada bajo diferentes escenarios.
1. Configuración Inicial
Primero, asegúrate de tener todos los mocks y servicios configurados correctamente en tu configuración de pruebas. Ya tienes la mayoría de los mocks establecidos, pero también necesitaremos mockear métodos adicionales como determineAction y getServiceIdOfVehicleType.
2. Añadir Casos de Prueba para editContract
Añade los siguientes casos de prueba en tu archivo de pruebas existente:
// ... [Importaciones existentes] ...
describe('EditServicesAditionalsComponent', () => {
// ... [Configuración existente] ...
beforeEach(() => {
fixture = TestBed.createComponent(EditServicesAditionalsComponent);
component = fixture.componentInstance;
companiesService = TestBed.inject(CompaniesService);
vehicleService = TestBed.inject(VehicleService);
location = TestBed.inject(Location) as jasmine.SpyObj<Location>;
formBuilder = TestBed.inject(FormBuilder);
headerService = TestBed.inject(HeaderService);
notificationService = TestBed.inject(NotificationsService);
// Configurar los spies para determineAction y getServiceIdOfVehicleType
spyOn(component, 'determineAction').and.callFake((vehicleId, serviceName, isChecked, price) => {
if (serviceName === 'Telemetría básica') {
if (isChecked) {
return 'NEW';
} else {
return 'DELETED';
}
}
return null;
});
spyOn(component, 'getServiceIdOfVehicleType').and.callFake((vehicleType, serviceType) => {
return 999; // Retornar un ID de servicio simulado
});
// Spy on sendDatatoEdit to verify it gets called with correct data
spyOn(component, 'sendDatatoEdit').and.callThrough();
fixture.detectChanges();
});
// ... [Casos de prueba existentes] ...
describe('#editContract', () => {
it('should prepare and send correct data when editContract is called with new services', () => {
// Arrange
component.contractId = '12345';
// Configurar formServices
component.formServices = formBuilder.group({
Moto: formBuilder.group({
id: [1],
active: [true],
vehicles: formBuilder.array([
formBuilder.group({
id: [122],
vehicleTypeId: [1],
quanty: [2],
brand: ['Niu'],
model: ['N GT'],
city: ['MEDELLÍN'],
telemetryBasic: [true],
telemetryPreo: [false],
price: [70000]
}),
formBuilder.group({
id: [123],
vehicleTypeId: [1],
quanty: [1],
brand: ['Niu'],
model: ['N GT'],
city: ['MEDELLÍN'],
telemetryBasic: [false],
telemetryPreo: [false],
price: [90000]
})
])
})
});
// Configurar respVehicles
component.respVehicles = [
{
id: 122,
contractId: 98,
vehicleTypeId: 1,
vehicleTypeName: "Moto",
vehicleModelName: "N GT",
vehicleBrandName: "Niu",
cityName: "MEDELLÍN",
valuePlan: 60000.0,
quantity: 1,
listServiceAdditional: []
},
{
id: 123,
contractId: 98,
vehicleTypeId: 1,
vehicleTypeName: "Moto",
vehicleModelName: "N GT",
vehicleBrandName: "Niu",
cityName: "MEDELLÍN",
valuePlan: 90000.0,
quantity: 1,
listServiceAdditional: []
}
];
// Act
component.editContract();
// Assert
expect(component.sendDatatoEdit).toHaveBeenCalledWith([
{
id: 122,
contractId: '12345',
vehicleTypeId: 1,
vehicleTypeName: 'Moto',
vehicleBrandName: 'Niu',
vehicleModelName: 'N GT',
cityName: 'MEDELLÍN',
listServiceAdditional: [
{
id: null, // Porque es 'NEW'
serviceId: 999, // Valor mockeado
name: 'Telemetría básica',
quantity: 2,
price: 70000,
action: 'NEW'
}
]
},
{
id: 123,
contractId: '12345',
vehicleTypeId: 1,
vehicleTypeName: 'Moto',
vehicleBrandName: 'Niu',
vehicleModelName: 'N GT',
cityName: 'MEDELLÍN',
listServiceAdditional: []
}
]);
});
it('should handle deleted services correctly', () => {
// Arrange
component.contractId = '12345';
// Configurar formServices con telemetryBasic desactivado
component.formServices = formBuilder.group({
Moto: formBuilder.group({
id: [1],
active: [true],
vehicles: formBuilder.array([
formBuilder.group({
id: [123],
vehicleTypeId: [1],
quanty: [1],
brand: ['Niu'],
model: ['N GT'],
city: ['MEDELLÍN'],
telemetryBasic: [false],
telemetryPreo: [false],
price: [90000]
})
])
})
});
// Configurar respVehicles con servicios existentes
component.respVehicles = [
{
id: 123,
contractId: 98,
vehicleTypeId: 1,
vehicleTypeName: "Moto",
vehicleModelName: "N GT",
vehicleBrandName: "Niu",
cityName: "MEDELLÍN",
valuePlan: 90000.0,
quantity: 1,
listServiceAdditional: [
{
id: 5,
serviceId: 561,
name: "Telemetría básica",
quantity: 1,
price: 70000.0,
action: "NO_ACTION"
}
]
}
];
// Act
component.editContract();
// Assert
expect(component.sendDatatoEdit).toHaveBeenCalledWith([
{
id: 123,
contractId: '12345',
vehicleTypeId: 1,
vehicleTypeName: 'Moto',
vehicleBrandName: 'Niu',
vehicleModelName: 'N GT',
cityName: 'MEDELLÍN',
listServiceAdditional: [
{
id: 5, // Porque es 'DELETED'
serviceId: 561, // Id del servicio existente
name: 'Telemetría básica',
quantity: 1,
price: 90000,
action: 'DELETED'
}
]
}
]);
});
it('should include existing services when no action is needed', () => {
// Arrange
component.contractId = '12345';
// Configurar formServices sin cambios en servicios
component.formServices = formBuilder.group({
Moto: formBuilder.group({
id: [1],
active: [true],
vehicles: formBuilder.array([
formBuilder.group({
id: [122],
vehicleTypeId: [1],
quanty: [2],
brand: ['Niu'],
model: ['N GT'],
city: ['MEDELLÍN'],
telemetryBasic: [false],
telemetryPreo: [false],
price: [70000]
}
)
])
})
});
// Configurar respVehicles con servicios existentes
component.respVehicles = [
{
id: 122,
contractId: 98,
vehicleTypeId: 1,
vehicleTypeName: "Moto",
vehicleModelName: "N GT",
vehicleBrandName: "Niu",
cityName: "MEDELLÍN",
valuePlan: 60000.0,
quantity: 1,
listServiceAdditional: [
{
id: 5,
serviceId: 561,
name: "Telemetría básica",
quantity: 1,
price: 70000.0,
action: "NO_ACTION"
}
]
}
];
// Act
component.editContract();
// Assert
expect(component.sendDatatoEdit).toHaveBeenCalledWith([
{
id: 122,
contractId: '12345',
vehicleTypeId: 1,
vehicleTypeName: 'Moto',
vehicleBrandName: 'Niu',
vehicleModelName: 'N GT',
cityName: 'MEDELLÍN',
listServiceAdditional: [
{
id: 5,
serviceId: 561,
name: 'Telemetría básica',
quantity: 1,
price: 70000,
action: null // No action necesario
}
]
}
]);
});
});
});
3. Explicación de los Casos de Prueba
Caso de Prueba: Preparar y Enviar Datos Correctos con Nuevos Servicios
Objetivo: Verificar que cuando se agrega un nuevo servicio (telemetryBasic: true), el método editContract prepara correctamente los datos y llama a sendDatatoEdit con la estructura esperada.
Configuración:
Se configura el formulario con dos vehículos: uno con telemetryBasic activado y otro sin servicios adicionales.
determineAction está mockeado para retornar 'NEW' si telemetryBasic está activado.
Resultado Esperado: sendDatatoEdit es llamado con una matriz que incluye el nuevo servicio añadido para el vehículo correspondiente.
Caso de Prueba: Manejar Servicios Eliminados Correctamente
Objetivo: Verificar que cuando se desactiva un servicio existente (telemetryBasic: false), el método editContract prepara correctamente los datos con la acción 'DELETED' y llama a sendDatatoEdit.
Configuración:
Se configura el formulario con un vehículo que previamente tenía un servicio adicional.
determineAction está mockeado para retornar 'DELETED' si telemetryBasic está desactivado.
Resultado Esperado: sendDatatoEdit es llamado con una matriz que incluye el servicio eliminado para el vehículo correspondiente.
Caso de Prueba: Incluir Servicios Existentes sin Necesidad de Acción
Objetivo: Verificar que cuando no se realizan cambios en los servicios adicionales, editContract incluye los servicios existentes sin acciones (action: null) y llama a sendDatatoEdit.
Configuración:
Se configura el formulario con un vehículo que no ha modificado sus servicios adicionales.
determineAction retorna null ya que no hay cambios.
Resultado Esperado: sendDatatoEdit es llamado con una matriz que incluye los servicios existentes sin acciones.
4. Consideraciones Adicionales
Mockear Métodos de Dependencia: Es importante moquear los métodos como determineAction y getServiceIdOfVehicleType para controlar sus salidas y facilitar la verificación de la lógica de editContract.
Verificar Diferentes Escenarios: Puedes agregar más casos de prueba para cubrir otros escenarios, como la edición de servicios existentes (action: 'EDIT'), la adición de múltiples servicios, o la combinación de diferentes acciones en múltiples vehículos.
Validar Estructura de Datos: Asegúrate de que la estructura de datos pasada a sendDatatoEdit coincida exactamente con lo que espera el backend o la lógica empresarial.
Cobertura Completa: Revisa que todos los caminos lógicos en editContract estén cubiertos por al menos un caso de prueba para asegurar una cobertura completa.
5. Conclusión
Estos casos de prueba ayudan a garantizar que el método editContract funcione correctamente en diferentes escenarios, preparando los datos adecuados y llamando a las funciones necesarias con la información correcta. Asegúrate de ejecutar estos tests y verificar que todos pasen, lo que aumentará la confianza en la funcionalidad del componente.
Copy first response
Not yet included in a published release.