Crear una nueva cuenta e insertar un cliente

Última modificación por Pablo Martínez Kirsten el 2022/03/02 14:07

Introducción

En este tutorial, permitiremos que se pueda crear una nueva cuenta asociada al cliente actual.

Si estas utilizando como backend el repositorio de Github, pasa directamente al punto Modificar el formulario para la nueva opción.

Requisitos previos

Es necesario modificar el backend de la inserción de la cuenta, para que si la llamada contiene el identificador de un cliente, lo añada a la cuenta recién creada.


BranchService.java

...

import model.core.dao.CustomerDao;

@Lazy
@Service("BranchService")
public class BranchService implements IBranchService {

   ....

   @Autowired
   private CustomerService customerService;

   ...

   @Override
   public EntityResult accountInsert(Map<String, Object> attributes) throws OntimizeJEERuntimeException {

        attributes.put(AccountDao.ATTR_ENTITYID, 2095);
        attributes.remove(AccountDao.ATTR_ANID);
        attributes.remove(AccountDao.ATTR_CDID);
        EntityResult toRet = this.daoHelper.insert(this.accountDao, attributes);

       if (toRet.getCode() == EntityResult.OPERATION_WRONG) {
           throw new OntimizeJEERuntimeException(toRet.getMessage());
       }

        StringBuilder builderfDC = new StringBuilder();
        builderfDC.append("00");
        builderfDC.append(attributes.get(AccountDao.ATTR_ENTITYID));
        builderfDC.append(attributes.get(AccountDao.ATTR_OFFICEID));

        Object accountKey = toRet.get(AccountDao.ATTR_ID);
       int accountNumber = this.accountDao.createAccountNumber((int) accountKey);
       int accountDC = this.accountDao.calculateCDID(builderfDC.toString(), accountNumber);

        Map<String, Object> mapAccountData = new HashMap<String, Object>();
        mapAccountData.put(AccountDao.ATTR_CDID, accountDC);
        mapAccountData.put(AccountDao.ATTR_ANID, accountNumber);

        Map<String, Object> mapAccountKey = new HashMap<String, Object>();
        mapAccountKey.put(AccountDao.ATTR_ID, accountKey);

        EntityResult accountUpdate = this.daoHelper.update(this.accountDao, mapAccountData, mapAccountKey);

       if (accountUpdate.getCode() == EntityResult.OPERATION_WRONG) {
           throw new OntimizeJEERuntimeException(accountUpdate.getMessage());
       }
       
       if (attributes.containsKey(CustomerDao.ATTR_ID)) {
            Map<String, Object> insertCustomer = new HashMap<String, Object>();
            insertCustomer.put(CustomerDao.ATTR_ID, attributes.get(CustomerDao.ATTR_ID));
            insertCustomer.put(AccountDao.ATTR_ID, toRet.get(AccountDao.ATTR_ID));
            EntityResult customerAccountInsert = customerService.customerAccountInsert(insertCustomer);
           if (customerAccountInsert.getCode() == EntityResult.OPERATION_WRONG) {
               throw new OntimizeJEERuntimeException(accountUpdate.getMessage());
           }
           
       }

       return toRet;
   }

   ...
}

Modificar el formulario para la nueva opción

En este caso, modificaremos el formulario existente para incluir un botón que permita añadir una nueva cuenta e insertar ese cliente. Será necesario tanto modificar el html para el botón, como el ts para pasarle los datos a un nuevo componente


customers-detail.component.html

<o-form fxFill #form service="customers" entity="customer" keys="CUSTOMERID" header-actions="R;I;U;D"
 show-header-navigation="no">
 <o-text-input attr="CUSTOMERID" sql-type="INTEGER" enabled="no"></o-text-input>
 <o-row fxFlex>
    ...
   <mat-tab-group fxFlex>
     <mat-tab label="{{ 'CUSTOMER_PERSONAL_INFORMATION' | oTranslate }}">
        ...
     </mat-tab>
     <mat-tab label="{{ 'ACCOUNTS' | oTranslate }}">
        ...

       <o-button (click)="openAccountDetailSelected()" label="Open Account Selected"></o-button>
       <o-button (click)="createNewAccount()" label="Create new account"></o-button>
     </mat-tab>
   </mat-tab-group>
 </o-row>
</o-form>
customers-detail.component.ts
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { MatDialog } from '@angular/material';
import { Router } from '@angular/router';
import { OFormComponent, OTableComponent } from 'ontimize-web-ngx';
import { intRateMonthlyFunction } from '../../../shared/shared.module';
import { AddAccountComponent } from './add-account/add-account.component';

@Component({
  selector: 'app-customers-detail',
  templateUrl: './customers-detail.component.html',
  styleUrls: ['./customers-detail.component.scss'],
  encapsulation: ViewEncapsulation.None,
  host: {
   '[class.customer-detail-form]': 'true'
  }
})
export class CustomersDetailComponent implements OnInit {

 @ViewChild('form', { static: false }) form: OFormComponent;
 @ViewChild('accountCustomerTable', { static: false }) accountTable: OTableComponent;
 public intRateMonthly = intRateMonthlyFunction;

 constructor(
   private router: Router,
   public dialog: MatDialog
  ) { }

 public openAccountDetailSelected() {
   let selected = this.accountTable.getSelectedItems();
   if (selected.length === 1) {
     let accountId = selected[0]['ACCOUNTID'];
     let customerId = selected[0]['CUSTOMERID'];
     this.router.navigate(['main/customers/' + customerId + '/' + accountId], { queryParams: { isdetail: true } });
    }
  }

 public createNewAccount() {
   let customerId = this.form.getFieldValue('CUSTOMERID');
   let date = new Date().getTime();
   this.dialog.open(AddAccountComponent, {
      data: {
        CUSTOMERID: customerId,
        STARTDATE: date
      }, disableClose: false
    })
  }

  ngOnInit() {
  }

}

Creación del nuevo componente

Crearemos el nuevo componente para crear una nueva cuenta. Para ello ejecutamos el siguiente comando dentro de la carpeta *customers-detail*

npx ng g c --skipTests add-account


add-account.component.html
<div mat-dialog-content>
 <o-form fxFill #form (onFormModeChange)="forceInsertMode($event)" (onInsert)="closeDialog($event)" service="branches"
   entity="account" header-actions="I" show-header-navigation="no">
   <o-combo attr="OFFICEID" label="OFFICEID" service="branches" entity="branch" value-column="OFFICEID"
     columns="OFFICEID;NAME" visible-columns="NAME" read-only="no" required="yes"></o-combo>
   <o-integer-input oHidden attr="CUSTOMERID"></o-integer-input>
   <o-date-input attr="STARTDATE"></o-date-input>
 </o-form>
</div>
add-account.component.ts
import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material';
import { OFormComponent } from 'ontimize-web-ngx';
import { MatDialogModule, MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-add-account',
  templateUrl: './add-account.component.html',
  styleUrls: ['./add-account.component.css']
})
export class AddAccountComponent implements OnInit {

 @ViewChild('form', { static: false }) form: OFormComponent;
 public dialog: MatDialogModule;
 constructor(
   @Inject(MAT_DIALOG_DATA) public data: any,
   private dialogRef: MatDialogRef<AddAccountComponent>
  ) { }

 public forceInsertMode(event: any) {
   if (event != OFormComponent.Mode().INSERT) {
     this.form.setInsertMode();
     this.form.setFieldValues(this.data)
    }
  }

 public closeDialog(event: any) {
   this.dialogRef.close();
  }

  ngOnInit() {
  }

}

Añadimos este nuevo componente al array de declaraciones del módulo de cliente, y además al array de entryComponents. Esto nos permite cargar el componente sin referenciarlo en la plantilla.

customers.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { OntimizeWebModule } from 'ontimize-web-ngx';
import { CustomersRoutingModule } from './customers-routing.module';
import { CustomersHomeComponent } from './customers-home/customers-home.component';
import { CustomersDetailComponent } from './customers-detail/customers-detail.component';
import { CustomersNewComponent } from './customers-new/customers-new.component';
import { SharedModule } from 'src/app/shared/shared.module';
import { AddAccountComponent } from './customers-detail/add-account/add-account.component';


@NgModule({
  declarations: [CustomersHomeComponent, CustomersDetailComponent, CustomersNewComponent, AddAccountComponent],
  imports: [
    CommonModule,
    SharedModule,
    OntimizeWebModule,
    CustomersRoutingModule
  ]
})
export class CustomersModule { }

<< Tutorial previoÍndicePróximo tutorial >>
Etiquetas:
Creado por Pablo Martínez Kirsten el 2021/03/14 19:32
    
This wiki is licensed under a Ontimize license
XWiki Enterprise 8.0