npm package: @processpuzzle/base-entity
Description: ![Build and Test](https://github.com/ZsZs/processpuzzle/actions/workflows/build-base-entity.yml/badge.svg) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=processpuzzle_base_entity&metric=alert_status)](https://sonarcloud.
Author: Zsolt Zsuffa
Latest version: 0.3.8

# @processpuzzle/base-entity

![Build and Test](https://github.com/ZsZs/processpuzzle/actions/workflows/build-base-entity.yml/badge.svg)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=processpuzzle_base_entity&metric=alert_status)](https://sonarcloud.io/summary?id=processpuzzle_base_entity)
[![Node version](https://img.shields.io/npm/v/%40processpuzzle%2Fbase-entity?style=flat)](https://www.npmjs.com/package/@processpuzzle/base-entity)

## Introduction
 
Base-Entity is a run-time form and table generator base on Entity Descriptor and Entity Attribute Descriptor. To make it short:

<a href="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-bird-eye-view.png?raw=true">
  <img src="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-bird-eye-view.png?raw=true" width=600px alt="Bird eye view">
</a>

From these **Inputs:**

- Entity Descriptor => Describes the subject entity and probable it's associated entities.
- Entity Attribute Descriptor => Specifies the presentation style of each attribute.

generates these **Outputs:**

- Reactive Form Component => Reactive Angular form, created dynamically, run-time.
- Angular Material Table => Angular Material Table, create dynamically, run-time.

Of course this is a very coarse, abstract view of the functionality. In more detail, the library offers the following classes:

<a href="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-architectural-context.png?raw=true">
  <img src="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-architectural-context.png?raw=true" width=600px alt="Architectural Context">
</a>

- Base Entity => interface to implement from the subject Custom Entity
- Base Entity Service => abstract class to extend by the Custom Service to deliver the Custom Entity
- Base Entity Mapper => abstract class to extend to map the Custom Entity from/to DTO
- Base Entity Store => signal store for the components generated by the library
- Base Entity Container => Angular component to contain the generated table and form
- Base Entity List => Angular Material Table to display the Custom Entities in a table form
- Base Entity Form => Reactive Angular Form to facilitate CRUD on a single custom object

## Usage

Basically the library user has to extend a couple of base classes. These extensions are minimal, it't more like configuration of the base class.

<a href="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-design_overview.png?raw=true">
  <img src="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-design_overview.png?raw=true" width=600px alt="Design Overview">
</a>

### Extend **Base Entity**

As the **Base Entity** interface defines only an ID, you are almost completely free how you define your Entity to be managed by the library. For an example see the [sample entities](https://github.com/ZsZs/processpuzzle/tree/develop/apps/processpuzzle-testbed/src/app/content/base-forms), like TestEntity, TestEntityComponent and TrunkData.

```typescript
export class TestEntity implements BaseEntity {
  id: string = uuidv4();
  name? = '';
  description?: string = '';
  boolean?: boolean;
  number?: number;
  date?: Date;
  selectable?: number;
  private enumValue: TestEnum;
}
```

The Base Entity Mapper increases the flexibility how you can define your Entity to be managed even more as it offers a mapping between the mostly predefined DTOs and the Entity in the front end. For an example see the [sample mappers](https://github.com/ZsZs/processpuzzle/tree/develop/apps/processpuzzle-testbed/src/app/content/base-forms), TestEntityMapper, TestEntityComponentMapper and TrunkDataMapper.
```typescript
@Injectable({ providedIn: 'root' })
export class TestEntityMapper implements BaseEntityMapper<TestEntity> {
  fromDto(dto: any): TestEntity {
    return new TestEntity(dto.id, dto.name, dto.description, dto.boolean, dto.number, dto.date, getEnumKeyByEnumValue<TestEnum>(TestEnum, dto.enumValue));
  }

  toDto(entity: TestEntity): any {
    return entity;
  }
}

function getEnumKeyByEnumValue<E>(myEnum: { [key: number]: string }, enumValue: any): E | undefined {
  return Object.values(myEnum)[enumValue] as E;
}
```
To be able to configure the rather generic Data Service (BaseEntityService), you have to subclass it and provide in the constructor the required mapper, configuration key and resource path for the base URL.
For an example see the [sample data services](https://github.com/ZsZs/processpuzzle/tree/develop/apps/processpuzzle-testbed/src/app/content/base-forms), like TestEntityService, TestEntityComponentService and TrunkDataService.
```typescript
@Injectable({ providedIn: 'root' })
export class TestEntityService extends BaseEntityService<TestEntity> {
  constructor(protected override entityMapper: TestEntityMapper) {
    super(entityMapper, 'TEST_SERVICE_ROOT', 'test-entity');
  }
}
```
Of course, you are free to define your own data access methods as much they are needed by your custom Signal Store or other objects.

The core piece of this library's domain layer is the BaseEntityStore, a signal store, which is used by the generated angular components. 
The BaseEntityStore provides methods for CRUD operations and enhanced usability status. For details see the diagram above, or the [source code](https://github.com/ZsZs/processpuzzle/blob/develop/libs/base-entity/src/lib/base-entity.store.ts)
To be able to use it, you just have to define your own signal store, with the usage of BaseEntityStore (Signal Store Feature).
```typescript
export const TestEntityStore = signalStore(
  { providedIn: 'root' },
  BaseEntityStore<TestEntity>(TestEntity, TestEntityService),
  BaseFormNavigatorStore<TestEntity>(TestEntity),
  BaseEntityTabsStore(),
  BaseEntityContainerStore(),
);
```
The BaseFormNavigatorStore, BaseEntityTabsStore and BaseEntityContainerStore provides additional enhanced usability services, which will be explained in the Design section.

```typescript
const selectables = Object.keys(TestEnum)
  .filter((key: any) => parseInt(key) >= 0)
  .map((key: string) => ({ key: key, value: TestEnum[key as keyof typeof TestEnum] }));

const nameAttr = new BaseEntityAttrDescriptor('name', FormControlType.TEXT_BOX, 'Name', undefined, true);
const descriptionAttr = new BaseEntityAttrDescriptor('description', FormControlType.TEXTAREA, 'Description');
const booleanAttr = new BaseEntityAttrDescriptor('boolean', FormControlType.CHECKBOX, 'Boolean');
const numberAttr = new BaseEntityAttrDescriptor('number', FormControlType.TEXT_BOX, 'Number', undefined, false, { inputType: 'number' });
const dateAttr = new BaseEntityAttrDescriptor('date', FormControlType.DATE, 'Date', undefined, false, { inputType: 'date' });
const enumAttr = new BaseEntityAttrDescriptor('enumValue', FormControlType.DROPDOWN, 'Enum', selectables);

export const testEntityDescriptors: BaseEntityAttrDescriptor<TestEntity>[] = [nameAttr, descriptionAttr, booleanAttr, numberAttr, dateAttr, enumAttr];

const baseEntityDescriptor: BaseEntityDescriptor = {
  entityName: 'Test Entity',
  store: this.store,
  attrDescriptors: testEntityAttrDescriptors,
  entityTitle: "this.store.currentEntity() ? this.store.currentEntity().name : ''",
};
```