Skip to content

Commit

Permalink
Merge pull request #138 from intuitem/CA-197-Show-an-error-message-to…
Browse files Browse the repository at this point in the history
…-the-user-when-he-tries-to-create-an-object-with-the-same-name-as-another-object-in-the-same-scope

Ca 197 show an error message to the user when he tries to create an object with the same name as another object in the same scope
  • Loading branch information
eric-intuitem authored Mar 13, 2024
2 parents 32fec32 + e8b682a commit db84833
Show file tree
Hide file tree
Showing 13 changed files with 223 additions and 205 deletions.
7 changes: 1 addition & 6 deletions backend/core/base_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,7 @@ def clean(self) -> None:
if not self.is_unique_in_scope(scope=scope, fields_to_check=_fields_to_check):
for field in _fields_to_check:
if not self.is_unique_in_scope(scope=scope, fields_to_check=[field]):
field_errors[field] = ValidationError(
_(
f"{getattr(self, field)} is already in use in this scope. Please choose another value."
),
code="unique",
)
field_errors[field] = f"{getattr(self, field)} is already used in this scope. Please choose another value."
super().clean()
if field_errors:
raise ValidationError(field_errors)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 5.0.2 on 2024-03-13 08:27

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('core', '0007_alter_requirementlevel_framework_and_more'),
]

operations = [
migrations.AlterField(
model_name='complianceassessment',
name='status',
field=models.CharField(blank=True, choices=[('planned', 'Planned'), ('in_progress', 'In progress'), ('in_review', 'In review'), ('done', 'Done'), ('deprecated', 'Deprecated')], default='planned', max_length=100, null=True, verbose_name='Status'),
),
migrations.AlterField(
model_name='riskassessment',
name='status',
field=models.CharField(blank=True, choices=[('planned', 'Planned'), ('in_progress', 'In progress'), ('in_review', 'In review'), ('done', 'Done'), ('deprecated', 'Deprecated')], default='planned', max_length=100, null=True, verbose_name='Status'),
),
]
13 changes: 12 additions & 1 deletion backend/core/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ class Threat(ReferentialObjectMixin):
Library, on_delete=models.CASCADE, null=True, blank=True, related_name="threats"
)

fields_to_check = ["ref_id", "name"]

class Meta:
verbose_name = _("Threat")
verbose_name_plural = _("Threats")
Expand Down Expand Up @@ -215,6 +217,8 @@ class ReferenceControl(ReferentialObjectMixin):
verbose_name=_("Typical evidence"), null=True, blank=True
)

fields_to_check = ["ref_id", "name"]

class Meta:
verbose_name = _("Reference control")
verbose_name_plural = _("Reference controls")
Expand Down Expand Up @@ -548,6 +552,8 @@ class Evidence(NameDescriptionMixin, FolderMixin):
verbose_name=_("Link"),
)

fields_to_check = ["name"]

class Meta:
verbose_name = _("Evidence")
verbose_name_plural = _("Evidences")
Expand Down Expand Up @@ -636,7 +642,7 @@ class Status(models.TextChoices):
verbose_name=_("Effort"),
)

fields_to_check = ["name", "category"]
fields_to_check = ["name"]

class Meta:
verbose_name = _("Applied control")
Expand Down Expand Up @@ -750,6 +756,8 @@ class Status(models.TextChoices):
choices=Status.choices,
default=Status.PLANNED,
verbose_name=_("Status"),
blank=True,
null=True
)
authors = models.ManyToManyField(
User,
Expand Down Expand Up @@ -1155,6 +1163,8 @@ class RiskScenario(NameDescriptionMixin):
max_length=500, blank=True, null=True, verbose_name=_("Justification")
)

fields_to_check = ["name"]

class Meta:
verbose_name = _("Risk scenario")
verbose_name_plural = _("Risk scenarios")
Expand Down Expand Up @@ -1274,6 +1284,7 @@ class Result(models.TextChoices):
verbose_name=_("Result"),
)


class Meta:
verbose_name = _("Compliance assessment")
verbose_name_plural = _("Compliance assessments")
Expand Down
14 changes: 12 additions & 2 deletions backend/core/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ def update(self, instance: models.Model, validated_data: Any) -> models.Model:
raise serializers.ValidationError(
{"urn": "Imported objects cannot be modified"}
)
return super().update(instance, validated_data)
try:
object_updated = super().update(instance, validated_data)
return object_updated
except Exception as e:
logger.error(e)
raise serializers.ValidationError(e.args[0])

def create(self, validated_data: Any):
logger.debug("validated data", **validated_data)
Expand All @@ -42,7 +47,12 @@ def create(self, validated_data: Any):
"folder": "You do not have permission to create objects in this folder"
}
)
return super().create(validated_data)
try:
object_created = super().create(validated_data)
return object_created
except Exception as e:
logger.error(e)
raise serializers.ValidationError(e.args[0])

class Meta:
model: models.Model
Expand Down
18 changes: 18 additions & 0 deletions frontend/src/lib/components/Forms/Form.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
import SuperDebug from 'sveltekit-superforms/client/SuperDebug.svelte';
import type { AnyZodObject } from 'zod';
import type { ModalStore } from '@skeletonlabs/skeleton';
import { getModalStore } from '@skeletonlabs/skeleton';
const modalStore: ModalStore = getModalStore();
export let data: SuperValidated<AnyZodObject>;
export let dataType: 'form' | 'json';
export let invalidateAll = true; // set to false to keep form data using muliple forms on a page
Expand All @@ -14,12 +19,25 @@
export let debug = false; // set to true to enable SuperDebug component
function handleFormUpdated({
form,
closeModal
}: {
form: any;
closeModal: boolean;
}) {
if (closeModal && form.valid) {
$modalStore[0] ? modalStore.close() : null;
}
}
export const _form = superForm(data, {
dataType: dataType,
invalidateAll: invalidateAll,
applyAction: applyAction,
resetForm: resetForm,
validators: validators,
onUpdated: ({ form }) => handleFormUpdated({ form, closeModal: true }),
onSubmit: onSubmit
});
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/lib/components/Forms/ModelForm.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
import { browser } from '$app/environment';
import { page } from '$app/stores';
import * as m from '$paraglide/messages.js';
import { localItems, toCamelCase } from '$lib/utils/locales';
import { languageTag } from '$paraglide/runtime';
export let form: SuperValidated<AnyZodObject>;
export let model: ModelInfo;
Expand Down
Loading

0 comments on commit db84833

Please sign in to comment.