Skip to content

Commit

Permalink
Nikita/groot 86 remove brand updates from databankgreen (#150)
Browse files Browse the repository at this point in the history
* deleted brand_update model.

* deleted brand_suggestion model.

* Revert "deleted brand_suggestion model."

This reverts commit e05e816.
  • Loading branch information
nikita-pardeshi-github authored Feb 23, 2024
1 parent f2a0428 commit c6f6920
Show file tree
Hide file tree
Showing 7 changed files with 27 additions and 219 deletions.
1 change: 0 additions & 1 deletion bankgreen/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@
name="subregion-autocomplete",
),
path("calendar/", views.calendar_redirect, name="calendar"),
path("update/<str:tag>/", views.CreateUpdateView.as_view(), name="update"),
path("banks/<str:tag>/", views.brand_redirect, name="brand_quicklink"),
path("sustainable-eco-banks/<str:tag>/", views.brand_redirect, name="brand_quicklink"),
path("update_success/", views.update_success, name="update_success"),
Expand Down
83 changes: 1 addition & 82 deletions brand/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
raise_validation_error_for_missing_country,
raise_validation_error_for_missing_region,
)
from brand.models.brand_update import BrandUpdate
from brand.models.brand_suggestion import BrandSuggestion
from brand.models.commentary import InstitutionCredential, InstitutionType
from brand.models.features import BrandFeature, FeatureType
Expand Down Expand Up @@ -141,82 +140,6 @@ def clean(self):
admin.site.login_template = "registration/login.html"


@admin.register(BrandUpdate)
class BrandUpdateAdmin(admin.ModelAdmin):
form = CountriesWidgetOverrideForm
fields = ["brand_link"] + BrandUpdate.UPDATE_FIELDS + ["additional_info", "email", "consent"]
readonly_fields = ["brand_link", "name", "aliases", "website", "bank_features"]
inlines = [BrandFeaturesInline]
autocomplete_fields = ["subregions"]

list_display = ("short_name", "update_tag", "created", "email", "merged")
list_filter = ("merged",)

def brand_link(self, obj):
"""
Returns a link to the parent Brand object in the admin interface.
"""
parent_brand = Brand.objects.get(tag=obj.update_tag)
url = reverse("admin:brand_brand_change", args=(str(parent_brand.pk),))
return format_html('<a href="{}">{}</a>', url, parent_brand)

brand_link.short_description = "Brand"

def save_model(self, request, obj, form, change):
original = Brand.objects.get(tag=obj.update_tag)

# overwrite all fields with values from updates
for field in BrandUpdate.UPDATE_FIELDS:
if field != "regions" and field != "subregions":
value = getattr(obj, field)
setattr(original, field, value)

# combine country, regions, and subregions
# if a country or region is not explicitly specified, add it
combined_subregions = obj.subregions.all() | original.subregions.all()
original.subregions.set(combined_subregions.distinct())

combined_regions = (
obj.regions.all()
| original.regions.all()
| Region.objects.filter(id__in=[x.region.id for x in combined_subregions])
).distinct()
original.regions.set(combined_regions)

implied_countries = set([x.country.code2 for x in combined_regions])
implied_countries = set([Country(x) for x in implied_countries])

combined_countries = set(obj.countries).union(implied_countries)
original.countries = list(combined_countries)

# It's possible for there to be duplicate feature types.
# in these cases, delete the original bank features with the same type
og_features = original.bank_features.all()
new_features = obj.bank_features.all()

new_feature_set = set([x.feature for x in new_features])
intersecting_features = [x.feature for x in og_features if x.feature in new_feature_set]

for x in intersecting_features:
og = og_features.filter(feature=x).first()
og_features = og_features.exclude(id=og.id)

new_combined_features = og_features | new_features

original.bank_features.all().delete()
original.bank_features.set(new_combined_features)

original.save()

obj.merged = True
obj.save()

# deleting the object results in a an error with regions in forms/models.py _save_m2m
# and creates a validation error. This has to do with how regions and subregions are configured.
# It's comented out for now.
# obj.delete()


@admin.register(SubRegion)
class SubRegionAdminOverride(SubRegionAdmin):
search_fields = SubRegionAdmin.search_fields + (
Expand Down Expand Up @@ -372,11 +295,7 @@ def save_model(self, request, obj, form, change):

def get_queryset(self, request):
# filter out all but base class
qs = (
super(BrandAdmin, self)
.get_queryset(request)
.filter(brandupdate__isnull=True, brandsuggestion__isnull=True)
)
qs = super(BrandAdmin, self).get_queryset(request).filter(brandsuggestion__isnull=True)
return qs

def number_of_related_datasources(self, obj):
Expand Down
37 changes: 1 addition & 36 deletions brand/forms.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,7 @@
from dal import autocomplete
from django import forms

from .models import BrandUpdate, BrandFeature


class CreateUpdateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CreateUpdateForm, self).__init__(*args, **kwargs)

self.fields["countries"].widget.attrs["class"] = "form-select"
self.fields["regions"].widget.attrs["class"] = "form-select"
self.fields["subregions"].widget.attrs["class"] = "form-select"
self.fields["additional_info"].widget.attrs["class"] = "form-control"
self.fields["consent"].widget.attrs["class"] = "form-check-input"

class Meta:
model = BrandUpdate
fields = BrandUpdate.UPDATE_FIELDS + ["additional_info", "email", "consent"]
widgets = {
"regions": autocomplete.ModelSelect2Multiple(
url="region-autocomplete",
attrs={
# Set some placeholder
"data-placeholder": "Start typing...",
# Only trigger autocompletion after 3 characters have been typed
"data-minimum-input-length": 3,
},
),
"subregions": autocomplete.ModelSelect2Multiple(
url="subregion-autocomplete",
attrs={
# Set some placeholder
"data-placeholder": "Start typing...",
# Only trigger autocompletion after 3 characters have been typed
"data-minimum-input-length": 3,
},
),
}
from .models import BrandFeature


class BrandFeaturesForm(forms.ModelForm):
Expand Down
23 changes: 23 additions & 0 deletions brand/migrations/0039_alter_brand_tag_delete_brandupdate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.1.7 on 2024-02-16 22:20

import brand.models.brand
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [("brand", "0038_commentary_embrace")]

operations = [
migrations.AlterField(
model_name="brand",
name="tag",
field=models.CharField(
help_text="the tag we use or this brand record at Bank.Green. ",
max_length=100,
unique=True,
validators=[brand.models.brand.validate_tag],
),
),
migrations.DeleteModel(name="BrandUpdate"),
]
1 change: 0 additions & 1 deletion brand/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from brand.models.brand import Brand
from brand.models.brand_update import BrandUpdate
from brand.models.commentary import Commentary, RatingChoice
from brand.models.features import BrandFeature, FeatureAvailabilityChoice, FeatureType
from brand.models.brand_suggestion import BrandSuggestion
33 changes: 0 additions & 33 deletions brand/models/brand_update.py

This file was deleted.

68 changes: 2 additions & 66 deletions brand/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
from dal import autocomplete
from django.core import serializers

from .forms import BrandFeaturesForm, CreateUpdateForm
from .models import Brand, BrandFeature, BrandUpdate
from .forms import BrandFeaturesForm
from .models import Brand, BrandFeature
from .models.commentary import InstitutionCredential, InstitutionType

import pathlib, csv, json, os
Expand Down Expand Up @@ -58,70 +58,6 @@ def get_queryset(self):
return qs


class CreateUpdateView(CreateView):
template_name = "update.html"
form_class = CreateUpdateForm
success_url = reverse_lazy("update_success")

def form_valid(self, form):
"""
If the form is valid, save the associated model.
"""
brand_update = form.save(commit=False)
context = self.get_context_data()
brand_update.update_tag = context["tag"]
brand_update.tag = context["tag"] + " (" + uuid4().hex + ")"
brand_update.save()

# proccess regions and subregions
regions = self.request.POST.getlist("regions")
for item in regions:
reg = Region.objects.get(pk=item)
brand_update.regions.add(reg)
subregions = self.request.POST.getlist("subregions")
for item in subregions:
subreg = SubRegion.objects.get(pk=item)
brand_update.subregions.add(subreg)

features = context["features"]
features.instance = brand_update
features.save()
return redirect(self.success_url)

def get_initial(self):
if hasattr(self, "original"): # ugly af
return model_to_dict(self.original)

def get_context_data(self, **kwargs):

# set tag
tag = self.kwargs.get("tag")
original = Brand.objects.get(tag=tag)
self.original = original

context = super(CreateUpdateView, self).get_context_data(**kwargs)

# set features
initial = [
model_to_dict(feature, fields=["offered", "details", "feature"])
for feature in self.original.bank_features.all()
]
BrandFeaturesFormSet = inlineformset_factory(
BrandUpdate,
BrandFeature,
form=BrandFeaturesForm,
extra=len(initial) + 3,
can_delete=False,
)

if self.request.POST:
context["features"] = BrandFeaturesFormSet(self.request.POST)
else:
context["features"] = BrandFeaturesFormSet(initial=initial)
context["tag"] = tag
return context


def update_success(request):
template_name = "update_success.html"

Expand Down

0 comments on commit c6f6920

Please sign in to comment.