From 03d2d25b05a4821e55de75b84e3e7fac1ff147f5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Valenta?= <git@imaniti.org>
Date: Tue, 18 Jul 2023 12:04:49 +0900
Subject: [PATCH] delete after-approval notices

---
 contracts/admin.py                            | 65 +++++++++++++++++--
 contracts/forms.py                            |  2 +-
 ...er_signee_options_alter_contract_status.py | 37 +++++++++--
 .../0066_alter_contractee_options.py          | 20 ++++--
 ...contractee_options_alter_signee_options.py | 33 ++++++++--
 contracts/models.py                           |  6 ++
 6 files changed, 140 insertions(+), 23 deletions(-)

diff --git a/contracts/admin.py b/contracts/admin.py
index ed869a6..80659a7 100644
--- a/contracts/admin.py
+++ b/contracts/admin.py
@@ -342,7 +342,50 @@ class ContractAdmin(
                 "Content-Type": "application/json",
             }
 
-            if obj.status == obj.StatusTypes.TO_BE_APPROVED:
+            if obj.status == obj.StatusTypes.WORK_IN_PROGRESS:
+                try:
+                    user = User.objects.filter(id=obj.created_by.id).first()
+
+                    notice = requests.post(
+                        settings.NASTENKA_API_URL,
+                        data=json.dumps(
+                            {
+                                "name": f"Smlouva vrácena k úpravě - {obj.name}",
+                                "description": (
+                                    obj.summary
+                                    if obj.summary not in (None, "")
+                                    else "Bez popisu."
+                                ),
+                                "contract_id": obj.id,
+                                "sso_ids": [user.sso_id],
+                            }
+                        ),
+                        headers=headers,
+                    ).raise_for_status()
+
+                    if obj.after_approval_nastenka_notice_id is not None:
+                        requests.delete(
+                            f"{settings.NASTENKA_API_URL}/{obj.after_approval_nastenka_notice_id}",
+                            headers=headers,
+                        ).raise_for_status()
+
+                        obj.after_approval_nastenka_notice_id = None
+                        obj.save()
+
+                    if obj.to_be_approved_nastenka_notice_id is not None:
+                        requests.delete(
+                            f"{settings.NASTENKA_API_URL}/{obj.to_be_approved_nastenka_notice_id}",
+                            headers=headers,
+                        ).raise_for_status()
+
+                        obj.to_be_approved_nastenka_notice_id = None
+                        obj.save()
+                except Exception as exception:
+                    logger.error(
+                        'Failed to send out "contract returned for editing" Nástěnka notification: %s',
+                        str(exception),
+                    )
+            elif obj.status == obj.StatusTypes.TO_BE_APPROVED:
                 try:
                     sso_ids = []
 
@@ -381,7 +424,7 @@ class ContractAdmin(
                 try:
                     user = User.objects.filter(id=obj.created_by.id).first()
 
-                    requests.post(
+                    notice = requests.post(
                         settings.NASTENKA_API_URL,
                         data=json.dumps(
                             {
@@ -396,7 +439,13 @@ class ContractAdmin(
                             }
                         ),
                         headers=headers,
-                    ).raise_for_status()
+                    )
+
+                    notice.raise_for_status()
+                    notice = notice.json()
+
+                    obj.after_approval_nastenka_notice_id = uuid.UUID(notice["id"])
+                    obj.save()
 
                     if obj.to_be_approved_nastenka_notice_id is not None:
                         requests.delete(
@@ -415,7 +464,7 @@ class ContractAdmin(
                 try:
                     user = User.objects.filter(id=obj.created_by.id).first()
 
-                    requests.post(
+                    notice = requests.post(
                         settings.NASTENKA_API_URL,
                         data=json.dumps(
                             {
@@ -430,7 +479,13 @@ class ContractAdmin(
                             }
                         ),
                         headers=headers,
-                    ).raise_for_status()
+                    )
+
+                    notice.raise_for_status()
+                    notice = notice.json()
+
+                    obj.after_approval_nastenka_notice_id = uuid.UUID(notice["id"])
+                    obj.save()
 
                     if obj.to_be_approved_nastenka_notice_id is not None:
                         requests.delete(
diff --git a/contracts/forms.py b/contracts/forms.py
index 935d34d..a6a99e7 100644
--- a/contracts/forms.py
+++ b/contracts/forms.py
@@ -80,7 +80,7 @@ class ContractAdminForm(forms.ModelForm):
                         if choice_key in (
                             Contract.StatusTypes.APPROVED,
                             Contract.StatusTypes.REJECTED,
-                            Contract.StatusTypes.WORK_IN_PROGRESS
+                            Contract.StatusTypes.WORK_IN_PROGRESS,
                         ):
                             allowed_choices.append(
                                 (
diff --git a/contracts/migrations/0065_alter_signee_options_alter_contract_status.py b/contracts/migrations/0065_alter_signee_options_alter_contract_status.py
index 712b59d..2934140 100644
--- a/contracts/migrations/0065_alter_signee_options_alter_contract_status.py
+++ b/contracts/migrations/0065_alter_signee_options_alter_contract_status.py
@@ -4,19 +4,42 @@ from django.db import migrations, models
 
 
 class Migration(migrations.Migration):
-
     dependencies = [
-        ('contracts', '0064_contract_to_be_approved_nastenka_notice_id'),
+        ("contracts", "0064_contract_to_be_approved_nastenka_notice_id"),
     ]
 
     operations = [
         migrations.AlterModelOptions(
-            name='signee',
-            options={'ordering': ['name', models.OrderBy(models.F('department'), descending=True, nulls_last=False)], 'permissions': [('edit_others', 'Upravit cizí'), ('delete_others', 'Odstranit cizí')], 'verbose_name': 'Jiná smluvní strana', 'verbose_name_plural': 'Ostatní smluvní strany'},
+            name="signee",
+            options={
+                "ordering": [
+                    "name",
+                    models.OrderBy(
+                        models.F("department"), descending=True, nulls_last=False
+                    ),
+                ],
+                "permissions": [
+                    ("edit_others", "Upravit cizĂ­"),
+                    ("delete_others", "Odstranit cizĂ­"),
+                ],
+                "verbose_name": "Jiná smluvní strana",
+                "verbose_name_plural": "OstatnĂ­ smluvnĂ­ strany",
+            },
         ),
         migrations.AlterField(
-            model_name='contract',
-            name='status',
-            field=models.CharField(choices=[('work_in_progress', 'Rozpracovaná'), ('to_be_approved', 'Ke schválení'), ('approved', 'Schválená'), ('rejected', 'Zamítnutá')], default='work_in_progress', help_text='Označením jako "Ke schválení" se smlouva předá schvalovateli.', max_length=16, verbose_name='Stav'),
+            model_name="contract",
+            name="status",
+            field=models.CharField(
+                choices=[
+                    ("work_in_progress", "Rozpracovaná"),
+                    ("to_be_approved", "Ke schválení"),
+                    ("approved", "Schválená"),
+                    ("rejected", "Zamítnutá"),
+                ],
+                default="work_in_progress",
+                help_text='Označením jako "Ke schválení" se smlouva předá schvalovateli.',
+                max_length=16,
+                verbose_name="Stav",
+            ),
         ),
     ]
diff --git a/contracts/migrations/0066_alter_contractee_options.py b/contracts/migrations/0066_alter_contractee_options.py
index 12bb14d..243e1a7 100644
--- a/contracts/migrations/0066_alter_contractee_options.py
+++ b/contracts/migrations/0066_alter_contractee_options.py
@@ -4,14 +4,26 @@ from django.db import migrations, models
 
 
 class Migration(migrations.Migration):
-
     dependencies = [
-        ('contracts', '0065_alter_signee_options_alter_contract_status'),
+        ("contracts", "0065_alter_signee_options_alter_contract_status"),
     ]
 
     operations = [
         migrations.AlterModelOptions(
-            name='contractee',
-            options={'ordering': ['name', models.OrderBy(models.F('department'), descending=True, nulls_last=False)], 'permissions': [('edit_others', 'Upravit cizí'), ('delete_others', 'Odstranit cizí')], 'verbose_name': 'Naše smluvní strana', 'verbose_name_plural': 'Naše smluvní strany'},
+            name="contractee",
+            options={
+                "ordering": [
+                    "name",
+                    models.OrderBy(
+                        models.F("department"), descending=True, nulls_last=False
+                    ),
+                ],
+                "permissions": [
+                    ("edit_others", "Upravit cizĂ­"),
+                    ("delete_others", "Odstranit cizĂ­"),
+                ],
+                "verbose_name": "Naše smluvní strana",
+                "verbose_name_plural": "Naše smluvní strany",
+            },
         ),
     ]
diff --git a/contracts/migrations/0067_alter_contractee_options_alter_signee_options.py b/contracts/migrations/0067_alter_contractee_options_alter_signee_options.py
index bfda986..b211adf 100644
--- a/contracts/migrations/0067_alter_contractee_options_alter_signee_options.py
+++ b/contracts/migrations/0067_alter_contractee_options_alter_signee_options.py
@@ -4,18 +4,39 @@ from django.db import migrations, models
 
 
 class Migration(migrations.Migration):
-
     dependencies = [
-        ('contracts', '0066_alter_contractee_options'),
+        ("contracts", "0066_alter_contractee_options"),
     ]
 
     operations = [
         migrations.AlterModelOptions(
-            name='contractee',
-            options={'ordering': ['name', models.OrderBy(models.F('department'), nulls_first=True)], 'permissions': [('edit_others', 'Upravit cizí'), ('delete_others', 'Odstranit cizí')], 'verbose_name': 'Naše smluvní strana', 'verbose_name_plural': 'Naše smluvní strany'},
+            name="contractee",
+            options={
+                "ordering": [
+                    "name",
+                    models.OrderBy(models.F("department"), nulls_first=True),
+                ],
+                "permissions": [
+                    ("edit_others", "Upravit cizĂ­"),
+                    ("delete_others", "Odstranit cizĂ­"),
+                ],
+                "verbose_name": "Naše smluvní strana",
+                "verbose_name_plural": "Naše smluvní strany",
+            },
         ),
         migrations.AlterModelOptions(
-            name='signee',
-            options={'ordering': ['name', models.OrderBy(models.F('department'), nulls_first=True)], 'permissions': [('edit_others', 'Upravit cizí'), ('delete_others', 'Odstranit cizí')], 'verbose_name': 'Jiná smluvní strana', 'verbose_name_plural': 'Ostatní smluvní strany'},
+            name="signee",
+            options={
+                "ordering": [
+                    "name",
+                    models.OrderBy(models.F("department"), nulls_first=True),
+                ],
+                "permissions": [
+                    ("edit_others", "Upravit cizĂ­"),
+                    ("delete_others", "Odstranit cizĂ­"),
+                ],
+                "verbose_name": "Jiná smluvní strana",
+                "verbose_name_plural": "OstatnĂ­ smluvnĂ­ strany",
+            },
         ),
     ]
diff --git a/contracts/models.py b/contracts/models.py
index bcd61d7..17e70ac 100644
--- a/contracts/models.py
+++ b/contracts/models.py
@@ -698,6 +698,12 @@ class Contract(NameStrMixin, models.Model):
         blank=True, null=True, verbose_name="ID oznámení o nové smlouvě v Nástěnce"
     )
 
+    after_approval_nastenka_notice_id = models.UUIDField(
+        blank=True,
+        null=True,
+        verbose_name="ID oznámení o schválení / vrácení v Nástěnce",
+    )
+
     @property
     def primary_contract_url(self) -> typing.Union[None, str]:
         if self.primary_contract is None:
-- 
GitLab