Skip to main content

Overview

PixelTech customer accounts provide a personalized shopping experience with real-time profile synchronization, saved address management, complete order history, and warranty tracking.

Account Creation

Registration Flow

1

Access Registration

Customer clicks “Register” or is prompted during checkout
2

Enter Credentials

  • Email address (used as username)
  • Password (minimum requirements enforced)
  • Optional: Full name during registration
3

Firebase Authentication

System creates account via Firebase Auth
4

User Document Created

Firestore document created at /users/{userId} with basic structure
5

Automatic Login

Customer automatically logged in after registration

Login Experience

Email & Password
  1. Customer enters email and password
  2. Firebase Auth validates credentials
  3. Session token generated
  4. Redirect to original destination or homepage

Profile Management

Profile Information

Customers can view and edit:

Personal Details

  • Full name
  • Document number (ID)
  • Birthdate
  • Contact phone

Account Info

  • Email address (read-only)
  • Account creation date
  • Last login information

Real-Time Profile Sync

How It Works
function initUserRealtimeSync() {
  // 1. Load from cache for instant display
  const cachedProfile = sessionStorage.getItem('pixeltech_user_profile');
  if (cachedProfile) {
    fillProfileForm(JSON.parse(cachedProfile));
  }
  
  // 2. Start real-time listener
  unsubscribeUser = onSnapshot(doc(db, "users", currentUserId), (snap) => {
    const freshData = snap.data();
    // Only update if data actually changed
    if (JSON.stringify(userProfileData) !== JSON.stringify(freshData)) {
      sessionStorage.setItem('pixeltech_user_profile', JSON.stringify(freshData));
      fillProfileForm(freshData);
    }
  });
}
Benefits
  • Instant Load: Profile displays immediately from cache
  • Auto-Sync: Changes made on another device appear instantly
  • Conflict Prevention: Real-time sync prevents overwriting recent changes
  • Smart Updates: Only updates form fields that user isn’t currently editing

Editing Profile

1

Customer Opens Profile

Navigate to /profile.html
2

Profile Loads

Data appears instantly from sessionStorage cache
3

Background Sync Starts

onSnapshot connection established to Firebase
4

Customer Edits Fields

Form fields are editable (except email)
5

Save Changes

Click “Save Changes” button
6

Firebase Update

await updateDoc(doc(db, "users", userId), {
  name: newName,
  document: newDocument,
  phone: newPhone,
  birthdate: newBirthdate,
  updatedAt: new Date()
});
7

Automatic UI Update

onSnapshot receives change and confirms update in UI
The system checks if user is actively typing in a field before auto-updating it. This prevents the frustrating experience of having your input overwritten.

Address Management

Saved Addresses

Customers can save multiple delivery addresses with the following features:

Address Properties

  • Alias (e.g., “Home”, “Office”, “Mom’s House”)
  • Full address (street, building, apartment)
  • Department (state/province)
  • City (from Colombia API)
  • Postal code (optional)
  • Delivery notes (e.g., “Ring bell twice”, “Leave with doorman”)
  • Default flag (star indicator ★)

Adding a New Address

1

Open Address Modal

Click ”+ New Address” button on profile page
2

Enter Alias

Name the address (e.g., “Home”, “Work”)
3

Search Department

Type department name (autocomplete with Colombia API)
4

Select Department

Click matching department from dropdown
5

Search City

Cities load for selected department, type to filter
6

Select City

Click matching city
7

Enter Address Details

  • Street address
  • Postal code (optional)
  • Delivery notes (optional)
8

Set as Default (Optional)

Check “Make this my default address”
9

Save Address

await updateDoc(doc(db, "users", userId), {
  addresses: arrayUnion(newAddress)
});

Address List Display

┌────────────────────────────────────┐
│  ⭐ HOME (Default)                │
│  Cra 15 #123-45 Apt 301           │
│  Bogotá, Cundinamarca             │
│  "Ring bell twice"                │
│                    [Edit] [Delete] │
└────────────────────────────────────┘

┌────────────────────────────────────┐
│  📍 OFFICE                         │
│  Cl 100 #8-55 Torre B Piso 12     │
│  Bogotá, Cundinamarca             │
│  "Security desk on 1st floor"     │
│                    [Edit] [Delete] │
└────────────────────────────────────┘

Editing Addresses

  1. Click Edit Button: Opens modal with pre-filled data
  2. Modify Fields: Change any information
  3. Save Changes: Updates address in Firebase
  4. Real-Time Update: Address list updates automatically via onSnapshot
If you edit the default address, it remains default. To change default address, edit a different address and check “Make this my default.”

Deleting Addresses

window.deleteAddress = async (index) => {
  if (!confirm("Delete this address?")) return;
  
  let currentAddresses = [...addressesCache];
  currentAddresses.splice(index, 1); // Remove address
  
  await updateDoc(doc(db, "users", userId), {
    addresses: currentAddresses
  });
  
  // onSnapshot automatically updates UI
};

Colombia API Integration

Address system uses Colombia’s official geographic API: Department Autocomplete
const response = await fetch('https://api-colombia.com/api/v1/Department');
const departments = await response.json();
// Returns: [{ id: 1, name: "Cundinamarca" }, ...]
City Autocomplete
const response = await fetch(`https://api-colombia.com/api/v1/Department/${deptId}/cities`);
const cities = await response.json();
// Returns cities for selected department
This ensures address data is standardized and reduces shipping errors from typos.

Order History

Viewing Order History

The profile page displays customer’s complete order history with:
  • Last 10 orders initially (load more button for older orders)
  • Real-time status updates (as admin processes orders)
  • Persistent caching (orders cached locally per user)
  • Delta synchronization (only new/changed orders downloaded)

Order History Sync

Smart Caching Strategy
function initOrdersRealtimeSync() {
  // 1. Load orders from localStorage cache
  const cachedRaw = localStorage.getItem('pixeltech_user_orders');
  if (cachedRaw) {
    const parsed = JSON.parse(cachedRaw);
    ordersCache = Object.values(parsed.map);
    renderOrdersList(ordersCache);
  }
  
  // 2. Determine if first load or delta update
  let query;
  if (lastSyncTime === 0) {
    // First load: get all orders
    query = query(ordersRef, 
      where("userId", "==", userId),
      orderBy("createdAt", "desc")
    );
  } else {
    // Return visit: only get updated orders
    query = query(ordersRef,
      where("userId", "==", userId),
      where("updatedAt", ">", new Date(lastSyncTime))
    );
  }
  
  // 3. Real-time listener
  unsubscribeOrders = onSnapshot(query, (snapshot) => {
    // Process only changed documents
    snapshot.docChanges().forEach(change => {
      if (change.type === 'added' || change.type === 'modified') {
        updateOrderInCache(change.doc.data());
      }
    });
  });
}

Order Card Display

Each order in history shows:

Order Card Layout

  • Order ID badge (e.g., “ORDER #AB12”)
  • Status badge with color-coding:
    • 🔶 Yellow: Pending Payment
    • 🔵 Blue: Confirmed/Paid
    • 🟣 Purple: Being Prepared
    • 🔷 Cyan: Dispatched/En Route
    • 🟢 Green: Delivered
    • 🔴 Red: Cancelled
  • Order date (e.g., “March 5, 2024”)
  • Item count (e.g., “3 products”)
  • Total amount (large, bold)
  • Arrow indicator (hover shows full details)

Filtering Orders

Complete HistoryShows every order the customer has ever placed, sorted newest first.

Order Status Timeline

Status badges use consistent color scheme across platform:
function getStatusConfig(status) {
  if (status === 'PENDIENTE_PAGO') 
    return { color: "yellow", icon: "clock", label: "Pending Payment" };
  if (['PAGADO', 'CONFIRMADO'].includes(status))
    return { color: "blue", icon: "check-circle", label: "Confirmed" };
  if (status === 'ALISTAMIENTO')
    return { color: "purple", icon: "box-open", label: "Preparing" };
  if (['DESPACHADO', 'EN_RUTA'].includes(status))
    return { color: "cyan", icon: "truck-fast", label: "En Route" };
  if (status === 'ENTREGADO')
    return { color: "emerald", icon: "house-check", label: "Delivered" };
  if (status === 'CANCELADO')
    return { color: "red", icon: "ban", label: "Cancelled" };
}

Session Management

Active Session Features

Persistent Login

Sessions persist across browser tabs and page reloads

Automatic Refresh

Firebase tokens automatically refresh before expiring

Cross-Device Sync

Profile changes sync between all logged-in devices

Secure Storage

Sensitive data stored in Firebase Auth, not localStorage

Logout Process

logoutBtn.addEventListener('click', async () => {
  if (confirm("Log out?")) {
    // 1. Clean up real-time listeners
    if (unsubscribeOrders) unsubscribeOrders();
    if (unsubscribeUser) unsubscribeUser();
    
    // 2. Sign out from Firebase
    await signOut(auth);
    
    // 3. Clear all cached data
    sessionStorage.clear();
    localStorage.removeItem('pixeltech_user_orders');
    
    // 4. Redirect to homepage
    window.location.href = "/index.html";
  }
});
Logging out clears all session data. However, the product catalog cache remains (it’s not user-specific).

Account Security

Password Reset

Customers can reset forgotten passwords:
  1. Click “Forgot Password” on login page
  2. Enter email address
  3. Firebase sends password reset email
  4. Customer clicks link in email
  5. Creates new password
  6. Automatically logged in

Data Privacy

Customer data handling:
  • Firebase Auth: Email/password secured by Google infrastructure
  • Firestore Rules: Users can only read/write their own data
  • No Public Exposure: User documents protected by security rules
  • HTTPS Only: All data transmitted over secure connections

Profile Completion

Automatic Profile Building

Profile gets completed automatically during checkout:
Minimal Profile
{
  "email": "[email protected]",
  "createdAt": "2024-03-05",
  "addresses": []
}
This approach reduces friction during registration while ensuring complete profiles after first purchase.

Shopping Cart

How addresses are used during checkout

Order Tracking

View and track orders from profile

Build docs developers (and LLMs) love