@simplix-boot/cli 0.0.0-stage → 2.0.0
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/LICENSE +25 -0
- package/LICENSE_KO +28 -0
- package/README.md +144 -2
- package/bin/simplix-boot.js +4 -0
- package/package.json +44 -4
- package/src/cli.js +103 -0
- package/src/commands/config.js +129 -0
- package/src/commands/generate.js +291 -0
- package/src/commands/generated.js +125 -0
- package/src/commands/init.js +41 -0
- package/src/commands/promote.js +172 -0
- package/src/commands/templates.js +100 -0
- package/src/commands/version.js +134 -0
- package/src/lib/analysis/fields.js +217 -0
- package/src/lib/analysis/imports.js +76 -0
- package/src/lib/analysis/structure.js +193 -0
- package/src/lib/analysis/types.js +94 -0
- package/src/lib/args.js +69 -0
- package/src/lib/comment-extractor.js +141 -0
- package/src/lib/config/fields.js +321 -0
- package/src/lib/config/parents.js +108 -0
- package/src/lib/config/paths.js +156 -0
- package/src/lib/config/yml.js +61 -0
- package/src/lib/console.js +70 -0
- package/src/lib/controller-name.js +33 -0
- package/src/lib/entity-analyzer.js +49 -0
- package/src/lib/entity-type-resolver.js +80 -0
- package/src/lib/entity-type.js +35 -0
- package/src/lib/errors.js +17 -0
- package/src/lib/export-config.js +74 -0
- package/src/lib/file-utils.js +77 -0
- package/src/lib/generate/file-plan.js +155 -0
- package/src/lib/generate/search-fields.js +111 -0
- package/src/lib/generate/settings.js +111 -0
- package/src/lib/generate/support-classes.js +47 -0
- package/src/lib/generate/template-vars.js +183 -0
- package/src/lib/git-utils.js +18 -0
- package/src/lib/name-field.js +42 -0
- package/src/lib/project.js +121 -0
- package/src/lib/promote-files.js +132 -0
- package/src/lib/rendered-output.js +13 -0
- package/src/lib/search-operators.js +87 -0
- package/src/lib/templates.js +50 -0
- package/src/lib/tracked-render.js +200 -0
- package/src/lib/version-check.js +194 -0
- package/src/lib/version-utils.js +89 -0
- package/templates/controller/rest/EntityRestController.java.template +517 -0
- package/templates/controller/web/EntityWebController.java.template +211 -0
- package/templates/dto/EntityDTOs.java.template +981 -0
- package/templates/repository/EntityRepository.java.template +78 -0
- package/templates/service/EntityService.java.template +790 -0
- package/templates/service/EntityTreeService.java.template +352 -0
- package/templates/test/EntityServiceTest.java.template +937 -0
- package/templates/test/EntityTreeServiceTest.java.template +842 -0
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
package <%= packagePaths['service'] %>;
|
|
2
|
+
|
|
3
|
+
import <%= packagePaths['dto'] %>.<%= classPrefix %>DTOs.*;
|
|
4
|
+
import <%= entityPackage %>.<%= entityName %>;
|
|
5
|
+
<% if (hasEmbeddedId) { %>
|
|
6
|
+
import <%= entityPackage %>.<%= entityName %>.<%= embeddedIdType %>;
|
|
7
|
+
<% } %>
|
|
8
|
+
import <%= packagePaths.repository %>.<%= entityName %>Repository;
|
|
9
|
+
<%
|
|
10
|
+
// A list's cards: counts per enum value (statusCounts: [field, ...]) and figures over fields
|
|
11
|
+
// (aggregates: [{ field, op }]), both read under the list's own search parameters.
|
|
12
|
+
const statusCountFields = ymlConfig.statusCounts || [];
|
|
13
|
+
const aggregateItems = ymlConfig.aggregates || [];
|
|
14
|
+
const hasFigures = statusCountFields.length > 0 || aggregateItems.length > 0;
|
|
15
|
+
// The method a customised service forces the caller's scope with (figureScope: { method,
|
|
16
|
+
// mayMatchNothing }): it takes the client's parameters and returns them scoped, as a Map, or as an
|
|
17
|
+
// Optional that is empty when the caller reaches no row (mayMatchNothing: true). The figures are
|
|
18
|
+
// read under it, so a card never counts rows the list hides.
|
|
19
|
+
const figureScope = ymlConfig.figureScope && ymlConfig.figureScope.method;
|
|
20
|
+
const needsTypedRepository = ymlConfig.timeAxisField || hasFigures;
|
|
21
|
+
// The class of the application that holds the figure DTOs and the scope wrapper; the project
|
|
22
|
+
// configuration names it under supportClasses.searchFigures.
|
|
23
|
+
const searchFigures = hasFigures || (ymlConfig.timeAxisField && figureScope)
|
|
24
|
+
? supportClasses.require('searchFigures', hasFigures ? 'statusCounts or aggregates' : 'timeAxisField with figureScope')
|
|
25
|
+
: null;
|
|
26
|
+
%>
|
|
27
|
+
<% if (hasFigures) { %>
|
|
28
|
+
import dev.simplecore.searchable.core.service.aggregate.SearchAggregator;
|
|
29
|
+
import <%= searchFigures.fqn %>;
|
|
30
|
+
import <%= searchFigures.fqn %>.AggregateValueDTO;
|
|
31
|
+
import <%= searchFigures.fqn %>.ValueCountDTO;
|
|
32
|
+
<% } %>
|
|
33
|
+
<% if (ymlConfig.timeAxisField) { %>
|
|
34
|
+
<% if (figureScope && !hasFigures) { %>
|
|
35
|
+
import <%= searchFigures.fqn %>;
|
|
36
|
+
<% } %>
|
|
37
|
+
import dev.simplecore.searchable.core.service.bucket.TimeBucketCounter;
|
|
38
|
+
|
|
39
|
+
import java.time.Instant;
|
|
40
|
+
<% } %>
|
|
41
|
+
<%
|
|
42
|
+
// Parse import statements for reference entities (excluding self-reference)
|
|
43
|
+
// Only import services for ManyToMany references (multiple: true) since ManyToOne uses FK ID directly
|
|
44
|
+
const importedServices = new Set();
|
|
45
|
+
const importedDTOs = new Set();
|
|
46
|
+
|
|
47
|
+
// Find ManyToMany reference types from yml configuration and generate imports if different package
|
|
48
|
+
let hasManyToManyRefs = false;
|
|
49
|
+
if (ymlConfig && ymlConfig.fields) {
|
|
50
|
+
Object.entries(ymlConfig.fields).forEach(([fieldName, ymlField]) => {
|
|
51
|
+
// Only generate service imports for ManyToMany references (multiple: true)
|
|
52
|
+
if (ymlField.reference && ymlField.reference.entity && ymlField.reference.entity !== entityName && ymlField.reference.multiple) {
|
|
53
|
+
hasManyToManyRefs = true;
|
|
54
|
+
const refEntity = ymlField.reference.entity;
|
|
55
|
+
const refModulePath = ymlField.reference.modulePath;
|
|
56
|
+
|
|
57
|
+
if (!importedServices.has(refEntity)) {
|
|
58
|
+
importedServices.add(refEntity);
|
|
59
|
+
if (refModulePath && refModulePath !== modulePath) {
|
|
60
|
+
// Different package - generate import
|
|
61
|
+
const servicePackage = basePackage + '.' + refModulePath.replace(/\//g, '.') + '.service';
|
|
62
|
+
%>
|
|
63
|
+
import <%= servicePackage %>.<%= refEntity %>Service;<%
|
|
64
|
+
} else { %>
|
|
65
|
+
// <%= refEntity %>Service will be available in same package<%
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
// Also check entity fields for ManyToMany relations
|
|
72
|
+
if (!hasManyToManyRefs && fields) {
|
|
73
|
+
hasManyToManyRefs = fields.some(f => f.relationType === 'ManyToMany' || (f.isCollection && f.typeKind === 'entity'));
|
|
74
|
+
}
|
|
75
|
+
if (hasManyToManyRefs) { %>
|
|
76
|
+
import org.springframework.beans.factory.ObjectProvider;
|
|
77
|
+
<% }
|
|
78
|
+
|
|
79
|
+
// Import entity classes used in getReference() for @MapsId/@OneToOne entity reference fields
|
|
80
|
+
const importedEntityRefs = new Set();
|
|
81
|
+
if (ymlConfig && ymlConfig.fields && fields) {
|
|
82
|
+
Object.entries(ymlConfig.fields).forEach(([fieldName, ymlField]) => {
|
|
83
|
+
if (ymlField.reference && !ymlField.reference.multiple && ymlField.reference.entity !== entityName) {
|
|
84
|
+
const entityField = fields.find(f => f.name === fieldName);
|
|
85
|
+
if (entityField && entityField.typeKind === 'entity' &&
|
|
86
|
+
(entityField.relationType === 'OneToOne' || entityField.relationType === 'ManyToOne')) {
|
|
87
|
+
const refEntity = ymlField.reference.entity;
|
|
88
|
+
if (!importedEntityRefs.has(refEntity) && entityField.importPath) {
|
|
89
|
+
importedEntityRefs.add(refEntity); %>
|
|
90
|
+
import <%= entityField.importPath %>;
|
|
91
|
+
<% }
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
} %>
|
|
96
|
+
|
|
97
|
+
<%
|
|
98
|
+
// ============== LOCALIZED FIELDS ==============
|
|
99
|
+
// Fields a list searches and sorts through the columns derived from a locale map. The pairing is
|
|
100
|
+
// I18nDerivedColumnListener's, and the DTO template repeats it to point the SearchDTO at those
|
|
101
|
+
// columns: a <x>I18n map beside a <x> base column, with at least one <x>Search or <x>Sort<Lang>
|
|
102
|
+
// following. The two templates cannot share this - EJS is rendered here without a filename, so
|
|
103
|
+
// there is no partial to include - which is why the listener, not either template, is the
|
|
104
|
+
// pairing's original.
|
|
105
|
+
//
|
|
106
|
+
// The rewrite is the application's: the project configuration names the class that moves a search
|
|
107
|
+
// over a localized field onto its derived columns under supportClasses.localizedSearchParams.
|
|
108
|
+
// Without it a localized field is searched and sorted as the plain column it also is.
|
|
109
|
+
const localizedSearchParams = supportClasses.find('localizedSearchParams');
|
|
110
|
+
const localizedFields = (localizedSearchParams ? entityFields : [])
|
|
111
|
+
.filter(field => field.name.endsWith('I18n')
|
|
112
|
+
&& entityFields.some(base => base.name === field.name.slice(0, -4) && base.type === 'String'))
|
|
113
|
+
.map(field => field.name.slice(0, -4))
|
|
114
|
+
.filter(root => entityFields.some(derived => derived.type === 'String'
|
|
115
|
+
&& (derived.name === `${root}Search`
|
|
116
|
+
|| (derived.name.startsWith(`${root}Sort`) && derived.name.length > `${root}Sort`.length))))
|
|
117
|
+
// Only a field this surface's yml declares reaches its SearchDTO; a second surface over the
|
|
118
|
+
// same entity (a self-scoped portal list) that leaves the name out has nothing to rewrite.
|
|
119
|
+
.filter(root => Boolean(ymlConfig.fields && ymlConfig.fields[root]));
|
|
120
|
+
|
|
121
|
+
const localizedFieldArgs = localizedFields.map(root => `"${root}"`).join(', ');
|
|
122
|
+
if (localizedFields.length > 0) { %>
|
|
123
|
+
import <%= localizedSearchParams.fqn %>;
|
|
124
|
+
<% } %>
|
|
125
|
+
import dev.simplecore.simplix.core.exception.ErrorCode;
|
|
126
|
+
import dev.simplecore.simplix.core.exception.SimpliXGeneralException;
|
|
127
|
+
import dev.simplecore.simplix.web.service.SimpliXBaseService;
|
|
128
|
+
import dev.simplecore.searchable.core.condition.SearchCondition;
|
|
129
|
+
import dev.simplecore.searchable.core.condition.parser.SearchableParamsParser;
|
|
130
|
+
import org.springframework.context.MessageSource;
|
|
131
|
+
import org.springframework.data.domain.Page;
|
|
132
|
+
<% if (exportConfig.enabled) { -%>
|
|
133
|
+
import dev.simplecore.simplix.excel.export.SearchExport;
|
|
134
|
+
import dev.simplecore.simplix.excel.export.ExportFormat;
|
|
135
|
+
import jakarta.servlet.http.HttpServletResponse;
|
|
136
|
+
import java.io.IOException;
|
|
137
|
+
<% } -%>
|
|
138
|
+
import org.springframework.stereotype.Service;
|
|
139
|
+
import org.springframework.transaction.annotation.Transactional;
|
|
140
|
+
|
|
141
|
+
import jakarta.persistence.EntityManager;
|
|
142
|
+
import java.util.*;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Service class for managing <%= entityName %> entities.
|
|
146
|
+
* Provides business logic for CRUD operations, batch processing, and search functionality for <%= entityName %> entities.
|
|
147
|
+
<% if (hasEmbeddedId) { %>
|
|
148
|
+
* This entity uses a composite key (<%= embeddedIdType %>).
|
|
149
|
+
<% } %>
|
|
150
|
+
*/
|
|
151
|
+
@Service
|
|
152
|
+
@Transactional(readOnly = true)
|
|
153
|
+
public class <%= classPrefix %>Service extends SimpliXBaseService<<%= entityName %>, <%= idType %>> {
|
|
154
|
+
<%
|
|
155
|
+
// Helper: Check if a type is a standard Java library type that should NOT be treated as an entity
|
|
156
|
+
function isStandardJavaType(typeName) {
|
|
157
|
+
if (!typeName) return false;
|
|
158
|
+
// Skip java.* types
|
|
159
|
+
if (typeName.startsWith('java.')) return true;
|
|
160
|
+
// Skip common Java types
|
|
161
|
+
const standardTypes = ['Instant', 'LocalDate', 'LocalDateTime', 'ZonedDateTime', 'Duration',
|
|
162
|
+
'BigDecimal', 'BigInteger', 'UUID', 'Optional',
|
|
163
|
+
'List', 'Set', 'Map', 'Collection', 'Iterable', 'String', 'Integer', 'Long', 'Boolean'];
|
|
164
|
+
return standardTypes.includes(typeName);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Helper: Check if field name already ends with 'Id' (to avoid 'IdId' pattern)
|
|
168
|
+
function fieldNameEndsWithId(fieldName) {
|
|
169
|
+
return fieldName.endsWith('Id') && fieldName !== 'Id';
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Helper: Get Lombok setter suffix for entity fields
|
|
173
|
+
// For primitive boolean fields with 'is' prefix, Lombok strips 'is': isOnline -> setOnline()
|
|
174
|
+
// For all other fields, the setter is the capitalized field name: name -> setName()
|
|
175
|
+
function getEntitySetterSuffix(field) {
|
|
176
|
+
if (field.type === 'boolean' && field.name.startsWith('is') && field.name.length > 2) {
|
|
177
|
+
return field.name.charAt(2).toUpperCase() + field.name.slice(3);
|
|
178
|
+
}
|
|
179
|
+
return field.name.charAt(0).toUpperCase() + field.name.slice(1);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Helper: Check if a reference field is an entity object (OneToOne/ManyToOne) vs a String FK ID field
|
|
183
|
+
function isEntityReferenceField(fieldName) {
|
|
184
|
+
const entityField = fields.find(f => f.name === fieldName);
|
|
185
|
+
return entityField && entityField.typeKind === 'entity' &&
|
|
186
|
+
(entityField.relationType === 'OneToOne' || entityField.relationType === 'ManyToOne');
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Helper: whether a reference is written through the create and update DTOs. Those DTOs carry
|
|
190
|
+
// the fields whose views include 'edit'; a reference shown only on the list or the detail is
|
|
191
|
+
// read-only, so nothing hands it to saveAndGetProjection and its DTO has no getter to read it from.
|
|
192
|
+
function isWrittenReference(field) {
|
|
193
|
+
return Boolean(field.reference && field.reference.entity !== entityName && field.views?.includes('edit'));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Helper: whether a referencing field holds the key itself (a scalar column such as grantedBy)
|
|
197
|
+
// rather than an association whose key sits one step further; the field's own type decides.
|
|
198
|
+
function holdsReferenceKey(fieldName) {
|
|
199
|
+
if (fieldNameEndsWithId(fieldName)) return true;
|
|
200
|
+
const entityField = fields.find(f => f.name === fieldName);
|
|
201
|
+
return Boolean(entityField) && entityField.typeKind !== 'entity' && !entityField.isCollection;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Helper: Get DTO field name for reference field (avoids 'IdId' pattern)
|
|
205
|
+
function getDtoFieldName(fieldName, isCollection) {
|
|
206
|
+
if (isCollection) {
|
|
207
|
+
return fieldNameEndsWithId(fieldName) ? `${fieldName}s` : `${fieldName}Ids`;
|
|
208
|
+
} else {
|
|
209
|
+
return holdsReferenceKey(fieldName) ? fieldName : `${fieldName}Id`;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Reference service member variables (only for ManyToMany - ManyToOne uses FK ID directly)
|
|
214
|
+
const addedServices = new Set();
|
|
215
|
+
fields.forEach(field => {
|
|
216
|
+
const ymlField = ymlConfig.fields?.[field.name];
|
|
217
|
+
// Only add service providers for ManyToMany relationships (collection references)
|
|
218
|
+
if (field.relationType === 'ManyToMany' || (field.isCollection && field.typeKind === 'entity')) {
|
|
219
|
+
const entityType = field.actualType || field.type;
|
|
220
|
+
// Skip self-reference fields and standard Java types
|
|
221
|
+
if (!addedServices.has(entityType) && entityType !== entityName && !isStandardJavaType(entityType)) {
|
|
222
|
+
addedServices.add(entityType); %>
|
|
223
|
+
private final ObjectProvider<<%= entityType %>Service> <%= _.camelCase(entityType + 'Service') %>Provider;
|
|
224
|
+
<% }
|
|
225
|
+
}
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
// Find additional ManyToMany reference types from yml configuration (excluding self-reference)
|
|
229
|
+
if (ymlConfig && ymlConfig.fields) {
|
|
230
|
+
Object.values(ymlConfig.fields).forEach(field => {
|
|
231
|
+
// Only generate for ManyToMany references (multiple: true)
|
|
232
|
+
if (field.reference && field.reference.entity && field.reference.multiple && !addedServices.has(field.reference.entity) && field.reference.entity !== entityName) {
|
|
233
|
+
addedServices.add(field.reference.entity); %>
|
|
234
|
+
private final ObjectProvider<<%= field.reference.entity %>Service> <%= _.camelCase(field.reference.entity + 'Service') %>Provider;
|
|
235
|
+
<% }
|
|
236
|
+
});
|
|
237
|
+
} %>
|
|
238
|
+
private final MessageSource messageSource;
|
|
239
|
+
<% if (needsTypedRepository) { %>
|
|
240
|
+
private final <%= entityName %>Repository repository;
|
|
241
|
+
<% } %>
|
|
242
|
+
<% if (ymlConfig.timeAxisField) { %>
|
|
243
|
+
private final TimeBucketCounter timeBucketCounter;
|
|
244
|
+
<% } %>
|
|
245
|
+
<% if (hasFigures) { %>
|
|
246
|
+
private final SearchAggregator searchAggregator;
|
|
247
|
+
<% } %>
|
|
248
|
+
/**
|
|
249
|
+
* Constructs a new <%= classPrefix %>Service with required dependencies.
|
|
250
|
+
*
|
|
251
|
+
* @param repository The repository for <%= entityName %> entities
|
|
252
|
+
* @param entityManager JPA EntityManager for database operations<%
|
|
253
|
+
Array.from(addedServices).forEach(entity => { %>
|
|
254
|
+
* @param <%= _.camelCase(entity + 'Service') %>Provider Provider for <%= entity %> service<%
|
|
255
|
+
}); %>
|
|
256
|
+
* @param messageSource Message source for i18n error messages<% if (ymlConfig.timeAxisField) { %>
|
|
257
|
+
* @param timeBucketCounter Counts the same rows per slice of time, for the range selector<% } %><% if (hasFigures) { %>
|
|
258
|
+
* @param searchAggregator Counts and sums the same rows, for the cards above the list<% } %>
|
|
259
|
+
*/
|
|
260
|
+
public <%= classPrefix %>Service(
|
|
261
|
+
<%= entityName %>Repository repository,
|
|
262
|
+
EntityManager entityManager<%
|
|
263
|
+
Array.from(addedServices).forEach(entity => { %>,
|
|
264
|
+
ObjectProvider<<%= entity %>Service> <%= _.camelCase(entity + 'Service') %>Provider<%
|
|
265
|
+
}); %>,
|
|
266
|
+
MessageSource messageSource<% if (ymlConfig.timeAxisField) { %>,
|
|
267
|
+
TimeBucketCounter timeBucketCounter<% } %><% if (hasFigures) { %>,
|
|
268
|
+
SearchAggregator searchAggregator<% } %>
|
|
269
|
+
) {
|
|
270
|
+
super(repository, entityManager);
|
|
271
|
+
<% Array.from(addedServices).forEach(entity => { %>
|
|
272
|
+
this.<%= _.camelCase(entity + 'Service') %>Provider = <%= _.camelCase(entity + 'Service') %>Provider;<%
|
|
273
|
+
}); %>
|
|
274
|
+
this.messageSource = messageSource;
|
|
275
|
+
<% if (needsTypedRepository) { %>
|
|
276
|
+
this.repository = repository;
|
|
277
|
+
<% } %>
|
|
278
|
+
<% if (ymlConfig.timeAxisField) { %>
|
|
279
|
+
this.timeBucketCounter = timeBucketCounter;
|
|
280
|
+
<% } %>
|
|
281
|
+
<% if (hasFigures) { %>
|
|
282
|
+
this.searchAggregator = searchAggregator;
|
|
283
|
+
<% } %>
|
|
284
|
+
}
|
|
285
|
+
<% if (ymlConfig.timeAxisField) { %>
|
|
286
|
+
/** The field a window over this record is measured on. */
|
|
287
|
+
private static final String TIME_AXIS_FIELD = "<%= ymlConfig.timeAxisField %>";
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Counts entries per slice of a window, under the conditions the list is currently read with.
|
|
291
|
+
*
|
|
292
|
+
* @param params Map of search parameters, the window keys already removed
|
|
293
|
+
* @param from the first instant in the window, inclusive
|
|
294
|
+
* @param to the instant the window ends at, exclusive
|
|
295
|
+
* @param buckets how many slices to divide the window into
|
|
296
|
+
* @return one count per bucket, oldest first
|
|
297
|
+
*/
|
|
298
|
+
public List<Long> countBuckets(Map<String, String> params, Instant from, Instant to, int buckets) {
|
|
299
|
+
<% if (figureScope) { -%>
|
|
300
|
+
// The strip counts the rows the list can show, so the caller's scope is forced as the list forces it.
|
|
301
|
+
return <%= searchFigures.name %>.scoped(<%= figureScope %>(new LinkedHashMap<>(params == null ? Map.of() : params)))
|
|
302
|
+
.map(scoped -> timeBucketCounter.count(<%= entityName %>.class, repository, bucketCondition(scoped),
|
|
303
|
+
TIME_AXIS_FIELD, from, to, buckets))
|
|
304
|
+
.orElseGet(() -> Collections.nCopies(buckets, 0L));
|
|
305
|
+
<% } else { -%>
|
|
306
|
+
return timeBucketCounter.count(<%= entityName %>.class, repository, bucketCondition(params == null ? Map.of() : params),
|
|
307
|
+
TIME_AXIS_FIELD, from, to, buckets);
|
|
308
|
+
<% } -%>
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
private SearchCondition<<%= classPrefix %>SearchDTO> bucketCondition(Map<String, String> params) {
|
|
312
|
+
return new SearchableParamsParser<<%= classPrefix %>SearchDTO>(<%= classPrefix %>SearchDTO.class)
|
|
313
|
+
<% if (localizedFields.length > 0) { %> .convert(<%= localizedSearchParams.name %>.rewrite(params, <%= localizedFieldArgs %>));
|
|
314
|
+
<% } else { %> .convert(params);
|
|
315
|
+
<% } -%>
|
|
316
|
+
}
|
|
317
|
+
<% } %>
|
|
318
|
+
<% if (statusCountFields.length > 0) { %>
|
|
319
|
+
/** The fields the list's cards count rows by. */
|
|
320
|
+
private static final Set<String> STATUS_COUNT_FIELDS = Set.of(<%- statusCountFields.map(f => `"${f}"`).join(', ') %>);
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Counts entries per value of one field, under the conditions the list is currently read with.
|
|
324
|
+
*
|
|
325
|
+
* @param field one of the fields the entity's generator input lists under {@code statusCounts}
|
|
326
|
+
* @param params Map of search parameters, {@code field} among them or not
|
|
327
|
+
* @return one count per value, every enum constant in declaration order
|
|
328
|
+
*/
|
|
329
|
+
public List<ValueCountDTO> statusCounts(String field, Map<String, String> params) {
|
|
330
|
+
if (!STATUS_COUNT_FIELDS.contains(field)) {
|
|
331
|
+
throw new SimpliXGeneralException(ErrorCode.GEN_BAD_REQUEST, "{error.search.countFieldUnknown}", null);
|
|
332
|
+
}
|
|
333
|
+
Map<String, String> filters = new LinkedHashMap<>(params == null ? Map.of() : params);
|
|
334
|
+
filters.remove("field");
|
|
335
|
+
<% if (figureScope) { -%>
|
|
336
|
+
return <%= searchFigures.name %>.scoped(<%= figureScope %>(filters))
|
|
337
|
+
.map(scoped -> searchAggregator.countByValue(<%= entityName %>.class, repository, figureCondition(scoped), field)
|
|
338
|
+
.stream().map(ValueCountDTO::of).toList())
|
|
339
|
+
.orElseGet(List::of);
|
|
340
|
+
<% } else { -%>
|
|
341
|
+
return searchAggregator.countByValue(<%= entityName %>.class, repository, figureCondition(filters), field)
|
|
342
|
+
.stream().map(ValueCountDTO::of).toList();
|
|
343
|
+
<% } -%>
|
|
344
|
+
}
|
|
345
|
+
<% } %>
|
|
346
|
+
<% if (aggregateItems.length > 0) { %>
|
|
347
|
+
/** The figures the list's cards show, in the order they are returned. */
|
|
348
|
+
private static final List<SearchAggregator.Aggregate> AGGREGATES = List.of(<% aggregateItems.forEach((a, i) => { %>
|
|
349
|
+
new SearchAggregator.Aggregate("<%= a.field %>", SearchAggregator.Op.parse("<%= a.op %>"))<%= i < aggregateItems.length - 1 ? ',' : '' %><% }); %>);
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Computes the list's figures, under the conditions the list is currently read with.
|
|
353
|
+
*
|
|
354
|
+
* @param params Map of search parameters
|
|
355
|
+
* @return one value per figure the entity's generator input lists under {@code aggregates}
|
|
356
|
+
*/
|
|
357
|
+
public List<AggregateValueDTO> aggregates(Map<String, String> params) {
|
|
358
|
+
<% if (figureScope) { -%>
|
|
359
|
+
return <%= searchFigures.name %>.scoped(<%= figureScope %>(params == null ? Map.of() : params))
|
|
360
|
+
.map(scoped -> searchAggregator.aggregate(<%= entityName %>.class, repository,
|
|
361
|
+
figureCondition(scoped), AGGREGATES)
|
|
362
|
+
.stream().map(AggregateValueDTO::of).toList())
|
|
363
|
+
.orElseGet(() -> AGGREGATES.stream().map(AggregateValueDTO::empty).toList());
|
|
364
|
+
<% } else { -%>
|
|
365
|
+
return searchAggregator.aggregate(<%= entityName %>.class, repository,
|
|
366
|
+
figureCondition(params == null ? Map.of() : params), AGGREGATES)
|
|
367
|
+
.stream().map(AggregateValueDTO::of).toList();
|
|
368
|
+
<% } -%>
|
|
369
|
+
}
|
|
370
|
+
<% } %>
|
|
371
|
+
<% if (hasFigures) { %>
|
|
372
|
+
private SearchCondition<<%= classPrefix %>SearchDTO> figureCondition(Map<String, String> params) {
|
|
373
|
+
return new SearchableParamsParser<<%= classPrefix %>SearchDTO>(<%= classPrefix %>SearchDTO.class)
|
|
374
|
+
<% if (localizedFields.length > 0) { %> .convert(<%= localizedSearchParams.name %>.rewrite(params, <%= localizedFieldArgs %>));
|
|
375
|
+
<% } else { %> .convert(params);
|
|
376
|
+
<% } -%>
|
|
377
|
+
}
|
|
378
|
+
<% } %>
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Creates a new <%= entityName %> entity from the provided DTO.
|
|
382
|
+
*
|
|
383
|
+
* @param createDTO DTO containing the data for the new <%= entityName %>
|
|
384
|
+
* @return <%= classPrefix %>DetailDTO of the created entity
|
|
385
|
+
* @throws SimpliXGeneralException with ErrorCode.GEN_NOT_FOUND if the saved entity cannot be retrieved
|
|
386
|
+
*/
|
|
387
|
+
@Transactional
|
|
388
|
+
public <%= classPrefix %>DetailDTO create(<%= classPrefix %>CreateDTO createDTO) {
|
|
389
|
+
<%= entityName %> entity = new <%= entityName %>();
|
|
390
|
+
modelMapper.map(createDTO, entity);
|
|
391
|
+
<%
|
|
392
|
+
// Generate auto-increment sortOrder logic if sortOrderConfig is present
|
|
393
|
+
if (ymlConfig && ymlConfig.sortOrderConfig && ymlConfig.sortOrderConfig.autoIncrement) {
|
|
394
|
+
const field = ymlConfig.sortOrderConfig.field;
|
|
395
|
+
const upperField = field.charAt(0).toUpperCase() + field.slice(1);
|
|
396
|
+
const scopeFields = ymlConfig.sortOrderConfig.scopeFields || [];
|
|
397
|
+
const gap = ymlConfig.sortOrderConfig.gap || 100;
|
|
398
|
+
|
|
399
|
+
if (scopeFields.length === 0) {
|
|
400
|
+
// Global scope - no condition needed
|
|
401
|
+
%>
|
|
402
|
+
// Auto-increment <%= field %> if not explicitly provided
|
|
403
|
+
if (entity.get<%= upperField %>() == null || entity.get<%= upperField %>() == 0) {
|
|
404
|
+
<%= entityName %>Repository typedRepository = (<%= entityName %>Repository) repository;
|
|
405
|
+
Integer max<%= upperField %> = typedRepository.findMax<%= upperField %>();
|
|
406
|
+
entity.set<%= upperField %>(max<%= upperField %> + <%= gap %>);
|
|
407
|
+
}
|
|
408
|
+
<% } else {
|
|
409
|
+
// Scoped - check if scope field is provided
|
|
410
|
+
const firstScopeField = scopeFields[0];
|
|
411
|
+
const upperFirstScopeField = firstScopeField.charAt(0).toUpperCase() + firstScopeField.slice(1);
|
|
412
|
+
const methodSuffix = scopeFields.map(f => f.charAt(0).toUpperCase() + f.slice(1)).join('And');
|
|
413
|
+
const getterArgs = scopeFields.map(f => `createDTO.get${f.charAt(0).toUpperCase() + f.slice(1)}()`).join(', ');
|
|
414
|
+
%>
|
|
415
|
+
// Auto-increment <%= field %> if not explicitly provided (scoped by <%= scopeFields.join(', ') %>)
|
|
416
|
+
if (entity.get<%= upperField %>() == null || entity.get<%= upperField %>() == 0) {
|
|
417
|
+
if (createDTO.get<%= upperFirstScopeField %>() != null) {
|
|
418
|
+
<%= entityName %>Repository typedRepository = (<%= entityName %>Repository) repository;
|
|
419
|
+
Integer max<%= upperField %> = typedRepository.findMax<%= upperField %>By<%= methodSuffix %>(<%= getterArgs %>);
|
|
420
|
+
entity.set<%= upperField %>(max<%= upperField %> + <%= gap %>);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
<% }
|
|
424
|
+
} %>
|
|
425
|
+
return saveAndGetProjection(entity<%
|
|
426
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
427
|
+
// Skip self-reference fields (e.g., parent referencing same entity)
|
|
428
|
+
if (isWrittenReference(field)) {
|
|
429
|
+
const entityField = fields.find(f => f.name === fieldName);
|
|
430
|
+
const isCollection = entityField && (entityField.isCollection || entityField.type?.startsWith('Set<') || entityField.type?.startsWith('List<') || entityField.relationType === 'ManyToMany');
|
|
431
|
+
// Use getDtoFieldName helper to avoid 'IdId' pattern
|
|
432
|
+
const dtoFieldName = getDtoFieldName(fieldName, isCollection);
|
|
433
|
+
%>, createDTO.get<%= dtoFieldName.charAt(0).toUpperCase() + dtoFieldName.slice(1) %>()<%
|
|
434
|
+
}
|
|
435
|
+
}); %>);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Updates an existing <%= entityName %> entity with the provided DTO data.
|
|
440
|
+
*
|
|
441
|
+
* @param entity The existing <%= entityName %> entity to update
|
|
442
|
+
* @param updateDto DTO containing the updated data
|
|
443
|
+
* @return <%= classPrefix %>DetailDTO of the updated entity
|
|
444
|
+
* @throws SimpliXGeneralException with ErrorCode.GEN_CONFLICT if the <%= ymlConfig.idField %> is changed, or ErrorCode.GEN_NOT_FOUND if the saved entity cannot be retrieved
|
|
445
|
+
*/
|
|
446
|
+
@Transactional
|
|
447
|
+
public <%= classPrefix %>DetailDTO update(<%= entityName %> entity, <%= classPrefix %>UpdateDTO updateDto) {
|
|
448
|
+
if (!Objects.equals(entity.get<%= capitalizeFirstLetter(ymlConfig.idField) %>(), updateDto.get<%= capitalizeFirstLetter(ymlConfig.idField) %>())) {
|
|
449
|
+
throw new SimpliXGeneralException(ErrorCode.GEN_CONFLICT, "{error.id.cannot.change}", null);
|
|
450
|
+
}
|
|
451
|
+
modelMapper.map(updateDto, entity);
|
|
452
|
+
return saveAndGetProjection(entity<%
|
|
453
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
454
|
+
// Skip self-reference fields (e.g., parent referencing same entity)
|
|
455
|
+
if (isWrittenReference(field)) {
|
|
456
|
+
const entityField = fields.find(f => f.name === fieldName);
|
|
457
|
+
const isCollection = entityField && (entityField.isCollection || entityField.type?.startsWith('Set<') || entityField.type?.startsWith('List<') || entityField.relationType === 'ManyToMany');
|
|
458
|
+
// Use getDtoFieldName helper to avoid 'IdId' pattern
|
|
459
|
+
const dtoFieldName = getDtoFieldName(fieldName, isCollection);
|
|
460
|
+
%>, updateDto.get<%= dtoFieldName.charAt(0).toUpperCase() + dtoFieldName.slice(1) %>()<%
|
|
461
|
+
}
|
|
462
|
+
}); %>);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Deletes a <%= entityName %> entity by its ID.
|
|
467
|
+
*
|
|
468
|
+
* @param <%= ymlConfig.idField %> The ID of the <%= entityName %> to delete
|
|
469
|
+
*/
|
|
470
|
+
@Transactional
|
|
471
|
+
public void delete(<%= idType %> <%= ymlConfig.idField %>) {
|
|
472
|
+
deleteById(<%= ymlConfig.idField %>);
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Deletes multiple <%= entityName %> entities by their IDs.
|
|
477
|
+
*
|
|
478
|
+
* @param <%= ymlConfig.idField %>s List of <%= entityName %> IDs to delete
|
|
479
|
+
*/
|
|
480
|
+
@Transactional
|
|
481
|
+
public void batchDelete(List<<%= idType %>> <%= ymlConfig.idField %>s) {
|
|
482
|
+
deleteAllByIds(<%= ymlConfig.idField %>s);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Searches for <%= entityName %> entities using provided search parameters.
|
|
487
|
+
*
|
|
488
|
+
<% if (localizedFields.length > 0) { %> * <p>A sort over a localized name is moved onto the column of the language the caller is
|
|
489
|
+
* reading, and the term typed into its filter is folded the way the stored value was. Without
|
|
490
|
+
* the first the list orders by whichever language the record happened to be created in;
|
|
491
|
+
* without the second a term whose case differs matches nothing.
|
|
492
|
+
*
|
|
493
|
+
<% } %> * @param params Map of search parameters and their values
|
|
494
|
+
* @return Page of <%= classPrefix %>ListDTO matching the search criteria
|
|
495
|
+
*/
|
|
496
|
+
public Page<<%= classPrefix %>ListDTO> search(Map<String, String> params) {
|
|
497
|
+
SearchCondition<<%= classPrefix %>SearchDTO> searchCondition =
|
|
498
|
+
new SearchableParamsParser<<%= classPrefix %>SearchDTO>(<%= classPrefix %>SearchDTO.class)
|
|
499
|
+
<% if (localizedFields.length > 0) { %> .convert(<%= localizedSearchParams.name %>.rewrite(params, <%= localizedFieldArgs %>));
|
|
500
|
+
<% } else { %> .convert(params);
|
|
501
|
+
<% } %> return findAllWithSearch(searchCondition, <%= classPrefix %>ListDTO.class);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Searches for <%= entityName %> entities using a SearchCondition object.
|
|
506
|
+
*
|
|
507
|
+
* @param searchCondition Search conditions for filtering <%= entityName %> entities
|
|
508
|
+
* @return Page of <%= classPrefix %>ListDTO matching the search criteria
|
|
509
|
+
*/
|
|
510
|
+
public Page<<%= classPrefix %>ListDTO> search(SearchCondition<<%= classPrefix %>SearchDTO> searchCondition) {
|
|
511
|
+
return findAllWithSearch(searchCondition, <%= classPrefix %>ListDTO.class);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
<% if (exportConfig.enabled) { %>
|
|
515
|
+
/**
|
|
516
|
+
* Writes every entry the list's search parameters match, so the file holds what the list
|
|
517
|
+
* shows under the same filters and order rather than only its first page.
|
|
518
|
+
*
|
|
519
|
+
* @param params the list's search parameters; {@code page} and {@code size} are ignored
|
|
520
|
+
* @param format the file kind
|
|
521
|
+
* @param response where the file is written
|
|
522
|
+
* @throws IOException when the response cannot be written
|
|
523
|
+
*/
|
|
524
|
+
public void export(Map<String, String> params, ExportFormat format, HttpServletResponse response)
|
|
525
|
+
throws IOException {
|
|
526
|
+
SearchExport.of(<%= exportConfig.dto %>.class, filters -> search(filters)<%= exportConfig.mapper %>)
|
|
527
|
+
.baseName("<%= exportConfig.baseName %>")
|
|
528
|
+
.write(params, format, response);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
<% } %>
|
|
532
|
+
/**
|
|
533
|
+
* Updates multiple <%= entityName %> entities in a single operation.
|
|
534
|
+
*
|
|
535
|
+
* @param updateDtos Set of DTOs containing update data for multiple <%= entityName %>s
|
|
536
|
+
* @return List of <%= classPrefix %>DetailDTO for the updated entities
|
|
537
|
+
* @throws SimpliXGeneralException with ErrorCode.GEN_CONFLICT or ErrorCode.GEN_NOT_FOUND propagated from update()
|
|
538
|
+
*/
|
|
539
|
+
@Transactional
|
|
540
|
+
public List<<%= classPrefix %>DetailDTO> multiUpdate(Set<<%= classPrefix %>UpdateDTO> updateDtos) {
|
|
541
|
+
List<<%= classPrefix %>DetailDTO> updatedEntities = new ArrayList<>();
|
|
542
|
+
|
|
543
|
+
for (<%= classPrefix %>UpdateDTO updateDto : updateDtos) {
|
|
544
|
+
if (updateDto.get<%= ymlConfig.idField.charAt(0).toUpperCase() + ymlConfig.idField.slice(1) %>() == null) {
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
Optional<<%= entityName %>> entityOpt = findById(updateDto.get<%= ymlConfig.idField.charAt(0).toUpperCase() + ymlConfig.idField.slice(1) %>());
|
|
549
|
+
if (entityOpt.isPresent()) {
|
|
550
|
+
<%= entityName %> entity = entityOpt.get();
|
|
551
|
+
<%= classPrefix %>DetailDTO updatedEntity = update(entity, updateDto);
|
|
552
|
+
updatedEntities.add(updatedEntity);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
return updatedEntities;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Performs batch updates on multiple <%= entityName %> entities.
|
|
561
|
+
*
|
|
562
|
+
* @param dto DTO containing the batch update data and target IDs<% const hasBatchUpdateFields = fields.some(field => { const ymlField = ymlConfig.fields?.[field.name]; return ymlField?.views?.includes('batchUpdate'); }); if (!hasBatchUpdateFields) { %>
|
|
563
|
+
* @throws UnsupportedOperationException always, as no fields are configured for batch update<% } %>
|
|
564
|
+
*/
|
|
565
|
+
@Transactional
|
|
566
|
+
public void batchUpdate(<%= classPrefix %>BatchUpdateDTO dto) {
|
|
567
|
+
<% if (hasBatchUpdateFields) { %>List<<%= entityName %>> entities = findAllById(dto.get<%= ymlConfig.idField.charAt(0).toUpperCase() + ymlConfig.idField.slice(1) %>s());
|
|
568
|
+
|
|
569
|
+
if (!entities.isEmpty()) {
|
|
570
|
+
entities.forEach(entity -> {
|
|
571
|
+
<% fields.forEach(field => {
|
|
572
|
+
// Process only fields allowed for batchUpdate from yml configuration
|
|
573
|
+
const ymlField = ymlConfig.fields?.[field.name];
|
|
574
|
+
if (!ymlField?.views?.includes('batchUpdate')) return;
|
|
575
|
+
|
|
576
|
+
const upperFieldName = field.name.charAt(0).toUpperCase() + field.name.slice(1);
|
|
577
|
+
if (field.typeKind === 'entity' || field.isRelation || field.relationType === 'ManyToOne') {
|
|
578
|
+
const idFieldName = ymlField.reference.idField;
|
|
579
|
+
const upperIdFieldName = idFieldName.charAt(0).toUpperCase() + idFieldName.slice(1);
|
|
580
|
+
if (field.isCollection || field.relationType === 'ManyToMany') { %>
|
|
581
|
+
if (dto.get<%= upperIdFieldName %>s() != null) {
|
|
582
|
+
<%
|
|
583
|
+
const collectionImpl = field.collectionType === 'List' ? 'ArrayList' : 'HashSet';
|
|
584
|
+
const entityType = field.isCollection ? field.actualType : field.type;
|
|
585
|
+
%>
|
|
586
|
+
entity.set<%= upperFieldName %>(new <%= collectionImpl %><>(<%= _.camelCase(entityType + 'Service') %>Provider.getIfAvailable().findAllById(dto.get<%= upperIdFieldName %>s())));
|
|
587
|
+
}
|
|
588
|
+
<% } else { %>
|
|
589
|
+
if (dto.get<%= upperIdFieldName %>() != null) {
|
|
590
|
+
entity.set<%= upperIdFieldName %>(dto.get<%= upperIdFieldName %>());
|
|
591
|
+
}
|
|
592
|
+
<% }
|
|
593
|
+
} else {
|
|
594
|
+
const setterSuffix = getEntitySetterSuffix(field); %>
|
|
595
|
+
if (dto.get<%= upperFieldName %>() != null) {
|
|
596
|
+
entity.set<%= setterSuffix %>(dto.get<%= upperFieldName %>());
|
|
597
|
+
}
|
|
598
|
+
<% }}); %>
|
|
599
|
+
});
|
|
600
|
+
|
|
601
|
+
saveAll(entities);
|
|
602
|
+
}<% } else {
|
|
603
|
+
%>// TODO: No fields configured for batch update - consider removing this method if not needed
|
|
604
|
+
throw new UnsupportedOperationException("Unimplemented method 'batchUpdate'");<% } %>
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
//----------------------------------
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* Saves a <%= entityName %> entity and returns its projection.
|
|
611
|
+
* Handles the relationships with other entities.
|
|
612
|
+
*
|
|
613
|
+
* @param entity The <%= entityName %> entity to save<%
|
|
614
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
615
|
+
// Skip self-reference fields
|
|
616
|
+
// Use fieldName (not reference.idField) to avoid duplicate parameter names when multiple fields reference same entity
|
|
617
|
+
if (isWrittenReference(field)) {
|
|
618
|
+
if (field.reference.multiple) { %>
|
|
619
|
+
* @param <%= fieldName %>Ids The <%= field.reference.entity %> IDs to set (for <%= fieldName %>)<%
|
|
620
|
+
} else { %>
|
|
621
|
+
* @param <%= fieldName %> The <%= field.reference.entity %> ID to set<%
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}); %>
|
|
625
|
+
* @return <%= classPrefix %>DetailDTO of the saved entity
|
|
626
|
+
* @throws SimpliXGeneralException with ErrorCode.GEN_NOT_FOUND if the saved entity cannot be retrieved
|
|
627
|
+
*/
|
|
628
|
+
private <%= classPrefix %>DetailDTO saveAndGetProjection(<%= entityName %> entity<%
|
|
629
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
630
|
+
// Skip self-reference fields
|
|
631
|
+
// Use fieldName (not reference.idField) to avoid duplicate parameter names when multiple fields reference same entity
|
|
632
|
+
if (isWrittenReference(field)) {
|
|
633
|
+
if (field.reference.multiple) { %>, Set<String> <%= fieldName %>Ids<% }
|
|
634
|
+
else { %>, String <%= fieldName %><% }
|
|
635
|
+
}
|
|
636
|
+
});
|
|
637
|
+
%>) {
|
|
638
|
+
<% if (Object.values(ymlConfig.fields || {}).some(f => isWrittenReference(f))) { %>
|
|
639
|
+
//----------------------------------
|
|
640
|
+
// Many-to-one relationships
|
|
641
|
+
//----------------------------------
|
|
642
|
+
<%
|
|
643
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
644
|
+
// Skip self-reference fields
|
|
645
|
+
// Use fieldName for parameter name to avoid duplicates when multiple fields reference same entity
|
|
646
|
+
if (isWrittenReference(field) && !field.reference.multiple) {
|
|
647
|
+
const serviceVar = _.camelCase(field.reference.entity);
|
|
648
|
+
const upperFieldName = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
|
|
649
|
+
const isEntityRef = isEntityReferenceField(fieldName);
|
|
650
|
+
if (isEntityRef) {
|
|
651
|
+
%>
|
|
652
|
+
// <%= field.reference.entity %> - entity reference (@OneToOne/@MapsId or @ManyToOne object)
|
|
653
|
+
if (<%= fieldName %> != null) {
|
|
654
|
+
entity.set<%= upperFieldName %>(entityManager.getReference(<%= field.reference.entity %>.class, <%= fieldName %>));
|
|
655
|
+
}
|
|
656
|
+
<% } else { %>
|
|
657
|
+
// <%= field.reference.entity %> - set FK ID field directly
|
|
658
|
+
if (<%= fieldName %> != null) {
|
|
659
|
+
entity.set<%= upperFieldName %>(<%= fieldName %>);
|
|
660
|
+
}
|
|
661
|
+
<% }
|
|
662
|
+
}
|
|
663
|
+
}); %>
|
|
664
|
+
|
|
665
|
+
//----------------------------------
|
|
666
|
+
// Many-to-many relationships
|
|
667
|
+
//----------------------------------
|
|
668
|
+
<%
|
|
669
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
670
|
+
// Skip self-reference fields
|
|
671
|
+
// Use fieldName for parameter name to avoid duplicates when multiple fields reference same entity
|
|
672
|
+
if (isWrittenReference(field) && field.reference.multiple) {
|
|
673
|
+
const serviceVar = _.camelCase(field.reference.entity);
|
|
674
|
+
const upperFieldName = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
|
|
675
|
+
%>
|
|
676
|
+
// <%= field.reference.entity %> (via <%= fieldName %>)
|
|
677
|
+
if (<%= fieldName %>Ids != null) {
|
|
678
|
+
<%= field.reference.entity %>Service <%= serviceVar %>Service = <%= serviceVar %>ServiceProvider.getIfAvailable();
|
|
679
|
+
if (<%= serviceVar %>Service != null) {
|
|
680
|
+
<%
|
|
681
|
+
const entityField = fields.find(f => f.name === fieldName);
|
|
682
|
+
const collectionImpl = entityField?.collectionType === 'List' ? 'ArrayList' : 'HashSet';
|
|
683
|
+
%>
|
|
684
|
+
entity.set<%= upperFieldName %>(new <%= collectionImpl %><>(<%= serviceVar %>Service.findAllById(<%= fieldName %>Ids)));
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
<%
|
|
688
|
+
}
|
|
689
|
+
}); %>
|
|
690
|
+
<% } %>
|
|
691
|
+
|
|
692
|
+
<%= entityName %> savedEntity = saveAndFlush(entity);
|
|
693
|
+
// A formula, a join-derived name and the auditing fields are filled when the row is read, so
|
|
694
|
+
// the row just written is read again before it is answered.
|
|
695
|
+
entityManager.refresh(savedEntity);
|
|
696
|
+
return findById(savedEntity.get<%= capitalizeFirstLetter(ymlConfig.idField || 'id') %>(), <%= classPrefix %>DetailDTO.class)
|
|
697
|
+
.orElseThrow(() -> new SimpliXGeneralException(ErrorCode.GEN_NOT_FOUND, "Failed to retrieve saved entity", null));
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
//----------------------------------
|
|
701
|
+
<% if (hasOrderField) {
|
|
702
|
+
const orderFieldName = orderField.name;
|
|
703
|
+
const upperOrderFieldName = orderFieldName.charAt(0).toUpperCase() + orderFieldName.slice(1);
|
|
704
|
+
const upperIdFieldName = ymlConfig.idField.charAt(0).toUpperCase() + ymlConfig.idField.slice(1);
|
|
705
|
+
%>
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Updates the order of a <%= entityName %> entity.
|
|
709
|
+
*
|
|
710
|
+
* @param orderUpdateDto DTO containing the ID and new order value
|
|
711
|
+
* @return <%= classPrefix %>DetailDTO of the updated entity
|
|
712
|
+
* @throws SimpliXGeneralException with ErrorCode.GEN_NOT_FOUND if the entity is not found
|
|
713
|
+
*/
|
|
714
|
+
@Transactional
|
|
715
|
+
public <%= classPrefix %>DetailDTO updateOrder(<%= classPrefix %>OrderUpdateDTO orderUpdateDto) {
|
|
716
|
+
<%= entityName %> entity = findById(orderUpdateDto.get<%= upperIdFieldName %>())
|
|
717
|
+
.orElseThrow(() -> new SimpliXGeneralException(ErrorCode.GEN_NOT_FOUND, "<%= entityName %> not found", null));
|
|
718
|
+
|
|
719
|
+
entity.set<%= upperOrderFieldName %>(orderUpdateDto.get<%= upperOrderFieldName %>());
|
|
720
|
+
|
|
721
|
+
return saveAndGetProjection(entity<%
|
|
722
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
723
|
+
// Skip self-reference fields (e.g., parent referencing same entity)
|
|
724
|
+
if (isWrittenReference(field)) {
|
|
725
|
+
if (field.reference.multiple) { %>, null<% }
|
|
726
|
+
else { %>, null<% }
|
|
727
|
+
}
|
|
728
|
+
}); %>);
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* Updates the order of multiple <%= entityName %> entities.
|
|
733
|
+
*
|
|
734
|
+
* @param orderUpdateDtos List of DTOs containing the IDs and new order values
|
|
735
|
+
* @return List of <%= classPrefix %>DetailDTO of the updated entities
|
|
736
|
+
* @throws SimpliXGeneralException with ErrorCode.GEN_NOT_FOUND if any entity is not found
|
|
737
|
+
*/
|
|
738
|
+
@Transactional
|
|
739
|
+
public List<<%= classPrefix %>DetailDTO> updateOrders(List<<%= classPrefix %>OrderUpdateDTO> orderUpdateDtos) {
|
|
740
|
+
List<<%= classPrefix %>DetailDTO> updatedEntities = new ArrayList<>();
|
|
741
|
+
|
|
742
|
+
for (<%= classPrefix %>OrderUpdateDTO orderUpdateDto : orderUpdateDtos) {
|
|
743
|
+
if (orderUpdateDto.get<%= upperIdFieldName %>() == null) {
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
<%= entityName %> entity = findById(orderUpdateDto.get<%= upperIdFieldName %>())
|
|
748
|
+
.orElseThrow(() -> new SimpliXGeneralException(ErrorCode.GEN_NOT_FOUND, "<%= entityName %> not found with ID: " + orderUpdateDto.get<%= upperIdFieldName %>(), null));
|
|
749
|
+
|
|
750
|
+
entity.set<%= upperOrderFieldName %>(orderUpdateDto.get<%= upperOrderFieldName %>());
|
|
751
|
+
<%= classPrefix %>DetailDTO updatedEntity = saveAndGetProjection(entity<%
|
|
752
|
+
Object.entries(ymlConfig.fields || {}).forEach(([fieldName, field]) => {
|
|
753
|
+
// Skip self-reference fields (e.g., parent referencing same entity)
|
|
754
|
+
if (isWrittenReference(field)) {
|
|
755
|
+
if (field.reference.multiple) { %>, null<% }
|
|
756
|
+
else { %>, null<% }
|
|
757
|
+
}
|
|
758
|
+
}); %>);
|
|
759
|
+
updatedEntities.add(updatedEntity);
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
return updatedEntities;
|
|
763
|
+
}
|
|
764
|
+
<% } %>
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Checks if the current user has the specified permission for the entity.
|
|
768
|
+
*
|
|
769
|
+
* @param permission The permission to check (e.g., "view", "edit", "delete")
|
|
770
|
+
* @param <%= ymlConfig.idField %> The ID of the entity to check permissions for. Can be null for new entities
|
|
771
|
+
* @param dto The DTO object containing entity data. Used when <%= ymlConfig.idField %> is null
|
|
772
|
+
* @return true if the user has the permission, false otherwise
|
|
773
|
+
* @throws UnsupportedOperationException as this method is not yet implemented
|
|
774
|
+
*/
|
|
775
|
+
@Override
|
|
776
|
+
public boolean hasOwnerPermission(String permission, <%= idType %> <%= ymlConfig.idField %>, Object dto) {
|
|
777
|
+
// // Example implementation
|
|
778
|
+
// <%= entityName %> entity = new <%= entityName %>();
|
|
779
|
+
// if (<%= ymlConfig.idField %> != null) {
|
|
780
|
+
// entity = findById(<%= ymlConfig.idField %>).orElseThrow(() -> new RuntimeException("<%= entityName %> not found"));
|
|
781
|
+
// } else {
|
|
782
|
+
// modelMapper.map(dto, entity);
|
|
783
|
+
// }
|
|
784
|
+
|
|
785
|
+
// TODO: Implement dynamic permission checking based on entity fields
|
|
786
|
+
// Use entity field analysis to determine ownership field dynamically
|
|
787
|
+
|
|
788
|
+
throw new UnsupportedOperationException("Unimplemented method 'hasPermission'");
|
|
789
|
+
}
|
|
790
|
+
}
|