Fixes für input fields, #60 -> AuditService
This commit is contained in:
parent
d2f6b3ec3f
commit
40ba402c70
|
|
@ -135,7 +135,7 @@ export const commercials = pgTable(
|
|||
export const listingEvents = pgTable('listing_events', {
|
||||
id: uuid('id').primaryKey().defaultRandom().notNull(),
|
||||
listingId: uuid('listing_id'), // Assuming listings are referenced by UUID, adjust as necessary
|
||||
userId: uuid('user_id'), // Nullable, if user is logged in, otherwise null
|
||||
email: varchar('email', { length: 255 }).references(() => users.email),
|
||||
eventType: varchar('event_type', { length: 50 }), // 'view', 'print', 'email', 'facebook', 'x', 'linkedin', 'contact'
|
||||
eventTimestamp: timestamp('event_timestamp').defaultNow(),
|
||||
userIp: varchar('user_ip', { length: 45 }), // Optional if you choose to track IP in frontend or backend
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ export class EventService {
|
|||
) {}
|
||||
async createEvent(event: ListingEvent) {
|
||||
// Speichere das Event in der Datenbank
|
||||
event.eventTimestamp = new Date();
|
||||
await this.conn.insert(listingEvents).values(event).execute();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -34,6 +34,8 @@ export const CustomerTypeEnum = z.enum(['buyer', 'seller', 'professional']);
|
|||
export const SubscriptionTypeEnum = z.enum(['free', 'professional', 'broker']);
|
||||
export const CustomerSubTypeEnum = z.enum(['broker', 'cpa', 'attorney', 'titleCompany', 'surveyor', 'appraiser']);
|
||||
export const ListingsCategoryEnum = z.enum(['commercialProperty', 'business']);
|
||||
export const ZodEventTypeEnum = z.enum(['view', 'print', 'email', 'facebook', 'x', 'linkedin', 'contact', 'favorite']);
|
||||
export type EventTypeEnum = z.infer<typeof ZodEventTypeEnum>;
|
||||
const PropertyTypeEnum = z.enum(['retail', 'land', 'industrial', 'office', 'mixedUse', 'multifamily', 'uncategorized']);
|
||||
const TypeEnum = z.enum([
|
||||
'automotive',
|
||||
|
|
@ -123,8 +125,9 @@ export const LicensedInSchema = z.object({
|
|||
}),
|
||||
registerNo: z.string().nonempty('License number is required'),
|
||||
});
|
||||
export const GeoSchema = z.object({
|
||||
name: z.string(),
|
||||
export const GeoSchema = z
|
||||
.object({
|
||||
name: z.string().optional().nullable(),
|
||||
state: z.string().refine(val => USStates.safeParse(val).success, {
|
||||
message: 'Invalid state. Must be a valid 2-letter US state code.',
|
||||
}),
|
||||
|
|
@ -148,6 +151,15 @@ export const GeoSchema = z.object({
|
|||
housenumber: z.string().optional().nullable(),
|
||||
street: z.string().optional().nullable(),
|
||||
zipCode: z.number().optional().nullable(),
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (!data.name && !data.county) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: 'You need to select either a city or a county',
|
||||
path: ['name'],
|
||||
});
|
||||
}
|
||||
});
|
||||
const phoneRegex = /^(\+1|1)?[-.\s]?\(?[2-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;
|
||||
export const UserSchema = z
|
||||
|
|
@ -320,8 +332,8 @@ export type ShareByEMail = z.infer<typeof ShareByEMailSchema>;
|
|||
export const ListingEventSchema = z.object({
|
||||
id: z.string().uuid(), // UUID für das Event
|
||||
listingId: z.string().uuid(), // UUID für das Listing
|
||||
userId: z.string().uuid().optional().nullable(), // UUID für den Benutzer, optional, wenn kein Benutzer eingeloggt ist
|
||||
eventType: z.enum(['view', 'print', 'email', 'facebook', 'x', 'linkedin', 'contact']), // Die Event-Typen
|
||||
email: z.string().email().optional().nullable(), // EMail des den Benutzer, optional, wenn kein Benutzer eingeloggt ist
|
||||
eventType: ZodEventTypeEnum, // Die Event-Typen
|
||||
eventTimestamp: z.string().datetime().or(z.date()), // Der Zeitstempel des Events, kann ein String im ISO-Format oder ein Date-Objekt sein
|
||||
userIp: z.string().max(45).optional().nullable(), // IP-Adresse des Benutzers, optional
|
||||
userAgent: z.string().max(255).optional().nullable(), // User-Agent des Benutzers, optional
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
}
|
||||
</label>
|
||||
<input
|
||||
[type]="kind"
|
||||
type="text"
|
||||
[id]="name"
|
||||
[ngModel]="value"
|
||||
(ngModelChange)="onInputChange($event)"
|
||||
|
|
|
|||
|
|
@ -21,14 +21,24 @@ import { ValidationMessagesService } from '../validation-messages.service';
|
|||
],
|
||||
})
|
||||
export class ValidatedInputComponent extends BaseInputComponent {
|
||||
@Input() kind: 'text' | 'number' | 'email' | 'tel' = 'text';
|
||||
@Input() kind: 'text' | 'number' | 'email' = 'text';
|
||||
@Input() mask: string;
|
||||
constructor(validationMessagesService: ValidationMessagesService) {
|
||||
super(validationMessagesService);
|
||||
}
|
||||
|
||||
onInputChange(event: string): void {
|
||||
this.value = event?.length > 0 ? event : null;
|
||||
onInputChange(event: string | number): void {
|
||||
if (this.kind === 'number') {
|
||||
if (typeof event === 'number') {
|
||||
this.value = event;
|
||||
} else {
|
||||
this.value = parseFloat(event);
|
||||
}
|
||||
} else {
|
||||
const text = event as string;
|
||||
this.value = text?.length > 0 ? event : null;
|
||||
}
|
||||
// this.value = event?.length > 0 ? (this.kind === 'number' ? parseFloat(event) : event) : null;
|
||||
this.onChange(this.value);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@
|
|||
</button>
|
||||
</div>
|
||||
}
|
||||
<share-button button="print" showText="true"></share-button>
|
||||
<share-button button="print" showText="true" (click)="createEvent('print')"></share-button>
|
||||
<!-- <share-button button="email" showText="true"></share-button> -->
|
||||
<div class="inline">
|
||||
<button class="share share-email text-white font-bold text-xs py-1.5 px-2 inline-flex items-center" (click)="showShareByEMail()">
|
||||
|
|
@ -52,9 +52,9 @@
|
|||
</button>
|
||||
</div>
|
||||
|
||||
<share-button button="facebook" showText="true"></share-button>
|
||||
<share-button button="x" showText="true"></share-button>
|
||||
<share-button button="linkedin" showText="true"></share-button>
|
||||
<share-button button="facebook" showText="true" (click)="createEvent('facebook')"></share-button>
|
||||
<share-button button="x" showText="true" (click)="createEvent('x')"></share-button>
|
||||
<share-button button="linkedin" showText="true" (click)="createEvent('linkedin')"></share-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -70,7 +70,7 @@
|
|||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<app-validated-input label="Phone Number" name="phoneNumber" [(ngModel)]="mailinfo.sender.phoneNumber" kind="tel" mask="(000) 000-0000"></app-validated-input>
|
||||
<app-validated-input label="Phone Number" name="phoneNumber" [(ngModel)]="mailinfo.sender.phoneNumber" mask="(000) 000-0000"></app-validated-input>
|
||||
<!-- <app-validated-input label="Country/State" name="state" [(ngModel)]="mailinfo.sender.state"></app-validated-input> -->
|
||||
<app-validated-ng-select label="State" name="state" [(ngModel)]="mailinfo.sender.state" [items]="selectOptions?.states"></app-validated-ng-select>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
|
|||
import { KeycloakService } from 'keycloak-angular';
|
||||
import { ShareButton } from 'ngx-sharebuttons/button';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
import { BusinessListing, User } from '../../../../../../bizmatch-server/src/models/db.model';
|
||||
import { BusinessListing, EventTypeEnum, User } from '../../../../../../bizmatch-server/src/models/db.model';
|
||||
import { KeycloakUser, MailInfo } from '../../../../../../bizmatch-server/src/models/main.model';
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import { EMailService } from '../../../components/email/email.service';
|
||||
|
|
@ -14,6 +14,7 @@ import { ValidatedNgSelectComponent } from '../../../components/validated-ng-sel
|
|||
import { ValidatedTextareaComponent } from '../../../components/validated-textarea/validated-textarea.component';
|
||||
import { ValidationMessagesService } from '../../../components/validation-messages.service';
|
||||
import { AuditService } from '../../../services/audit.service';
|
||||
import { GeoService } from '../../../services/geo.service';
|
||||
import { HistoryService } from '../../../services/history.service';
|
||||
import { ListingsService } from '../../../services/listings.service';
|
||||
import { MailService } from '../../../services/mail.service';
|
||||
|
|
@ -73,6 +74,7 @@ export class DetailsBusinessListingComponent {
|
|||
private messageService: MessageService,
|
||||
private auditService: AuditService,
|
||||
public emailService: EMailService,
|
||||
private geoService: GeoService,
|
||||
) {
|
||||
this.router.events.subscribe(event => {
|
||||
if (event instanceof NavigationEnd) {
|
||||
|
|
@ -89,9 +91,9 @@ export class DetailsBusinessListingComponent {
|
|||
this.user = await this.userService.getByMail(this.keycloakUser.email);
|
||||
this.mailinfo = createMailInfo(this.user);
|
||||
}
|
||||
this.auditService.createEvent({ listingId: this.listing.id, eventType: 'view', eventTimestamp: new Date(), userAgent: navigator.userAgent, userId: this.user?.email });
|
||||
try {
|
||||
this.listing = await lastValueFrom(this.listingsService.getListingById(this.id, 'business'));
|
||||
this.auditService.createEvent(this.listing.id, 'view', this.user?.email);
|
||||
this.listingUser = await this.userService.getByMail(this.listing.email);
|
||||
this.description = this.sanitizer.bypassSecurityTrustHtml(this.listing.description);
|
||||
} catch (error) {
|
||||
|
|
@ -110,6 +112,7 @@ export class DetailsBusinessListingComponent {
|
|||
this.mailinfo.email = this.listingUser.email;
|
||||
this.mailinfo.listing = this.listing;
|
||||
await this.mailService.mail(this.mailinfo);
|
||||
this.auditService.createEvent(this.listing.id, 'contact', this.user?.email);
|
||||
this.messageService.addMessage({ severity: 'success', text: 'Your message has been sent to the creator of the listing', duration: 3000 });
|
||||
} catch (error) {
|
||||
this.messageService.addMessage({
|
||||
|
|
@ -155,6 +158,7 @@ export class DetailsBusinessListingComponent {
|
|||
save() {
|
||||
this.listing.favoritesForUser.push(this.user.email);
|
||||
this.listingsService.save(this.listing, 'business');
|
||||
this.auditService.createEvent(this.listing.id, 'favorite', this.user?.email);
|
||||
}
|
||||
isAlreadyFavorite() {
|
||||
return this.listing.favoritesForUser.includes(this.user.email);
|
||||
|
|
@ -169,6 +173,7 @@ export class DetailsBusinessListingComponent {
|
|||
type: 'business',
|
||||
});
|
||||
if (result) {
|
||||
this.auditService.createEvent(this.listing.id, 'email', this.user?.email);
|
||||
this.messageService.addMessage({
|
||||
severity: 'success',
|
||||
text: 'Your Email has beend sent',
|
||||
|
|
@ -176,4 +181,8 @@ export class DetailsBusinessListingComponent {
|
|||
});
|
||||
}
|
||||
}
|
||||
|
||||
createEvent(eventType: EventTypeEnum) {
|
||||
this.auditService.createEvent(this.listing.id, eventType, this.user?.email);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@
|
|||
</button>
|
||||
</div>
|
||||
}
|
||||
<share-button button="print" showText="true"></share-button>
|
||||
<share-button button="print" showText="true" (click)="createEvent('print')"></share-button>
|
||||
<!-- <share-button button="email" showText="true"></share-button> -->
|
||||
<div class="inline">
|
||||
<button class="share share-email text-white font-bold text-xs py-1.5 px-2 inline-flex items-center" (click)="showShareByEMail()">
|
||||
|
|
@ -48,9 +48,9 @@
|
|||
</button>
|
||||
</div>
|
||||
|
||||
<share-button button="facebook" showText="true"></share-button>
|
||||
<share-button button="x" showText="true"></share-button>
|
||||
<share-button button="linkedin" showText="true"></share-button>
|
||||
<share-button button="facebook" showText="true" (click)="createEvent('facebook')"></share-button>
|
||||
<share-button button="x" showText="true" (click)="createEvent('x')"></share-button>
|
||||
<share-button button="linkedin" showText="true" (click)="createEvent('linkedin')"></share-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -73,7 +73,7 @@
|
|||
<app-validated-input label="Your Email" name="email" [(ngModel)]="mailinfo.sender.email" kind="email"></app-validated-input>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<app-validated-input label="Phone Number" name="phoneNumber" [(ngModel)]="mailinfo.sender.phoneNumber" kind="tel" mask="(000) 000-0000"></app-validated-input>
|
||||
<app-validated-input label="Phone Number" name="phoneNumber" [(ngModel)]="mailinfo.sender.phoneNumber" mask="(000) 000-0000"></app-validated-input>
|
||||
<!-- <app-validated-input label="Country/State" name="state" [(ngModel)]="mailinfo.sender.state"></app-validated-input> -->
|
||||
<app-validated-ng-select label="State" name="state" [(ngModel)]="mailinfo.sender.state" [items]="selectOptions?.states"></app-validated-ng-select>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { KeycloakService } from 'keycloak-angular';
|
|||
import { GalleryModule, ImageItem } from 'ng-gallery';
|
||||
import { ShareButton } from 'ngx-sharebuttons/button';
|
||||
import { lastValueFrom } from 'rxjs';
|
||||
import { CommercialPropertyListing, User } from '../../../../../../bizmatch-server/src/models/db.model';
|
||||
import { CommercialPropertyListing, EventTypeEnum, User } from '../../../../../../bizmatch-server/src/models/db.model';
|
||||
import { CommercialPropertyListingCriteria, ErrorResponse, KeycloakUser, MailInfo } from '../../../../../../bizmatch-server/src/models/main.model';
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import { EMailService } from '../../../components/email/email.service';
|
||||
|
|
@ -97,6 +97,7 @@ export class DetailsCommercialPropertyListingComponent {
|
|||
}
|
||||
try {
|
||||
this.listing = (await lastValueFrom(this.listingsService.getListingById(this.id, 'commercialProperty'))) as CommercialPropertyListing;
|
||||
this.auditService.createEvent(this.listing.id, 'view', this.user?.email);
|
||||
this.listingUser = await this.userService.getByMail(this.listing.email);
|
||||
this.description = this.sanitizer.bypassSecurityTrustHtml(this.listing.description);
|
||||
import('flowbite').then(flowbite => {
|
||||
|
|
@ -142,6 +143,7 @@ export class DetailsCommercialPropertyListingComponent {
|
|||
this.mailinfo.email = this.listingUser.email;
|
||||
this.mailinfo.listing = this.listing;
|
||||
await this.mailService.mail(this.mailinfo);
|
||||
this.auditService.createEvent(this.listing.id, 'contact', this.user?.email);
|
||||
this.messageService.addMessage({ severity: 'success', text: 'Your message has been sent to the creator of the listing', duration: 3000 });
|
||||
} catch (error) {
|
||||
this.messageService.addMessage({
|
||||
|
|
@ -166,6 +168,7 @@ export class DetailsCommercialPropertyListingComponent {
|
|||
save() {
|
||||
this.listing.favoritesForUser.push(this.user.email);
|
||||
this.listingsService.save(this.listing, 'commercialProperty');
|
||||
this.auditService.createEvent(this.listing.id, 'favorite', this.user?.email);
|
||||
}
|
||||
isAlreadyFavorite() {
|
||||
return this.listing.favoritesForUser.includes(this.user.email);
|
||||
|
|
@ -180,6 +183,7 @@ export class DetailsCommercialPropertyListingComponent {
|
|||
type: 'commercialProperty',
|
||||
});
|
||||
if (result) {
|
||||
this.auditService.createEvent(this.listing.id, 'email', this.user?.email);
|
||||
this.messageService.addMessage({
|
||||
severity: 'success',
|
||||
text: 'Your Email has beend sent',
|
||||
|
|
@ -187,4 +191,7 @@ export class DetailsCommercialPropertyListingComponent {
|
|||
});
|
||||
}
|
||||
}
|
||||
createEvent(eventType: EventTypeEnum) {
|
||||
this.auditService.createEvent(this.listing.id, eventType, this.user?.email);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,15 +117,8 @@
|
|||
</div>
|
||||
</div> -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<app-validated-input
|
||||
label="Years Established Since"
|
||||
name="established"
|
||||
[(ngModel)]="listing.established"
|
||||
kind="number"
|
||||
mask="0000"
|
||||
(ngModelChange)="onNumericInputChange($event, 'listing.established')"
|
||||
></app-validated-input>
|
||||
<app-validated-input label="Employees" name="employees" [(ngModel)]="listing.employees" kind="number" mask="0000" (ngModelChange)="onNumericInputChange($event, 'listing.employees')"></app-validated-input>
|
||||
<app-validated-input label="Established In" name="established" [(ngModel)]="listing.established" mask="0000" kind="number"></app-validated-input>
|
||||
<app-validated-input label="Employees" name="employees" [(ngModel)]="listing.employees" mask="0000" kind="number"></app-validated-input>
|
||||
</div>
|
||||
|
||||
<div class="flex mb-4 space-x-4">
|
||||
|
|
@ -199,13 +192,7 @@
|
|||
</ng-select>
|
||||
</div>
|
||||
<!-- } -->
|
||||
<app-validated-input
|
||||
label="Internal Listing Number"
|
||||
name="internalListingNumber"
|
||||
[(ngModel)]="listing.internalListingNumber"
|
||||
kind="number"
|
||||
(ngModelChange)="onNumericInputChange($event, 'listing.internalListingNumber')"
|
||||
></app-validated-input>
|
||||
<app-validated-input label="Internal Listing Number" name="internalListingNumber" [(ngModel)]="listing.internalListingNumber" kind="number" mask="00000000000000000000"></app-validated-input>
|
||||
</div>
|
||||
|
||||
<!-- <div class="mb-4">
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@
|
|||
<app-validated-input label="Your Email" name="email" [(ngModel)]="mailinfo.sender.email" kind="email"></app-validated-input>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<app-validated-input label="Phone Number" name="phoneNumber" [(ngModel)]="mailinfo.sender.phoneNumber" kind="tel" mask="(000) 000-0000"></app-validated-input>
|
||||
<app-validated-input label="Phone Number" name="phoneNumber" [(ngModel)]="mailinfo.sender.phoneNumber" mask="(000) 000-0000"></app-validated-input>
|
||||
<div>
|
||||
<app-validated-ng-select label="State" name="state" [(ngModel)]="mailinfo.sender.state" [items]="selectOptions?.states"></app-validated-ng-select>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,9 +1,10 @@
|
|||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { BehaviorSubject, lastValueFrom, Observable } from 'rxjs';
|
||||
import { ListingEvent } from '../../../../bizmatch-server/src/models/db.model';
|
||||
import { EventTypeEnum, ListingEvent } from '../../../../bizmatch-server/src/models/db.model';
|
||||
import { LogMessage } from '../../../../bizmatch-server/src/models/main.model';
|
||||
import { environment } from '../../environments/environment';
|
||||
import { GeoService } from './geo.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
|
|
@ -20,47 +21,26 @@ export class AuditService {
|
|||
private geoLocationSubject = new BehaviorSubject<any>(null);
|
||||
public geoLocation$: Observable<any> = this.geoLocationSubject.asObservable();
|
||||
|
||||
constructor(private http: HttpClient) {}
|
||||
constructor(private http: HttpClient, private geoService: GeoService) {}
|
||||
|
||||
async log(message: LogMessage): Promise<void> {
|
||||
lastValueFrom(this.http.post(`${this.apiBaseUrl}/bizmatch/log`, message));
|
||||
}
|
||||
async createEvent(event: ListingEvent): Promise<void> {
|
||||
lastValueFrom(this.http.post(`${this.apiBaseUrl}/bizmatch/event`, event));
|
||||
}
|
||||
// Function to get the IP address
|
||||
private getIpAddress(): Observable<{ ip: string }> {
|
||||
return this.http.get<{ ip: string }>(`/ipinfo?format=json`);
|
||||
}
|
||||
|
||||
// Function to get geolocation using IP address
|
||||
private getGeolocation(ip: string): Observable<any> {
|
||||
return this.http.get(`/ipinfo/${ip}?token=${this.apiKey}`);
|
||||
}
|
||||
|
||||
// Fetch IP and Geolocation only once, if not already fetched
|
||||
fetchIpAndGeoLocation(): void {
|
||||
if (!this.geoLocationSubject.getValue()) {
|
||||
this.getIpAddress().subscribe({
|
||||
next: response => {
|
||||
this.getGeolocation(response.ip).subscribe({
|
||||
next: geoData => {
|
||||
this.geoLocationSubject.next(geoData); // Store the geolocation data
|
||||
},
|
||||
error: geoError => {
|
||||
console.error('Error fetching geolocation:', geoError);
|
||||
},
|
||||
});
|
||||
},
|
||||
error: ipError => {
|
||||
console.error('Error fetching IP address:', ipError);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Method to provide the stored geolocation data
|
||||
getGeoLocationData(): Observable<any> {
|
||||
return this.geoLocation$; // Returns the observable for other components to subscribe
|
||||
async createEvent(id: string, eventType: EventTypeEnum, userId: string): Promise<void> {
|
||||
const ipInfo = await this.geoService.getIpInfo();
|
||||
const [latitude, longitude] = ipInfo.loc ? ipInfo.loc.split(',') : [null, null]; //.map(Number);
|
||||
const listingEvent: ListingEvent = {
|
||||
listingId: id,
|
||||
eventType,
|
||||
eventTimestamp: new Date(),
|
||||
userAgent: navigator.userAgent,
|
||||
email: userId,
|
||||
userIp: ipInfo.ip,
|
||||
locationCountry: ipInfo.country,
|
||||
locationCity: ipInfo.city,
|
||||
locationLat: latitude,
|
||||
locationLng: longitude,
|
||||
};
|
||||
lastValueFrom(this.http.post(`${this.apiBaseUrl}/bizmatch/event`, listingEvent));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { BehaviorSubject, lastValueFrom, Observable } from 'rxjs';
|
||||
import { CityAndStateResult, CountyResult, GeoResult, IpInfo } from '../../../../bizmatch-server/src/models/main.model';
|
||||
import { Place } from '../../../../bizmatch-server/src/models/server.model';
|
||||
import { environment } from '../../environments/environment';
|
||||
|
|
@ -11,6 +11,9 @@ import { environment } from '../../environments/environment';
|
|||
export class GeoService {
|
||||
private apiBaseUrl = environment.apiBaseUrl;
|
||||
private baseUrl: string = 'https://nominatim.openstreetmap.org/search';
|
||||
private ipInfo$ = new BehaviorSubject<IpInfo | null>(null);
|
||||
private fetchingData: Observable<IpInfo> | null = null;
|
||||
private readonly storageKey = 'ipInfo';
|
||||
constructor(private http: HttpClient) {}
|
||||
|
||||
findCitiesStartingWith(prefix: string, state?: string): Observable<GeoResult[]> {
|
||||
|
|
@ -27,7 +30,49 @@ export class GeoService {
|
|||
let headers = new HttpHeaders().set('X-Hide-Loading', 'true').set('Accept-Language', 'en-US');
|
||||
return this.http.get(`${this.baseUrl}?q=${prefix},US&format=json&addressdetails=1&limit=5`, { headers }) as Observable<Place[]>;
|
||||
}
|
||||
fetchIpAndGeoLocation(): Observable<IpInfo> {
|
||||
private fetchIpAndGeoLocation(): Observable<IpInfo> {
|
||||
return this.http.get<IpInfo>(`${this.apiBaseUrl}/bizmatch/geo/ipinfo/georesult/wysiwyg`);
|
||||
}
|
||||
|
||||
// getIpInfo(): Observable<IpInfo | null> {
|
||||
// if (this.ipInfo$.getValue() !== null) {
|
||||
// // Wenn wir bereits Daten haben, geben wir sie sofort zurück
|
||||
// return this.ipInfo$.asObservable();
|
||||
// } else if (this.fetchingData) {
|
||||
// // Wenn wir gerade Daten abrufen, geben wir diesen Observable zurück
|
||||
// return this.fetchingData;
|
||||
// } else {
|
||||
// // Ansonsten initiieren wir den Abruf
|
||||
// this.fetchingData = this.fetchIpAndGeoLocation().pipe(
|
||||
// tap(data => this.ipInfo$.next(data)),
|
||||
// catchError(error => {
|
||||
// console.error('Error fetching IP info:', error);
|
||||
// this.ipInfo$.next(null);
|
||||
// return of(null);
|
||||
// }),
|
||||
// shareReplay(1),
|
||||
// );
|
||||
// return this.fetchingData;
|
||||
// }
|
||||
// }
|
||||
async getIpInfo(): Promise<IpInfo | null> {
|
||||
// Versuche zuerst, die Daten aus dem sessionStorage zu holen
|
||||
const storedData = sessionStorage.getItem(this.storageKey);
|
||||
if (storedData) {
|
||||
return JSON.parse(storedData);
|
||||
}
|
||||
|
||||
try {
|
||||
// Wenn keine Daten im Storage, hole sie vom Server
|
||||
const data = await lastValueFrom(this.http.get<IpInfo>(`${this.apiBaseUrl}/bizmatch/geo/ipinfo/georesult/wysiwyg`));
|
||||
|
||||
// Speichere die Daten im sessionStorage
|
||||
sessionStorage.setItem(this.storageKey, JSON.stringify(data));
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('Error fetching IP info:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue