Skip to content

EllysonAlves/TiConvida

Repository files navigation

TiConvida - Referral Program Web App

A complete referral web application built with React + Vite + TypeScript, designed to manage customer referrals and rewards. Currently runs with a fully functional local mock API, ready for IXCSoft integration.

🚀 Features

Current Implementation (Mock API)

  • User Authentication - Register & Login with client/admin roles
  • Referral Management - Create, track, and manage referrals
  • Reward System - Automatic reward generation on approved referrals
  • User Dashboard - View personal referrals and earned rewards
  • Admin Dashboard - Manage all referrals, approve/reject, export to CSV
  • Responsive Design - Mobile-first with Tailwind CSS
  • Form Validation - React Hook Form + Zod schemas
  • State Management - Zustand for auth + React Query for data
  • Toast Notifications - User-friendly success/error messages
  • Accessibility - ARIA labels, keyboard navigation, focus management
  • Testing - Vitest + Testing Library with example tests

Ready for Integration

  • 🔌 IXCSoft Service - Placeholder functions with detailed TODO comments
  • 🔌 Environment Config - .env support for API endpoints and tokens
  • 🔌 Clear Integration Points - Marked with // TODO: INTEGRAR IXCSoft AQUI

📦 Tech Stack

Category Technology
Framework React 18 + Vite 5
Language TypeScript 5
Routing React Router DOM 6
State Management Zustand 4
Data Fetching TanStack Query (React Query) 5
Forms React Hook Form 7 + Zod 3
Styling Tailwind CSS 3
HTTP Client Axios 1
Testing Vitest + Testing Library
Code Quality ESLint + Prettier

🛠️ Getting Started

Prerequisites

  • Node.js 18+ and npm/pnpm/yarn

Installation

# Install dependencies
npm install

# Create environment file (optional for now)
cp .env.example .env

# Start development server
npm run dev

The app will open at http://localhost:5173

Available Scripts

npm run dev        # Start dev server
npm run build      # Build for production
npm run preview    # Preview production build
npm run test       # Run tests
npm run test:ui    # Run tests with UI
npm run lint       # Lint code
npm run format     # Format code with Prettier

👤 Demo Users (Mock Data)

Regular Client User

  • Email: joao@example.com
  • Password: joao@example.com (same as email)
  • Can: Make referrals, view dashboard

Admin User

  • Email: admin@ticonvida.com
  • Password: admin@ticonvida.com
  • Can: Access admin dashboard, approve/reject referrals, export CSV

Note: In the mock implementation, password = email for simplicity


📂 Project Structure

TiConvida/
├── src/
│   ├── components/          # Reusable UI components
│   │   ├── Header.tsx
│   │   ├── Footer.tsx
│   │   ├── ProtectedRoute.tsx
│   │   ├── ReferralForm.tsx
│   │   ├── ReferralList.tsx
│   │   ├── RewardCard.tsx
│   │   └── Toast/
│   │       ├── ToastContainer.tsx
│   │       └── useToast.ts
│   ├── hooks/               # Custom React hooks
│   │   ├── useAuth.ts
│   │   ├── useReferrals.ts
│   │   └── useRewards.ts
│   ├── routes/              # Page components
│   │   ├── Landing.tsx
│   │   ├── NotFound.tsx
│   │   ├── Auth/
│   │   │   ├── Login.tsx
│   │   │   └── Register.tsx
│   │   └── Dashboard/
│   │       ├── UserDashboard.tsx
│   │       └── AdminDashboard.tsx
│   ├── services/            # API and service layers
│   │   ├── api.ts           # Axios instance
│   │   ├── mockApi.ts       # In-memory mock API
│   │   └── ixcService.ts    # IXCSoft integration placeholders
│   ├── store/               # Zustand stores
│   │   └── authStore.ts
│   ├── types/               # TypeScript type definitions
│   │   ├── User.ts
│   │   ├── Referral.ts
│   │   ├── Reward.ts
│   │   └── index.ts
│   ├── utils/               # Utility functions
│   │   ├── dateFormat.ts
│   │   ├── csvExport.ts
│   │   └── index.ts
│   ├── tests/               # Test files
│   │   ├── setup.ts
│   │   ├── ReferralForm.test.ts
│   │   └── referralFlow.test.ts
│   ├── App.tsx              # Main app component
│   ├── main.tsx             # App entry point
│   ├── index.css            # Tailwind + custom styles
│   └── vite-env.d.ts        # Vite environment types
├── index.html
├── package.json
├── vite.config.ts
├── tsconfig.json
├── tailwind.config.js
├── .eslintrc.cjs
├── .prettierrc
└── README.md

🔗 IXCSoft Integration Guide

The application is structured to facilitate IXCSoft integration. All integration points are clearly marked with comments.

Integration Points

1. Customer Verification (src/services/ixcService.ts)

export async function verifyCustomer(email: string, phone?: string)

When to call: During user registration when isClient=true

Purpose: Verify if the user exists in IXCSoft system

Expected IXCSoft Endpoint: GET /cliente?email={email}

Implementation location: src/services/mockApi.tsmockAuthApi.register()

TODO comment marker:

// TODO: INTEGRAR IXCSoft AQUI
// Se isClient=true, verificar se o email/telefone existe na base IXCSoft

2. Reward Application (src/services/ixcService.ts)

export async function applyReward(payload: ApplyRewardPayload)

When to call: When admin approves a referral

Purpose: Apply credit/discount to customer's account

Expected IXCSoft Endpoint: POST /financeiro/credito or POST /cliente/aplicar_desconto

Implementation location: src/services/mockApi.tsmockReferralsApi.updateStatus()

TODO comment marker:

// TODO: INTEGRAR IXCSoft AQUI - Aplicar recompensa no sistema IXC

3. Contract Creation (src/services/ixcService.ts)

export async function createContract(payload: CreateContractPayload)

When to call: When a referred friend signs up as a new customer

Purpose: Create new customer contract in IXCSoft

Expected IXCSoft Endpoint: POST /cliente or POST /contrato/novo

Future implementation: Add a new customer signup flow


Environment Configuration

Create a .env file with your IXCSoft credentials:

VITE_IXCSOFT_API_URL=https://seu-sistema.ixcsoft.com.br/webservice/v1
VITE_IXCSOFT_API_TOKEN=your-api-token-here

Integration Steps

  1. Uncomment IXCSoft functions in src/services/ixcService.ts
  2. Replace mock calls with real IXCSoft service calls:
    • Find // TODO: INTEGRAR IXCSoft AQUI comments
    • Import and call ixcService functions
  3. Configure authentication headers in ixcService.ts
  4. Test with IXCSoft sandbox environment first
  5. Handle errors and add proper error messages
  6. Update reward logic based on actual IXCSoft response

Example Integration

Before (Mock):

// src/services/mockApi.ts
register: async (data: RegisterData): Promise<AuthUser> => {
  // ...
  let ixcsId: string | undefined = undefined;
  if (data.isClient) {
    // Simulate IXC verification
    ixcsId = `IXC-${Math.floor(Math.random() * 100000)}`;
  }
  // ...
}

After (Real IXCSoft):

import { ixcService } from './ixcService';

register: async (data: RegisterData): Promise<AuthUser> => {
  // ...
  let ixcsId: string | undefined = undefined;
  if (data.isClient) {
    const verification = await ixcService.verifyCustomer(data.email, data.phone);
    if (verification.exists) {
      ixcsId = verification.ixcsId;
    } else {
      throw new Error('Cliente não encontrado no sistema IXCSoft');
    }
  }
  // ...
}

🧪 Testing

Run Tests

npm run test        # Run all tests
npm run test:ui     # Open Vitest UI

Included Tests

  1. Unit Tests - ReferralForm.test.ts

    • Validates Zod schema for referral form
    • Tests field validations (name, email, message length)
  2. Integration Tests - referralFlow.test.ts

    • Complete referral creation flow
    • Referral status updates (approve/reject)
    • Automatic reward creation on approval
    • User referral retrieval

Adding More Tests

Create test files in src/tests/ following the naming convention *.test.ts or *.test.tsx.


🎨 Customization

Branding Colors

Edit tailwind.config.js to change primary colors:

colors: {
  primary: {
    50: '#eff6ff',
    // ... customize your brand colors
    900: '#1e3a8a',
  },
}

Reward Types

Add new reward types in src/types/Reward.ts:

export type RewardType = 'free_month' | 'voucher' | 'discount' | 'your_new_type';

Then update the UI components (RewardCard.tsx) accordingly.


🚧 Roadmap / Future Enhancements

  • Complete IXCSoft integration
  • Email notifications for referrals
  • Referral link generation (shareable URLs)
  • Social media sharing integration
  • Analytics dashboard
  • Multi-language support (i18n)
  • Dark mode
  • Progressive Web App (PWA) support
  • Advanced admin reporting
  • Referral tier system (gamification)

📝 License

This project is private and proprietary.


🤝 Contributing

This is a private project. Contact the development team for contribution guidelines.


📞 Support

For questions or issues:


✨ Key Implementation Notes

Authentication Flow

  1. User registers → useRegister() hook
  2. On successful registration, auth token stored in localStorage
  3. Zustand store (authStore) manages auth state globally
  4. Protected routes use <ProtectedRoute> wrapper

Referral Flow

  1. User submits referral form → ReferralForm component
  2. Form validation with Zod → useCreateReferral() hook
  3. Mock API creates referral with pending status
  4. Admin approves via Admin Dashboard → useUpdateReferralStatus()
  5. On approval, reward automatically created and linked to user

Data Fetching Pattern

  • React Query handles all server state
  • Query keys defined in hooks (referralKeys, rewardKeys)
  • Automatic refetching and cache invalidation
  • Loading and error states managed by hooks

Mock API Design

  • In-memory data storage (arrays)
  • Simulates network delay (500ms)
  • Pre-seeded with 2 users and 3 referrals
  • Fully functional without backend

Built with ❤️ for TiConvida

About

Aplicação web para programa de indicações e convites, desenvolvida com TypeScript.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages