1.2.27 • Published 5 months ago

greencode-saas-factory v1.2.27

Weekly downloads
-
License
-
Repository
-
Last release
5 months ago

Greencode SaaS Factory Documentation

A comprehensive toolkit for rapidly building SaaS applications with React, Firebase, and Redux.

Installation

npm install greencode-saas-factory

Core Features

1. Authentication Component

A fully customizable authentication component that handles:

  • Login
  • Signup
  • Password Reset
  • Custom signup fields
import { Authentication } from 'greencode-saas-factory';

function App() {
  return (
    <Authentication
      onLogin={async (email, password) => {
        // Handle login
      }}
      onSignup={async (email, password, data) => {
        // Handle signup
      }}
      onForgotPassword={async (email) => {
        // Handle password reset
      }}
      // Customization options
      logo={<YourLogo />}
      headerText="Welcome"
      customSignupFields={[
        {
          key: "company",
          label: "Company Name",
          type: "text",
          placeholder: "Enter company name"
        }
      ]}
      // Feature flags
      showLogin={true}
      showSignup={true}
      showForgotPassword={true}
    />
  );
}

2. Firebase Data Services

Normalized Service

Handles individual documents with optimal querying and caching:

import { NormalizedService } from 'greencode-saas-factory';

// Initialize
const userService = new NormalizedService(firestore, 'users');

// CRUD Operations
await userService.create({ name: 'John', email: 'john@example.com' });
await userService.getById('userId');
await userService.update('userId', { name: 'John Doe' });
await userService.delete('userId');

// Advanced Querying
await userService.getAll({
  where: [{ field: 'status', operator: '==', value: 'active' }],
  orderBy: [{ field: 'createdAt', direction: 'desc' }],
  limitTo: 10
});

Denormalized Service

Handles collections with array-based storage (optimal for bulk operations):

import { DenormalizedService } from 'greencode-saas-factory';

// Initialize
const service = new DenormalizedService(firebaseConfig);

// Array Operations
await service.setDocument('collection', 'docId', items);
await service.addItem('collection', newItem);
await service.updateItem('collection', 'docId', 'itemId', updates);
await service.deleteItem('collection', 'docId', 'itemId');

// Querying
await service.queryDocuments('collection', {
  filters: [{ field: 'status', operator: '==', value: 'active' }],
  limit: 10
});

3. Redux Integration

Pre-configured Redux slices for common SaaS functionalities:

Authentication State

import { 
  loginStart, 
  loginSuccess, 
  loginFailure,
  selectUser,
  selectIsAuthenticated 
} from 'greencode-saas-factory';

// Dispatch actions
dispatch(loginStart());
dispatch(loginSuccess(userData));
dispatch(loginFailure(error));

// Select state
const user = useSelector(selectUser);
const isAuthenticated = useSelector(selectIsAuthenticated);

Data Management

import { 
  fetchStart,
  fetchSuccess,
  fetchFailure,
  selectData
} from 'greencode-saas-factory';

// Dispatch actions
dispatch(fetchStart());
dispatch(fetchSuccess(data));
dispatch(fetchFailure(error));

// Select state
const data = useSelector(selectData);

Form Management

import {
  setFormData,
  clearFormData,
  setFormError,
  selectFormData,
  selectFormErrors
} from 'greencode-saas-factory';

// Dispatch actions
dispatch(setFormData({ field: value }));
dispatch(setFormError({ field: 'error message' }));

// Select state
const formData = useSelector(selectFormData);
const formErrors = useSelector(selectFormErrors);

UI State

import {
  openModal,
  closeModal,
  showNotification,
  selectModalOpen,
  selectNotification
} from 'greencode-saas-factory';

// Dispatch actions
dispatch(openModal('modalName'));
dispatch(showNotification({ message: 'Success!', type: 'success' }));

// Select state
const isModalOpen = useSelector(selectModalOpen);
const notification = useSelector(selectNotification);

Theme Support

Customize your application's theme:

import { getTheme } from 'greencode-saas-factory';

// Get default theme or customize
const theme = getTheme({
  // Your theme overrides
});

Best Practices

  1. Data Structure: Choose between NormalizedService and DenormalizedService based on your data needs:

    • Use NormalizedService for individual documents with complex queries
    • Use DenormalizedService for bulk operations and array-based storage
  2. State Management: Utilize the provided Redux slices for consistent state management across your application

  3. Authentication: Leverage the Authentication component's customization options to match your brand and requirements

  4. Performance: Both services include built-in caching and optimization strategies for better performance

This package provides a solid foundation for building modern SaaS applications with React and Firebase, handling common concerns like authentication, data management, and state management out of the box.

UI

1. Core Components

1.1 CrudForm

A dynamic form component with validation, history, and security features.

interface CrudFormProps<T> {
  fields: FormField<T>[];
  onSubmit: (values: T) => Promise<void>;
  crud: UseCrudReturn<T>;
  csrfToken: string;
  enableHistory?: boolean;
  // ... other props
}

// Usage
<CrudForm<User>
  fields={[
    {
      name: 'email',
      type: 'email',
      validation: [{
        test: (v) => /@company\.com$/.test(v),
        message: "Company email required"
      }]
    }
  ]}
  onSubmit={handleSubmit}
  crud={crud}
  csrfToken={csrfToken}
/>

Key Features:

  • Input sanitization & XSS protection
  • Cross-field dependency management
  • Undo/redo history stack
  • CSRF token validation
  • Zod schema integration
  • Error boundaries & accessibility

1.2 CrudTable

Virtualized table with enterprise-grade features.

interface CrudTableProps<D> {
  columns: Array<CustomColumn<D>>;
  data: D[];
  serverSideTotal: number;
  userRole?: string;
  // ... other props
}

// Usage
<CrudTable<User>
  columns={[
    {
      Header: 'Name',
      accessor: 'name',
      permission: 'admin',
      filter: 'text'
    }
  ]}
  data={users}
  serverSideTotal={1000}
  userRole="admin"
/>

Key Features:

  • Virtualized rendering with react-window
  • Role-based column permissions
  • Server-side pagination
  • Customizable filters
  • Row selection & batch operations
  • Audit logging integration

1.3 CrudModal

Animated modal system with security tracking.

<CrudModal
  isOpen={isOpen}
  onClose={close}
  mode="delete"
  title="Confirm Deletion"
  contentSecurityPolicy="default-src 'self'"
  onOpenTrack={analytics.trackModalOpen}
>
  <DeleteConfirmation />
</CrudModal>

Security Features:

  • CSP support
  • Focus management
  • Glassmorphism effect
  • Motion presets
  • Error context logging
  • XSS-safe content rendering

2. Form Components

2.1 FormInput

Secure input component with advanced features.

<FormInput
  type="password"
  label="Password"
  showCharacterCount
  sanitize={sanitizePassword}
  validation={passwordValidations}
/>

Features:

  • Password strength meter
  • Input masking
  • Character counter
  • Clipboard sanitization
  • Floating labels
  • Cross-browser consistency

3. State Management

3.1 useCrud Hook

Central state manager for CRUD operations.

const {
  data,
  errors,
  performAction,
  trackChange,
  undo,
  redo,
  auditLog,
  handleVersionConflict
} = useCrud<User>(initialData, {
  validationSchema: UserSchema,
  csrfTokenEndpoint: '/api/csrf'
});

Methods:

  • performAction() - CSRF-protected operations
  • trackChange() - Audit-logged mutations
  • applyOptimisticUpdate() - UI-first updates
  • Conflict resolution system
  • Versioned undo/redo

4. Security System

4.1 CSRF Protection

// Automatic token handling
const refreshCsrfToken = async () => {
  const encrypted = await encryptToken(rawToken);
  document.cookie = `XSRF-TOKEN=${encrypted}; Secure; HttpOnly`;
  return encrypted;
};

Features:

  • SHA-256 token encryption
  • Automatic cookie management
  • Header injection
  • Token refresh queue
  • Error recovery

4.2 Input Sanitization

const sanitizeInput = (input: string, options?: SanitizeOptions) => {
  return DOMPurify.sanitize(input, {
    ALLOWED_TAGS: [],
    FORBID_ATTR: ['style', 'onclick']
  });
};

Protections:

  • XSS prevention
  • Attribute whitelisting
  • Pattern filtering
  • Length restrictions
  • DOM injection protection

5. Performance Features

5.1 Virtualized Table

<VariableSizeList
  height={600}
  itemCount={rows.length}
  itemSize={getRowHeight}
  width="100%"
/>

Optimizations:

  • Dynamic row height calculation
  • Windowed rendering
  • Memoized columns
  • GPU-accelerated scrolling
  • Mobile-responsive layout

5.2 State Management

// Optimistic updates
const applyOptimisticUpdate = (update: Partial<T>) => {
  setState(prev => ({
    versionNumber: prev.versionNumber + 1,
    auditLog: [...prev.auditLog, newEntry]
  }));
};

Features:

  • Version conflict detection
  • Atomic state transitions
  • Throttled validation
  • Auto-save functionality
  • Compressed history storage

6. Audit & Monitoring

6.1 Audit Logging

interface AuditEntry {
  timestamp: Date;
  action: 'CREATE' | 'UPDATE' | 'DELETE';
  details: string;
  version: number;
}

Tracking:

  • User actions
  • Validation errors
  • CSRF events
  • Version changes
  • Conflict resolutions
  • Performance metrics

7. Error Handling

7.1 Error Boundaries

<ErrorBoundary
  FallbackComponent={({ error, reset }) => (
    <ErrorFallback error={error} locale={locale} />
  )}
>
  <CrudForm {...props} />
</ErrorBoundary>

Features:

  • Contextual error messages
  • Recovery mechanisms
  • Error code taxonomy
  • Stack trace preservation
  • Localization support

8. Best Practices

8.1 Security

// Secure cookie settings
document.cookie = `XSRF-TOKEN=${token}; 
  Secure; 
  HttpOnly; 
  SameSite=Strict;
  Path=/;
  Max-Age=86400`;

Recommendations:

  • Always validate CSRF tokens
  • Use Content Security Policies
  • Sanitize all user inputs
  • Implement role-based access
  • Encrypt sensitive data
  • Regular security audits

8.2 Performance

// Virtualization config
const setRowHeight = useCallback((index: number, height: number) => {
  rowHeights.current[index] = height;
  listRef.current?.resetAfterIndex(index);
}, []);

Optimization Tips:

  • Use windowing for large datasets
  • Memoize expensive calculations
  • Throttle validation
  • Optimize re-renders
  • Use compression
  • Implement caching

This documentation covers the core aspects of the Greencode SaaS Factory. For detailed implementation guides and advanced use cases, refer to our interactive storybook documentation.

1.2.27

5 months ago

1.2.26

5 months ago

1.2.25

5 months ago

1.2.24

5 months ago

1.2.23

5 months ago

1.2.22

5 months ago

1.2.21

5 months ago

1.2.20

5 months ago

1.2.19

5 months ago

1.3.0

5 months ago

1.2.18

5 months ago

1.2.17

5 months ago

1.2.16

5 months ago

1.2.15

5 months ago

1.2.14

5 months ago

1.2.13

5 months ago

1.2.12

5 months ago

1.2.11

5 months ago

1.1.11

5 months ago

1.1.10

5 months ago

1.1.9

5 months ago

1.1.8

5 months ago

1.1.7

5 months ago

1.1.5

5 months ago

1.1.4

5 months ago

1.1.3

5 months ago

1.1.2

5 months ago

1.1.0

5 months ago

1.1.1

5 months ago

1.0.23

5 months ago

1.0.22

5 months ago

1.0.21

5 months ago

1.0.20

5 months ago

1.0.19

5 months ago

1.0.18

5 months ago

1.0.17

5 months ago

1.0.16

5 months ago

1.0.15

5 months ago

1.0.14

5 months ago

1.0.13

5 months ago

1.0.12

5 months ago

1.0.11

5 months ago

1.0.10

5 months ago

1.0.9

5 months ago

1.0.8

5 months ago

1.0.7

5 months ago

1.0.6

5 months ago

1.0.5

5 months ago

1.0.4

5 months ago

1.0.3

5 months ago

1.0.2

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago