Çağrı Merkezi Kaydı

Çağrı Merkezi Kaydı Script

let checkinDate = this.recordService.formGroup.controls.CHECKIN.value;
let checkoutDate = this.recordService.formGroup.controls.CHECKOUT.value;
let diff = moment(checkoutDate).diff(moment(checkinDate), 'd');

this.querySelector('.ang-field-CHECKIN').querySelector('.mat-form-field-suffix').style.display='none';
this.querySelector('.ang-field-CHECKOUT').querySelector('.mat-form-field-suffix').style.display='none';

(() => {
  
  const {
    startWith,
    tap,
    combineLatest,
    debounceTime,
    map,
    filter,
    takeUntil,
  } = rxjs;
  const formControls = this.allFormControls;
  const changes = {
    LOS: false,
    CHECKOUT: false,
    CHECKIN: false,
  };
  const losChanges = formControls.LOS.valueChanges.pipe(
    startWith(formControls.LOS.value),
    tap(() => (changes.LOS = true))
  );
  const coutChanges = formControls.CHECKOUT.valueChanges.pipe(
    startWith(formControls.CHECKOUT.value),
    tap(() => (changes.CHECKOUT = true))
  );
  const cinChanges = formControls.CHECKIN.valueChanges.pipe(
    startWith(formControls.CHECKIN.value),
    tap(() => (changes.CHECKIN = true))
  );
  combineLatest([losChanges, coutChanges, cinChanges])
    .pipe(
      debounceTime(0),
      map(([LOS, CHECKOUT, CHECKIN]) => {
        const ret = {
          changes: Object.keys(changes).filter((key) => changes[key]),
          values: {
            LOS: LOS != null && LOS !== '' ? +LOS : null,
            CHECKOUT: moment(CHECKOUT),
            CHECKIN: moment(CHECKIN),
          },
        };
        
        Object.keys(changes).forEach((key) => (changes[key] = false));
        return ret;
      }),
      filter((changeObj) => {
        return (
          changeObj.changes.length === 1 &&
          changeObj.values.CHECKOUT.isValid() &&
          changeObj.values.CHECKIN.isValid() &&
          typeof changeObj.values.LOS === 'number'
          
        );
      }),
      tap((changeObj) => {
        const cinDay = changeObj.values.CHECKIN.clone().startOf('day');
        const coutDay = changeObj.values.CHECKOUT.clone().startOf('day');
        const dynamicLOS = coutDay.diff(cinDay, 'days', false);
        if (
          changeObj.changes[0] === 'LOS' ||
          changeObj.changes[0] === 'CHECKIN'
        ) {
          
          changeObj.values.CHECKOUT.add(
            changeObj.values.LOS - dynamicLOS,
            'days'
          );
        } else if (changeObj.changes[0] === 'CHECKOUT') {
          
          changeObj.values.LOS = dynamicLOS;
        }
        formControls.CHECKOUT.setValue(
          changeObj.values.CHECKOUT.format('YYYY-MM-DD HH:mm:ss.SSS')
        );
        formControls.CHECKIN.setValue(
          changeObj.values.CHECKIN.format('YYYY-MM-DD HH:mm:ss.SSS')
        );
        formControls.LOS.setValue(changeObj.values.LOS);
      }),
      takeUntil(this.isDestroy$)
    )
    .subscribe();
})();


this._save = async function (close = true, refresh = false) {
  let data = this.recordService.formGroup.getRawValue();

  

  if (this.recordService.formGroup.controls.REQUESTDATE.value == null)
    this.recordService.formGroup.controls.REQUESTDATE.setValue(
      moment().format('YYYY-MM-DD HH:mm:ss')
    );

  let phoneControl = this.recordService.formGroup.controls.PHONE.value;
  let emailControl = this.recordService.formGroup.controls.EMAIL.value;
  let guestControl = this.recordService.formGroup.controls.GUESTID.value;
  if (guestControl == null) {
    let msg4 = `You must enter a guest`;
    msg4 = angus.languageService.dynamicTranslator.translate(msg4);
    angus.api.angusDialog.warn(msg4);
    return false;
  }
  if (!phoneControl) {
    let msg3 = `You must enter a Phone Number`;
    msg3 = angus.languageService.dynamicTranslator.translate(msg3);
    angus.api.angusDialog.warn(msg3);
    return false;
  }

  await rxjs.timer(0).toPromise();
  this.progress = true;

  try {
    let uid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
      .replace(/[xy]/g, (c) => {
        var r = (Math.random() * 16) | 0,
          v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      })
      .toUpperCase();
    this.recordService.formGroup.controls.UID.setValue(uid);
    this.recordService.formGroup.controls.INSERTHOTELID.setValue(
      angus.api.tenant.HOTELID
    );

    let resp = await angus.api
      .execSP({
        BaseObject: 'HOTEL_CONTACTREQUEST',
        Object: 'SP_CONTACT_REQUEST_INSERT_UPDATE',
        Parameters: this.recordService.formGroup.getRawValue(),
      })
      .toPromise();
    if (!resp?.[0]?.[0]?.CONTACTREQUESTID) {
      let msgError = `Contact request Id is null`;
      msgError = angus.languageService.dynamicTranslator.translate(msgError);
      angus.api.angusDialog.warn(msgError);
      return false;
    }
    if (refresh) {
      await this.recordService.component.getData(
        resp?.[0]?.[0]?.CONTACTREQUESTID
      );
    }
    console.log('save ok', close, refresh);
    if (close) {
      this.onClose();
    } else {
      this.recordService.formGroup.markAsUntouched();
    }
    
    this.progress = false;
    return true;
  } catch (e) {
    angus.api.angusDialog.error(e);
    console.error('SP_CONTACT_REQUEST_INSERT_UPDATE', e);
    this.progress = false;
    return false;
  }
};

this.onSave = this._save.bind(this);

const onClose = this.onClose;
this.onClose = (...args) => {
  if (parent) {
    parent.postMessage('window.close', '*');
  }
  return onClose.bind(this)(...args);
};


this.recordService._getResCountAndUpdateButtonText = async (guestid) => {
  let resCount = await angus.api
    .select({
      Object: 'QG_HOTEL_RESERVATION',
      Select: ['ID'],
      Where: [
        {
          Column: 'CHECKIN',
          Operator: '>',
          Value: moment(angus.api.tenant.PROGDATE).format(
            'YYYY-MM-DD HH:mm:ss.SSS'
          ),
        },
        {
          Column: 'RESSTATEID',
          Operator: '=',
          Value: 2,
        },
        {
          Column: 'RESGUESTID',
          Operator: '=',
          Value: guestid
            ? guestid
            : this.recordService.formGroup.controls.GUESTID.value,
        },
      ],
      Paging: {
        ItemsPerPage: 100,
        Current: 1,
      },
    })
    .then((response) => {
      
      return response.ResultSets[0].length;
    });
  this.recordService.formGroup.controls.FUTURERESCOUNT.setValue(resCount);
  
  
};

this.recordService._getUnfinishedCall = async (phoneNumber) => {
  return this.recordService.component.api
    .select({
      Object: 'QG_EXT_HOTEL_CONTACTREQUEST',
      Where: [
        {
          Column: 'PHONE',
          Operator: '=',
          Value: phoneNumber,
        },
        {
          Column: 'REQUESTCLOSED',
          Operator: '=',
          Value: 0,
        },
      ],
      Paging: {
        ItemsPerPage: 1,
        Current: 1,
      },
      Select: ['ID'],
    })
    .then(async (response) => {
      if (
        response &&
        response.ResultSets[0] &&
        response.ResultSets[0][0] &&
        response.ResultSets[0][0].ID
      ) {
        let id = response.ResultSets[0][0].ID;
        return id;
      }
    });
};

const guestControlOrCreate = async (phoneNumber) => {
  this.recordService.component.api
    .select({
      Object: 'HOTEL_GUEST',
      Where: [
        {
          Column: 'PHONE',
          Operator: '=',
          Value: phoneNumber,
        },
      ],
      Joins: [
        {
          Object: 'QG_HOTEL_GUEST_VIP_TYPE',
          Key: 'ID',
          Fields: ['VIPTYPE'],
          Field: 'VIPTYPEID',
        },
      ],
      Paging: {
        ItemsPerPage: 1,
        Current: 1,
      },
      Select: [
        'ID',
        'NAME',
        'SURNAME',
        'EMAIL',
        'NATIONALIDNO',
        'BIRTHDATE',
        'REPEATCOUNT',
        'CALLCOUNT',
        'VIPTYPEID',
        'PREFERENCECOUNT',
        'TASKCOUNT',
        'COMMENTCOUNT',
      ],
    })
    .then((response) => {
      if (response.ResultSets[0].length > 0) {
        let guestId = response.ResultSets[0][0].ID;
        let guestName = response.ResultSets[0][0].NAME;
        let guestLastName = response.ResultSets[0][0].SURNAME;
        let guestEmail = response.ResultSets[0][0].EMAIL;
        let guestNationalIdNo = response.ResultSets[0][0].NATIONALIDNO;
        //let guestBirthDate = response.ResultSets[0][0].BIRTHDATE;
        let guestRepeat = response.ResultSets[0][0].REPEATCOUNT;
        let guestCall = response.ResultSets[0][0].CALLCOUNT;
        let guestPreference = response.ResultSets[0][0].PREFERENCECOUNT;
        let guestTask = response.ResultSets[0][0].TASKCOUNT;
        let guestComment = response.ResultSets[0][0].COMMENTCOUNT;
        let guestVipId = response.ResultSets[0][0].VIPTYPEID;
        let guestVipType = response.ResultSets[0][0].VIPTYPEID_VIPTYPE;
        this.recordService.formGroup.controls.GUESTID.setValue(guestId);
        if (guestNationalIdNo && !guestEmail) {
          this.recordService.formGroup.controls.GUESTID_NAME_PHONE.setValue(
            guestName + ' ' + guestLastName + ' ' + guestNationalIdNo
          );
        } else if (!guestNationalIdNo && guestEmail) {
          this.recordService.formGroup.controls.GUESTID_NAME_PHONE.setValue(
            guestName + ' ' + guestLastName + ' ' + guestEmail
          );
        } else if (!guestNationalIdNo && !guestEmail) {
          this.recordService.formGroup.controls.GUESTID_NAME_PHONE.setValue(
            guestName + ' ' + guestLastName
          );
        } else if (guestNationalIdNo && guestEmail) {
          this.recordService.formGroup.controls.GUESTID_NAME_PHONE.setValue(
            guestName +
              ' ' +
              guestLastName +
              ' ' +
              guestNationalIdNo +
              ' ' +
              guestEmail
          );
        }
        this.recordService.formGroup.controls.GUESTID_NAME.setValue(guestName);
        this.recordService.formGroup.controls.GUESTID_LNAME.setValue(
          guestLastName
        );
        this.recordService.formGroup.controls.EMAIL.setValue(guestEmail);
        this.recordService.formGroup.controls.GUESTID_REPEATCOUNT.setValue(
          guestRepeat
        );
        this.recordService.formGroup.controls.GUESTID_CALLCOUNT.setValue(
          guestCall
        );
        this.recordService.formGroup.controls.GUESTID_TASKCOUNT.setValue(
          guestTask
        );
        this.recordService.formGroup.controls.GUESTID_PREFERENCECOUNT.setValue(
          guestPreference
        );
        this.recordService.formGroup.controls.GUESTID_COMMENTCOUNT.setValue(
          guestComment
        );
        this.recordService.formGroup.controls.VIPTYPEID.setValue(guestVipId);
        this.recordService.formGroup.controls.VIPTYPEID_VIPTYPE.setValue(
          guestVipType
        );
      } else {
        this.recordService.formGroup.controls.GUESTID_NAME_PHONE.setValue(null);
        this.recordService.formGroup.controls.GUESTID_NAME.setValue(null);
        this.recordService.formGroup.controls.GUESTID_LNAME.setValue(null);
        this.recordService.formGroup.controls.EMAIL.setValue(null);
        this.recordService.formGroup.controls.GUESTID_REPEATCOUNT.setValue(
          null
        );
        this.recordService.elements.btnRepeatHistory.api.innerComponent.text =
          '(' + 0 + ')';
        this.recordService.formGroup.controls.GUESTID_CALLCOUNT.setValue(null);
        this.recordService.elements.btnPreferenceHistory.api.innerComponent.text =
          '(' + 0 + ')';
        this.recordService.elements.btnTaskHistory.api.innerComponent.text =
          '(' + 0 + ')';
        this.recordService.elements.btnCommentHistory.api.innerComponent.text =
          '(' + 0 + ')';
        this.recordService.formGroup.controls.VIPTYPEID.setValue(null);
        this.recordService.formGroup.controls.VIPTYPEID_VIPTYPE.setValue(null);

        (async () => {
          const newGuest = await openNewGuestRecord(phoneNumber);
          if (newGuest?.ID) {
            newGuest['ID_NAME_ID_BIRTH'] = await getNameIdBirth(newGuest.ID);
            setNewGuestToRecord(newGuest);
          }
        })();
      }
    });
};

const openNewGuestRecord = async (phoneNumber) => {
  return this.recordService.component.popupService
    .openRecord('guest-cards', null, { PHONE: phoneNumber }, undefined, 'full')
    .afterClosed()
    .toPromise();
};

const getNameIdBirth = async (guestId) => {
  return this.recordService.component.api
    .select({
      Object: 'QG_HOTEL_GUEST',
      Where: [
        {
          Column: 'ID',
          Operator: '=',
          Value: guestId,
        },
      ],
      Paging: {
        ItemsPerPage: 1,
        Current: 1,
      },
      Select: ['NAME_ID_BIRTH'],
    })
    .then((response) => {
      return response.ResultSets[0][0].NAME_ID_BIRTH;
    });
};

const setNewGuestToRecord = (guestData) => {
  const controls = this.recordService.formGroup.controls;
  controls.GUESTID_NAME.setValue(guestData.NAME);
  controls.GUESTID_LNAME.setValue(guestData.LNAME);
  controls.GUESTID_NAME_PHONE.setValue(guestData.ID_NAME_ID_BIRTH);
  controls.GUESTID.setValue(guestData.ID);
};

////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////

const awaitIf = async (fn, ms = 100) => {
  await new Promise(async (resolve, reject) => {
    let result = false;
    try {
      result = fn();
    } catch (e) {}

    if (result) {
      resolve(true);
    } else {
      await rxjs.timer(ms).toPromise();
      resolve(await awaitIf(fn));
    }
  });
};

setTimeout(() => {
  this.recordService.formGroup.controls.BOOKINGHOTELID.valueChanges
    .pipe(
      rxjs.startWith(this.recordService.formGroup.controls.BOOKINGHOTELID.value)
    )
    .subscribe((hotelId) => {
      if (hotelId) {
        this.recordService.formGroup.controls.GROUPHOTEL.setValue(0);
        this.recordService.formGroup.controls.GROUPHOTEL.markAsDirty();
      } else {
        this.recordService.formGroup.controls.GROUPHOTEL.setValue(1);
        this.recordService.formGroup.controls.GROUPHOTEL.markAsDirty();
      }
    });

  this.recordService.formGroup.controls.GUESTID.valueChanges.subscribe(
    async (guestid) => {
      if (typeof guestid === 'object') {
        return;
      }
      await this.recordService._getResCountAndUpdateButtonText(guestid);
      if (
        document.querySelector(
          '.ang-record-group-hotels-calllogs .ang-panel-P3'
        ).style.display !== 'none'
      ) {
        if (guestid) {
          setTimeout(() => {
            let data = this.recordService.formGroup.getRawValue();
            if (data.GUESTID_NAME && data.GUESTID_LNAME) {
              let filtre = [
                { Column: 'NAME', Operator: '=', Value: data.GUESTID_NAME },
                { Column: 'SURNAME', Operator: '=', Value: data.GUESTID_LNAME },
              ];
              let dataGrid = this.recordService.grids[
                'group-calllogs-select-grids'
              ].grid;
              dataGrid.extraFilters = filtre;
              dataGrid.loadData();
            }
          }, 0);
        }
      }
    }
  );

  document.querySelector(
    `.ang-record-${this.recordID} .ang-panel-P3`
  ).style.display = 'none';
  document.querySelector(
    `.ang-record-${this.recordID} .ang-panel-P3`
  ).parentElement.style.display = 'none';
  document.querySelector(
    `.ang-record-${this.recordID} .dynamic-container`
  ).style.gridTemplateAreas = `"P1" "T1" "P2"`;
  document.querySelector('#splitByQty .mat-icon').style.transform =
    'rotate(90deg)';

  this.recordService.formGroup.controls.NOTES.valueChanges
    .pipe(rxjs.startWith(this.recordService.formGroup.controls.NOTES.value))
    .subscribe((notes) => {
      if (notes && notes.includes('[')) {
        let jsonData = JSON.parse(notes);
        let text =
          jsonData[0].Hotel +
          ' ' +
          jsonData[0].Checkin +
          ' / ' +
          jsonData[0].Checkout +
          ' Adult: ' +
          jsonData[0].Adult +
          ' ' +
          jsonData[0].TotalPrice;
        setTimeout(() => {
          this.recordService.formGroup.controls.ONLINEBOOKINGINFO.setValue(
            text
          );
        }, 1000);
        document.querySelector('div.group.ang-group-jsonNotes').style.display =
          'grid';
      } else {
        document.querySelector('div.group.ang-group-jsonNotes').style.display =
          'none';
      }
    });

  const toDate = (v) =>
    moment(v).set({ hour: 0, minute: 0, second: 0, millisecond: 0 });
  (async () => {
    await awaitIf(() => this.recordService.formGroup.controls['CHECKIN']);

    const checkIn = this.recordService.formGroup.controls['CHECKIN'];
    const checkOut = this.recordService.formGroup.controls['CHECKOUT'];

    

   
    await awaitIf(() => this.recordService.formGroup.controls['PHONE']);
    let phoneNumber = new URL(location.href).searchParams.get('phone');
    if (phoneNumber !== null && phoneNumber !== '') {
      let direction = new URL(location.href).searchParams.get('direction');
      if (direction == 'outbound') {
        if (phoneNumber.match(/\+{1}?[1-9]0?[1-9]/g)) {
          phoneNumber = '+9' + phoneNumber.substring(2);
        }
        if (phoneNumber.match(/\+{1}?[1-9][0]{2}?[1-9]/g)) {
          phoneNumber = '+' + phoneNumber.substring(4);
        }
        this.recordService.formGroup.controls.CALLDIRECTION.setValue(1);
        this.recordService.formGroup.controls.CALLDIRECTION.markAsDirty();
      } else {
        this.recordService.formGroup.controls.CALLDIRECTION.setValue(0);
        this.recordService.formGroup.controls.CALLDIRECTION.markAsDirty();
      }
      this.recordService.formGroup.controls.PHONE.setValue(phoneNumber);

      let callId = await this.recordService._getUnfinishedCall(phoneNumber);
      if (callId) {
        setTimeout(async () => {
          await this.recordService.component.getData(callId);
          await this.recordService._getResCountAndUpdateButtonText();
        }, 1000);
      } else {
        guestControlOrCreate(phoneNumber);
        
        let url_stringg = location.href;
        let urll = new URL(url_stringg);
        let destination = urll.searchParams.get('destination');
        let createtypeid = urll.searchParams.get('createtypeid');
        if (createtypeid == 2) {
          this.recordService.formGroup.controls.CREATETYPEID.setValue(2);
          this.recordService.formGroup.controls.CONTACTTYPEID.setValue(0);
        }
        if (destination) {
          let resp = await angus.api.select({
            Object: 'QG_ACCOUNTING_BRANCH_PHONENUMBERS',
            Select: ['HOTELNAME', 'SOURCE'],
            Where: [
              {
                Column: 'PHONENUMBER',
                Operator: '=',
                Value: destination,
              },
            ],
            Paging: {
              ItemsPerPage: 1,
              Current: 1,
            },
          });
          if (resp?.ResultSets?.[0]?.[0]) {
            this.recordService.formGroup.controls.HOTELNAME.setValue(
              resp.ResultSets[0][0].HOTELNAME
            );
            this.recordService.formGroup.controls.HOTELNAME.markAsDirty();
            if (resp.ResultSets[0][0].SOURCE) {
              this.recordService.formGroup.controls.REFGROUPID.setValue(
                parseInt(resp.ResultSets[0][0].SOURCE)
              );
              this.recordService.formGroup.controls.REFGROUPID.markAsDirty();
            }
          }
        }
       
        const resGuestControl = this.recordService.elements.selectGuest.api
          .innerComponent.innerComponent.formControl;
        const guestFc = this.recordService.formGroup.controls.GUESTID;
        guestFc.valueChanges
          .pipe(
            window.rxjs.takeUntil(this.isDestroy$),
            window.rxjs.filter((x) => typeof x === 'number'),
            window.rxjs.distinctUntilChanged(),
            window.rxjs.switchMap((x) => {
              return window.rxjs.from(
                angus.api.select({
                  Object: 'QG_HOTEL_RESERVATION',
                  Select: ['ID'],
                  Where: [
                    {
                      Column: 'CHECKIN',
                      Operator: '>',
                      Value: moment(angus.api.tenant.PROGDATE).format(
                        'YYYY-MM-DD HH:mm:ss.SSS'
                      ),
                    },
                    {
                      Column: 'RESSTATEID',
                      Operator: '=',
                      Value: 2,
                    },
                    {
                      Column: 'RESGUESTID',
                      Operator: '=',
                      Value: this.recordService.formGroup.controls.GUESTID
                        .value,
                    },
                  ],
                  Paging: {
                    ItemsPerPage: 100,
                    Current: 1,
                  },
                })
              );
            })
          )
          .subscribe(async (response) => {
            console.log('response', response);
            const count = response.ResultSets[0].length;
            // this.recordService.elements.btnFutureRepeatHistory.api.innerComponent.text =
            //   '(' + (count || 0) + ')';

            this.recordService.formGroup.controls.FUTURERESCOUNT.setValue(
              count
            );
            //await this.recordService._getResCountAndUpdateButtonText();
          });
      }
      //yeni yeri son

      const resultControl = this.recordService.elements.groupCancelResult.api
        .innerComponent.innerComponent.formControl;
      this.recordService.formGroup.controls.REQUESTTYPEID_NAME.valueChanges.subscribe(
        (x) => {
          if (x) {
            this.recordService.formGroup.controls.CONTACTRESULTID.setValue(
              null
            );
            resultControl.setValue('abc');
            resultControl.setValue('');
          }
        }
      );
    }
  })();

  this.recordService.formGroup.controls.BOOKINGHOTELID_NAME.valueChanges
    .pipe(
      rxjs.startWith(
        this.recordService.formGroup.controls.BOOKINGHOTELID_NAME.value
      )
    )
    .subscribe((x) => {
      if (x) {
        this.recordService.formGroup.controls.GROUPHOTEL.setValue(0);
      } else {
        this.recordService.formGroup.controls.GROUPHOTEL.setValue(1);
      }
    });
}, 1000);

Last updated