14 Commits

Author SHA1 Message Date
b6b0402a5e update asset descriptor retrieval and editing for composite assets
All checks were successful
Build / build (push) Successful in 1m28s
2025-06-18 08:14:45 +02:00
e3c0737206 Enhance asset handling with type-specific retrieval and null safety improvements 2025-06-18 07:43:15 +02:00
50ac15f8a8 Working on composites
All checks were successful
Build / build (push) Successful in 3m42s
2025-06-17 18:53:26 +02:00
cdaccb3840 Add composite asset support with creation and descriptor handling
All checks were successful
Build / build (push) Successful in 1m45s
2025-06-16 06:56:35 +02:00
069e38fef9 Add composite asset creation functionality with new views and asset descriptor handling
All checks were successful
Build / build (push) Successful in 1m22s
2025-06-15 20:27:17 +02:00
40e13ec585 Enhance asset display by linking builds and handling null builds in overview
All checks were successful
Build / build (push) Successful in 1m23s
2025-06-15 17:29:50 +02:00
bb15c55e46 Improve asset sorting by brand, model, and QR code with null handling
All checks were successful
Build / build (push) Successful in 2m27s
Deploy / build (push) Successful in 3m1s
2025-06-15 09:48:07 +02:00
35c2e07c05 Update build view to link part types for better navigation
All checks were successful
Build / build (push) Successful in 2m2s
Deploy / build (push) Successful in 2m43s
2025-06-15 09:27:32 +02:00
92187fd345 Handle non-positive capacities in idealUnitForCapacity method 2025-06-15 09:27:29 +02:00
0dbab45651 Enhance asset display by handling null builds and sorting assets by QR code 2025-06-15 09:26:08 +02:00
14ac78982f Reorder fields in HddAsset for clarity
All checks were successful
Build / build (push) Successful in 1m20s
2025-06-15 09:14:13 +02:00
b4c493c27b Merge pull request 'Add support for builds' (#2) from builds into master
All checks were successful
Build / build (push) Successful in 1m51s
Deploy / build (push) Successful in 2m23s
Reviewed-on: #2
2025-06-15 09:06:19 +02:00
8e26a73243 Add build management features and views
All checks were successful
Build / build (push) Successful in 2m10s
2025-06-15 09:03:47 +02:00
8cbededc79 Initial support for builds
All checks were successful
Build / build (push) Successful in 2m16s
2025-06-15 07:47:30 +02:00
25 changed files with 773 additions and 120 deletions

View File

@@ -1,7 +1,12 @@
package be.seeseepuff.pcinv.controllers; package be.seeseepuff.pcinv.controllers;
import be.seeseepuff.pcinv.meta.AssetDescriptor;
import be.seeseepuff.pcinv.models.Asset;
import be.seeseepuff.pcinv.models.GenericAsset;
import be.seeseepuff.pcinv.models.WorkLogEntry; import be.seeseepuff.pcinv.models.WorkLogEntry;
import be.seeseepuff.pcinv.services.AssetService; import be.seeseepuff.pcinv.services.AssetService;
import be.seeseepuff.pcinv.services.BuildService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
@@ -14,8 +19,10 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.Set;
/** /**
* Controller for handling web requests related to assets. * Controller for handling web requests related to assets.
@@ -32,6 +39,8 @@ public class WebController {
private static final String ASSETS = "assets"; private static final String ASSETS = "assets";
/// The name of the model attribute that holds the asset being viewed or edited. /// The name of the model attribute that holds the asset being viewed or edited.
private static final String ASSET = "asset"; private static final String ASSET = "asset";
/// The name of the model attribute that holds the list of asset types.
private static final String TYPES = "types";
/// The name of the model attribute that holds a list of all properties of all descriptors. /// The name of the model attribute that holds a list of all properties of all descriptors.
private static final String PROPERTIES = "properties"; private static final String PROPERTIES = "properties";
/// The name of the model attribute that holds the action to be performed. /// The name of the model attribute that holds the action to be performed.
@@ -42,6 +51,12 @@ public class WebController {
private static final String INPUT_LIST = "inputLists"; private static final String INPUT_LIST = "inputLists";
/// The name of the model attribute that holds the current work log entries. /// The name of the model attribute that holds the current work log entries.
private static final String WORKLOG = "worklog"; private static final String WORKLOG = "worklog";
/// The name of the model attribute that holds the current build being viewed or edited.
private static final String BUILD = "build";
/// The name of the model attribute that holds the build information.
private static final String BUILD_INFO = "buildInfo";
/// The name of the model attribute that holds the builds available for selection.
private static final String BUILDS = "builds";
/// The name of the input field for the current size of the work log. /// The name of the input field for the current size of the work log.
private static final String WORKLOG_SIZE = "worklog_size"; private static final String WORKLOG_SIZE = "worklog_size";
@@ -49,6 +64,7 @@ public class WebController {
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd MMM yyyy 'at' HH:mm"); private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd MMM yyyy 'at' HH:mm");
private final AssetService assetService; private final AssetService assetService;
private final BuildService buildService;
/** /**
* Handles the root URL and returns the index page with asset descriptors and asset count. * Handles the root URL and returns the index page with asset descriptors and asset count.
@@ -86,10 +102,96 @@ public class WebController {
model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(type)); model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(type));
model.addAttribute(DESCRIPTORS, tree); model.addAttribute(DESCRIPTORS, tree);
model.addAttribute(PROPERTIES, tree.stream().flatMap(d -> d.getProperties().stream()).toList()); model.addAttribute(PROPERTIES, tree.stream().flatMap(d -> d.getProperties().stream()).toList());
model.addAttribute(ASSETS, assetService.getAssetsByType(type)); var assets = assetService.getAssetsByType(type);
assets.sort(Comparator
.comparing((Asset a) -> a.getAsset().getBrand(), Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing((Asset a) -> a.getAsset().getModel(), Comparator.nullsFirst(Comparator.naturalOrder()))
.thenComparing(Asset::getQr));
model.addAttribute(ASSETS, assets);
return "browse_type"; return "browse_type";
} }
/**
* Handles the browsing of all builds.
* Displays a list of all builds available in the system.
*/
@GetMapping("/builds")
public String browseBuilds(Model model) {
model.addAttribute(TIME, System.currentTimeMillis());
model.addAttribute(BUILDS, buildService.getAllBuilds());
return "builds";
}
/**
* Handles the viewing of a specific build by its ID.
* If the build does not exist, it redirects to the builds page.
*/
@GetMapping("/build/{id}")
public String viewBuild(Model model, @PathVariable long id) {
model.addAttribute(TIME, System.currentTimeMillis());
var build = buildService.getBuildById(id);
if (build == null) {
return "redirect:/builds";
}
model.addAttribute(BUILD, build);
model.addAttribute(BUILD_INFO, buildService.getBuildInfo(build));
model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptors());
return "build_view";
}
/**
* Shows a view where the user can create a specific type of composite asset.
*/
@GetMapping("/create_composite")
public String createCompositeType(Model model, HttpServletRequest request) {
var parameters = request.getParameterMap();
if (parameters == null || parameters.isEmpty()) {
model.addAttribute(TIME, System.currentTimeMillis());
model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptors());
return "create_composite";
} else {
model.addAttribute(TIME, System.currentTimeMillis());
model.addAttribute(ACTION, "create");
var descriptors = new ArrayList<AssetDescriptor>();
var inputLists = new HashMap<String, Set<String>>();
descriptors.add(assetService.getAssetDescriptor(GenericAsset.TYPE));
for (String assetType : parameters.keySet()) {
descriptors.add(assetService.getAssetDescriptor(assetType));
inputLists.putAll(assetService.getInputList(assetType));
}
model.addAttribute(DESCRIPTORS, descriptors);
model.addAttribute(DESCRIPTOR, AssetDescriptor.builder()
.type("composite")
.displayName("Composite Asset")
.pluralName("Composite Assets")
.build());
model.addAttribute(INPUT_LIST, inputLists);
model.addAttribute(BUILDS, buildService.getAllBuilds());
model.addAttribute(TYPES, parameters.keySet().stream().toList());
return "create_asset";
}
}
/**
* Handles the creation of a new build.
*/
@PostMapping("/create_build")
public String createBuild(Model model, @RequestBody MultiValueMap<String, String> formData) {
model.addAttribute(TIME, System.currentTimeMillis());
var build = buildService.createBuild(formData.getFirst("name"), formData.getFirst("description"));
return "redirect:/build/" + build.getId();
}
/**
* Deletes a build by its ID.
*/
@GetMapping("/delete_build/{id}")
public String deleteBuild(Model model, @PathVariable long id) {
model.addAttribute(TIME, System.currentTimeMillis());
buildService.deleteBuild(id);
return "redirect:/builds";
}
/** /**
* Handles the view of an asset by its QR code. * Handles the view of an asset by its QR code.
* If the asset does not exist, it redirects to the index page. * If the asset does not exist, it redirects to the index page.
@@ -113,18 +215,18 @@ public class WebController {
model.addAttribute(TIME, System.currentTimeMillis()); model.addAttribute(TIME, System.currentTimeMillis());
model.addAttribute(ACTION, "view"); model.addAttribute(ACTION, "view");
var asset = assetService.getAssetByQr(qr); var composite = assetService.getAssetByQr(qr);
if (asset == null) { if (composite == null) {
return "redirect:/"; return "redirect:/";
} }
var workLogSizeStr = formData.getFirst(WORKLOG_SIZE); var workLogSizeStr = formData.getFirst(WORKLOG_SIZE);
if (workLogSizeStr != null) { if (workLogSizeStr != null) {
var workLogSize = Integer.parseInt(workLogSizeStr); var workLogSize = Integer.parseInt(workLogSizeStr);
if (asset.getAsset().getWorkLog().size() == workLogSize) { if (composite.getAsset().getWorkLog().size() == workLogSize) {
var comment = formData.getFirst("comment"); var comment = formData.getFirst("comment");
if (comment != null && !comment.isBlank()) { if (comment != null && !comment.isBlank()) {
assetService.addWorkLogEntry(asset, comment); assetService.addWorkLogEntry(composite, comment);
} }
} }
} }
@@ -167,7 +269,7 @@ public class WebController {
return "redirect:/"; return "redirect:/";
} }
model.addAttribute(ASSET, asset); model.addAttribute(ASSET, asset);
model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(asset.getAsset().getType())); model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(asset));
model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(asset.getAsset().getType())); model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(asset.getAsset().getType()));
model.addAttribute(WORKLOG, asset.getAsset().getWorkLog().stream() model.addAttribute(WORKLOG, asset.getAsset().getWorkLog().stream()
.sorted(Comparator.comparing(WorkLogEntry::getDate).reversed()) .sorted(Comparator.comparing(WorkLogEntry::getDate).reversed())
@@ -202,9 +304,39 @@ public class WebController {
model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(type)); model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(type));
model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(type)); model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(type));
model.addAttribute(INPUT_LIST, assetService.getInputList(type)); model.addAttribute(INPUT_LIST, assetService.getInputList(type));
model.addAttribute(BUILDS, buildService.getAllBuilds());
return "create_asset"; return "create_asset";
} }
/**
* Handles the form submission for creating an asset.
*
* @param model The model to add attributes to.
* @param type The type of asset to create.
* @return The view name for creating the asset.
*/
@PostMapping(
value = "/create/{type}",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE
)
public String createTypePost(Model model, @PathVariable String type, @RequestBody MultiValueMap<String, String> formData) {
model.addAttribute(TIME, System.currentTimeMillis());
var formMap = new HashMap<String, String>();
formData.forEach((key, values) -> {
if (!values.isEmpty()) {
formMap.put(key, values.getFirst());
}
});
if (type.equals("composite")) {
var compositeTypes = formData.get("type");
var asset = assetService.createCompositeAsset(compositeTypes, formMap);
return "redirect:/view/" + asset.getQr();
} else {
var asset = assetService.createAsset(type, formMap);
return "redirect:/view/" + asset.getQr();
}
}
/** /**
* Shows a view where the user can edit an existing asset. * Shows a view where the user can edit an existing asset.
* *
@@ -220,9 +352,10 @@ public class WebController {
String assetType = asset.getAsset().getType(); String assetType = asset.getAsset().getType();
model.addAttribute(ACTION, "edit"); model.addAttribute(ACTION, "edit");
model.addAttribute(ASSET, asset); model.addAttribute(ASSET, asset);
model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(assetType)); model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(asset));
model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(assetType)); model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(assetType));
model.addAttribute(INPUT_LIST, assetService.getInputList(assetType)); model.addAttribute(INPUT_LIST, assetService.getInputList(assetType));
model.addAttribute(BUILDS, buildService.getAllBuilds());
return "create_asset"; return "create_asset";
} }
@@ -241,7 +374,7 @@ public class WebController {
String assetType = asset.getAsset().getType(); String assetType = asset.getAsset().getType();
model.addAttribute(ACTION, "duplicate"); model.addAttribute(ACTION, "duplicate");
model.addAttribute(ASSET, asset); model.addAttribute(ASSET, asset);
model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(assetType)); model.addAttribute(DESCRIPTORS, assetService.getAssetDescriptorTree(asset));
model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(assetType)); model.addAttribute(DESCRIPTOR, assetService.getAssetDescriptor(assetType));
model.addAttribute(INPUT_LIST, assetService.getInputList(assetType)); model.addAttribute(INPUT_LIST, assetService.getInputList(assetType));
return "create_asset"; return "create_asset";
@@ -264,27 +397,4 @@ public class WebController {
var asset = assetService.editAsset(qr, formMap); var asset = assetService.editAsset(qr, formMap);
return "redirect:/view/" + asset.getQr(); return "redirect:/view/" + asset.getQr();
} }
/**
* Handles the form submission for creating an asset.
*
* @param model The model to add attributes to.
* @param type The type of asset to create.
* @return The view name for creating the asset.
*/
@PostMapping(
value = "/create/{type}",
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE
)
public String createTypePost(Model model, @PathVariable String type, @RequestBody MultiValueMap<String, String> formData) {
model.addAttribute(TIME, System.currentTimeMillis());
var formMap = new HashMap<String, String>();
formData.forEach((key, values) -> {
if (!values.isEmpty()) {
formMap.put(key, values.getFirst());
}
});
var asset = assetService.createAsset(type, formMap);
return "redirect:/view/" + asset.getQr();
}
} }

View File

@@ -16,9 +16,19 @@ import java.util.function.Supplier;
@Getter @Getter
@Builder @Builder
public class AssetDescriptor { public class AssetDescriptor {
public static final AssetDescriptor COMPOSITE = AssetDescriptor.builder()
.type("composite")
.displayName("Composite Asset")
.pluralName("Composite Assets")
.visible(false)
.build();
/// The type of property, e.g.: ram, asset, etc... /// The type of property, e.g.: ram, asset, etc...
private final String type; private final String type;
/// The Java class of the type.
private final Class<?> assetClass;
/// The displayable name of the property, e.g.: "Random Access Memory" /// The displayable name of the property, e.g.: "Random Access Memory"
private final String displayName; private final String displayName;
@@ -46,6 +56,7 @@ public class AssetDescriptor {
Objects.requireNonNull(assetInfo, "Asset class must be annotated with @AssetInfo"); Objects.requireNonNull(assetInfo, "Asset class must be annotated with @AssetInfo");
var builder = AssetDescriptor.builder() var builder = AssetDescriptor.builder()
.type(assetInfo.type()) .type(assetInfo.type())
.assetClass(assetType)
.displayName(assetInfo.displayName()) .displayName(assetInfo.displayName())
.pluralName(assetInfo.pluralName()) .pluralName(assetInfo.pluralName())
.visible(assetInfo.isVisible()) .visible(assetInfo.isVisible())
@@ -99,6 +110,19 @@ public class AssetDescriptor {
return String.format("%s-%s", type, property.getName()); return String.format("%s-%s", type, property.getName());
} }
/**
* Gets the property with the specified name.
*
* @param name The name of the property to retrieve.
* @return The AssetProperty with the given name.
*/
public AssetProperty getProperty(String name) {
return properties.stream()
.filter(property -> property.getName().equals(name))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No property found with name: " + name));
}
/** /**
* Creates a new instance of the asset type described by this descriptor. * Creates a new instance of the asset type described by this descriptor.
* *

View File

@@ -20,8 +20,47 @@ public class AssetDescriptors {
* @param assetType The type of the asset to load properties for. * @param assetType The type of the asset to load properties for.
*/ */
public void loadFrom(Class<?> assetType) { public void loadFrom(Class<?> assetType) {
var property = AssetDescriptor.loadFrom(assetType); add(AssetDescriptor.loadFrom(assetType));
assets.add(property); }
/**
* Adds a new asset descriptor to the collection.
*
* @param assetDescriptor The asset descriptor to add.
*/
public void add(AssetDescriptor assetDescriptor) {
assets.add(assetDescriptor);
}
/**
* Gets the descriptor for a specific asset type.
*
* @param type The type of the asset to retrieve the descriptor for.
*/
public AssetDescriptor getDescriptorForType(String type) {
return assets.stream()
.filter(assetDescriptor -> assetDescriptor.getType().equals(type))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No asset descriptor found for type: " + type));
}
/**
* Gets the property for a specific asset type and property name.
*
* @param type The type of the asset to retrieve the property for.
* @param propertyName The name of the property to retrieve.
*/
public AssetProperty getPropertyForType(String type, String propertyName) {
return getDescriptorForType(type).getProperty(propertyName);
}
/**
* Gets the generic property for a specific property name.
*
* @param propertyName The name of the property to retrieve.
*/
public AssetProperty getGenericProperty(String propertyName) {
return getPropertyForType("asset", propertyName);
} }
@Override @Override

View File

@@ -1,12 +1,8 @@
package be.seeseepuff.pcinv.meta; package be.seeseepuff.pcinv.meta;
import be.seeseepuff.pcinv.models.Asset; import be.seeseepuff.pcinv.models.*;
import be.seeseepuff.pcinv.models.AssetCondition;
import be.seeseepuff.pcinv.models.GenericAsset;
import be.seeseepuff.pcinv.models.ReadWrite;
import jakarta.annotation.Nonnull; import jakarta.annotation.Nonnull;
import jakarta.annotation.Nullable; import jakarta.annotation.Nullable;
import lombok.AllArgsConstructor;
import lombok.Builder; import lombok.Builder;
import lombok.Getter; import lombok.Getter;
import lombok.Singular; import lombok.Singular;
@@ -28,7 +24,7 @@ public class AssetProperty {
/// The name of the property as it should be displayed, e.g., "Brand", "Model", etc. /// The name of the property as it should be displayed, e.g., "Brand", "Model", etc.
private final String displayName; private final String displayName;
/// The type of the property, which can be a string or an integer. /// The type of the property, which can be a string or an integer.
private final Type type; private final PropertyType type;
/// Whether the property is required for the asset. /// Whether the property is required for the asset.
private final boolean required; private final boolean required;
/// A set of options for the property, used for enum types. /// A set of options for the property, used for enum types.
@@ -49,31 +45,6 @@ public class AssetProperty {
/// A description of the property, if any. /// A description of the property, if any.
private final String description; private final String description;
/**
* Enum representing the possible types of asset properties.
*/
@AllArgsConstructor
public enum Type {
STRING(false),
INTEGER(false),
BOOLEAN(false),
CAPACITY(false),
CONDITION(true),
READWRITE(true),
;
/// Set to `true` if the type is an enum, `false` otherwise.
public final boolean isEnum;
/**
* Returns the name of the type, or "enum" if it is an enum type.
*
* @return The name of the type or "enum" if it is an enum.
*/
public String nameOrEnum() {
return isEnum ? "enum" : name();
}
}
/** /**
* Loads an AssetProperty from a given field. * Loads an AssetProperty from a given field.
* *
@@ -99,7 +70,11 @@ public class AssetProperty {
.setter((obj, value) -> { .setter((obj, value) -> {
try { try {
property.setAccessible(true); property.setAccessible(true);
if (obj instanceof Asset asset) {
property.set(asset.getAsset(property.getDeclaringClass()), Converters.convert(value, property.getType()));
} else {
property.set(obj, Converters.convert(value, property.getType())); property.set(obj, Converters.convert(value, property.getType()));
}
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -110,7 +85,12 @@ public class AssetProperty {
obj = asset.getAsset(); obj = asset.getAsset();
} }
property.setAccessible(true); property.setAccessible(true);
if (obj instanceof Asset asset) {
return property.get(asset.getAsset(property.getDeclaringClass()));
} else {
return property.get(obj); return property.get(obj);
}
} catch (IllegalAccessException e) { } catch (IllegalAccessException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@@ -131,7 +111,7 @@ public class AssetProperty {
builder.option(option); builder.option(option);
} }
} }
if (type == Type.CAPACITY) { if (type == PropertyType.CAPACITY) {
var capacityAnnotation = property.getAnnotation(Capacity.class); var capacityAnnotation = property.getAnnotation(Capacity.class);
builder.capacityAsSI(capacityAnnotation.si()); builder.capacityAsSI(capacityAnnotation.si());
builder.capacityAsIEC(capacityAnnotation.iec()); builder.capacityAsIEC(capacityAnnotation.iec());
@@ -146,19 +126,21 @@ public class AssetProperty {
* @return The type of the property. * @return The type of the property.
* @throws IllegalArgumentException if the property type is unsupported. * @throws IllegalArgumentException if the property type is unsupported.
*/ */
private static Type determineType(Field property) { private static PropertyType determineType(Field property) {
if (property.getType() == String.class) { if (property.getType() == String.class) {
return Type.STRING; return PropertyType.STRING;
} else if (property.isAnnotationPresent(Capacity.class)) { } else if (property.isAnnotationPresent(Capacity.class)) {
return Type.CAPACITY; return PropertyType.CAPACITY;
} else if (property.getType() == Integer.class || property.getType() == int.class || property.getType() == Long.class || property.getType() == long.class) { } else if (property.getType() == Integer.class || property.getType() == int.class || property.getType() == Long.class || property.getType() == long.class) {
return Type.INTEGER; return PropertyType.INTEGER;
} else if (property.getType() == Boolean.class || property.getType() == boolean.class) { } else if (property.getType() == Boolean.class || property.getType() == boolean.class) {
return Type.BOOLEAN; return PropertyType.BOOLEAN;
} else if (property.getType() == AssetCondition.class) { } else if (property.getType() == AssetCondition.class) {
return Type.CONDITION; return PropertyType.CONDITION;
} else if (property.getType() == ReadWrite.class) { } else if (property.getType() == ReadWrite.class) {
return Type.READWRITE; return PropertyType.READWRITE;
} else if (property.getType() == Build.class) {
return PropertyType.BUILD;
} else { } else {
throw new IllegalArgumentException("Unsupported property type: " + property.getType()); throw new IllegalArgumentException("Unsupported property type: " + property.getType());
} }
@@ -204,12 +186,15 @@ public class AssetProperty {
var value = getValue(asset); var value = getValue(asset);
if (value == null) { if (value == null) {
return "?"; return "?";
} else if (type == Type.BOOLEAN) { } else if (type == PropertyType.BOOLEAN) {
return (boolean) value ? "Yes" : "No"; return (boolean) value ? "Yes" : "No";
} else if (type == Type.INTEGER || type == Type.STRING) { } else if (type == PropertyType.INTEGER || type == PropertyType.STRING) {
return value.toString(); return value.toString();
} else if (type == Type.CAPACITY) { } else if (type == PropertyType.CAPACITY) {
return convertCapacity((Long) value).toString(); return convertCapacity((Long) value).toString();
} else if (type == PropertyType.BUILD) {
var build = (Build) value;
return build.getName();
} else if (type.isEnum) { } else if (type.isEnum) {
if (value instanceof AssetEnum assetEnum) { if (value instanceof AssetEnum assetEnum) {
return assetEnum.getDisplayName(); return assetEnum.getDisplayName();
@@ -224,7 +209,7 @@ public class AssetProperty {
if (value == null) { if (value == null) {
return null; return null;
} }
if (type != Type.CAPACITY) { if (type != PropertyType.CAPACITY) {
throw new IllegalStateException("Property '" + name + "' is not a capacity type."); throw new IllegalStateException("Property '" + name + "' is not a capacity type.");
} }
return CapacityInfo.of(value, capacityAsIEC, capacityAsSI); return CapacityInfo.of(value, capacityAsIEC, capacityAsSI);

View File

@@ -44,6 +44,10 @@ public class CapacityInfo {
} }
public static CapacityUnit idealUnitForCapacity(long capacity, CapacityUnit[] units) { public static CapacityUnit idealUnitForCapacity(long capacity, CapacityUnit[] units) {
if (capacity <= 0) {
return CapacityUnit.BYTES; // Default to bytes for non-positive capacities
}
return Arrays.stream(units) return Arrays.stream(units)
.sorted(Comparator.comparing(CapacityUnit::getBytes).reversed()) .sorted(Comparator.comparing(CapacityUnit::getBytes).reversed())
.filter(unit -> capacity % unit.getBytes() == 0) .filter(unit -> capacity % unit.getBytes() == 0)

View File

@@ -0,0 +1,31 @@
package be.seeseepuff.pcinv.meta;
import lombok.AllArgsConstructor;
/**
* Enum representing the possible types of asset properties.
*/
@AllArgsConstructor
public enum PropertyType
{
STRING(false),
INTEGER(false),
BOOLEAN(false),
CAPACITY(false),
CONDITION(true),
READWRITE(true),
BUILD(false),
;
/// Set to `true` if the type is an enum, `false` otherwise.
public final boolean isEnum;
/**
* Returns the name of the type, or "enum" if it is an enum type.
*
* @return The name of the type or "enum" if it is an enum.
*/
public String nameOrEnum()
{
return isEnum ? "enum" : name();
}
}

View File

@@ -9,5 +9,24 @@ public interface Asset {
return getAsset().getQr(); return getAsset().getQr();
} }
/**
* Returns the asset as a specific type.
* @param assetType The type of asset to return, e.g., CpuAsset.class.
* @return The asset cast to the specified type.
* @param <T> The type of asset to return, must extend Asset.
* @throws IllegalArgumentException if the requested assetType is not compatible with this asset.
*/
@SuppressWarnings("unchecked")
default <T> T getAsset(Class<T> assetType) {
if (assetType.equals(GenericAsset.class)) {
return (T) getAsset();
}
if (assetType.equals(this.getClass())) {
return (T) this;
}
throw new IllegalArgumentException("No asset of type " + assetType.getSimpleName() + " found in composite.");
}
void setAsset(GenericAsset asset); void setAsset(GenericAsset asset);
} }

View File

@@ -0,0 +1,50 @@
package be.seeseepuff.pcinv.models;
import jakarta.persistence.*;
import lombok.*;
import java.util.List;
@Getter
@Setter
@Builder
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(
name = "builds",
uniqueConstraints = @UniqueConstraint(columnNames = "name")
)
public class Build
{
@Id
@GeneratedValue
private long id;
/**
* Indicates whether this build is a meta build.
* A meta build is a build that does not represent a physical computer,
* but rather a collection of parts that can be used in other builds.
*
* It is used internally to represents parts that are explicitly not part of a build.
*/
private boolean meta;
/**
* The name of the build.
*/
private String name;
/**
* A description of the build.
* This can be used to provide additional information about the build.
*/
private String description;
/**
* A list of parts that are included in the build.
*/
@OneToMany(mappedBy = "build")
@OrderBy("type, brand, model, qr")
private List<GenericAsset> parts;
}

View File

@@ -0,0 +1,20 @@
package be.seeseepuff.pcinv.models;
import be.seeseepuff.pcinv.meta.CapacityInfo;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class BuildInfo {
private long totalRam;
/**
* Calculates the total RAM capacity of the build.
*
* @return A CapacityInfo object representing the total RAM capacity.
*/
public CapacityInfo getTotalRamCapacity() {
return CapacityInfo.of(totalRam);
}
}

View File

@@ -0,0 +1,76 @@
package be.seeseepuff.pcinv.models;
import jakarta.annotation.Nullable;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a composite asset that can contain multiple other assets.
*/
@Getter
@Setter
@RequiredArgsConstructor
@AllArgsConstructor
public class Composite implements Asset {
private final GenericAsset genericAsset;
private List<Asset> assets = new ArrayList<>();
/**
* Constructs a Composite with a single asset.
*
* @param asset The asset to be added to the composite.
*/
public Composite(Asset asset) {
this.genericAsset = asset.getAsset();
addAsset(asset);
}
@Override
public <T> T getAsset(Class<T> assetType) {
if (assetType.equals(GenericAsset.class)) {
//noinspection unchecked
return (T) getAsset();
}
if (assetType.equals(Composite.class)) {
return assetType.cast(this);
}
for (Asset asset : assets) {
if (assetType.isInstance(asset)) {
return assetType.cast(asset);
}
}
throw new IllegalArgumentException("No asset of type " + assetType.getSimpleName() + " found in composite.");
}
/**
* Adds an asset to the composite.
*
* @param asset The asset to add. If null, it will not be added.
*/
public void addAsset(@Nullable Asset asset) {
if (asset == null) {
return;
}
assets.add(asset);
}
@Override
public long getId() {
return genericAsset.getId();
}
@Override
public GenericAsset getAsset() {
return genericAsset;
}
@Override
public void setAsset(GenericAsset asset) {
throw new UnsupportedOperationException("Composite is note a modifiable database record.");
}
}

View File

@@ -30,24 +30,24 @@ public class CpuAsset implements Asset
@Description("The number of cores in the CPU.") @Description("The number of cores in the CPU.")
@Property("Cores") @Property("Cores")
private int cores; private Integer cores;
@Description("The number of threads in the CPU.") @Description("The number of threads in the CPU.")
@Property("Threads") @Property("Threads")
private int threads; private Integer threads;
@Description("The base clock speed of the CPU in MHz.") @Description("The base clock speed of the CPU in MHz.")
@Property("Base Clock Speed (MHz)") @Property("Base Clock Speed (MHz)")
private int baseClockSpeed; private Integer baseClockSpeed;
@Description("The boost clock speed of the CPU in MHz.") @Description("The boost clock speed of the CPU in MHz.")
@Property("Boost Clock Speed (MHz)") @Property("Boost Clock Speed (MHz)")
@HideInOverview @HideInOverview
private int boostClockSpeed; private Integer boostClockSpeed;
@Description("The thermal design power (TDP) of the CPU in watts.") @Description("The thermal design power (TDP) of the CPU in watts.")
@Property("Thermal Design Power (TDP) (W)") @Property("Thermal Design Power (TDP) (W)")
private int tdp; private Integer tdp;
@Description("The socket type of the CPU.") @Description("The socket type of the CPU.")
@Property("Socket Type") @Property("Socket Type")
@@ -63,5 +63,5 @@ public class CpuAsset implements Asset
@Description("The manufacturing process of the CPU in nanometers.") @Description("The manufacturing process of the CPU in nanometers.")
@Property("Manufacturing Process (nm)") @Property("Manufacturing Process (nm)")
@HideInOverview @HideInOverview
private int manufacturingProcess; private Integer manufacturingProcess;
} }

View File

@@ -73,4 +73,9 @@ public class GenericAsset
@OneToMany(mappedBy = "asset", cascade = CascadeType.ALL, orphanRemoval = true) @OneToMany(mappedBy = "asset", cascade = CascadeType.ALL, orphanRemoval = true)
private List<WorkLogEntry> workLog; private List<WorkLogEntry> workLog;
@ManyToOne
@Property("Part of build")
@Description("Select which build this asset is placed in.")
private Build build;
} }

View File

@@ -57,16 +57,16 @@ public class HddAsset implements Asset
@InputList @InputList
private String driveType; private String driveType;
@Description("Number of heads in the drive.")
@Property("Heads")
@HideInOverview
private Integer heads;
@Description("Number of cylinders in the drive.") @Description("Number of cylinders in the drive.")
@Property("Cylinders") @Property("Cylinders")
@HideInOverview @HideInOverview
private Integer cylinders; private Integer cylinders;
@Description("Number of heads in the drive.")
@Property("Heads")
@HideInOverview
private Integer heads;
@Description("Number of sectors in the drive.") @Description("Number of sectors in the drive.")
@Property("Sectors") @Property("Sectors")
@HideInOverview @HideInOverview

View File

@@ -28,7 +28,7 @@ public class PowerSupplyAsset implements Asset
@Description("The wattage rating of the power supply in watts.") @Description("The wattage rating of the power supply in watts.")
@Property("Wattage") @Property("Wattage")
private int wattage; private Integer wattage;
@Description("The efficiency rating of the power supply, e.g., 80 Plus Bronze, Silver, Gold, Platinum, Titanium.") @Description("The efficiency rating of the power supply, e.g., 80 Plus Bronze, Silver, Gold, Platinum, Titanium.")
@Property("Efficiency Rating") @Property("Efficiency Rating")
@@ -42,25 +42,25 @@ public class PowerSupplyAsset implements Asset
@Description("The number number of Molex connectors.") @Description("The number number of Molex connectors.")
@Property("4-pin Molex Connectors") @Property("4-pin Molex Connectors")
private int molexConnectors; private Integer molexConnectors;
@Description("The number of 4-pin floppy connectors.") @Description("The number of 4-pin floppy connectors.")
@Property("4-pin Floppy Connectors") @Property("4-pin Floppy Connectors")
private int floppyConnectors; private Integer floppyConnectors;
@Description("The number of SATA power connectors.") @Description("The number of SATA power connectors.")
@Property("15-pin SATA Connectors") @Property("15-pin SATA Connectors")
private int sataConnectors; private Integer sataConnectors;
@Description("The number of 6-pin PCIe connectors.") @Description("The number of 6-pin PCIe connectors.")
@Property("6-pin PCIe Connectors") @Property("6-pin PCIe Connectors")
private int pcie6Connectors; private Integer pcie6Connectors;
@Description("The number of 8-pin PCIe connectors.") @Description("The number of 8-pin PCIe connectors.")
@Property("8-pin PCIe Connectors") @Property("8-pin PCIe Connectors")
private int pcie8Connectors; private Integer pcie8Connectors;
@Description("The number of 4-pin ATX 12V connectors.") @Description("The number of 4-pin ATX 12V connectors.")
@Property("4-pin ATX 12V Connectors") @Property("4-pin ATX 12V Connectors")
private int atx12vConnectors; private Integer atx12vConnectors;
} }

View File

@@ -0,0 +1,17 @@
package be.seeseepuff.pcinv.repositories;
import be.seeseepuff.pcinv.models.Build;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BuildRepository extends JpaRepository<Build, Long>
{
Build getBuildByNameAndMeta(String name, boolean meta);
Build getBuildById(long id);
List<Build> findAllByMeta(boolean meta);
}

View File

@@ -1,10 +1,8 @@
package be.seeseepuff.pcinv.services; package be.seeseepuff.pcinv.services;
import be.seeseepuff.pcinv.meta.AssetDescriptor; import be.seeseepuff.pcinv.meta.*;
import be.seeseepuff.pcinv.meta.AssetDescriptors;
import be.seeseepuff.pcinv.meta.AssetInfo;
import be.seeseepuff.pcinv.meta.AssetProperty;
import be.seeseepuff.pcinv.models.Asset; import be.seeseepuff.pcinv.models.Asset;
import be.seeseepuff.pcinv.models.Composite;
import be.seeseepuff.pcinv.models.GenericAsset; import be.seeseepuff.pcinv.models.GenericAsset;
import be.seeseepuff.pcinv.models.WorkLogEntry; import be.seeseepuff.pcinv.models.WorkLogEntry;
import be.seeseepuff.pcinv.repositories.AssetRepository; import be.seeseepuff.pcinv.repositories.AssetRepository;
@@ -31,6 +29,7 @@ public class AssetService {
private final WorkLogRepository workLogRepository; private final WorkLogRepository workLogRepository;
private final Collection<AssetRepository<?>> repositories; private final Collection<AssetRepository<?>> repositories;
private final EntityManager entityManager; private final EntityManager entityManager;
private final BuildService buildService;
/** /**
* Returns the count of all assets in the repository. * Returns the count of all assets in the repository.
@@ -48,12 +47,23 @@ public class AssetService {
* @return the Asset associated with the given QR code * @return the Asset associated with the given QR code
* @throws IllegalArgumentException if no asset is found with the given QR code * @throws IllegalArgumentException if no asset is found with the given QR code
*/ */
public Asset getAssetByQr(long qr) { public Composite getAssetByQr(long qr) {
var genericAsset = genericRepository.findByQr(qr); var genericAsset = genericRepository.findByQr(qr);
if (genericAsset == null) { if (genericAsset == null) {
throw new IllegalArgumentException("No asset found with QR code: " + qr); throw new IllegalArgumentException("No asset found with QR code: " + qr);
} }
return getRepositoryFor(genericAsset.getType()).findByAsset(genericAsset); if (genericAsset.getType().equals("composite")) {
var assets = new ArrayList<Asset>();
for (var repository : repositories) {
var asset = repository.findByAsset(genericAsset);
if (asset != null) {
assets.add(asset);
}
}
return new Composite(genericAsset, assets);
} else {
return new Composite(getRepositoryFor(genericAsset.getType()).findByAsset(genericAsset));
}
} }
/** /**
@@ -111,18 +121,34 @@ public class AssetService {
* @return the AssetProperties for the specified type * @return the AssetProperties for the specified type
*/ */
public AssetDescriptor getAssetDescriptor(String type) { public AssetDescriptor getAssetDescriptor(String type) {
if (type.equals("composite")) {
return AssetDescriptor.COMPOSITE;
}
return getAssetDescriptors().getAssets().stream() return getAssetDescriptors().getAssets().stream()
.filter(asset -> asset.getType().equals(type)) .filter(asset -> asset.getType().equals(type))
.findFirst() .findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unknown asset type: " + type)); .orElseThrow(() -> new IllegalArgumentException("Unknown asset type: " + type));
} }
/**
* Gets the asset descriptor for a specific asset instance.
*
* @param asset the asset instance to retrieve the descriptor for
* @return the AssetDescriptor for the specified asset
*/
public AssetDescriptor getAssetDescriptor(Asset asset) {
var type = asset.getClass().getAnnotation(AssetInfo.class).type();
return getAssetDescriptor(type);
}
/** /**
* Retrieves a tree of asset descriptors for the specified type. * Retrieves a tree of asset descriptors for the specified type.
* *
* @param type the type of asset to retrieve descriptors for * @param type the type of asset to retrieve descriptors for
* @return a list of AssetDescriptors for the specified type * @return a list of AssetDescriptors for the specified type
* @deprecated Change to use Composite instead
*/ */
@Deprecated
public List<AssetDescriptor> getAssetDescriptorTree(String type) { public List<AssetDescriptor> getAssetDescriptorTree(String type) {
if (type.equals(GenericAsset.TYPE)) { if (type.equals(GenericAsset.TYPE)) {
return List.of(getAssetDescriptor(GenericAsset.TYPE)); return List.of(getAssetDescriptor(GenericAsset.TYPE));
@@ -130,6 +156,21 @@ public class AssetService {
return List.of(getAssetDescriptor(GenericAsset.TYPE), getAssetDescriptor(type)); return List.of(getAssetDescriptor(GenericAsset.TYPE), getAssetDescriptor(type));
} }
/**
* Retrieves a tree of asset descriptors for the specified composite.
*
* @param composite the composite to retrieve descriptors for
* @return a set of AssetDescriptors for the composite
*/
public Set<AssetDescriptor> getAssetDescriptorTree(Composite composite) {
var tree = new TreeSet<>(Comparator.comparing(AssetDescriptor::getDisplayName));
tree.add(getAssetDescriptor(GenericAsset.TYPE));
for (var asset : composite.getAssets()) {
tree.add(getAssetDescriptor(asset));
}
return tree;
}
/** /**
* Creates a new asset of the specified type with the provided form data. * Creates a new asset of the specified type with the provided form data.
* *
@@ -140,12 +181,12 @@ public class AssetService {
@Transactional @Transactional
public Asset createAsset(String type, Map<String, String> formData) { public Asset createAsset(String type, Map<String, String> formData) {
var genericDescriptor = getAssetDescriptor(GenericAsset.TYPE); var genericDescriptor = getAssetDescriptor(GenericAsset.TYPE);
var assetDescriptor = getAssetDescriptor(type);
var genericAsset = new GenericAsset(); var genericAsset = new GenericAsset();
genericAsset.setType(type); genericAsset.setType(type);
fillIn(genericAsset, genericDescriptor, formData); fillIn(genericAsset, genericDescriptor, formData);
var assetDescriptor = getAssetDescriptor(type);
var asset = assetDescriptor.newInstance(); var asset = assetDescriptor.newInstance();
fillIn(asset, assetDescriptor, formData); fillIn(asset, assetDescriptor, formData);
@@ -155,6 +196,36 @@ public class AssetService {
return asset; return asset;
} }
/**
* Creates a composite asset with multiple asset types.
*
* @param type The list of asset types to include in the composite asset.
* @param formData The form data containing the properties for each asset type.
* @return The generic asset.
*/
@Transactional
public GenericAsset createCompositeAsset(List<String> type, Map<String, String> formData) {
if (type.isEmpty()) {
throw new IllegalArgumentException("At least one asset type must be provided.");
}
var genericDescriptor = getAssetDescriptor(GenericAsset.TYPE);
var genericAsset = new GenericAsset();
genericAsset.setType("composite");
fillIn(genericAsset, genericDescriptor, formData);
genericAsset = genericRepository.saveAndFlush(genericAsset);
for (var assetType : type) {
var assetDescriptor = getAssetDescriptor(assetType);
var asset = assetDescriptor.newInstance();
fillIn(asset, assetDescriptor, formData);
asset.setAsset(genericAsset);
getRepositoryFor(assetType).saveAndFlushAsset(asset);
}
return genericAsset;
}
/** /**
* Edits an existing asset with the provided form data. * Edits an existing asset with the provided form data.
* *
@@ -164,20 +235,21 @@ public class AssetService {
*/ */
@Transactional @Transactional
public Asset editAsset(long qr, Map<String, String> formData) { public Asset editAsset(long qr, Map<String, String> formData) {
var genericAsset = genericRepository.findByQr(qr); var composite = getAssetByQr(qr);
if (genericAsset == null) { if (composite == null) {
throw new IllegalArgumentException("No asset found with QR code: " + qr); throw new IllegalArgumentException("No asset found with QR code: " + qr);
} }
var assetType = genericAsset.getType(); fillIn(composite.getGenericAsset(), getAssetDescriptor(GenericAsset.TYPE), formData);
var assetDescriptor = getAssetDescriptor(assetType); genericRepository.saveAndFlush(composite.getGenericAsset());
var asset = getRepositoryFor(assetType).findByAsset(genericAsset);
fillIn(genericAsset, getAssetDescriptor(GenericAsset.TYPE), formData); for (var asset : composite.getAssets()) {
var assetDescriptor = getAssetDescriptor(asset);
fillIn(asset, assetDescriptor, formData); fillIn(asset, assetDescriptor, formData);
getRepositoryFor(assetDescriptor.getType()).saveAndFlushAsset(asset);
}
genericRepository.saveAndFlush(genericAsset); return getAssetByQr(qr);
return getRepositoryFor(assetType).saveAndFlushAsset(asset);
} }
/** /**
@@ -225,7 +297,7 @@ public class AssetService {
* @return The parsed value as an Object. * @return The parsed value as an Object.
*/ */
private Object parseValue(AssetDescriptor descriptor, AssetProperty property, Map<String, String> values) { private Object parseValue(AssetDescriptor descriptor, AssetProperty property, Map<String, String> values) {
if (property.getType() == AssetProperty.Type.CAPACITY) { if (property.getType() == PropertyType.CAPACITY) {
var value = values.get(descriptor.asString(property) + "-value"); var value = values.get(descriptor.asString(property) + "-value");
var unit = values.get(descriptor.asString(property) + "-unit"); var unit = values.get(descriptor.asString(property) + "-unit");
if (value == null || value.isBlank() || unit == null || unit.isBlank()) { if (value == null || value.isBlank() || unit == null || unit.isBlank()) {
@@ -244,16 +316,22 @@ public class AssetService {
return null; return null;
} }
if (property.getType() == AssetProperty.Type.INTEGER) { if (property.getType() == PropertyType.INTEGER) {
return Integer.parseInt(stringValue); return Integer.parseInt(stringValue);
} else if (property.getType() == AssetProperty.Type.STRING) { } else if (property.getType() == PropertyType.STRING) {
return stringValue; return stringValue;
} else if (property.getType() == AssetProperty.Type.BOOLEAN) { } else if (property.getType() == PropertyType.BOOLEAN) {
return switch (stringValue.toLowerCase()) { return switch (stringValue.toLowerCase()) {
case "true" -> true; case "true" -> true;
case "false" -> false; case "false" -> false;
default -> null; default -> null;
}; };
} else if (property.getType() == PropertyType.BUILD) {
var build = buildService.getBuildById(Integer.parseInt(stringValue));
if (build == null) {
throw new IllegalArgumentException("Invalid build ID for property '" + property.getName() + "': " + stringValue);
}
return build;
} else if (property.getType().isEnum) { } else if (property.getType().isEnum) {
for (var option : property.getOptions()) { for (var option : property.getOptions()) {
if (option.getValue().equals(stringValue)) { if (option.getValue().equals(stringValue)) {

View File

@@ -0,0 +1,113 @@
package be.seeseepuff.pcinv.services;
import be.seeseepuff.pcinv.models.Build;
import be.seeseepuff.pcinv.models.BuildInfo;
import be.seeseepuff.pcinv.repositories.BuildRepository;
import be.seeseepuff.pcinv.repositories.RamRepository;
import jakarta.annotation.PostConstruct;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* A service that manages computer builds.
*/
@Service
@RequiredArgsConstructor
public class BuildService {
private final BuildRepository buildRepository;
private final RamRepository ramRepository;
@PostConstruct
private void init() {
Build empty = buildRepository.getBuildByNameAndMeta("None", true);
if (empty == null) {
empty = Build.builder()
.name("None")
.meta(true)
.build();
}
empty.setDescription("A meta build to hold unused parts.");
empty = buildRepository.save(empty);
}
/**
* Gets a list of all computer builds, including meta builds.
*
* @return A list of all builds.
*/
public List<Build> getAllBuilds() {
return buildRepository.findAll();
}
/**
* Gets a list of all computer builds, excluding meta builds.
*
* @return A list of all builds.
*/
public List<Build> getAllRealBuilds() {
return buildRepository.findAllByMeta(false);
}
/**
* Gets a build by its ID.
*
* @param id The ID of the build to retrieve.
* @return The build with the given ID, or null if not found.
*/
public Build getBuildById(long id) {
return buildRepository.getBuildById(id);
}
/**
* Creates a new build with the given name and description.
*
* @param name The name of the build.
* @param description The description of the build.
* @return The created build.
*/
@Transactional
public Build createBuild(String name, String description) {
Build build = Build.builder()
.name(name)
.description(description)
.build();
return buildRepository.saveAndFlush(build);
}
/**
* Deletes a build by its ID.
*
* @param id The ID of the build to delete.
*/
@Transactional
public void deleteBuild(long id) {
Build build = buildRepository.getBuildById(id);
for (var part : build.getParts()) {
part.setBuild(null);
}
buildRepository.deleteById(id);
}
/**
* Gets the build information for a given build ID.
*
* @param build The build object for which to retrieve the information.
* @return The BuildInfo object containing the build information.
* @throws IllegalArgumentException if the build with the given ID does not exist.
*/
public BuildInfo getBuildInfo(Build build) {
var buildInfo = new BuildInfo();
for (var part : build.getParts()) {
if (part.getType().equals("ram")) {
var asset = ramRepository.findByAsset(part);
if (asset.getCapacity() != null) {
buildInfo.setTotalRam(buildInfo.getTotalRam() + asset.getCapacity());
}
}
}
return buildInfo;
}
}

View File

@@ -9,7 +9,8 @@
<tr th:each="a : ${assets}"> <tr th:each="a : ${assets}">
<td th:each="p : ${properties}" th:if="${!p.hideInOverview}"> <td th:each="p : ${properties}" th:if="${!p.hideInOverview}">
<a th:if="${p.name == 'qr'}" th:href="'/view/'+${a.getQr()}" th:text="${p.renderValue(a)}"></a> <a th:if="${p.name == 'qr'}" th:href="'/view/'+${a.getQr()}" th:text="${p.renderValue(a)}"></a>
<span th:if="${p.name != 'qr'}" th:text="${p.renderValue(a)}"></span> <a th:if="${p.name == 'build' && a.getAsset().getBuild() != null}" th:href="'/build/'+${a.getAsset().getBuild().getId()}" th:text="${p.renderValue(a)}"></a>
<span th:if="${p.name != 'qr' && (p.name != 'build' || a.getAsset().getBuild() == null)}" th:text="${p.renderValue(a)}"></span>
</td> </td>
<td> <td>
<a th:href="'/view/'+${a.getQr()}">View</a> <a th:href="'/view/'+${a.getQr()}">View</a>

View File

@@ -0,0 +1,24 @@
<body th:replace="~{fragments :: base(title=${'Build ' + build.getName()}, content=~{::content})}">
<div th:fragment="content">
<ul>
<li><b>Name: </b><span th:text="${build.name}"></span></li>
<li><b>Description: </b><span th:text="${build.description}"></span></li>
<li><b>Part Count: </b><span th:text="${build.getParts()?.size() ?: 0}"></span></li>
<li><b>Total RAM: </b><span th:text="${buildInfo.getTotalRamCapacity().getCapacityInUnit()} + ' ' + ${buildInfo.getTotalRamCapacity().getIdealUnit().displayName}"></span></li>
</ul>
<table border="1" cellpadding="4">
<tr bgcolor="#d3d3d3">
<th>QR</th>
<th>Type</th>
<th>Brand</th>
<th>Model</th>
</tr>
<tr th:each="p : ${build.getParts()}">
<td><a th:href="'/view/' + ${p.qr}" th:text="${p.qr}"></a></td>
<td><a th:href="'/browse/' + ${p.type}" th:text="${descriptors.getDescriptorForType(p.type).displayName}"></a></td>
<td th:text="${descriptors.getGenericProperty('brand').renderValue(p)}"></td>
<td th:text="${descriptors.getGenericProperty('model').renderValue(p)}"></td>
</tr>
</table>
</div>
</body>

View File

@@ -0,0 +1,28 @@
<body th:replace="~{fragments :: base(title='Builds', content=~{::content})}">
<div th:fragment="content">
<table border="1" cellpadding="4">
<tr bgcolor="#d3d3d3">
<th>Name</th>
<th>Description</th>
<th>Part Count</th>
<th>Actions</th>
</tr>
<tr th:each="b : ${builds}">
<td><a th:href="'/build/' + ${b.id}" th:text="${b.getName()}"></a></td>
<td th:text="${b.getDescription()}"></td>
<td th:text="${b.getParts()?.size() ?: 0}"></td>
<td>
<a th:if="${!b.isMeta()}" th:href="${'/delete_build/' + b.id}">Delete</a>
</td>
</tr>
<form action="/create_build" method="post">
<tr>
<td><label><input type="text" name="name" placeholder="Name"></label></td>
<td><label><input type="text" name="description" placeholder="Description"></label></td>
<td></td>
<td><input type="submit" value="Create"></td>
</tr>
</form>
</table>
</div>
</body>

View File

@@ -2,12 +2,14 @@
<div th:fragment="content"> <div th:fragment="content">
<h2>Create a <span th:text="${descriptor.displayName}"></span></h2> <h2>Create a <span th:text="${descriptor.displayName}"></span></h2>
<form th:action="'/'+${(action == 'duplicate') ? 'create' : action}+'/'+${(asset != null && action != 'duplicate') ? asset.getQr() : descriptor.getType()}" method="post"> <form th:action="'/'+${(action == 'duplicate') ? 'create' : action}+'/'+${(asset != null && action != 'duplicate') ? asset.getQr() : descriptor.getType()}" method="post">
<input th:each="t : ${types}" type="hidden" name="type" th:value="${t}"/>
<div th:each="d : ${descriptors}"> <div th:each="d : ${descriptors}">
<h2 th:text="${d.displayName}"></h2> <h2 th:text="${d.displayName}"></h2>
<table border="1" cellpadding="4"> <table border="1" cellpadding="4">
<tr th:each="p : ${d.getProperties()}"> <tr th:each="p : ${d.getProperties()}">
<td bgcolor="#d3d3d3"><b><label th:text="${p.displayName}" th:for="${d.asString(p)}" th:title="${p.description}"></label></b></td> <td bgcolor="#d3d3d3"><b><label th:text="${p.displayName}" th:for="${d.asString(p)}" th:title="${p.description}"></label></b></td>
<td th:switch="${p.type.nameOrEnum()}"> <td th:switch="${p.type.nameOrEnum()}">
<!-- Property Type: String List -->
<span th:case="STRING"> <span th:case="STRING">
<select th:if="${p.inputList}" th:id="${d.asString(p)+'-list'}" th:name="${d.asString(p)+'-list'}"> <select th:if="${p.inputList}" th:id="${d.asString(p)+'-list'}" th:name="${d.asString(p)+'-list'}">
<option value="__new__">New...</option> <option value="__new__">New...</option>
@@ -17,8 +19,9 @@
<input type="text" th:id="${d.asString(p)}" th:name="${d.asString(p)}" th:value="${p.getValue(asset)}" th:placeholder="${p.displayName}" th:required="${p.required}"/> <input type="text" th:id="${d.asString(p)}" th:name="${d.asString(p)}" th:value="${p.getValue(asset)}" th:placeholder="${p.displayName}" th:required="${p.required}"/>
</span> </span>
<input th:case="STRING" type="text" th:id="${d.asString(p)}" th:name="${d.asString(p)}" th:value="${p.getValue(asset)}" th:placeholder="${p.displayName}" th:required="${p.required}"/> <input th:case="STRING" type="text" th:id="${d.asString(p)}" th:name="${d.asString(p)}" th:value="${p.getValue(asset)}" th:placeholder="${p.displayName}" th:required="${p.required}"/>
<!-- Property Type: Integer -->
<input th:case="INTEGER" type="number" th:id="${d.asString(p)}" th:name="${d.asString(p)}" th:value="${(p.name == 'qr' && action == 'duplicate') ? null : p.getValue(asset)}" th:required="${p.required}"/> <input th:case="INTEGER" type="number" th:id="${d.asString(p)}" th:name="${d.asString(p)}" th:value="${(p.name == 'qr' && action == 'duplicate') ? null : p.getValue(asset)}" th:required="${p.required}"/>
<!-- <input th:case="BOOLEAN" type="checkbox" th:id="${d.asString(p)}" th:name="${d.asString(p)}" th:value="true" th:checked="${asset != null ? p.getValue(asset) : p.defaultValue}"/>--> <!-- Property Type: Boolean -->
<span th:case="BOOLEAN"> <span th:case="BOOLEAN">
<input th:name="${d.asString(p)}" th:id="${d.asString(p)}+'-null'" type="radio" value="null" th:checked="${asset == null || (p.getValue(asset) == null)}"> <input th:name="${d.asString(p)}" th:id="${d.asString(p)}+'-null'" type="radio" value="null" th:checked="${asset == null || (p.getValue(asset) == null)}">
<label th:for="${d.asString(p)}+'-null'">Not known</label> <label th:for="${d.asString(p)}+'-null'">Not known</label>
@@ -27,9 +30,11 @@
<input th:name="${d.asString(p)}" th:id="${d.asString(p)}+'-false'" type="radio" value="false" th:checked="${asset != null && (p.getValue(asset) == false)}"> <input th:name="${d.asString(p)}" th:id="${d.asString(p)}+'-false'" type="radio" value="false" th:checked="${asset != null && (p.getValue(asset) == false)}">
<label th:for="${d.asString(p)}+'-false'">No</label> <label th:for="${d.asString(p)}+'-false'">No</label>
</span> </span>
<!-- Property Type: Enum -->
<select th:case="enum" th:id="${d.asString(p)}" th:name="${d.asString(p)}"> <select th:case="enum" th:id="${d.asString(p)}" th:name="${d.asString(p)}">
<option th:each="o : ${p.options}" th:value="${o.value}" th:text="${o.displayName}" th:selected="${asset != null ? (p.getValue(asset) == o.enumConstant) : o.defaultValue}">Good</option> <option th:each="o : ${p.options}" th:value="${o.value}" th:text="${o.displayName}" th:selected="${asset != null ? (p.getValue(asset) == o.enumConstant) : o.defaultValue}">Good</option>
</select> </select>
<!-- Property Type: Capacity -->
<span th:case="CAPACITY"> <span th:case="CAPACITY">
<input type="number" th:id="${d.asString(p)+'-value'}" th:name="${d.asString(p)+'-value'}" th:required="${p.required}" th:value="${p.asCapacity(asset)?.getCapacityInUnit() ?: ''}"/> <input type="number" th:id="${d.asString(p)+'-value'}" th:name="${d.asString(p)+'-value'}" th:required="${p.required}" th:value="${p.asCapacity(asset)?.getCapacityInUnit() ?: ''}"/>
<select th:id="${d.asString(p)}+'-unit'" th:name="${d.asString(p)}+'-unit'"> <select th:id="${d.asString(p)}+'-unit'" th:name="${d.asString(p)}+'-unit'">
@@ -44,6 +49,13 @@
<option value="1099511627776" th:if="${p.capacityAsIEC}" th:selected="${p.asCapacity(asset)?.getIdealUnit()?.name() == 'TEBIBYTES'}">TiB</option> <option value="1099511627776" th:if="${p.capacityAsIEC}" th:selected="${p.asCapacity(asset)?.getIdealUnit()?.name() == 'TEBIBYTES'}">TiB</option>
</select> </select>
</span> </span>
<!-- Property Type: Build-->
<span th:case="BUILD">
<select th:id="${d.asString(p)}" th:name="${d.asString(p)}">
<option value="" th:selected="${p.getValue(asset) == null}">(Unknown)</option>
<option th:each="b : ${builds}" th:value="${b.getId()}" th:selected="${p.getValue(asset) == b}" th:text="${b.getName()}">My PC Build</option>
</select>
</span>
<b th:case="*">Bad input type for <span th:text="${d.type}+'-'+${p.type}"></span></b> <b th:case="*">Bad input type for <span th:text="${d.type}+'-'+${p.type}"></span></b>
</td> </td>
</tr> </tr>

View File

@@ -0,0 +1,11 @@
<body th:replace="~{fragments :: base(title='Select type to create', content=~{::content})}">
<div th:fragment="content">
<h2>Create a new composite device</h2>
<form method="get" action="/create_composite">
<div th:each="d : ${descriptors.getAssets()}" th:if="${d.visible}"><label><input type="checkbox" value="on" th:name="${d.type}"><span th:text="${d.displayName}"></span></label></div>
<p>
<input type="submit" value="Create Composite">
</p>
</form>
</div>
</body>

View File

@@ -2,6 +2,7 @@
<div th:fragment="content"> <div th:fragment="content">
<h2>Create a new device</h2> <h2>Create a new device</h2>
<ul> <ul>
<li><a href="/create_composite"><i>Composite</i></a></li>
<li th:each="d : ${descriptors.getAssets()}" th:if="${d.visible}"><a th:href="'/create/'+${d.getType()}" th:text="${d.displayName}"></a></li> <li th:each="d : ${descriptors.getAssets()}" th:if="${d.visible}"><a th:href="'/create/'+${d.getType()}" th:text="${d.displayName}"></a></li>
</ul> </ul>
</div> </div>

View File

@@ -10,6 +10,7 @@
<a href="/">Home</a> <a href="/">Home</a>
<a href="/browse">Browse</a> <a href="/browse">Browse</a>
<a href="/create">Create</a> <a href="/create">Create</a>
<a href="/builds">Builds</a>
<hr> <hr>
<div th:replace="${content}"> <div th:replace="${content}">
</div> </div>

View File

@@ -7,7 +7,11 @@
<table border="1" cellpadding="4"> <table border="1" cellpadding="4">
<tr th:each="p : ${d.properties}"> <tr th:each="p : ${d.properties}">
<th bgcolor="lightgray"><b th:text="${p.displayName}"></b></th> <th bgcolor="lightgray"><b th:text="${p.displayName}"></b></th>
<td th:text="${p.renderValue(asset)}"></td> <td th:if="${p.name == 'build'}">
<a th:if="${asset.getAsset().getBuild() != null}" th:href="'/build/' + ${asset.getAsset().getBuild().id}" th:text="${p.renderValue(asset)}"></a>
<span th:if="${asset.getAsset().getBuild() == null}" th:text="${p.renderValue(asset)}"></span>
</td>
<td th:if="${p.name != 'build'}" th:text="${p.renderValue(asset)}"></td>
</tr> </tr>
</table> </table>
</div> </div>