Skip to content

Commit

Permalink
remove taxes and tax calculation from app
Browse files Browse the repository at this point in the history
  • Loading branch information
ripgrim committed Sep 29, 2024
1 parent c31824a commit 0b67698
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 105 deletions.
23 changes: 4 additions & 19 deletions src/app/cart/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,18 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { ConfirmationModal } from "@/components/ConfirmationModal"
import { LinearBlur } from "progressive-blur"
import { useToast } from "@/hooks/use-toast"
import { ToastAction } from "@/components/ui/toast"
import LottieTrash from "@/components/LottieTrash"
import LottieArrow from "@/components/LottieArrow"
import ShinyGrid from "@/components/ui/ShinyGrid"
import TextTransition, { presets } from "react-text-transition";
import CartCard from "@/components/cart/CartCard";
import { useCart } from '@/app/cart/src/hooks/useCart';
import { formatNumber } from '@/app/cart/src/hooks/cartUtils';
import { Plus, Share2 } from "lucide-react"
import TwinklingGrid from "@/components/ui/TwinklingGrid"
import { TaxRegion } from "@/helpers/taxes"; // Add this import
import { GroceryItem } from '@/app/cart/src/hooks/useCart'; // Add this import
import { GroceryItem } from '@/app/cart/src/hooks/useCart';

interface CartCardProps {
item: GroceryItem;
taxRegion: TaxRegion | null;
formatNumber: (num: number | null | undefined) => string;
removeItem: (id: number) => void;
updateItemQuantity: (id: number, quantity: number) => void;
Expand All @@ -36,7 +32,6 @@ function CartContent() {
const { toast } = useToast()
const {
items,
selectedState,
newItemName,
newItemPrice,
addItem,
Expand All @@ -46,10 +41,7 @@ function CartContent() {
clearCart,
setNewItemName,
setNewItemPrice,
setSelectedState,
taxRate,
subtotal,
taxAmount,
} = useCart();

const [backModalOpen, setBackModalOpen] = useState(false)
Expand All @@ -63,8 +55,6 @@ function CartContent() {
const [isItemChanged, setIsItemChanged] = useState(false);
const [totalChanged, setTotalChanged] = useState(false);

const total = subtotal + taxAmount;

const handleItemNameKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
e.preventDefault();
Expand Down Expand Up @@ -148,7 +138,7 @@ function CartContent() {
}

if (isItemChanged) {
const newTotal = subtotal + taxAmount;
const newTotal = subtotal;
if (newTotal !== previousTotal) {
setTotalChanged(true);
if (newTotal > previousTotal) {
Expand All @@ -171,7 +161,7 @@ function CartContent() {
setIsItemChanged(false);
}
}
}, [isItemChanged, subtotal, taxAmount, previousTotal]);
}, [isItemChanged, subtotal, previousTotal]);

return (
<div className="min-h-screen bg-transparent flex flex-col relative z-10">
Expand Down Expand Up @@ -221,7 +211,6 @@ function CartContent() {
<CartCard
key={item.id}
item={item}
taxRegion={selectedState}
formatNumber={formatNumber}
removeItem={(id) => {
removeItem(id);
Expand Down Expand Up @@ -255,14 +244,10 @@ function CartContent() {
/>
<div className="px-4 bg-black">
<div className="flex flex-col py-2 mb-2 w-full">
<div className="flex justify-between items-center">
<span className="text-sm text-white">Subtotal:</span>
<span className="text-white">{formatNumber(subtotal)} USD</span>
</div>
<div className="flex justify-between items-center mt-1">
<span className="text-lg font-bold text-white">Total:</span>
<TextTransition springConfig={presets.gentle} direction={transitionDirection} inline={true} className={`text-lg font-bold ${totalChanged ? transitionColor : 'text-white'}`}>
{formatNumber(total)} USD
{formatNumber(subtotal)} USD
</TextTransition>
</div>
<form onSubmit={handleSubmit} className="flex flex-col space-y-2 pb-4 w-full">
Expand Down
40 changes: 10 additions & 30 deletions src/app/cart/src/hooks/cartUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,48 +7,28 @@ export const formatNumber = (num: number | null | undefined): string => {

export const encodeData = (data: SharedData): string => {
const itemsString = data.items.map(item => `${item.name}:${item.price}:${item.quantity}`).join(';');
const countryString = data.countryCode ? `C:${data.countryCode}` : '';
const regionString = data.region ? `R:${data.region}` : '';
return [itemsString, countryString, regionString].filter(Boolean).join(';');
return itemsString;
};

export const decodeData = (encodedData: string): SharedData => {
const parts = encodedData.split(';');
const items: GroceryItem[] = [];
let countryCode: string | null = null;
let region: string | null = null;

parts.forEach(part => {
if (part.startsWith('C:')) {
countryCode = part.slice(2);
} else if (part.startsWith('R:')) {
region = part.slice(2);
} else {
const [name, price, quantity] = part.split(':');
items.push({
id: Date.now() + Math.random(),
name,
price: parseFloat(price),
quantity: parseInt(quantity, 10)
});
}
const items: GroceryItem[] = parts.map(part => {
const [name, price, quantity] = part.split(':');
return {
id: Date.now() + Math.random(),
name,
price: parseFloat(price),
quantity: parseInt(quantity, 10)
};
});

return { items, countryCode, region };
return { items };
};

export const calculateSubtotal = (items: GroceryItem[]): number => {
return items.reduce((total, item) => total + item.price * item.quantity, 0);
};

export const calculateTax = (subtotal: number, taxRate: number): number => {
return subtotal * (taxRate / 100);
};

export const calculateTotal = (subtotal: number, taxAmount: number): number => {
return subtotal + taxAmount;
};

export const roundToTwoDecimals = (num: number): number => {
return Math.round((num + Number.EPSILON) * 100) / 100;
};
42 changes: 2 additions & 40 deletions src/app/cart/src/hooks/useCart.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useEffect, useReducer } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { useToast } from "@/hooks/use-toast";
import { usStates, TaxRegion } from "@/helpers/taxes";
import { encodeData, decodeData } from './cartUtils';
import { SharedData as EncodedSharedData } from '../types/cart';

Expand All @@ -14,12 +13,10 @@ export interface GroceryItem {

interface SharedData {
items: GroceryItem[];
stateName: string | null;
}

interface CartState {
items: GroceryItem[];
selectedState: TaxRegion | null;
newItemName: string;
newItemPrice: string;
}
Expand All @@ -29,14 +26,12 @@ type CartAction =
| { type: 'ADD_ITEM'; payload: GroceryItem }
| { type: 'REMOVE_ITEM'; payload: number }
| { type: 'UPDATE_ITEM_QUANTITY'; payload: { id: number; quantity: number } }
| { type: 'SET_STATE'; payload: TaxRegion | null }
| { type: 'SET_NEW_ITEM_NAME'; payload: string }
| { type: 'SET_NEW_ITEM_PRICE'; payload: string }
| { type: 'CLEAR_CART' };

const initialState: CartState = {
items: [],
selectedState: null,
newItemName: "",
newItemPrice: "",
};
Expand All @@ -56,8 +51,6 @@ function cartReducer(state: CartState, action: CartAction): CartState {
item.id === action.payload.id ? { ...item, quantity: action.payload.quantity } : item
)
};
case 'SET_STATE':
return { ...state, selectedState: action.payload };
case 'SET_NEW_ITEM_NAME':
return { ...state, newItemName: action.payload };
case 'SET_NEW_ITEM_PRICE':
Expand Down Expand Up @@ -90,10 +83,6 @@ export function useCart() {
console.error('[useCart] Error parsing stored cart items:', error);
}
}
const storedState = localStorage.getItem('selectedState');
if (storedState) {
dispatch({ type: 'SET_STATE', payload: JSON.parse(storedState) });
}
};

console.log('[useCart] Loading data from localStorage');
Expand All @@ -105,10 +94,6 @@ export function useCart() {
if (data) {
const decodedData = decodeData(data) as EncodedSharedData;
dispatch({ type: 'SET_ITEMS', payload: decodedData.items });
if (decodedData.region) {
const state = usStates.find(s => s.name === decodedData.region);
if (state) dispatch({ type: 'SET_STATE', payload: state });
}
}
}
}, [searchParams]);
Expand All @@ -120,12 +105,6 @@ export function useCart() {
}
}, [state.items]);

useEffect(() => {
if (state.selectedState) {
localStorage.setItem('selectedState', JSON.stringify(state.selectedState));
}
}, [state.selectedState]);

const addItem = (name: string, price: number) => {
const newItem: GroceryItem = {
id: Date.now(),
Expand Down Expand Up @@ -156,17 +135,10 @@ export function useCart() {

const handleShare = async () => {
const sharedData: SharedData = {
items: state.items,
stateName: state.selectedState?.name || null
items: state.items
};

const encodedData: EncodedSharedData = {
items: sharedData.items,
countryCode: 'US', // Hardcoded for US
region: sharedData.stateName || ''
};

const encodedString = encodeData(encodedData);
const encodedString = encodeData(sharedData);
// ... rest of the function
};

Expand Down Expand Up @@ -199,14 +171,7 @@ export function useCart() {
dispatch({ type: 'SET_NEW_ITEM_PRICE', payload: price });
};

const setSelectedState = (stateName: string) => {
const newState = usStates.find(state => state.name === stateName) || null;
dispatch({ type: 'SET_STATE', payload: newState });
};

const taxRate = state.selectedState?.taxRate || 0;
const subtotal = state.items.reduce((sum, item) => sum + item.price * item.quantity, 0);
const taxAmount = subtotal * (taxRate / 100);

return {
...state,
Expand All @@ -217,11 +182,8 @@ export function useCart() {
clearCart,
setNewItemName,
setNewItemPrice,
setSelectedState,
setBackConfirmed,
getBackConfirmed,
taxRate,
subtotal,
taxAmount,
};
}
13 changes: 0 additions & 13 deletions src/app/cart/src/types/cart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,4 @@ export interface GroceryItem {

export interface SharedData {
items: GroceryItem[];
countryCode: string | null;
region: string | null;
}

export interface Country {
code: string;
name: string;
regions: TaxRegion[];
}

export interface TaxRegion {
name: string;
rate: number;
}
3 changes: 0 additions & 3 deletions src/components/cart/CartCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Plus, Minus } from "lucide-react";
import SwipeableCard from "@/components/ui/SwipeableCard";
import { TaxRegion } from "@/helpers/taxes";

interface GroceryItem {
id: number;
Expand All @@ -14,7 +13,6 @@ interface GroceryItem {

interface CartCardProps {
item: GroceryItem;
taxRegion: TaxRegion | null;
formatNumber: (num: number) => string;
removeItem: (id: number) => void;
updateItemQuantity: (id: number, quantity: number) => void;
Expand All @@ -23,7 +21,6 @@ interface CartCardProps {

const CartCard: React.FC<CartCardProps> = ({
item,
taxRegion,
formatNumber,
removeItem,
updateItemQuantity,
Expand Down

0 comments on commit 0b67698

Please sign in to comment.