lib-common-angular 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
File without changes
@@ -0,0 +1,45 @@
1
+ {
2
+ "lenguage": "Sprache",
3
+ "index": "Startseite",
4
+
5
+ "menu": {
6
+ "start": "Start",
7
+ "list_user": "Benutzer auflisten",
8
+ "register": "Registrieren",
9
+ "login": "Anmelden",
10
+ "log_out": "Abmelden",
11
+ "contact": "Kontakt",
12
+ "servicios": "Dienstleistungen"
13
+ },
14
+
15
+ "slider-index-paradiceDog": {
16
+ "subTitulo-1": "Service nach Hause",
17
+ "subTitulo-2": "Katzen und Hunde",
18
+ "subTitulo-3": "Internats- oder Heimdienst",
19
+ "titulo-1": "Hundesalon für Haustiere",
20
+ "titulo-2": "Tierpension",
21
+ "titulo-3": "Hundetraining",
22
+ "beschreibung-1": "In unserem Hundesalon-Service kümmern wir uns mit größter Sorgfalt und Professionalität um das Wohlbefinden und die Schönheit Ihres Haustieres. Wir wissen, dass Ihr Hund ein Teil Ihrer Familie ist, und deshalb bieten wir eine persönliche Pflege, die auf die individuellen Bedürfnisse Ihres Haustieres zugeschnitten ist. Unsere Dienstleistungen umfassen einen stilisierten Haarschnitt, der sich an die Rasse und die individuellen Eigenschaften Ihres Haustieres anpasst.",
23
+ "beschreibung-2": "Unsere Tierpension ist der ideale Ort, an dem Ihr bester Freund den Tag in einer sicheren, unterhaltsamen und liebevollen Umgebung verbringen kann. In unserer Tierpension genießen die Tiere großzügige Spielbereiche, in denen sie mit anderen Tieren in Kontakt treten, sich bewegen und unter ständiger Aufsicht unseres professionellen Pflegeteams erkunden können.",
24
+ "beschreibung-3": "Unser Hundetrainingsservice wurde entwickelt, um Ihnen zu helfen, eine starke und harmonische Beziehung zu Ihrem Hund aufzubauen, die auf Vertrauen, Respekt und effektiver Kommunikation basiert. Mit positiven und personalisierten Trainingsmethoden konzentrieren wir uns darauf, die Fähigkeiten und Verhaltensweisen zu entwickeln, die Ihr Hund benötigt, um ein gehorsamer, glücklicher und gut ausgeglichener Begleiter zu werden. Wir bieten eine Vielzahl von Trainingsprogrammen an, die an die individuellen Bedürfnisse und Eigenschaften jedes Hundes angepasst sind."
25
+ },
26
+
27
+ "auth": {
28
+ "write_your_data": "Geben Sie Ihre Daten ein",
29
+ "firtsName": "Vorname",
30
+ "secondName": "Nachname",
31
+ "phone": "Telefon",
32
+ "Nickname": "Spitzname"
33
+ },
34
+ "works": {
35
+ "work_in_progress": "Laufende Arbeiten",
36
+ "create-work": "Arbeit Erstellen"
37
+ },
38
+ "meta_key_words": {
39
+ "title": "ZIGMA INFLATABLES - Hersteller von aufblasbaren Produkten",
40
+ "keywords": "zigma inflatables, Hersteller von aufblasbaren Produkten, Verkauf aufblasbarer Produkte, aufblasbare Produkte, Verleih von aufblasbaren Produkten, Hersteller aufblasbarer Produkte, aufblasbare Produkte, Hüpfburgen, aufblasbare Rutschen, aufblasbare Zelte, Werbeaufsteller",
41
+ "description": "Wir stellen alle Arten von aufblasbaren Produkten her, innovative und aktuelle Designs, wettbewerbsfähige Preise und Qualität an einem Ort."
42
+ },
43
+ "footer_properties": "Alle Rechte vorbehalten von Juliao Sistem"
44
+
45
+ }
@@ -0,0 +1,47 @@
1
+ {
2
+
3
+ "lenguage": "Lenguage",
4
+ "index":"Start",
5
+ "Our": "Nuestros",
6
+ "menu":{
7
+ "start":"Start",
8
+ "list_user":"List Users",
9
+ "register":"Register",
10
+ "login":"Login",
11
+ "log_out":"Close Session",
12
+ "contact": "Contact",
13
+ "servicios": "Services"
14
+
15
+ },
16
+
17
+ "slider-index-paradiceDog": {
18
+ "subTitulo-1": "Home Service",
19
+ "subTitulo-2": "Cats and Dogs",
20
+ "subTitulo-3": "Boarding or Home Service",
21
+ "titulo-1": "Pet Grooming",
22
+ "titulo-2": "Pet Daycare",
23
+ "titulo-3": "Dog Training",
24
+ "description-1": "In our pet grooming service, we dedicate ourselves to caring for and beautifying your pet with the utmost care and professionalism. We know that your dog is part of your family, so we offer personalized care tailored to their specific needs. Our services include a stylish haircut that adapts to the breed and individual characteristics of your pet.",
25
+ "description-2": "Our daycare is the perfect place for your best friend to spend the day in a safe, fun, and loving environment. In our daycare, pets enjoy large play areas where they can socialize with other animals, exercise, and explore under the constant supervision of our professional caregivers.",
26
+ "description-3": "Our dog training service is designed to help you build a strong and harmonious relationship with your dog, based on trust, respect, and effective communication. With positive and personalized training methods, we focus on developing the skills and behaviors your dog needs to become an obedient, happy, and well-balanced companion. We offer a variety of training programs tailored to the individual needs and characteristics of each dog."
27
+ },
28
+
29
+ "auth":{
30
+ "write_your_data":"write your data",
31
+ "firtsName":"Firts Name",
32
+ "secondName":"Last Name",
33
+ "phone":"Phone",
34
+ "Nickname":"Nickname"
35
+ },
36
+ "works":{
37
+ "work_in_progress":"Work In Progress",
38
+ "create-work":"Create work"
39
+ },
40
+ "meta_key_words":{
41
+ "title":"Application -Administrative Ecommerce",
42
+ "keywords":"administrative application, creator of ecommerse, how to create ecommerse application, how to sell online, platforms to manage my business,e-commerce",
43
+ "description":"Application to create your virtual store we are the best option on the market and at the best price manage and publish your business with us"
44
+ },
45
+
46
+ "footer_properties":"All Rights Reserved By Juliao Sistem "
47
+ }
@@ -0,0 +1,49 @@
1
+ {
2
+
3
+ "lenguage": "Idioma",
4
+ "index":"Inicio",
5
+
6
+
7
+ "menu":{
8
+ "start":"Inicio",
9
+ "list_user":" Lista Usuarios",
10
+ "register":"Registro",
11
+ "login":"Iniciar Session",
12
+ "log_out":"Cerrar Session",
13
+ "contact": "Contacto",
14
+ "servicios": "Servicios"
15
+ },
16
+
17
+ "slider-index-paradiceDog":{
18
+ "subTitulo-1":"Servicio a domicilio",
19
+ "subTitulo-2":"Gatos y Perros",
20
+ "subTitulo-3":"Servicio de internado o a Domicilio",
21
+ "titulo-1":"Peluquería para mascotas",
22
+ "titulo-2":"Guarderia para mascotas",
23
+ "titulo-3":"Entrenamiento Canino",
24
+ "descripcion-1":"En nuestro servicio de peluquería canina, nos dedicamos a cuidar y embellecer a tu mascota con el máximo cariño y profesionalismo. Sabemos que tu perro es parte de tu familia, y por eso ofrecemos un cuidado personalizado y adaptado a sus necesidades específicas. Nuestros servicios incluyen un corte de pelo estilizado que se adapta a la raza y características individuales de tu mascota",
25
+ "descripcion-2":"Nuestra guardería es el lugar ideal para que tu mejor amigo pase el día en un ambiente seguro, divertido y lleno de amor. En nuestra guardería, las mascotas disfrutan de amplias áreas de juego donde pueden socializar con otros animales, ejercitarse y explorar bajo la supervisión constante de nuestro equipo de cuidadores profesionales",
26
+ "descripcion-3":"Nuestro servicio de entrenamiento canino está diseñado para ayudarte a construir una relación fuerte y armoniosa con tu perro, basada en la confianza, el respeto y la comunicación efectiva. Con métodos de entrenamiento positivos y personalizados, nos enfocamos en desarrollar las habilidades y comportamientos que tu perro necesita para convertirse en un compañero obediente, feliz y bien equilibrado. Ofrecemos una variedad de programas de entrenamiento adaptados a las necesidades y características individuales de cada perro"
27
+ },
28
+
29
+ "auth":{
30
+ "write_your_data":"Escriba sus Datos",
31
+ "firtsName":"Nombre",
32
+ "secondName":"Apellidos",
33
+ "phone":"Telefono",
34
+ "Nickname":"Apodo"
35
+ },
36
+ "works":{
37
+ "work_in_progress":"Trabajos En Curso",
38
+ "create-work":"Crear Trabajo"
39
+ },
40
+ "meta_key_words":{
41
+ "title":"ZIGMA INFLABLES - Fabrica De Inflables",
42
+ "keywords":"zigma inflables , fabrica de inflables , venta inflables, inflables , alquiler de inflables,Fabrica inflables, inflables, castillos inflables, toboganes inflables, carpas inflables , inflables publicitarios",
43
+ "description":"Fabricamos todo tipo de inflables, diseños novedosos y actualizados, precios competitivos y calidad en un solo lugar."
44
+ },
45
+
46
+ "footer_properties": "Todos los Derechos Reservados por Juliao Sistem"
47
+
48
+
49
+ }
@@ -0,0 +1,44 @@
1
+ {
2
+ "lenguage": "Idioma",
3
+ "index": "Início",
4
+
5
+ "menu": {
6
+ "start": "Início",
7
+ "list_user": "Listar Usuários",
8
+ "register": "Registrar",
9
+ "login": "Iniciar Sessão",
10
+ "log_out": "Encerrar Sessão",
11
+ "contact": "Contato",
12
+ "servicios": "Serviços"
13
+ },
14
+ "slider-index-paradiceDog": {
15
+ "subTitulo-1": "Serviço a domicílio",
16
+ "subTitulo-2": "Gatos e Cães",
17
+ "subTitulo-3": "Serviço de internamento ou a Domicílio",
18
+ "titulo-1": "Tosa e Banho para Animais",
19
+ "titulo-2": "Creche para Animais",
20
+ "titulo-3": "Treinamento Canino",
21
+ "descricao-1": "No nosso serviço de tosa e banho para cães, nos dedicamos a cuidar e embelezar seu pet com o máximo de carinho e profissionalismo. Sabemos que seu cão é parte da sua família, por isso oferecemos um cuidado personalizado e adaptado às suas necessidades específicas. Nossos serviços incluem um corte de pelo estilizado que se adapta à raça e características individuais do seu pet.",
22
+ "descricao-2": "Nossa creche é o lugar ideal para que seu melhor amigo passe o dia em um ambiente seguro, divertido e cheio de amor. Na nossa creche, os animais desfrutam de amplas áreas de lazer onde podem socializar com outros animais, se exercitar e explorar sob a supervisão constante da nossa equipe de cuidadores profissionais.",
23
+ "descricao-3": "Nosso serviço de treinamento canino foi projetado para ajudá-lo a construir uma relação forte e harmoniosa com seu cão, baseada na confiança, respeito e comunicação eficaz. Com métodos de treinamento positivos e personalizados, nos concentramos em desenvolver as habilidades e comportamentos que seu cão precisa para se tornar um companheiro obediente, feliz e equilibrado. Oferecemos uma variedade de programas de treinamento adaptados às necessidades e características individuais de cada cão."
24
+ },
25
+
26
+ "auth": {
27
+ "write_your_data": "Insira seus Dados",
28
+ "firtsName": "Nome",
29
+ "secondName": "Sobrenome",
30
+ "phone": "Telefone",
31
+ "Nickname": "Apelido"
32
+ },
33
+ "works": {
34
+ "work_in_progress": "Trabalhos em Andamento",
35
+ "create-work": "Criar Trabalho"
36
+ },
37
+ "meta_key_words": {
38
+ "title": "ZIGMA INFLÁVEIS - Fábrica de Infláveis",
39
+ "keywords": "zigma infláveis, fábrica de infláveis, venda infláveis, infláveis, aluguel de infláveis, fábrica de infláveis, infláveis, castelos infláveis, escorregadores infláveis, tendas infláveis, infláveis publicitários",
40
+ "description": "Fabricamos todo tipo de infláveis, designs inovadores e atualizados, preços competitivos e qualidade em um só lugar."
41
+ },
42
+ "footer_properties": "Todos os Direitos Reservados por Juliao Sistem"
43
+
44
+ }
@@ -0,0 +1,66 @@
1
+ import { Injectable } from '@angular/core';
2
+ import { State, Action, StateContext } from '@ngxs/store';
3
+ import { BusinessDTO } from '@juliaosistem/core-dtos';
4
+ import { PlantillaResponse } from 'juliaositembackenexpress/dist/utils/PlantillaResponse';
5
+ import { createGenericCrudActions } from './state-generic/generic-crud.actions';
6
+ import { GenericCrudState } from './state-generic/generic-crud.state';
7
+ import { GenericCrudHttpService } from '../../componentes/shared/services/generic-crud.service/generic-crud.service';
8
+ import { HttpClient } from '@angular/common/http';
9
+ import { LibConfigService } from '../../config/lib-config.service';
10
+ import { MetaDataService } from '../../componentes/shared/services/meta-data.service.ts/meta-data.service';
11
+
12
+ // 🔹 Crear acciones genéricas para Business
13
+ const businessActions = createGenericCrudActions<BusinessDTO>('Business');
14
+
15
+ @State<PlantillaResponse<BusinessDTO>>({
16
+ name: 'business',
17
+ defaults: {
18
+ data: undefined,
19
+ dataList: [],
20
+ message: '',
21
+ rta: false,
22
+ },
23
+ })
24
+ @Injectable()
25
+ export class BusinessState extends GenericCrudState<BusinessDTO, BusinessDTO> {
26
+ constructor(
27
+ http: HttpClient,
28
+ config: LibConfigService,
29
+ meta: MetaDataService
30
+ ) {
31
+ const genericService = new GenericCrudHttpService<BusinessDTO>(
32
+ http,
33
+ config,
34
+ meta,
35
+ 'baseUrlBusiness' // Key del endpoint en LibConfigService
36
+ );
37
+ super(genericService, businessActions);
38
+ }
39
+
40
+ // 🔹 Acción opcional para cargar datos mock específicos
41
+ @Action(businessActions.LoadMock)
42
+ loadMockBusiness(ctx: StateContext<PlantillaResponse<BusinessDTO>>) {
43
+ try {
44
+ const service = this.service as GenericCrudHttpService<BusinessDTO>;
45
+ const mockData = service.getMockData?.() || [];
46
+ ctx.patchState({
47
+ data: undefined,
48
+ dataList: mockData,
49
+ message: mockData.length
50
+ ? 'Business mock cargados correctamente'
51
+ : 'No hay datos mock disponibles',
52
+ rta: mockData.length > 0,
53
+ });
54
+ } catch (error) {
55
+ ctx.patchState({
56
+ data: undefined,
57
+ dataList: [],
58
+ message: 'Error al cargar datos mock',
59
+ rta: false,
60
+ });
61
+ }
62
+ }
63
+ }
64
+
65
+ // Exportar acciones para usar en componentes
66
+ export const BusinessActions = businessActions;
@@ -0,0 +1,76 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { Injectable } from '@angular/core';
3
+ import { State, Selector, Action, StateContext } from '@ngxs/store';
4
+ import { CategoriaDTO } from '@juliaosistem/core-dtos';
5
+ import { PlantillaResponse } from 'juliaositembackenexpress/dist/utils/PlantillaResponse';
6
+ import { createGenericCrudActions } from './state-generic/generic-crud.actions';
7
+ import { GenericCrudHttpService } from '../../componentes/shared/services/generic-crud.service/generic-crud.service';
8
+ import { HttpClient } from '@angular/common/http';
9
+ import { LibConfigService } from '../../config/lib-config.service';
10
+ import { MetaDataService } from '../../componentes/shared/services/meta-data.service.ts/meta-data.service';
11
+ import { tap } from 'rxjs';
12
+ import { GenericCrudActions, GenericCrudState } from './state-generic/generic-crud.state';
13
+ import { ProductService } from '../../componentes/shared/services/product.service';
14
+
15
+
16
+ // Crear acciones genéricas para ProductoDTO
17
+ const categoriaproductoActions = createGenericCrudActions<CategoriaDTO>('categoriaproducto');
18
+ export const CategoriaproductoActions = categoriaproductoActions;
19
+
20
+ @State<PlantillaResponse<CategoriaDTO>>({
21
+ name: 'categoriaproducto',
22
+ defaults: {
23
+ data: undefined,
24
+ dataList: [],
25
+ message: '',
26
+ rta: false,
27
+ },
28
+ })
29
+ @Injectable()
30
+ export class CategoriaProductoState extends GenericCrudState<CategoriaDTO, CategoriaDTO> {
31
+ constructor(
32
+ private http: HttpClient,
33
+ private config: LibConfigService,
34
+ private meta: MetaDataService,
35
+ private productSvc: ProductService,
36
+ ) {
37
+ const service = new GenericCrudHttpService<CategoriaDTO>(
38
+ http,
39
+ config,
40
+ meta,
41
+ 'baseUrlCategoryProduct'
42
+ );
43
+ super(service, CategoriaproductoActions as unknown as GenericCrudActions<CategoriaDTO>);
44
+ }
45
+
46
+ @Selector()
47
+ static getProductos(state: PlantillaResponse<CategoriaDTO>) {
48
+ return state.dataList;
49
+ }
50
+
51
+ @Action(CategoriaproductoActions.All)
52
+ all(ctx: StateContext<PlantillaResponse<CategoriaDTO>>, action: any) {
53
+ return this.service.all(action.payload).pipe(
54
+ tap(res => ctx.setState(res))
55
+ );
56
+ }
57
+ @Action(CategoriaproductoActions.LoadMock)
58
+ override loadMock(ctx: StateContext<PlantillaResponse<CategoriaDTO>>) {
59
+ try {
60
+ const mockData = this.productSvc.mockCategoriaInflablesDTO();
61
+ ctx.patchState({
62
+ data: undefined,
63
+ dataList: mockData,
64
+ message: mockData.length ? 'Datos mock cargados correctamente' : 'No hay datos mock disponibles',
65
+ rta: !!mockData.length,
66
+ });
67
+ } catch (error) {
68
+ ctx.patchState({
69
+ data: undefined,
70
+ dataList: [],
71
+ message: 'Error al cargar datos mock ' + error,
72
+ rta: false,
73
+ });
74
+ }
75
+ }
76
+ }
@@ -0,0 +1,55 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { Injectable } from '@angular/core';
3
+ import { State, Selector, Action, StateContext } from '@ngxs/store';
4
+ import { ProductoDTO } from '@juliaosistem/core-dtos';
5
+ import { PlantillaResponse } from 'juliaositembackenexpress/dist/utils/PlantillaResponse';
6
+ import { createGenericCrudActions } from './state-generic/generic-crud.actions';
7
+ import { GenericCrudHttpService } from '../../componentes/shared/services/generic-crud.service/generic-crud.service';
8
+ import { HttpClient } from '@angular/common/http';
9
+ import { LibConfigService } from '../../config/lib-config.service';
10
+ import { MetaDataService } from '../../componentes/shared/services/meta-data.service.ts/meta-data.service';
11
+ import { tap } from 'rxjs';
12
+ import { GenericCrudActions, GenericCrudState } from './state-generic/generic-crud.state';
13
+ import { MonedaDTO } from '@juliaosistem/core-dtos';
14
+
15
+ // Crear acciones genéricas para ProductoDTO
16
+ const monedaActions = createGenericCrudActions<ProductoDTO>('moneda');
17
+ export const MonedaActions = monedaActions;
18
+
19
+ @State<PlantillaResponse<MonedaDTO>>({
20
+ name: 'moneda',
21
+ defaults: {
22
+ data: undefined,
23
+ dataList: [],
24
+ message: '',
25
+ rta: false,
26
+ },
27
+ })
28
+ @Injectable()
29
+ export class MonedaState extends GenericCrudState<MonedaDTO, MonedaDTO> {
30
+ constructor(
31
+ private http: HttpClient,
32
+ private config: LibConfigService,
33
+ private meta: MetaDataService
34
+ ) {
35
+ const service = new GenericCrudHttpService<MonedaDTO>(
36
+ http,
37
+ config,
38
+ meta,
39
+ 'baseUrlCurrency'
40
+ );
41
+ super(service, MonedaActions as unknown as GenericCrudActions<MonedaDTO>);
42
+ }
43
+
44
+ @Selector()
45
+ static getProductos(state: PlantillaResponse<MonedaDTO>) {
46
+ return state.dataList;
47
+ }
48
+
49
+ @Action(MonedaActions.All)
50
+ all(ctx: StateContext<PlantillaResponse<MonedaDTO>>, action: any) {
51
+ return this.service.all(action.payload).pipe(
52
+ tap(res => ctx.setState(res))
53
+ );
54
+ }
55
+ }
@@ -0,0 +1,157 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { Injectable } from '@angular/core';
3
+ import { State, Selector, Action, StateContext } from '@ngxs/store';
4
+ import { ProductoDTO } from '@juliaosistem/core-dtos';
5
+ import { PlantillaResponse } from 'juliaositembackenexpress/dist/utils/PlantillaResponse';
6
+ import { createGenericCrudActions } from './state-generic/generic-crud.actions';
7
+ import { GenericCrudHttpService } from '../../componentes/shared/services/generic-crud.service/generic-crud.service';
8
+ import { HttpClient } from '@angular/common/http';
9
+ import { LibConfigService } from '../../config/lib-config.service';
10
+ import { MetaDataService } from '../../componentes/shared/services/meta-data.service.ts/meta-data.service';
11
+ import { tap } from 'rxjs';
12
+ import {
13
+ GenericCrudActions,
14
+ GenericCrudState,
15
+ } from './state-generic/generic-crud.state';
16
+ import { ProductService } from '../../componentes/shared/services/product.service';
17
+ import { createSelector } from '@ngxs/store';
18
+
19
+ // Crear acciones genéricas para ProductoDTO
20
+ const productosActions = createGenericCrudActions<ProductoDTO>('producto');
21
+ export const ProductosActions = productosActions;
22
+ @State<PlantillaResponse<ProductoDTO>>({
23
+ name: 'producto',
24
+ defaults: {
25
+ data: undefined,
26
+ dataList: [],
27
+ message: '',
28
+ rta: false,
29
+ },
30
+ })
31
+ @Injectable()
32
+ export class ProductosState extends GenericCrudState<ProductoDTO, ProductoDTO> {
33
+ constructor(
34
+ private http: HttpClient,
35
+ private config: LibConfigService,
36
+ private meta: MetaDataService,
37
+ private productSvc: ProductService
38
+ ) {
39
+
40
+ const service = new GenericCrudHttpService<ProductoDTO>(
41
+ http,
42
+ config,
43
+ meta,
44
+ 'baseUrlProducts',
45
+ );
46
+ super(
47
+ service,
48
+ ProductosActions as unknown as GenericCrudActions<ProductoDTO>,
49
+ );
50
+ }
51
+
52
+ // Selector para lista de productos
53
+ @Selector()
54
+ static getProductos(state: PlantillaResponse<ProductoDTO>) {
55
+ return state.dataList;
56
+ }
57
+
58
+ /**
59
+ * Selector factory para obtener productos por id de categoría.
60
+ * @param idCategoria
61
+ * @returns
62
+ */
63
+ static selectByCategoriaId(idCategoria: string) {
64
+ return createSelector([
65
+ (state: { producto: PlantillaResponse<ProductoDTO> }) => state.producto
66
+ ], (response: PlantillaResponse<ProductoDTO>) => {
67
+ const list = (response?.dataList as ProductoDTO[]) || [];
68
+ return list.filter(p => String(p.idCategoria) === String(idCategoria));
69
+ });
70
+ }
71
+
72
+ // Acción All
73
+ @Action(ProductosActions.All)
74
+ all(ctx: StateContext<PlantillaResponse<ProductoDTO>>, action: any) {
75
+ return this.service
76
+ .all(action.payload)
77
+ .pipe(tap((res) => ctx.setState(res)));
78
+ }
79
+ @Action(ProductosActions.Add)
80
+ override add(ctx: StateContext<PlantillaResponse<ProductoDTO>>, action: any) {
81
+ return this.service.add(action.payload, action.queryParams).pipe(
82
+ tap((res) => {
83
+ const state = ctx.getState();
84
+ const newItem = res.data;
85
+ if (newItem && state.dataList) {
86
+ ctx.setState({
87
+ ...state,
88
+ dataList: [...state.dataList, newItem],
89
+ data: newItem,
90
+ message: res.message,
91
+ rta: true,
92
+ });
93
+ }
94
+ })
95
+ );
96
+ }
97
+
98
+ @Action(ProductosActions.Update)
99
+ override update(ctx: StateContext<PlantillaResponse<ProductoDTO>>, action: any) {
100
+ return this.service.update(action.payload, action.queryParams).pipe(
101
+ tap((res) => {
102
+ const state = ctx.getState();
103
+ const updatedItem = res.data;
104
+ if (updatedItem && state.dataList) {
105
+ ctx.setState({
106
+ ...state,
107
+ dataList: state.dataList.map((item: any) =>
108
+ item.id === updatedItem.id ? updatedItem : item
109
+ ),
110
+ data: updatedItem,
111
+ message: res.message,
112
+ rta: true,
113
+ });
114
+ }
115
+ })
116
+ );
117
+ }
118
+
119
+ @Action(ProductosActions.Delete)
120
+ override delete(ctx: StateContext<PlantillaResponse<ProductoDTO>>, action: any) {
121
+ return this.service.delete(action.queryParams).pipe(
122
+ tap((res) => {
123
+ const state = ctx.getState();
124
+ if (state.dataList) {
125
+ ctx.setState({
126
+ ...state,
127
+ dataList: state.dataList.filter((item: any) => item.id !== action.id),
128
+ message: res.message,
129
+ rta: true,
130
+ });
131
+ }
132
+ })
133
+ );
134
+ }
135
+ @Action(ProductosActions.LoadMock)
136
+ override loadMock(ctx: StateContext<PlantillaResponse<ProductoDTO>>) {
137
+ try {
138
+ const mockData = this.productSvc.mockProductosInflablesDTO();
139
+ ctx.patchState({
140
+ data: undefined,
141
+ dataList: mockData,
142
+ message: mockData.length
143
+ ? 'Datos mock cargados correctamente'
144
+ : 'No hay datos mock disponibles',
145
+ rta: !!mockData.length,
146
+ });
147
+ } catch (error) {
148
+ ctx.patchState({
149
+ data: undefined,
150
+ dataList: [],
151
+ message: 'Error al cargar datos mock ' + error,
152
+ rta: false,
153
+ });
154
+ }
155
+ }
156
+
157
+ }
@@ -0,0 +1,39 @@
1
+ import { QueryParams } from 'juliaositembackenexpress/dist/utils/queryParams';
2
+
3
+ // eslint-disable-next-line max-lines-per-function
4
+ export function createGenericCrudActions<RQ>(entityName: string) {
5
+
6
+ class All {
7
+ static readonly type = `[${entityName}] ALL`;
8
+ constructor(public payload: QueryParams, public filters?: Map<string, string>) {}
9
+ }
10
+
11
+ class Add {
12
+ static readonly type = `[${entityName}] ADD`;
13
+ constructor(public payload: RQ, public queryParams: QueryParams) {}
14
+ }
15
+
16
+ class Update {
17
+ static readonly type = `[${entityName}] UPDATE`;
18
+ constructor(public payload: RQ, public queryParams: QueryParams) {}
19
+ }
20
+
21
+ class Delete {
22
+ static readonly type = `[${entityName}] DELETE`;
23
+ constructor(public queryParams: QueryParams) {}
24
+ }
25
+
26
+ // Nueva acción para cargar datos mock en demos
27
+ class LoadMock {
28
+ static readonly type = `[${entityName}] LOAD_MOCK`;
29
+ constructor() {}
30
+ }
31
+
32
+ return {
33
+ All,
34
+ Add,
35
+ Update,
36
+ Delete,
37
+ LoadMock,
38
+ };
39
+ }
@@ -0,0 +1,83 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { Injectable } from '@angular/core';
3
+ import { StateContext, Selector, Action, createSelector } from '@ngxs/store';
4
+ import { PlantillaResponse } from 'juliaositembackenexpress/dist/utils/PlantillaResponse';
5
+ import { GenericCrudHttpService } from '../../../componentes/shared/services/generic-crud.service/generic-crud.service';
6
+ import { tap } from 'rxjs';
7
+
8
+ export interface GenericCrudActions<RQ> {
9
+ All: new (payload: any, filters?: Map<string, string>) => any;
10
+ Add: new (payload: RQ, queryParams: any) => any;
11
+ Update: new (payload: RQ, queryParams: any) => any;
12
+ Delete: new (queryParams: any) => any;
13
+ LoadMock: new () => any;
14
+ }
15
+
16
+ @Injectable()
17
+ export abstract class GenericCrudState<RES, RQ> {
18
+ protected constructor(
19
+ protected readonly service: GenericCrudHttpService<RES>,
20
+ protected readonly actions: GenericCrudActions<RQ>
21
+ ) {}
22
+
23
+ @Selector()
24
+ static getResponse<RES>(state: PlantillaResponse<RES>): PlantillaResponse<RES> {
25
+ return state;
26
+ }
27
+
28
+ /**
29
+ * Selector factory para obtener un elemento por id desde el estado genérico.
30
+ * Uso: store.selectSnapshot(YourState.selectById(id))
31
+ */
32
+ static selectById<RES>(id: string | number) {
33
+ return createSelector([
34
+ // Reutiliza el selector base que expone el response del estado
35
+ (this as unknown as typeof GenericCrudState).getResponse as (state: PlantillaResponse<RES>) => PlantillaResponse<RES>
36
+ ], (response: PlantillaResponse<RES>) => {
37
+ const list = (response?.dataList as unknown as Array<{ id?: string | number }> | undefined) ?? [];
38
+ return list.find((item) => String(item?.id ?? '') === String(id)) as unknown as RES | undefined;
39
+ });
40
+ }
41
+
42
+ @Action(function (this: GenericCrudState<RES, RQ>) { return this.actions.All; } as any)
43
+ All({ setState }: StateContext<PlantillaResponse<RES>>, action: any) {
44
+ return this.service.all(action.payload).pipe(
45
+ tap(res => setState(res))
46
+ );
47
+ }
48
+
49
+ @Action(function (this: GenericCrudState<RES, RQ>) { return this.actions.Add; } as any)
50
+ add(ctx: StateContext<PlantillaResponse<RES>>, action: any) {
51
+ return this.service.add(action.payload, action.queryParams);
52
+ }
53
+
54
+ @Action(function (this: GenericCrudState<RES, RQ>) { return this.actions.Update; } as any)
55
+ update(ctx: StateContext<PlantillaResponse<RES>>, action: any) {
56
+ return this.service.update(action.payload, action.queryParams);
57
+ }
58
+
59
+ @Action(function (this: GenericCrudState<RES, RQ>) { return this.actions.Delete; } as any)
60
+ delete(ctx: StateContext<PlantillaResponse<RES>>, action: any) {
61
+ return this.service.delete(action.queryParams);
62
+ }
63
+
64
+ @Action(function (this: GenericCrudState<RES, RQ>) { return this.actions.LoadMock; } as any)
65
+ loadMock(ctx: StateContext<PlantillaResponse<RES>>) {
66
+ try {
67
+ const mockData = (this.service as any).getMockData?.() ?? [];
68
+ ctx.patchState({
69
+ data: undefined,
70
+ dataList: mockData,
71
+ message: mockData.length ? 'Datos mock cargados correctamente' : 'No hay datos mock disponibles',
72
+ rta: !!mockData.length,
73
+ });
74
+ } catch (error) {
75
+ ctx.patchState({
76
+ data: undefined,
77
+ dataList: [],
78
+ message: 'Error al cargar datos mock ' + error,
79
+ rta: false,
80
+ });
81
+ }
82
+ }
83
+ }