Skip to content

Commit

Permalink
Run pre-commit
Browse files Browse the repository at this point in the history
  • Loading branch information
robert-w-gries committed Nov 11, 2024
1 parent 632a2ba commit 50d89a7
Show file tree
Hide file tree
Showing 34 changed files with 687 additions and 386 deletions.
2 changes: 2 additions & 0 deletions dear_petition/petition/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ class ContactAdmin(admin.ModelAdmin):
list_filter = ("category",)
ordering = ("category", "name")


@admin.register(models.Agency)
class AgencyAdmin(ImportExportModelAdmin):
resource_classes = [resources.AgencyResource]
Expand All @@ -167,6 +168,7 @@ class AgencyAdmin(ImportExportModelAdmin):
list_filter = ("category",)
ordering = ("category", "name")


@admin.register(models.Client)
class ClientAdmin(admin.ModelAdmin):
list_display = ("pk", "name", "category", "address1")
Expand Down
21 changes: 14 additions & 7 deletions dear_petition/petition/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ class Meta:
"zipcode",
]


class AgencySerializer(ContactSerializer):
class Meta:
model = Agency
Expand Down Expand Up @@ -320,9 +321,13 @@ def validate_batch(self, value):
class BatchSerializer(serializers.ModelSerializer):
records = CIPRSRecordSerializer(many=True, read_only=True)
petitions = PetitionSerializer(many=True, read_only=True)
generate_letter_errors = ValidationField(method_name='get_generate_errors_data', serializer=GenerateDocumentSerializer)
generate_summary_errors = ValidationField(method_name='get_generate_errors_data', serializer=GenerateDocumentSerializer)

generate_letter_errors = ValidationField(
method_name="get_generate_errors_data", serializer=GenerateDocumentSerializer
)
generate_summary_errors = ValidationField(
method_name="get_generate_errors_data", serializer=GenerateDocumentSerializer
)

def get_generate_errors_data(self, obj):
return {"batch": obj.pk}

Expand Down Expand Up @@ -353,7 +358,7 @@ class BatchDetailSerializer(serializers.ModelSerializer):
)
attorney = ContactSerializer(read_only=True)
client_id = serializers.PrimaryKeyRelatedField(
source='client', queryset=Client.objects.all(), write_only=True, required=False
source="client", queryset=Client.objects.all(), write_only=True, required=False
)
client = ClientSerializer(read_only=True)
client_errors = serializers.SerializerMethodField()
Expand Down Expand Up @@ -383,7 +388,7 @@ class Meta:
"client_id",
"generate_letter_errors",
"generate_summary_errors",
"client_errors"
"client_errors",
]
read_only_fields = ["user", "pk", "date_uploaded", "records", "petitions"]

Expand All @@ -393,13 +398,15 @@ def get_petitions(self, instance):
batch=instance.pk,
).order_by("county", "jurisdiction")
return ParentPetitionSerializer(parent_petitions, many=True).data

def get_client_errors(self, instance):
errors = []
if not instance.client:
return errors
if not instance.client.dob:
errors.append("Date of birth missing. The petition generator will try its best to identify a date of birth from the records at time of petition creation.")
errors.append(
"Date of birth missing. The petition generator will try its best to identify a date of birth from the records at time of petition creation."
)
return errors


Expand Down
29 changes: 17 additions & 12 deletions dear_petition/petition/api/tests/test_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,13 @@

from rest_framework import status

from dear_petition.petition.tests.factories import BatchFactory, CIPRSRecordFactory, OffenseFactory, ClientFactory, OffenseRecordFactory
from dear_petition.petition.tests.factories import (
BatchFactory,
CIPRSRecordFactory,
OffenseFactory,
ClientFactory,
OffenseRecordFactory,
)

pytestmark = pytest.mark.django_db

Expand All @@ -34,37 +40,36 @@ def test_batch_post_multiple_files(api_client, fake_pdf, fake_pdf2, mock_import)
assert mock_import.assert_called_once
assert "id" in response.data


def test_adjust_for_new_client_dob():
"""Test that when a DOB is added or updated on the client, the batch is updated accordingly."""

batch = BatchFactory()
record = CIPRSRecordFactory(batch=batch, offense_date=datetime.date(2000,1,1), dob=None)
offense = OffenseFactory(ciprs_record=record, disposition_method="OTHER") # Conviction charge
offense_record = OffenseRecordFactory(
action="CONVICTED", offense=offense
)
record = CIPRSRecordFactory(batch=batch, offense_date=datetime.date(2000, 1, 1), dob=None)
offense = OffenseFactory(ciprs_record=record, disposition_method="OTHER") # Conviction charge
offense_record = OffenseRecordFactory(action="CONVICTED", offense=offense)

client = ClientFactory(dob=timezone.now().date()) # Create a youngster
client = ClientFactory(dob=timezone.now().date()) # Create a youngster
batch.client = client
batch.save()
batch.adjust_for_new_client_dob()

assert offense_record in batch.underaged_conviction_records()

batch.client.dob = datetime.date(1800,1,1) # Update the youngster to be an elder
batch.client.dob = datetime.date(1800, 1, 1) # Update the youngster to be an elder
batch.client.save()
batch.refresh_from_db() # adjust_for_new_client_dob should get automatically called in Client save
batch.refresh_from_db() # adjust_for_new_client_dob should get automatically called in Client save
assert offense_record not in batch.underaged_conviction_records()

client = ClientFactory(dob=datetime.date(1800,1,1)) # Create an elder
client = ClientFactory(dob=datetime.date(1800, 1, 1)) # Create an elder
batch.client = client
batch.save()
batch.adjust_for_new_client_dob()
assert offense_record not in batch.underaged_conviction_records()

batch.client.dob = timezone.now().date() # Update the elder to be a youngster
batch.client.dob = timezone.now().date() # Update the elder to be a youngster
batch.client.save()
batch.refresh_from_db() # adjust_for_new_client_dob should get automatically called in Client save
batch.refresh_from_db() # adjust_for_new_client_dob should get automatically called in Client save
assert offense_record in batch.underaged_conviction_records()

# try un-setting client to test default behavior when no DOB known
Expand Down
47 changes: 27 additions & 20 deletions dear_petition/petition/api/viewsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,18 +224,26 @@ def preview_import_agencies(self, request):
else row_result.instance.address1
)
row_diff = {
'name': row_result.instance.name,
'address': address,
'city': row_result.instance.city,
'state': row_result.instance.state,
'zipcode': row_result.instance.zipcode,
'county': row_result.instance.county,
'is_sheriff': row_result.instance.is_sheriff,
"name": row_result.instance.name,
"address": address,
"city": row_result.instance.city,
"state": row_result.instance.state,
"zipcode": row_result.instance.zipcode,
"county": row_result.instance.county,
"is_sheriff": row_result.instance.is_sheriff,
}
if row_result.import_type == RowResult.IMPORT_TYPE_SKIP:
continue
elif row_result.import_type == RowResult.IMPORT_TYPE_NEW:
row_diff['new_fields'] = ['name', 'address', 'city', 'state', 'zipcode', 'county', 'is_sheriff']
row_diff["new_fields"] = [
"name",
"address",
"city",
"state",
"zipcode",
"county",
"is_sheriff",
]
else:
original_address = (
f"{row_result.original.address1}, {row_result.original.address2}"
Expand All @@ -247,7 +255,7 @@ def preview_import_agencies(self, request):
if original_address != address:
row_diff["new_fields"].append("address")

for field in ['name', 'city', 'state', 'zipcode', 'county', 'is_sheriff']:
for field in ["name", "city", "state", "zipcode", "county", "is_sheriff"]:
if getattr(row_result.original, field) != getattr(row_result.instance, field):
row_diff["new_fields"].append(field)

Expand Down Expand Up @@ -370,7 +378,7 @@ def generate_summary(self, request, pk):
] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
resp["Content-Disposition"] = 'attachment; filename="Records Summary.docx"'
return resp

@action(
detail=True,
methods=[
Expand Down Expand Up @@ -398,8 +406,8 @@ def generate_spreadsheet(self, request, pk):
],
)
def combine_batches(self, request):
batch_ids = request.data['batchIds']
label = request.data['label']
batch_ids = request.data["batchIds"]
label = request.data["label"]
user_id = request.user.id

if not batch_ids:
Expand All @@ -408,33 +416,32 @@ def combine_batches(self, request):
)
if not label:
return Response(
"A new label needs to be included for the client.", status=status.HTTP_400_BAD_REQUEST
"A new label needs to be included for the client.",
status=status.HTTP_400_BAD_REQUEST,
)

new_batch = combine_batches(batch_ids, label, user_id)
return Response(self.get_serializer(new_batch).data)

@action(
detail=True,
methods=[
"post",
],
)
def assign_client_to_batch(self, request, pk):
client_id = request.data['client_id']
client_id = request.data["client_id"]

try:
client = pm.Client.objects.get(pk=client_id)
except pm.Client.DoesNotExist:
return Response(
"Unknown client.", status=status.HTTP_400_BAD_REQUEST
)
return Response("Unknown client.", status=status.HTTP_400_BAD_REQUEST)
batch = self.get_object()
batch.client = client
batch.save()
batch.adjust_for_new_client_dob()
return Response({"batch_id": batch.pk})

@action(
detail=False,
methods=[
Expand All @@ -448,7 +455,7 @@ def import_spreadsheet(self, request):
for file in files:
label = os.path.basename(file.name)
batch = pm.Batch.objects.create(label=label, user=user)
batch.files.create(file=file)
batch.files.create(file=file)
file.seek(0)
workbook = load_workbook(filename=file)
resource.import_data(workbook, batch)
Expand Down
14 changes: 7 additions & 7 deletions dear_petition/petition/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,13 +161,13 @@ def contact3():
@pytest.fixture
def client():
return ClientFactory(
name='Test Name',
address1='123 Test Ct',
address2='Apt A',
city='Durham',
state='NC',
zipcode='27701',
dob = timezone.now().date() # I wasn't born yesterday
name="Test Name",
address1="123 Test Ct",
address2="Apt A",
city="Durham",
state="NC",
zipcode="27701",
dob=timezone.now().date(), # I wasn't born yesterday
)


Expand Down
10 changes: 5 additions & 5 deletions dear_petition/petition/etl/load.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,17 +79,17 @@ def create_petitions_from_records(batch, form_type):
jurisdiction=petition_type["jurisdiction"],
county=petition_type["county"],
)
sheriff_agency = pm.Agency.get_sherriff_office_by_county(
petition_type["county"]
)

sheriff_agency = pm.Agency.get_sherriff_office_by_county(petition_type["county"])

# petition arresting agencies - add agencies parsed from portal and assign sheriff's office for county
if sheriff_agency is not None:
logger.info(
f"Detected {sheriff_agency.name} as {petition_type['county']} county's sherrif's office. Adding as default agency."
)
petition.agencies.add(sheriff_agency)
offense_record_agencies = pm.Agency.objects.filter(pk__in=record_set.exclude(agency__isnull=True).values_list('agency'))
offense_record_agencies = pm.Agency.objects.filter(
pk__in=record_set.exclude(agency__isnull=True).values_list("agency")
)
petition.agencies.add(*offense_record_agencies)

link_offense_records(petition)
Expand Down
4 changes: 3 additions & 1 deletion dear_petition/petition/etl/refresh.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ def refresh_offenses(record):
agency = Agency.objects.none()
agency_name = data_offense_record.get("Agency", "")
if agency_name:
agency = Agency.agencies_with_clean_name.filter(clean_name__icontains=agency_name)
agency = Agency.agencies_with_clean_name.filter(
clean_name__icontains=agency_name
)
if agency.exists():
logger.info(f"Matched agency '{agency.first().name}' to offense")

Expand Down
21 changes: 11 additions & 10 deletions dear_petition/petition/etl/tests/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,8 @@ def test_recalculate_petitions(petition):
assert not petition.has_attachments()




def test_combine_batches(batch, batch_file, fake_pdf):
record = CIPRSRecordFactory(
batch=batch, jurisdiction=constants.DISTRICT_COURT, county="DURHAM"
)
record = CIPRSRecordFactory(batch=batch, jurisdiction=constants.DISTRICT_COURT, county="DURHAM")
record.refresh_record_from_data()

second_batch = BatchFactory()
Expand Down Expand Up @@ -90,17 +86,21 @@ def test_combine_batches(batch, batch_file, fake_pdf):
],
"Disposed On": "2018-02-01",
"Disposition Method": "DISPOSED BY JUDGE",
}
},
],
"Superior Court Offense Information": [],
}
second_batch_file = BatchFileFactory(batch=second_batch, file=fake_pdf)

second_record = CIPRSRecordFactory(
batch=second_batch, data = second_record_data, batch_file=second_batch_file, jurisdiction=constants.DISTRICT_COURT, county="DURHAM"
batch=second_batch,
data=second_record_data,
batch_file=second_batch_file,
jurisdiction=constants.DISTRICT_COURT,
county="DURHAM",
)
second_record.refresh_record_from_data()

assert batch.records.count() == 1
assert pm.Offense.objects.filter(ciprs_record__batch__id=batch.id).count() == 1
assert pm.Offense.objects.filter(ciprs_record__batch__id=second_batch.id).count() == 2
Expand All @@ -112,8 +112,9 @@ def test_combine_batches(batch, batch_file, fake_pdf):

assert new_batch.records.count() == 2
assert pm.Offense.objects.filter(ciprs_record__batch__id=new_batch.id).count() == 3
assert pm.OffenseRecord.objects.filter(offense__ciprs_record__batch__id=new_batch.id).count() == 4
assert (
pm.OffenseRecord.objects.filter(offense__ciprs_record__batch__id=new_batch.id).count() == 4
)
assert new_batch.files.count() == 2
assert new_batch.label == new_label
assert new_batch.user_id == user_id

Loading

0 comments on commit 50d89a7

Please sign in to comment.