Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // add-customer-to-class.component.ts:
- import { Component, OnInit, ViewChild } from '@angular/core';
- import { ClassesService } from '../services/classes.service';
- import { CommonModule, DatePipe, formatDate } from '@angular/common';
- import {
- FormBuilder,
- FormGroup,
- FormsModule,
- ReactiveFormsModule,
- Validators,
- } from '@angular/forms';
- import { MatSnackBar, MatSnackBarModule } from '@angular/material/snack-bar';
- import { ClassSearchResult } from '../models/classSearchResult';
- import { colorChoices } from '../constants/colorChoices';
- import { MatCardModule } from '@angular/material/card';
- import { MatIconModule } from '@angular/material/icon';
- import { MatInputModule } from '@angular/material/input';
- import { MatSelectModule } from '@angular/material/select';
- import { MatButtonModule } from '@angular/material/button';
- import { MatNativeDateModule } from '@angular/material/core';
- import { MatFormFieldModule } from '@angular/material/form-field';
- import { MatListModule } from '@angular/material/list';
- import { MatStepperModule } from '@angular/material/stepper';
- import { MatStepper } from '@angular/material/stepper';
- import { FlexLayoutModule } from '@angular/flex-layout';
- //import moment from 'moment';
- import { IconToggleGroupComponent } from '../icon-toggle-group/icon-toggle-group.component';
- import { Customer } from '../models/customer';
- import { MatDialog } from '@angular/material/dialog';
- import { ExistingCustomerModalComponent } from './existing-customer-modal/existing-customer-modal.component';
- import { CustomerService } from '../services/customer.service';
- import { FileUploadComponent } from '../file-upload/file-upload.component';
- import { CustomerAddFormComponent } from '../customers/add-form/customer-add-form.component';
- @Component({
- selector: 'app-add-customer-to-class',
- standalone: true,
- imports: [
- CommonModule,
- MatCardModule,
- MatIconModule,
- MatInputModule,
- MatListModule,
- MatSelectModule,
- MatButtonModule,
- MatNativeDateModule,
- MatSnackBarModule,
- MatStepperModule,
- FormsModule,
- ReactiveFormsModule,
- MatFormFieldModule,
- FlexLayoutModule,
- IconToggleGroupComponent,
- FileUploadComponent,
- CustomerAddFormComponent,
- ],
- providers: [DatePipe],
- templateUrl: './add-customer-to-class.component.html',
- styleUrl: './add-customer-to-class.component.sass',
- })
- export class AddCustomerToClassComponent implements OnInit {
- @ViewChild('stepper') private stepper!: MatStepper;
- classes: ClassSearchResult[] = [];
- selectedClass: ClassSearchResult | null = null;
- addCustomerForm: FormGroup;
- colorChoices: string[] = colorChoices;
- classTimeMapping!: { [formattedTime: string]: ClassSearchResult };
- customerId: number | null = null;
- @ViewChild('classImageUpload') classImageUpload!: FileUploadComponent;
- @ViewChild('customerForm') customerForm!: CustomerAddFormComponent;
- constructor(
- private classesService: ClassesService,
- private fb: FormBuilder,
- private snackBar: MatSnackBar,
- private datePipe: DatePipe,
- public dialog: MatDialog,
- public customersService: CustomerService
- ) {
- this.addCustomerForm = this.fb.group({
- name: ['', Validators.required],
- phone: ['', Validators.required],
- email: ['', Validators.email],
- color_choice: ['', Validators.required],
- });
- }
- createClassTimeMapping() {
- this.classTimeMapping = this.classes.reduce((acc, currentClass) => {
- const formattedTime = this.datePipe.transform(
- currentClass.date,
- 'shortTime',
- 'UTC'
- );
- if (formattedTime) {
- acc[formattedTime] = currentClass;
- }
- return acc;
- }, {} as { [formattedTime: string]: ClassSearchResult });
- }
- ngOnInit(): void {
- this.fetchClassesForToday();
- }
- justDate(date: Date) {
- const year = date.getFullYear();
- const month = (date.getMonth() + 1).toString().padStart(2, '0'); // Adding 1 because getMonth() is zero-based
- const day = date.getDate().toString().padStart(2, '0');
- return `${month}/${day}/${year}`;
- }
- fetchClassesForToday(): void {
- const today = this.justDate(new Date());
- this.classesService.searchClasses({ date: today }).subscribe({
- next: (data) => {
- this.classes = data;
- this.createClassTimeMapping();
- },
- error: (error) => console.error('Error fetching classes', error),
- });
- }
- selectClass(formattedTime: string): void {
- this.selectedClass = this.classTimeMapping[formattedTime];
- this.stepper.next();
- }
- getFormattedTimes(): (string | null)[] {
- return Object.keys(this.classTimeMapping ?? {});
- }
- handleAddExistingCustomer(event: {
- customer: Customer;
- additionalData: any;
- }): void {
- const { customer, additionalData } = event; // Destructure the object
- this.classesService
- .addCustomer(
- customer,
- this.selectedClass!.class_id,
- additionalData.color_choice
- )
- .subscribe({
- next: (classCustomer) => {
- this.snackBar.open('Existing customer added successfully!', 'Close', {
- duration: 5000,
- horizontalPosition: 'center',
- verticalPosition: 'top',
- });
- this.customerId = classCustomer.customer_id;
- },
- error: (err) => {
- console.error(err);
- this.snackBar.open('Failed to add existing customer.', 'Close', {
- duration: 5000,
- horizontalPosition: 'center',
- verticalPosition: 'top',
- });
- },
- });
- }
- handleTest(foo: string): void {
- debugger;
- }
- handleAddNewCustomer(event: {
- name: string;
- phone: string;
- email: string;
- receive_text: boolean;
- receive_email: boolean;
- additionalData: any;
- }): void {
- const { name, phone, email, receive_text, receive_email, additionalData } =
- event;
- this.classesService
- .addNewCustomer(
- name,
- phone,
- email,
- receive_text,
- receive_email,
- additionalData.color_choice,
- this.selectedClass!.class_id
- )
- .subscribe({
- next: (classCustomer) => {
- this.snackBar.open('Customer added successfully!', 'Close', {
- duration: 5000,
- horizontalPosition: 'center',
- verticalPosition: 'top',
- });
- this.customerId = classCustomer.customer_id;
- },
- error: (err) => {
- console.error(err);
- this.snackBar.open('Failed to add customer.', 'Close', {
- duration: 5000,
- horizontalPosition: 'center',
- verticalPosition: 'top',
- });
- },
- });
- }
- complete(): void {
- let continueWithoutImages = true;
- let addAnother = false;
- if (!this.classImageUpload.images.length) {
- continueWithoutImages = confirm(
- "You haven't uploaded any images. Are you sure you want to continue?"
- );
- }
- if (continueWithoutImages) {
- addAnother = confirm(
- "You're all set! We'll text you when your piece is ready to pick up! Would you like to add another class member?"
- );
- }
- if (addAnother) {
- this.addCustomerForm.reset();
- this.customerId = null;
- this.stepper.selectedIndex = 1;
- }
- }
- }
- // add-customer-to-class.html:
- <ng-container *ngIf="classes.length > 0; else noClassesFound">
- <mat-vertical-stepper linear #stepper="matVerticalStepper">
- <mat-step>
- <ng-template matStepLabel>Select your class (start time)</ng-template>
- <icon-toggle-group
- [values]="getFormattedTimes()"
- (change)="selectClass($event)"
- >
- </icon-toggle-group>
- </mat-step>
- <mat-step [stepControl]="addCustomerForm">
- <ng-template matStepLabel>Add your details</ng-template>
- <customer-add-form #customerForm>
- (addExistingCustomer)="handleAddExistingCustomer($event)"
- (addNewCustomer)="handleAddNewCustomer($event)"
- (testFunc)="handleTest($event); console.log('Parent template capturing
- event:', $event)" >
- <ng-template #colorChoiceField let-formGroup="formGroup">
- <mat-form-field appearance="fill">
- <mat-label>Color Choice</mat-label>
- <mat-select
- [formControl]="formGroup.controls['color_choice']"
- required
- >
- <mat-option *ngFor="let color of colorChoices" [value]="color">
- {{ color }}
- </mat-option>
- </mat-select>
- </mat-form-field>
- </ng-template>
- <div custom-buttons>
- <button
- mat-raised-button
- color="primary"
- type="submit"
- [disabled]="customerForm.addCustomerForm.invalid"
- >
- Add Me
- </button>
- </div>
- </customer-add-form>
- <div #testDiv>Test Div Content</div>
- </mat-step>
- <mat-step>
- <ng-template matStepLabel>Upload a picture of your piece</ng-template>
- <file-upload
- #classImageUpload
- *ngIf="selectedClass && customerId"
- imageType="classCustomer"
- [objectIds]="[selectedClass.class_id, customerId]"
- >
- </file-upload>
- <br />
- <button mat-raised-button color="primary" (click)="complete()">
- Finish
- </button>
- </mat-step>
- </mat-vertical-stepper>
- </ng-container>
- <ng-template #noClassesFound>
- <p>No classes found today.</p>
- </ng-template>
- // customer-add-form.component.ts:
- import {
- Component,
- EventEmitter,
- Input,
- Output,
- OnInit,
- ContentChild,
- TemplateRef,
- ViewChild,
- } from '@angular/core';
- import {
- FormBuilder,
- FormControl,
- FormGroup,
- ReactiveFormsModule,
- Validators,
- } from '@angular/forms';
- import { CustomerService } from '../../services/customer.service';
- import { ClassSearchResult } from '../../models/classSearchResult';
- import { colorChoices } from '../../constants/colorChoices';
- import { Customer } from '../../models/customer';
- import { MatFormFieldModule } from '@angular/material/form-field';
- import { CommonModule } from '@angular/common';
- import { MatCheckboxModule } from '@angular/material/checkbox';
- import { MatSelectModule } from '@angular/material/select';
- import { MatInputModule } from '@angular/material/input';
- @Component({
- selector: 'customer-add-form',
- standalone: true,
- imports: [
- ReactiveFormsModule,
- MatFormFieldModule,
- CommonModule,
- MatCheckboxModule,
- MatSelectModule,
- MatInputModule,
- ],
- templateUrl: './customer-add-form.component.html',
- styleUrls: ['./customer-add-form.component.sass'],
- })
- export class CustomerAddFormComponent implements OnInit {
- @Output() customerAdded = new EventEmitter<number>();
- @Output() addExistingCustomer = new EventEmitter<{
- customer: Customer;
- additionalData: any;
- }>();
- @Output() addNewCustomer = new EventEmitter<{
- name: string;
- phone: string;
- email: string;
- receive_text: boolean;
- receive_email: boolean;
- additionalData: any;
- }>();
- @Output() testFunc = new EventEmitter();
- @ContentChild('additionalFields') additionalFields!: TemplateRef<any>; // Injected custom fields
- @ViewChild('templateControls') templateControls!: any;
- addCustomerForm!: FormGroup;
- colorChoices: string[] = colorChoices;
- @Input() additionalFieldsTemplate!: any;
- constructor(
- private fb: FormBuilder,
- private customersService: CustomerService
- ) {}
- ngOnInit(): void {
- this.addCustomerForm = this.fb.group({
- name: ['', Validators.required],
- phone: ['', Validators.required],
- email: ['', Validators.email],
- receive_text: [true],
- receive_email: [true],
- agree_terms: [false, Validators.requiredTrue],
- });
- console.log('Child component initialized');
- }
- ngAfterViewInit(): void {
- this.addAdditionalFields();
- console.log('Child component View initialized');
- }
- addAdditionalFields(): void {
- if (this.templateControls) {
- // Iterate over each field passed through the template
- this.templateControls.forEach((control: any) => {
- const controlName = control.name;
- const isRequired = control.required;
- const validators = isRequired ? [Validators.required] : [];
- this.addCustomerForm.addControl(
- controlName,
- new FormControl('', validators)
- );
- });
- }
- }
- testEmit(): void {
- console.log('Child emitting testFunc event:', 'test');
- this.testFunc.emit('test');
- }
- addCustomer(): void {
- if (this.addCustomerForm.valid) {
- const { name, phone, email, receive_text, receive_email } =
- this.addCustomerForm.value;
- const additionalData = this.getAdditionalData();
- this.customersService.searchByPhone(phone).subscribe({
- next: (existingCustomer: Customer) => {
- // Handle the case when the customer exists
- this.addExistingCustomer.emit({
- customer: existingCustomer,
- additionalData,
- });
- this.testFunc.emit('poo');
- },
- error: () => {
- // Handle the case when the customer doesn't exist
- this.addNewCustomer.emit({
- name,
- phone,
- email,
- receive_text,
- receive_email,
- additionalData,
- });
- },
- });
- }
- }
- getAdditionalData(): any {
- const {
- name,
- phone,
- email,
- receive_text,
- receive_email,
- agree_terms,
- ...additionalData
- } = this.addCustomerForm.value;
- return additionalData;
- }
- }
- // customer-add-form.component.html:
- <form [formGroup]="addCustomerForm" (ngSubmit)="addCustomer()">
- <mat-form-field appearance="fill">
- <mat-label>Name</mat-label>
- <input matInput formControlName="name" placeholder="Name" required />
- </mat-form-field>
- <mat-form-field appearance="fill">
- <mat-label>Phone</mat-label>
- <input matInput formControlName="phone" placeholder="Phone" />
- </mat-form-field>
- <mat-form-field appearance="fill">
- <mat-label>Email</mat-label>
- <input matInput formControlName="email" placeholder="Email" />
- </mat-form-field>
- <ng-container *ngIf="additionalFields">
- <ng-container
- *ngTemplateOutlet="
- additionalFields;
- context: { formGroup: addCustomerForm }
- "
- ></ng-container>
- </ng-container>
- <mat-checkbox formControlName="receive_text"
- >Receive Text Messages</mat-checkbox
- >
- <!-- Receive Email Checkbox -->
- <mat-checkbox formControlName="receive_email">Receive Emails</mat-checkbox>
- <!-- Agree to Terms and Conditions Checkbox -->
- <mat-checkbox formControlName="agree_terms">
- I agree to the
- <a href="/terms.html" target="_blank">Terms of Service</a> and
- <a href="/privacy.html" target="_blank">Privacy Policy</a>
- </mat-checkbox>
- <ng-content select="[custom-buttons]"></ng-content>
- </form>
- <button (click)="testEmit()">test</button>
Advertisement
Add Comment
Please, Sign In to add comment