npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cobranza-apps/entities

v0.3.3

Published

Central data model definitions for the Cobranza App system

Readme

@cobranza-apps/entities — Cobranza App Entities Library

Central data model definitions (entities, enums, types) for the Cobranza App system — a multi-tenant SaaS for debt management and payment reconciliation. This package serves as the Single Source of Truth (SSOT) for all data models across the ecosystem.

About

The primary goal of this repository is to provide a clean, structured, and authoritative source of truth for all data models in the Cobranza App platform.

By centralizing entity definitions in one versioned TypeScript package, we ensure consistency across:

  • NestJS backend microservices
  • Angular frontend applications
  • Future services (mobile apps, scripts, etc.)

Core Principles

  • TypeScript First — All definitions are in modern TypeScript with strict mode.
  • Multi-Tenancy Ready — Every major entity includes companyId for tenant isolation.
  • Audit & Soft Delete — Standard audit fields (createdAt, updatedAt, deletedAt, createdBy, updatedBy) built into every entity.
  • Extensibility — Entities are designed to be extended in consuming projects without modifying the library.
  • Consistency — Clear naming conventions, detailed JSDoc comments, and organized barrel exports.

Types and Interfaces

The library provides shared type aliases and base interfaces used across all domain entities:

| Type | Description | |------|-------------| | UUID | Unique identifier for all primary and foreign keys | | Money | Monetary amount (string, precision-safe) | | Decimal | Decimal column values (string, precision-safe) | | JsonData | JSONB column data (Record<string, unknown>) | | DateString | ISO date string (e.g., 'YYYY-MM-DD') |

| Interface | Description | |-----------|-------------| | BaseEntity | Base interface with id, createdAt, updatedAt, createdBy?, updatedBy? | | SoftDeletable | Mixin interface with deletedAt?, deletedBy? for soft-delete support | | EncryptedValue | Container for encrypted fields (encryptedData, keyName, algorithm?, version?) | | Location | Geographic location (address, city, state, country, zipCode, coordinates?) |

Data Encryption

Sensitive fields in this library are stored as EncryptedValue objects rather than plain strings. Encryption is performed by the consuming microservice, not by this library.

EncryptedValue Type

import { EncryptedValue } from '@cobranza-apps/entities';

const encrypted: EncryptedValue = {
  encryptedData: 'U2FsdGVkX1+vupppZksvRf5pq5g5XjFRlipTg9+MvKLJmzJ...',
  keyName: 'client_pii_key',
  algorithm: 'AES-256-GCM',
  version: 1,
};

Entities with Encrypted Fields

| Entity | Encrypted Fields | Hash Columns | |--------|-----------------|--------------| | Company | businessName, taxId, contact, phone | taxIdHash, contactHash | | User | fullName, phone | none | | Client | fullName, taxId, email, phone | taxIdHash, emailHash | | BankTransaction | description, reference | referenceHash | | BankStatement | notes | none | | Notification | to, from, subject, body | none | | PaymentProof | notes | none |

Encryption Flow Across Microservices

  1. Ingress: A microservice receives plain-text sensitive data via API, message queue, or event.
  2. Validation: Data is validated against the entity DTO.
  3. Encryption: The service encrypts sensitive fields using its configured key.
  4. Persistence: The encrypted payload is stored as EncryptedValue (JSONB in the database).
  5. Egress: When another microservice reads the entity, it receives the EncryptedValue and decrypts it using the same key name.

Encryption and decryption always happen inside the microservice boundary, never in the database or in transit without TLS.

Searchable Encrypted Fields (Hash Columns)

Fields that must support exact-match queries (e.g., tax ID lookup, email uniqueness check) have a parallel xxxHash column containing a SHA-256 hex digest of the plain-text value. The hash is computed before encryption and stored alongside the encrypted payload.

| Field | Hash Column | Use Case | |-------|-------------|----------| | Client.taxId | Client.taxIdHash | Exact-match client lookup by tax ID | | Client.email | Client.emailHash | Uniqueness check and lookup | | Company.taxId | Company.taxIdHash | Exact-match company lookup | | Company.contact | Company.contactHash | Contact search | | BankTransaction.reference | BankTransaction.referenceHash | Reference search and matching |

For implementation details, see encryption-usage-guide.md.

Available Entities

Entities are organized into 9 domain modules:

  • companyCompany, CompanyPlan, CompanyUser, Role, User
  • clientClient
  • debtDebt, DebtSchedule
  • paymentPayment, PaymentAttempt, PaymentProof
  • bankBankStatement, BankTransaction, PaymentMatch
  • invoiceInvoice, InvoiceTemplate
  • receiptReceipt, ReceiptTemplate
  • notificationNotification, NotificationTemplate
  • summaryClientDebtSummary, CompanyMonthlySummary

All entities are plain TypeScript interfaces. They contain no decorators or runtime logic, making them safe to import into any framework.

DTOs (Data Transfer Objects)

Each entity has companion DTOs for API layer communication. They are co-located with their entity files and exported through the same barrel exports.

| DTO Type | Purpose | |----------|---------| | CreateXxxDto | Required fields for entity creation (omits id, audit timestamps, and system-managed fields) | | UpdateXxxDto | Optional fields for entity updates (Partial<CreateXxxDto>) | | XxxResponse | Full entity shape returned by API responses (extends the entity interface) |

DTOs use TypeScript utility types (Omit, Partial, extends) for type-safe, zero-overhead abstractions. Import them alongside entities:

import { Client, CreateClientDto, UpdateClientDto } from '@cobranza-apps/entities';

// Creating a new client
const payload: CreateClientDto = {
  name: 'Acme Corp',
  email: '[email protected]',
  companyId: '550e8400-e29b-41d4-a716-446655440000',
};

// Updating an existing client
const updatePayload: UpdateClientDto = {
  email: '[email protected]',
};

For full property definitions, see entities-definition.csv. For relationship diagrams, see entities-relationship-diagram-overview.md.

JSON Schemas

Each entity has a companion JSON Schema (Draft-07) file for runtime validation, dynamic form generation, OpenAPI spec generation, and AI agent integration.

Schemas are located in src/schemas/ and are exported individually and as a grouped schemas object:

import { debtSchema, clientSchema } from '@cobranza-apps/entities';
// or grouped access
import { schemas } from '@cobranza-apps/entities';
const debtValidationSchema = schemas.debt.debt;

Domain Groups

| Domain | Schema Count | |--------|-------------| | company | 5 (Company, CompanyPlan, User, Role, CompanyUser) | | client | 1 (Client) | | debt | 2 (Debt, DebtSchedule) | | payment | 3 (Payment, PaymentAttempt, PaymentProof) | | bank | 3 (BankStatement, BankTransaction, PaymentMatch) | | invoice | 2 (Invoice, InvoiceTemplate) | | receipt | 2 (Receipt, ReceiptTemplate) | | notification | 2 (Notification, NotificationTemplate) | | summary | 2 (ClientDebtSummary, CompanyMonthlySummary) |

Use Cases

  • Dynamic Forms — drive form field generation from schema definitions
  • Runtime Validation — validate incoming payloads against entity schemas
  • Swagger / OpenAPI — generate API specifications from JSON Schemas
  • AI Agents — provide structured entity contracts for LLM-based integrations

Tech Stack

| Technology | Purpose | |------------|---------| | TypeScript >= 5.x | Strict-mode type definitions | | Node.js >= 20.x LTS | Build tooling runtime | | npm >= 10.x | Package manager and publish tool |

Zero runtime dependencies. The library exports only TypeScript interfaces, types, and enums — no services, no side effects, no network calls.

Installation & Usage

Install the package via npm:

npm install @cobranza-apps/entities

Import directly into your project:

import { Client, Debt, DebtStatus, Currency } from '@cobranza-apps/entities';

The library exports only TypeScript interfaces, types, and enums — no runtime code, no side effects.

Basic Import

import { Client, Debt, DebtStatus, Currency } from '@cobranza-apps/entities';

Extending an Entity in NestJS

Because the library exports plain interfaces, you can extend them with NestJS decorators in your consuming project without modifying the library:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
import { Debt as DebtBase } from '@cobranza-apps/entities';

@Entity()
export class Debt implements DebtBase {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  companyId: string;

  @Column()
  clientId: string;

  @Column()
  description: string;

  @Column('decimal')
  totalAmount: string;

  @Column()
  currency: string;

  @Column()
  dueDate: Date;

  @Column()
  issueDate: Date;

  @Column()
  status: string;

  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  createdAt: Date;

  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  updatedAt: Date;
}

Using Types in an Angular Service

import { Injectable } from '@angular/core';
import { Client, Debt } from '@cobranza-apps/entities';

@Injectable({ providedIn: 'root' })
export class DebtService {
  async getClientDebts(clientId: string): Promise<Debt[]> {
    const response = await fetch(`/api/clients/${clientId}/debts`);
    return response.json();
  }

  async createClient(payload: Omit<Client, 'id' | 'createdAt' | 'updatedAt'>): Promise<Client> {
    const response = await fetch('/api/clients', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    return response.json();
  }
}

Working with Enums

import { DebtStatus, PaymentStatus, Currency } from '@cobranza-apps/entities';

function canCancelDebt(status: DebtStatus): boolean {
  return status === DebtStatus.PENDING || status === DebtStatus.OVERDUE;
}

function isPaymentCompleted(status: PaymentStatus): boolean {
  return status === PaymentStatus.COMPLETED;
}

Usage Examples

For detailed, copy-paste-ready integration examples, see:

Related Documentation