Skip to content

Commit

Permalink
Merge pull request #30 from rufener/document2
Browse files Browse the repository at this point in the history
Document with filefield
  • Loading branch information
rufener authored Dec 22, 2023
2 parents 3492f4e + 0d3208e commit 4d06423
Show file tree
Hide file tree
Showing 18 changed files with 366 additions and 373 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Generated by Django 4.2.8 on 2023-12-19 08:04

from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

dependencies = [
('ne_sop_api', '0018_document_author_document_size_alter_event_time'),
]

operations = [
migrations.AlterField(
model_name='document',
name='author',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='ne_sop_api.entity'),
),
migrations.AlterField(
model_name='document',
name='item',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='documents', to='ne_sop_api.item'),
),
migrations.CreateModel(
name='NewDocument',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('uuid', models.UUIDField(default=uuid.uuid4, editable=False)),
('created', models.DateTimeField(auto_now_add=True)),
('note', models.CharField(blank=True, default='', max_length=500)),
('filename', models.CharField(default=None, max_length=200)),
('version', models.PositiveIntegerField(default=None)),
('size', models.PositiveIntegerField(default=0)),
('file', models.FileField(upload_to='')),
('author', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='ne_sop_api.entity')),
('item', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='item_documents', to='ne_sop_api.item')),
('template', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='ne_sop_api.template')),
],
options={
'ordering': ['created'],
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Generated by Django 4.2.8 on 2023-12-20 09:10

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('ne_sop_api', '0019_alter_document_author_alter_document_item_and_more'),
('ne_sop_api', '0019_item_enddate_item_startdate_alter_document_author'),
]

operations = [
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Generated by Django 4.2.8 on 2023-12-21 07:18

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('ne_sop_api', '0020_entity_users'),
('ne_sop_api', '0020_merge_20231220_1010'),
]

operations = [
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Generated by Django 4.2.8 on 2023-12-21 15:36

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import ne_sop_api.utils


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('ne_sop_api', '0021_merge_0020_entity_users_0020_merge_20231220_1010'),
]

operations = [
migrations.DeleteModel(
name='Document',
),
migrations.RenameModel('NewDocument', 'Document'),
migrations.AlterField(
model_name='entity',
name='type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='ne_sop_api.entitytype'),
),
migrations.AlterField(
model_name='entity',
name='users',
field=models.ManyToManyField(blank=True, related_name='users', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='event',
name='type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='ne_sop_api.eventtype'),
),
migrations.AlterField(
model_name='item',
name='status',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='ne_sop_api.itemstatus'),
),
migrations.AlterField(
model_name='item',
name='support',
field=models.ManyToManyField(blank=True, related_name='item', to='ne_sop_api.entity'),
),
migrations.AlterField(
model_name='item',
name='type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='ne_sop_api.itemtype'),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Generated by Django 4.2.8 on 2023-12-22 14:48

from django.db import migrations, models
import django.db.models.deletion
import ne_sop_api.utils


class Migration(migrations.Migration):

dependencies = [
('ne_sop_api', '0022_remove_document_relpath_remove_document_valid_and_more'),
]

operations = [
migrations.AlterField(
model_name='document',
name='file',
field=models.FileField(upload_to=ne_sop_api.utils.Utils.get_upload_path),
),
migrations.AlterField(
model_name='document',
name='item',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='documents', to='ne_sop_api.item'),
),
migrations.AlterField(
model_name='item',
name='created',
field=models.DateTimeField(auto_now_add=True, default='2023-12-22 15:48:00'),
preserve_default=False,
),
]
21 changes: 12 additions & 9 deletions back/ne_sop_backend/ne_sop_api/models.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from django.db import models
from django.contrib.auth.models import User
import uuid
from pathlib import Path
from pathlib import Path, PurePath
import os

from ne_sop_api.utils import Utils

# %% ENTITY TYPE
class EntityType(models.Model):
Expand Down Expand Up @@ -71,7 +73,7 @@ def __str__(self):

# %% ITEM
class Item(models.Model):
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)
number = models.CharField(max_length=30, blank=True, default="")
title = models.CharField(max_length=512, blank=True, default="")
Expand Down Expand Up @@ -175,23 +177,24 @@ def __str__(self):


class Document(models.Model):
created = models.DateTimeField(auto_now_add=True)
uuid = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False)
created = models.DateTimeField(auto_now_add=True)
template = models.ForeignKey(Template, null=True, on_delete=models.SET_NULL)
note = models.CharField(max_length=500, blank=True, default="")
valid = models.BooleanField(default=True)
relpath = models.CharField(default=None, max_length=200)
filename = models.CharField(default=None, max_length=200)
version = models.PositiveIntegerField(default=None)
size = models.PositiveIntegerField(default=0, null=False)
item = models.ForeignKey(Item, related_name="document", on_delete=models.CASCADE)
item = models.ForeignKey(Item, related_name="documents", on_delete=models.CASCADE)
author = models.ForeignKey(Entity, null=True, on_delete=models.SET_NULL)
file = models.FileField(upload_to=Utils.get_upload_path)

class Meta:
ordering = ["created"]

@property
def filename(self):
return Path(self.relpath).name
def relpath(self):
return PurePath(str(self.item.created.year), str(self.item.id), self.file.name)

def __str__(self):
return self.filename
return self.file.name

93 changes: 64 additions & 29 deletions back/ne_sop_backend/ne_sop_api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
from rest_framework import serializers
from ne_sop_api.utils import Utils
import os

from ne_sop_api.models import (
Document,
Entity,
Expand Down Expand Up @@ -266,33 +269,6 @@ class Meta:
]


class DocumentByItemSerializer(serializers.ModelSerializer):
template = serializers.SlugRelatedField(
queryset=Template.objects.all(),
slug_field="name",
)
author = serializers.SlugRelatedField(
queryset=Entity.objects.all(),
slug_field="name",
)

class Meta:
model = Document
fields = [
"id",
"created",
# "uuid",
"template",
"note",
# "valid",
# "relpath",
"version",
"filename",
"size",
"author",
]


class FileSerializer(serializers.Serializer):
file = serializers.FileField()

Expand Down Expand Up @@ -322,6 +298,63 @@ class Meta:
]


class DocumentSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(required=False, read_only=False)

template = serializers.SlugRelatedField(slug_field='name', read_only=True)
template_id = serializers.PrimaryKeyRelatedField(source='template', queryset=Template.objects.all(), write_only=True)

author = serializers.SlugRelatedField(slug_field='name', read_only=True)
author_id = serializers.PrimaryKeyRelatedField(source='author', queryset=Entity.objects.all(), write_only=True)

version = serializers.IntegerField(required=False)

item = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all())

class Meta:
model = Document
fields = [
"id",
"uuid",
"created",
"filename",
"template",
"template_id",
"note",
"version",
"size",
"item",
"author",
"author_id",
"file",
]

def create(self, validated_data):
version = Utils.get_next_documentVersion(Document, validated_data)
validated_data['version'] = version


template = validated_data.get('template')

file = validated_data.get('file', None)

filename = file.name
file_extension = filename.rsplit(".", 1)[1]

if int(template.id) != int(os.environ["NESOP_TEMPLATE_AUTRE_ID"]):
template = Template.objects.filter(id=template.id).first()
filename = template.filename

filename = filename.rsplit(".", 1)[0] + f"_v{version}." + file_extension

file.name = filename
validated_data['file'] = file
validated_data['filename'] = filename

document = Document.objects.create(**validated_data)
return document


class NewItemSerializer(serializers.ModelSerializer):
type = serializers.PrimaryKeyRelatedField(
required=True,
Expand Down Expand Up @@ -351,6 +384,8 @@ class NewItemSerializer(serializers.ModelSerializer):

events = NewEventSerializer(required=False, many=True)

documents = DocumentSerializer(required=False, many=True)

class Meta:
model = Item
fields = [
Expand All @@ -368,6 +403,7 @@ class Meta:
"lead",
"support",
"events",
"documents",
"valid",
]

Expand Down Expand Up @@ -443,7 +479,6 @@ def update(self, instance, validated_data):

# IF EVENT ALREADY EXISTS, UPDATE IT
if event_id:
print("Update (event exists)")
event_instance = Event.objects.get(id=event_id, item=instance)
event_instance.date = new_event.get("date", event_instance.date)
event_instance.time = new_event.get("time", event_instance.time)
Expand All @@ -456,7 +491,7 @@ def update(self, instance, validated_data):

# IF EVENT DOES NOT EXISTS, CREATE IT
else:
print("CREATE (event does not exist)")
Event.objects.create(item=instance, **new_event)

return instance

10 changes: 1 addition & 9 deletions back/ne_sop_backend/ne_sop_api/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.urls import path, include, re_path
from django.urls import path, include

# from rest_framework.urlpatterns import format_suffix_patterns
from ne_sop_api import views
Expand All @@ -21,14 +21,6 @@

urlpatterns = [
path("api/", include(router.urls)),
re_path(
r"^api/fileupload/(?P<filename>[^/]+)$",
views.FileUploadView.as_view(),
),
re_path(
r"^api/filedownload/(?P<pk>[^/]+)$",
views.FileDownloadView.as_view(),
),
path(
"api/schema/",
SpectacularAPIView.as_view(),
Expand Down
17 changes: 17 additions & 0 deletions back/ne_sop_backend/ne_sop_api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,21 @@ def iterateFilename(cls, filepath):
count += 1
filepath_ = PurePath( f'_{count}.'.join(str(filepath).rsplit('.', 1)) )
return filepath_

@classmethod
def get_upload_path(cls, instance, filename):
return PurePath(str(instance.item.created.year), str(instance.item.id), filename)

@classmethod
def get_next_documentVersion(cls, DocumentModel, data):
documents = DocumentModel.objects.filter(
item=data['item'],
template=data['template']
).all().order_by("-version")

version = 1
if len(documents) > 0:
version = documents[0].version + 1

return version

Loading

0 comments on commit 4d06423

Please sign in to comment.