src/app/features/change-history/model/audit-record.ts

Description

One audited write, as recorded by the replication-backend in the derived <db>-audit database.

Deliberately declares no field for the document's entityId: that name collides with Entity's own private entityId accessor, so a schema field of that name would not create an own property and would corrupt the record's _id. The changed record is derived from this document's own id instead (see record), which needs no field and no data migration.

Extends

Entity

Relationships

Used by

No results matching.

Depends on

Index

Properties
Methods
Accessors

Properties

database
Type : string
Decorators :
@DatabaseField()

source database name, e.g. app

Static Readonly DATABASE
Type : unknown
Default value : `${Entity.DATABASE}-audit`
Inherited from Entity

written by the backend into a database of its own, never replicated here

Static Readonly DATABASE_REMOTE_ONLY
Type : unknown
Default value : true
Inherited from Entity
Optional diff
Type : any
Decorators :
@DatabaseField()

What changed, in a shape that depends on operation:

  • create: a jsondiffpatch whole-value add, i.e. [<the new document>]
  • update: a jsondiffpatch delta keyed by field name, each value [<before>, <after>]
  • delete: a structural delta of the tombstone. A deletion replicates stripped of its content, so this names no displayable fields
  • baseline: the full document as it stood when logging was switched on, not a delta - there is nothing prior to diff against

Untyped on purpose: the keys are field names of whichever entity type was changed, so no schema of this type can describe them.

Static Readonly icon
Type : IconName
Default value : "clock-rotate-left"
Inherited from Entity
Static Readonly isInternalEntity
Type : unknown
Default value : true
Inherited from Entity
Static Readonly label
Type : unknown
Default value : $localize`:AuditRecord label:Change`
Inherited from Entity
Static Readonly labelPlural
Type : unknown
Default value : $localize`:AuditRecord label plural:Changes`
operation
Type : ChangeOperation
Decorators :
@DatabaseField()

the kind of write, as the backend names it

parentRev
Type : string
Decorators :
@DatabaseField()

the written revision's parent

rev
Type : string
Decorators :
@DatabaseField()

_rev of the written revision, not of this audit document

timestamp
Type : Date
Decorators :
@DatabaseField()

server-set time of the change

Static Readonly toStringAttributes
Type : []
Default value : ["record"]
Inherited from Entity
user
Type : AuditUser
Decorators :
@DatabaseField()

server-set from the authenticated user

Static Optional _isCustomizedType
todo: This property is no longer used and will be removed in future versions.
Type : boolean
Inherited from Entity

True if this type's schema has been customized dynamically from the config.

_rev
Type : string
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity

internal database doc revision, used to detect conflicts by PouchDB/CouchDB

anonymized
Type : boolean
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity

Whether this entity has been anonymized and therefore cannot be re-activated.

Static color
Type : string | ColorMapping[]
Inherited from Entity

color used for to highlight this entity type across the app.

Can be either:

  • A simple string (hex color code) for a single color
  • An array of ColorMapping objects for conditional colors based on entity properties
created
Type : UpdateMetadata
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity
Static Optional enableUserAccounts
Type : boolean
Inherited from Entity

Whether to enable user account creation for this entity type. When true, the UI will allow management of user accounts associated with this entity.

Static ENTITY_TYPE
Type : string
Default value : "Entity"
Inherited from Entity

The entity's type. In classes extending Entity this is usually overridden by the class annotation @DatabaseEntity('NewEntity'). The type needs to be used as routing path in lower case. The routing path can be defined in the configuration file.

Static hasPII
Type : boolean
Default value : false
Inherited from Entity

whether this entity type can contain "personally identifiable information" (PII) and therefore should follow strict data protection requirements and offer a function to anonymize records.

inactive
Type : boolean
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity
Static schema
Type : EntitySchema
Inherited from Entity

EntitySchema defining property transformations from/to the database. This is auto-generated from the property annotations @DatabaseField().

see /additional-documentation/how-to-guides/create-a-new-entity-type.html

Static Optional toBlockDetailsAttributes
Type : EntityBlockConfig
Inherited from Entity

Defining which attributes will be displayed in a tooltip on hover when the record is displayed as an entity-block.

updated
Type : UpdateMetadata
Decorators :
@DatabaseField({anonymize: 'retain', isInternalField: true})
Inherited from Entity

Methods

assertValid
assertValid()
Inherited from Entity

Checks if the entity is valid and if the check fails, throws an error explaining the failed check.

Returns : void
Public copy
copy(newId: string | boolean)
Inherited from Entity

Deep copy of the entity. The resulting entity will be of the same type as this (taking into account subclassing). All schema field values that are objects or arrays are deep-cloned to avoid shared mutable state between original and copy.

Parameters :
Name Type Optional Default value Description
newId string | boolean No false

if true, a new entityId will be generated; if a string, that value is used as new entityId

Returns : unknown
Static createPrefixedId
createPrefixedId(type: string, id: string)
Inherited from Entity

Create a prefixed id by adding the type prefix if it isn't already part of the given id.

Parameters :
Name Type Optional Description
type string No

The type prefix to be added.

id string No

The id to be extended with a prefix.

Returns : string
Static extractEntityIdFromId
extractEntityIdFromId(id: string)
Inherited from Entity

Extract entityId without prefix.

Parameters :
Name Type Optional Description
id string No

An entity's id including prefix.

Returns : string
Static extractTypeFromId
extractTypeFromId(id: string)
Inherited from Entity

Extract the ENTITY_TYPE from an id.

Parameters :
Name Type Optional Description
id string No

An entity's id including prefix.

Returns : string
Public getColor
getColor()
Inherited from Entity

Used by some generic UI components to set the color for the entity instance. Override this method as needed.

Returns : string
Static getColorWithConditions
getColorWithConditions(entity: Entity)
Inherited from Entity

Static method to evaluate conditional colors for an entity based on ColorMapping configuration.

Parameters :
Name Type Optional
entity Entity No
Returns : string
getConstructor
getConstructor()
Inherited from Entity

Get the class (Entity or the actual subclass of the instance) to call static methods on the correct class considering inheritance

Public getId
getId(withoutPrefix: unknown)
Inherited from Entity

Returns the id of this entity.

Note that an id is final and can't be changed after the object has been instantiated, hence there is no setId() method.

Parameters :
Name Type Optional Default value
withoutPrefix unknown No false
Returns : string

the unique id of this entity

getSchema
getSchema()
Inherited from Entity

Get the entity schema of this class

Returns : EntitySchema
Public getType
getType()
Inherited from Entity

Returns the type which is used to categorize this entity in the database.

Important: Do not overwrite this method! Types are handled internally.

Returns : string

the entity's type (which is the class name).

Public getWarningLevel
getWarningLevel()
Inherited from Entity

Override getWarningLevel() to define when the entity is in a critical condition and should be color-coded and highlighted in generic components of the UI.

Returns : WarningLevel

Accessors

record
getrecord()

the changed record's id, e.g. Child:123

Returns : string
recordType
getrecordType()

the changed record's type, e.g. Child

Returns : string
changedFields
getchangedFields()

The names of the fields this write changed.

Readable from this record alone, unlike the before/after values, because a delta is already keyed by field name. Empty for a delete, which replicates as a tombstone stripped of its content.

Returns : string[]
author
getauthor()

the recorded author, which is a user-entity id when one was recorded

Returns : string
import { IconName } from "@fortawesome/fontawesome-svg-core";
import { Entity } from "../../../core/entity/model/entity";
import { DatabaseField } from "../../../core/entity/database-field.decorator";
import { DatabaseEntity } from "../../../core/entity/database-entity.decorator";
import { changedFieldsOf } from "../change-history-normalize";
import { ChangeOperation } from "../change-history.types";

/**
 * How many `:`-separated parts trail the changed record's id in an audit
 * record's id, which the backend builds as
 * `AuditRecord:<record id>:<ISO timestamp>:<rev>`.
 *
 * Four, not two: an ISO timestamp carries two colons of its own
 * (`2026-08-01T10:00:00.000Z`), so it accounts for three of them, plus one for
 * the revision.
 */
const AUDIT_ID_TRAILING_PARTS = 4;

/** the author of a change, as the backend records it */
export interface AuditUser {
  id?: string;
  name?: string;
  roles?: string[];
}

/**
 * One audited write, as recorded by the replication-backend in the derived
 * `<db>-audit` database.
 *
 * Deliberately declares no field for the document's `entityId`: that name
 * collides with Entity's own private `entityId` accessor, so a schema field of
 * that name would not create an own property and would corrupt the record's
 * `_id`. The changed record is derived from this document's own id instead
 * (see {@link record}), which needs no field and no data migration.
 */
@DatabaseEntity("AuditRecord")
export class AuditRecord extends Entity {
  /** written by the backend into a database of its own, never replicated here */
  static override readonly DATABASE = `${Entity.DATABASE}-audit`;
  static override readonly DATABASE_REMOTE_ONLY = true;

  static override readonly isInternalEntity = true;
  static override readonly toStringAttributes = ["record"];
  static override readonly label = $localize`:AuditRecord label:Change`;
  static override readonly labelPlural = $localize`:AuditRecord label plural:Changes`;
  static override readonly icon: IconName = "clock-rotate-left";

  /** server-set time of the change */
  @DatabaseField() timestamp: Date;

  /** the kind of write, as the backend names it */
  @DatabaseField() operation: ChangeOperation;

  /** server-set from the authenticated user */
  @DatabaseField() user: AuditUser;

  /** `_rev` of the written revision, not of this audit document */
  @DatabaseField() rev: string;

  /** the written revision's parent */
  @DatabaseField() parentRev: string;

  /** source database name, e.g. `app` */
  @DatabaseField() database: string;

  /**
   * What changed, in a shape that depends on {@link operation}:
   *
   * - `create`: a jsondiffpatch whole-value add, i.e. `[<the new document>]`
   * - `update`: a jsondiffpatch delta keyed by field name, each value
   *   `[<before>, <after>]`
   * - `delete`: a structural delta of the tombstone. A deletion replicates
   *   stripped of its content, so this names no displayable fields
   * - `baseline`: the full document as it stood when logging was switched on,
   *   not a delta - there is nothing prior to diff against
   *
   * Untyped on purpose: the keys are field names of whichever entity type was
   * changed, so no schema of this type can describe them.
   */
  @DatabaseField() diff?: any;

  /** the changed record's id, e.g. `Child:123` */
  get record(): string {
    // everything before the trailing timestamp and revision. The record's own
    // id contains a colon too, so this counts from the end rather than the start
    const parts = this.getId(true).split(":");
    return parts.slice(0, -AUDIT_ID_TRAILING_PARTS).join(":");
  }

  /** the changed record's type, e.g. `Child` */
  get recordType(): string {
    return Entity.extractTypeFromId(this.record);
  }

  /**
   * The names of the fields this write changed.
   *
   * Readable from this record alone, unlike the before/after values, because a
   * delta is already keyed by field name. Empty for a delete, which replicates
   * as a tombstone stripped of its content.
   */
  get changedFields(): string[] {
    return changedFieldsOf(this);
  }

  /** the recorded author, which is a user-entity id when one was recorded */
  get author(): string {
    return this.user?.name ?? this.user?.id ?? "";
  }
}

results matching ""

    No results matching ""