Files
marketplaces/src/app/pages/item-detail/item-detail.component.ts

326 lines
11 KiB
TypeScript
Raw Normal View History

2026-03-24 02:46:58 +04:00
import { Component, OnInit, OnDestroy, signal, computed, ChangeDetectionStrategy, inject } from '@angular/core';
2026-02-19 01:23:25 +04:00
import { DecimalPipe } from '@angular/common';
2026-01-18 18:57:06 +04:00
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { ApiService, CartService, TelegramService, LanguageService, SeoService } from '../../services';
2026-03-24 02:25:50 +04:00
import { AuthService } from '../../services/auth.service';
2026-03-24 02:46:58 +04:00
import { Item, ItemDetail, DescriptionField } from '../../models';
2026-01-18 18:57:06 +04:00
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
import { Subscription } from 'rxjs';
import { environment } from '../../../environments/environment';
2026-02-26 21:54:21 +04:00
import { SecurityContext } from '@angular/core';
import { getDiscountedPrice, getAllImages, getStockStatus, getBadgeClass, getTranslatedField } from '../../utils/item.utils';
2026-02-26 22:23:08 +04:00
import { LangRoutePipe } from '../../pipes/lang-route.pipe';
2026-02-26 23:09:20 +04:00
import { TranslatePipe } from '../../i18n/translate.pipe';
import { TranslateService } from '../../i18n/translate.service';
2026-01-18 18:57:06 +04:00
@Component({
selector: 'app-item-detail',
2026-02-26 23:09:20 +04:00
imports: [DecimalPipe, RouterLink, FormsModule, LangRoutePipe, TranslatePipe],
2026-01-18 18:57:06 +04:00
templateUrl: './item-detail.component.html',
styleUrls: ['./item-detail.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ItemDetailComponent implements OnInit, OnDestroy {
item = signal<Item | null>(null);
selectedPhotoIndex = signal(0);
loading = signal(true);
error = signal<string | null>(null);
isnovo = environment.theme === 'novo';
2026-03-24 02:46:58 +04:00
// Variant selection
selectedColour = signal<string | null>(null);
selectedSize = signal<string | null>(null);
availableColours = computed(() => {
const details = this.item()?.itemDetails;
if (!details?.length) return [] as string[];
const unique = [...new Set(details.map(d => d.colour || d.color).filter((c): c is string => !!c))];
return unique;
});
availableSizes = computed(() => {
const details = this.item()?.itemDetails;
if (!details?.length) return [] as string[];
// If a colour is selected, only show sizes available for that colour
const colour = this.selectedColour();
const filtered = colour
? details.filter(d => (d.colour || d.color) === colour)
: details;
const unique = [...new Set(filtered.map(d => d.size).filter((s): s is string => !!s))];
return unique;
});
selectedDetail = computed<ItemDetail | null>(() => {
const details = this.item()?.itemDetails;
if (!details?.length) return null;
const colour = this.selectedColour();
const size = this.selectedSize();
return details.find(d =>
(!colour || (d.colour || d.color) === colour) &&
(!size || d.size === size)
) ?? null;
});
effectivePrice = computed(() => {
const detail = this.selectedDetail();
return detail?.price ?? this.item()?.price ?? 0;
});
effectiveCurrency = computed(() => {
const detail = this.selectedDetail();
return detail?.currency ?? this.item()?.currency ?? '';
});
effectiveRemaining = computed(() => {
const detail = this.selectedDetail();
return detail?.remaining ?? this.item()?.quantity ?? null;
});
2026-01-18 18:57:06 +04:00
newReview = {
rating: 0,
comment: '',
anonymous: false
};
reviewSubmitStatus = signal<'idle' | 'loading' | 'success' | 'error'>('idle');
private routeSubscription?: Subscription;
2026-02-26 21:54:21 +04:00
private reviewResetTimeout?: ReturnType<typeof setTimeout>;
private reviewErrorTimeout?: ReturnType<typeof setTimeout>;
private reloadTimeout?: ReturnType<typeof setTimeout>;
private seoService = inject(SeoService);
2026-02-26 23:09:20 +04:00
private i18n = inject(TranslateService);
2026-03-24 02:25:50 +04:00
private authService = inject(AuthService);
2026-01-18 18:57:06 +04:00
constructor(
private route: ActivatedRoute,
private apiService: ApiService,
private cartService: CartService,
private telegramService: TelegramService,
2026-02-20 10:44:03 +04:00
private sanitizer: DomSanitizer,
private languageService: LanguageService
2026-01-18 18:57:06 +04:00
) {}
ngOnInit(): void {
this.routeSubscription = this.route.params.subscribe(params => {
const id = parseInt(params['id'], 10);
this.loadItem(id);
});
}
ngOnDestroy(): void {
this.routeSubscription?.unsubscribe();
2026-02-26 21:54:21 +04:00
if (this.reviewResetTimeout) clearTimeout(this.reviewResetTimeout);
if (this.reviewErrorTimeout) clearTimeout(this.reviewErrorTimeout);
if (this.reloadTimeout) clearTimeout(this.reloadTimeout);
this.seoService.resetToDefaults();
2026-01-18 18:57:06 +04:00
}
loadItem(itemID: number): void {
this.loading.set(true);
this.apiService.getItem(itemID).subscribe({
next: (item) => {
this.item.set(item);
2026-03-24 02:46:58 +04:00
this.initVariantSelection(item);
2026-02-26 21:54:21 +04:00
this.seoService.setItemMeta(item);
2026-01-18 18:57:06 +04:00
this.loading.set(false);
},
error: (err) => {
this.error.set('Failed to load item');
this.loading.set(false);
console.error('Error loading item:', err);
}
});
}
2026-03-24 02:46:58 +04:00
private initVariantSelection(item: Item): void {
// Auto-select the first available colour and size from itemDetails
const details = item.itemDetails;
if (details?.length) {
const firstColour = details[0].colour || details[0].color || null;
this.selectedColour.set(firstColour);
const firstSize = details[0].size || null;
this.selectedSize.set(firstSize);
} else {
this.selectedColour.set(item.colour ?? null);
this.selectedSize.set(item.size ?? null);
}
}
selectColour(colour: string): void {
this.selectedColour.set(colour);
// If current size is not available for the new colour, reset to first available
const sizes = this.availableSizes();
if (sizes.length && this.selectedSize() && !sizes.includes(this.selectedSize()!)) {
this.selectedSize.set(sizes[0]);
}
}
selectSize(size: string): void {
this.selectedSize.set(size);
}
2026-01-18 18:57:06 +04:00
selectPhoto(index: number): void {
this.selectedPhotoIndex.set(index);
}
addToCart(): void {
const currentItem = this.item();
if (currentItem) {
2026-03-24 02:46:58 +04:00
this.cartService.addItem(currentItem.itemID, 1, {
colour: this.selectedColour() ?? undefined,
size: this.selectedSize() ?? undefined,
price: this.effectivePrice(),
currency: this.effectiveCurrency()
});
2026-01-18 18:57:06 +04:00
}
}
getDiscountedPrice(): number {
const currentItem = this.item();
if (!currentItem) return 0;
2026-03-24 02:46:58 +04:00
const price = this.effectivePrice();
const discount = currentItem.discount || 0;
return discount > 0 ? price * (1 - discount / 100) : price;
2026-01-18 18:57:06 +04:00
}
2026-02-20 10:44:03 +04:00
// BackOffice integration helpers
getItemName(): string {
const currentItem = this.item();
if (!currentItem) return '';
const lang = this.languageService.currentLanguage();
return getTranslatedField(currentItem, 'name', lang);
}
getSimpleDescription(): string {
const currentItem = this.item();
if (!currentItem) return '';
2026-03-24 02:46:58 +04:00
return currentItem.simpleDescription || currentItem.description || '';
2026-02-20 10:44:03 +04:00
}
hasDescriptionFields(): boolean {
const currentItem = this.item();
return !!(currentItem?.descriptionFields && currentItem.descriptionFields.length > 0);
}
getTranslatedDescriptionFields(): DescriptionField[] {
const currentItem = this.item();
if (!currentItem) return [];
const lang = this.languageService.currentLanguage();
const translation = currentItem.translations?.[lang];
if (translation?.description && translation.description.length > 0) {
return translation.description;
}
return currentItem.descriptionFields || [];
}
getStockClass(): string {
const currentItem = this.item();
if (!currentItem) return 'high';
return getStockStatus(currentItem);
}
getStockLabel(): string {
const status = this.getStockClass();
switch (status) {
case 'high': return 'В наличии';
case 'medium': return 'Заканчивается';
case 'low': return 'Последние штуки';
case 'out': return 'Нет в наличии';
default: return 'В наличии';
}
}
readonly getBadgeClass = getBadgeClass;
2026-01-18 18:57:06 +04:00
getSafeHtml(html: string): SafeHtml {
2026-02-26 21:54:21 +04:00
return this.sanitizer.sanitize(SecurityContext.HTML, html) || '';
2026-01-18 18:57:06 +04:00
}
getRatingStars(rating: number): string {
const fullStars = Math.floor(rating);
const hasHalfStar = rating % 1 >= 0.5;
2026-02-26 21:54:21 +04:00
let stars = '★'.repeat(fullStars);
if (hasHalfStar) stars += '☆';
2026-01-18 18:57:06 +04:00
return stars;
}
formatDate(timestamp: string): string {
const date = new Date(timestamp);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
2026-02-26 23:09:20 +04:00
if (diffDays === 0) return this.i18n.t('itemDetail.today');
if (diffDays === 1) return this.i18n.t('itemDetail.yesterday');
if (diffDays < 7) return `${diffDays} ${this.i18n.t('itemDetail.daysAgo')}`;
if (diffDays < 30) return `${Math.floor(diffDays / 7)} ${this.i18n.t('itemDetail.weeksAgo')}`;
2026-01-18 18:57:06 +04:00
return date.toLocaleDateString('ru-RU', {
day: 'numeric',
month: 'long',
year: 'numeric'
});
}
setRating(rating: number): void {
this.newReview.rating = rating;
}
getUserDisplayName(): string | null {
if (!this.telegramService.isTelegramApp()) {
2026-02-26 23:09:20 +04:00
return this.i18n.t('itemDetail.defaultUser');
2026-01-18 18:57:06 +04:00
}
return this.telegramService.getDisplayName();
}
submitReview(): void {
if (!this.newReview.rating || !this.newReview.comment.trim()) {
return;
}
const currentItem = this.item();
if (!currentItem) return;
this.reviewSubmitStatus.set('loading');
const reviewData = {
itemID: currentItem.itemID,
rating: this.newReview.rating,
comment: this.newReview.comment.trim(),
2026-03-24 02:25:50 +04:00
sessionID: this.authService.session()?.sessionId || '',
2026-01-18 18:57:06 +04:00
timestamp: new Date().toISOString()
};
this.apiService.submitReview(reviewData).subscribe({
next: (response) => {
this.reviewSubmitStatus.set('success');
this.newReview = { rating: 0, comment: '', anonymous: false };
2026-02-26 21:54:21 +04:00
// Сброс состояния через 3 секунды
this.reviewResetTimeout = setTimeout(() => {
2026-01-18 18:57:06 +04:00
this.reviewSubmitStatus.set('idle');
}, 3000);
2026-02-26 21:54:21 +04:00
// Перезагрузить данные товара после отправки отзыва
this.reloadTimeout = setTimeout(() => {
2026-01-18 18:57:06 +04:00
this.loadItem(currentItem.itemID);
}, 500);
},
error: (err) => {
console.error('Error submitting review:', err);
this.reviewSubmitStatus.set('error');
2026-02-26 21:54:21 +04:00
// Сброс состояния об ошибке через 5 секунд
this.reviewErrorTimeout = setTimeout(() => {
2026-01-18 18:57:06 +04:00
this.reviewSubmitStatus.set('idle');
}, 5000);
}
});
}
}