Skip to content

Commit

Permalink
Improved cart quantities and fixed Sweep to Cart function
Browse files Browse the repository at this point in the history
  • Loading branch information
amenconi committed Jan 30, 2024
1 parent 0eda115 commit cc0aa93
Show file tree
Hide file tree
Showing 15 changed files with 301 additions and 194 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ export class FilterStorageService {
public marketNftsResetVisible$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public marketNftsFilters$: BehaviorSubject<MarketNftsFilters> =
new BehaviorSubject<MarketNftsFilters>({
sortBy: this.marketNftsFiltersOptions.sortItems[0].value,
sortBy: this.marketNftsFiltersOptions.sortItems[2].value,
});

public marketCollectionsFiltersOptions = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,23 +100,23 @@ <h4 class="modal-title">Your Cart</h4>
*ngIf="discount(item.collection, item.nft) < 1"
>
{{
cartItemPrices[item.nft.uid]?.originalPrice
cartItemPrices[item.nft.uid].originalPrice
| formatToken
: (item.nft?.placeholderNft
? item.collection?.mintingData?.network
: item.nft?.mintingData?.network)
: (item.nft.placeholderNft
? item.collection.mintingData?.network
: item.nft.mintingData?.network)
: true
: true
| async
}}
</div>
<div class="text-lg font-bold truncate">
{{
cartItemPrices[item.nft.uid]?.discountedPrice
cartItemPrices[item.nft.uid].discountedPrice
| formatToken
: (item.nft?.placeholderNft
? item.collection?.mintingData?.network
: item.nft?.mintingData?.network)
: (item.nft.placeholderNft
? item.collection.mintingData?.network
: item.nft.mintingData?.network)
: true
: true
| async
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ export class CartModalComponent implements OnInit, OnDestroy {
ngOnInit() {
this.subscriptions.add(
this.cartService.getCartItems().subscribe((items) => {
// console.log('[CartModalComponent-ngOnInit] Cart items updated:', items);
this.cartItemsStatus = items.map((item) => this.cartItemStatus(item));
this.cartItemsQuantities = items.map((item) => this.cartItemSaleAvailableQty(item));
items.forEach((item) => {
Expand Down Expand Up @@ -77,28 +76,22 @@ export class CartModalComponent implements OnInit, OnDestroy {
}

private refreshCartData() {
// console.log('Refreshing cart items...');
const cartItems = this.cartService.getCartItems().getValue();
// console.log('Current cart items:', cartItems);

const freshDataObservables = cartItems.map((item) =>
this.nftApi.getNftById(item.nft.uid).pipe(
take(1),
map((freshNft) => {
// console.log(`Fetched fresh data for NFT ${item.nft.uid}:`, freshNft);
return freshNft ? { ...item, nft: freshNft } : item;
}),
catchError((error) => {
// console.error(`Error fetching fresh data for NFT ${item.nft.uid}:`, error);
return of(item);
}),
),
);

forkJoin(freshDataObservables).subscribe(
(freshCartItems) => {
// console.log('Fresh cart items:', freshCartItems);

this.cartService.updateCartItems(freshCartItems);

this.cartItemsStatus = freshCartItems.map((item) => this.cartItemStatus(item));
Expand All @@ -111,8 +104,6 @@ export class CartModalComponent implements OnInit, OnDestroy {
this.cartItemPrices[item.nft.uid] = { originalPrice, discountedPrice };
});

// console.log('Finished refreshing cart items.');

this.cd.markForCheck();
},
(error) => {
Expand All @@ -124,17 +115,25 @@ export class CartModalComponent implements OnInit, OnDestroy {

public updateQuantity(event: Event, itemId: string): void {
const inputElement = event.target as HTMLInputElement;
const newQuantity = Number(inputElement.value);

if (newQuantity === 0) {
this.cartService.removeFromCart(itemId);
} else {
const cartItems = this.cartService.getCartItems().getValue();
const itemIndex = cartItems.findIndex((cartItem) => cartItem.nft.uid === itemId);
if (itemIndex !== -1) {
cartItems[itemIndex].quantity = newQuantity;
this.cartService.saveCartItems();
let newQuantity = Number(inputElement.value);

const cartItems = this.cartService.getCartItems().getValue();
const itemIndex = cartItems.findIndex((cartItem) => cartItem.nft.uid === itemId);

if (itemIndex !== -1) {
const maxQuantity = this.cartItemsQuantities[itemIndex];
const minQuantity = 1;

if (newQuantity < minQuantity) {
newQuantity = minQuantity;
inputElement.value = minQuantity.toString();
} else if (newQuantity > maxQuantity) {
newQuantity = maxQuantity;
inputElement.value = maxQuantity.toString();
}

cartItems[itemIndex].quantity = newQuantity;
this.cartService.saveCartItems();
}
}

Expand Down Expand Up @@ -170,20 +169,15 @@ export class CartModalComponent implements OnInit, OnDestroy {
}

public cartItemStatus(item: CartItem): any {
// console.log("[cart-modal.component-cartItemStatus] function called");
const itemAvailable = this.cartService.isCartItemAvailableForSale(item);
if (itemAvailable) {
// console.log("[cart-modal.component-cartItemStatus] returning Available, itemAvailable: " + itemAvailable);
return 'Available';
}
// console.log("[cart-modal.component-cartItemStatus] returning Not Available, itemAvailable: " + itemAvailable);
return 'Not Available';
}

private cartItemSaleAvailableQty(item: CartItem): number {
// console.log("[cart-modal.component-cartItemSaleAvailableQty] function called");
const availQty = this.cartService.getAvailableNftQuantity(item);
// console.log("[cart-modal.component] cartItemSaleAvailableQty, qty: " + availQty);
return availQty;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ <h3 nz-typography nzTitle level="4" class="mb-2">Network/Token: {{ group.tokenSy
{{
item.salePrice
| formatToken
: (item.nft?.placeholderNft
? item.collection?.mintingData?.network
: item.nft?.mintingData?.network)
: (item.nft.placeholderNft
? item.collection.mintingData?.network
: item.nft.mintingData?.network)
: true
: true
| async
Expand All @@ -70,9 +70,9 @@ <h3 nz-typography nzTitle level="4" class="mb-2">Network/Token: {{ group.tokenSy
{{
item.quantity * item.salePrice
| formatToken
: (item.nft?.placeholderNft
? item.collection?.mintingData?.network
: item.nft?.mintingData?.network)
: (item.nft.placeholderNft
? item.collection.mintingData?.network
: item.nft.mintingData?.network)
: true
: true
| async
Expand Down
30 changes: 10 additions & 20 deletions src/app/components/cart/services/cart.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ export class CartService {
private notification: NzNotificationService,
private helperService: HelperService,
public auth: AuthService,
) {
// console.log('CartService instance created');
}
) {}

public showCart(): void {
this.showCartSubject.next(true);
Expand Down Expand Up @@ -59,9 +57,7 @@ export class CartService {
` has been added to your cart.`,
'',
);
// console.log('[CartService] NFT added to cart:', cartItem);
} else {
// console.log('[CartService] NFT is already in the cart:', cartItem);
this.notification.error($localize`This NFT already exists in your cart.`, '');
}
}
Expand All @@ -71,7 +67,6 @@ export class CartService {
const updatedCartItems = this.cartItemsSubject.value.filter((item) => item.nft.uid !== itemId);
this.cartItemsSubject.next(updatedCartItems);
this.saveCartItems();
// console.log('[CartService-removeFromCart] Cart updated:', updatedCartItems);
}

public removeItemsFromCart(itemIds: string[]): void {
Expand All @@ -95,33 +90,32 @@ export class CartService {
}

public getCartItems(): BehaviorSubject<CartItem[]> {
// console.log('[CartService] getCartItems function called.');
return this.cartItemsSubject;
}

public updateCartItems(updatedItems: CartItem[]): void {
this.cartItemsSubject.next(updatedItems); // Update the BehaviorSubject with the new cart items
this.saveCartItems(); // Save the updated cart items to local storage or your backend
this.cartItemsSubject.next(updatedItems);
this.saveCartItems();
}

public saveCartItems(): void {
// console.log('[CartService] getCartItems function called.');
setItem(StorageItem.CartItems, this.cartItemsSubject.value);
// console.log('[CartService] Saving cart items to local storage:', this.cartItemsSubject.value);
}

private loadCartItems(): CartItem[] {
// console.log('[CartService] Loading cart items from local storage');
const items = getItem(StorageItem.CartItems) as CartItem[];
// console.log('[CartService] Cart items loaded from local storage:', items);
return items || [];
}

public isNftAvailableForSale(nft: Nft, collection: Collection): boolean {
const isLocked = this.helperService.isLocked(nft, collection, true);
const isOwner = nft.owner === this.auth.member$.value?.uid;

let isOwner = false;
if (nft.owner != null && this.auth.member$.value?.uid != null) {
isOwner = nft.owner === this.auth.member$.value?.uid;
}

const availableForSale = this.helperService.isAvailableForSale(nft, collection);
// console.log(`[cart.service-isNftAvailableForSale] results for NFT ${nft.name}; availableForSale: ${availableForSale}, isLocked: ${isLocked}, isOwner: ${isOwner}`);

return !isLocked && availableForSale && (!isOwner || !nft.owner);
}
Expand All @@ -135,16 +129,12 @@ export class CartService {
cartItem.nft,
cartItem.collection,
);
// console.log("[cart.service-getAvailableNftQuantity] function called for cartItem.nft.name: " + cartItem.nft.name + ", isAvailableForSale: " + isAvailableForSale);

if (cartItem.nft.placeholderNft && isAvailableForSale) {
// console.log("[service-getAvailableNftQuantity] returning qty, placeholder: " + cartItem.nft.placeholderNft + ". availableNfts " + cartItem.collection.availableNfts);
return cartItem.collection.availableNfts || 0;
} else if (isAvailableForSale) {
// console.log("[service-getAvailableNftQuantity] returning 1, isAvailableForSale: " + isAvailableForSale + ". placeholder: " + cartItem.nft.placeholderNft);
return 1;
}
// console.log("[service-getAvailableNftQuantity] returning 0, isAvailableForSale: " + isAvailableForSale + ". placeholder: " + cartItem.nft.placeholderNft);
return 0;
}

Expand Down Expand Up @@ -176,6 +166,6 @@ export class CartService {

public calcPrice(item: CartItem, discount: number): number {
const itemPrice = item.nft?.availablePrice || item.nft?.price || 0;
return this.calc(itemPrice, discount); // assuming calc method applies the discount
return this.calc(itemPrice, discount);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,9 @@
class="text-sm font-medium truncate text-foregrounds-primary dark:text-foregrounds-primary-dark"
>
{{
collection?.floorPrice
? (collection?.floorPrice
| formatToken : collection?.mintingData?.network : false : true : 2
collection.floorPrice
? (collection.floorPrice
| formatToken : collection.mintingData?.network : false : true : 2
| async)
: '-'
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ <h4 nz-typography class="pt-4 mb-1" i18n>Avatar</h4>
[nzValue]="s.value"
>
<nz-avatar
[nzSrc]="nftCache[s.value]?.media"
[nzSrc]="nftCache[s.value].media"
[nzSize]="32"
class="mr-3 border-2 border-foregrounds-tertiary dark:border-foregrounds-tertiary-dark"
nzShape="circle"
Expand All @@ -96,7 +96,7 @@ <h4 nz-typography class="pt-4 mb-1" i18n>Avatar</h4>
<ng-template #selectTpl let-s>
<div class="flex items-center space-x-4">
<nz-avatar
[nzSrc]="nftCache[s.nzValue]?.media"
[nzSrc]="nftCache[s.nzValue].media"
[nzSize]="32"
class="mr-3 border-2 border-foregrounds-tertiary dark:border-foregrounds-tertiary-dark"
nzShape="circle"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ export class NftCheckoutComponent implements OnInit, OnDestroy {
return this._collection;
}

@Input() nftQuantity = 1;

@Output() wenOnClose = new EventEmitter<void>();

public purchasedNft?: Nft | null;
Expand Down Expand Up @@ -156,6 +158,7 @@ export class NftCheckoutComponent implements OnInit, OnDestroy {
) {}

public ngOnInit(): void {
console.log('[nft-checkout] loaded, qty passed in: ', this.nftQuantity);
this.receivedTransactions = false;
const listeningToTransaction: string[] = [];
this.transaction$.pipe(untilDestroyed(this)).subscribe((val) => {
Expand Down
13 changes: 12 additions & 1 deletion src/app/pages/collection/pages/collection/collection.page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,15 @@ import {
RANKING_TEST,
} from '@build-5/interfaces';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { BehaviorSubject, first, firstValueFrom, skip, Subscription } from 'rxjs';
import {
Subject,
BehaviorSubject,
first,
firstValueFrom,
skip,
Subscription,
takeUntil,
} from 'rxjs';
import { DataService } from '../../services/data.service';
import { NotificationService } from './../../../../@core/services/notification/notification.service';

Expand All @@ -51,6 +59,7 @@ export class CollectionPage implements OnInit, OnDestroy {
private guardiansSubscription$?: Subscription;
private guardiansRankModeratorSubscription$?: Subscription;
private subscriptions$: Subscription[] = [];
private destroy$ = new Subject<void>();

constructor(
public deviceService: DeviceService,
Expand Down Expand Up @@ -309,6 +318,8 @@ export class CollectionPage implements OnInit, OnDestroy {
public ngOnDestroy(): void {
this.cancelSubscriptions();
this.guardiansSubscription$?.unsubscribe();
this.destroy$.next();
this.destroy$.complete();
}

public get networkTypes(): typeof Network {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ export class CollectionNftStateService {
}

private updateAvailableNftsCount(nfts: Nft[], collection: Collection) {
console.log(
'[collectionNfts.service-updateAvailableNftsCount] function called with (nfts, collection): ',
nfts,
collection,
);
const availableNftsCount = nfts.filter((nft) =>
this.cartService.isNftAvailableForSale(nft, collection),
).length;
Expand Down
Loading

0 comments on commit cc0aa93

Please sign in to comment.