Skip to content

Commit

Permalink
chore:Added Api to get report Type and modified fields
Browse files Browse the repository at this point in the history
  • Loading branch information
ayeshmcg committed Oct 18, 2024
1 parent 60b20dd commit f85fcc9
Show file tree
Hide file tree
Showing 11 changed files with 174 additions and 32 deletions.
1 change: 1 addition & 0 deletions bc_obps/reporting/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
from .report_person_responsible import get_report_person_responsible_by_version_id
from .report_person_responsible import save_report_contact
from .report_activity import save_report_activity_data
from .reports import get_report_type_by_version
16 changes: 15 additions & 1 deletion bc_obps/reporting/api/reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
from reporting.schema.report_operation import ReportOperationOut, ReportOperationIn
from reporting.schema.reporting_year import ReportingYearOut
from .router import router
from ..models import ReportingYear
from ..models import ReportingYear, ReportVersion
from ..schema.report_version import ReportingVersionOut


@router.post(
Expand Down Expand Up @@ -71,3 +72,16 @@ def save_report(
@handle_http_errors()
def get_reporting_year(request: HttpRequest) -> Tuple[Literal[200], ReportingYear]:
return 200, ReportingYearService.get_current_reporting_year()


@router.get(
"/report-version/{version_id}/report-type",
response={200: ReportingVersionOut, custom_codes_4xx: Message},
tags=EMISSIONS_REPORT_TAGS,
description="Retrieve the report type for a specific reporting version, including the reporting year and due date.",
# auth=authorize("all_roles"),
)
@handle_http_errors()
def get_report_type_by_version(request: HttpRequest, version_id: int) -> tuple[Literal[200], ReportVersion]:
report_type = ReportService.get_report_type_by_version_id(version_id)
return 200, report_type
18 changes: 18 additions & 0 deletions bc_obps/reporting/migrations/0021_reportversion_report_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.9 on 2024-10-17 21:59

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('reporting', '0020_report_person_responsible'),
]

operations = [
migrations.AddField(
model_name='reportversion',
name='report_type',
field=models.CharField(db_comment='Report type', default='Annual Report', max_length=1000),
),
]
5 changes: 5 additions & 0 deletions bc_obps/reporting/models/report_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ class ReportVersion(TimeStampedModel):
db_comment="True if this version is the latest submitted one",
default=False,
)
report_type = models.CharField(
max_length=1000,
db_comment="Report type",
default="Annual Report",
)

class ReportVersionStatus(models.TextChoices):
Draft = 'draft'
Expand Down
13 changes: 13 additions & 0 deletions bc_obps/reporting/schema/report_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from ninja import ModelSchema

from reporting.models import ReportVersion


class ReportingVersionOut(ModelSchema):
"""
Schema for the get reporting year endpoint request output
"""

class Meta:
model = ReportVersion
fields = ['report_type']
4 changes: 4 additions & 0 deletions bc_obps/service/report_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,3 +103,7 @@ def save_report_operation(cls, report_version_id: int, data: ReportOperationIn)
report_operation.save()

return report_operation

@staticmethod
def get_report_type_by_version_id(version_id: int) -> ReportVersion:
return ReportVersion.objects.get(id=version_id)
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ import { formatDate } from "@reporting/src/app/utils/formatDate";
interface Props {
formData: any;
version_id: number;
reportType: {
report_type: string;
};
reportingYear: {
reporting_year: number;
report_due_date: string;
Expand Down Expand Up @@ -44,19 +47,22 @@ const taskListElements: TaskListElement[] = [
export default function OperationReview({
formData,
version_id,
reportType,
reportingYear,
allActivities,
allRegulatedProducts,
}: Props) {
const router = useRouter();
const [schema, setSchema] = useState<RJSFSchema>(operationReviewSchema);
const [uiSchema, setUiSchema] = useState<RJSFSchema>(operationReviewUiSchema);
const [formDataState, setFormDataState] = useState<any>(formData);
const saveAndContinueUrl = `/reports/${version_id}/person-responsible`;
const reportingWindowEnd = formatDate(
reportingYear.reporting_window_end,
"MMM DD YYYY",
);

// Function to handle form data submission
const submitHandler = async (
data: { formData?: any },
reportVersionId: number,
Expand All @@ -66,22 +72,30 @@ export default function OperationReview({

const formDataObject = safeJsonParse(JSON.stringify(data.formData));

// Prepare the data based on the operation report type
const preparedData = {
...formDataObject,
activities: formDataObject.activities?.map((activityId: any) => {
const activity = allActivities.find((a) => a.id === activityId);
if (!activity)
throw new Error(`Activity with ID ${activityId} not found`);
return activity.name;
}),
regulated_products: formDataObject.regulated_products?.map(
(productId: any) => {
const product = allRegulatedProducts.find((p) => p.id === productId);
if (!product)
throw new Error(`Product with ID ${productId} not found`);
return product.name;
},
),
// Check the report type and set activities and regulated_products to empty arrays if it's a simple report
activities:
formDataState.operation_report_type === "Simple Report"
? []
: formDataObject.activities?.map((activityId: any) => {
const activity = allActivities.find((a) => a.id === activityId);
if (!activity)
throw new Error(`Activity with ID ${activityId} not found`);
return activity.name;
}),
regulated_products:
formDataState.operation_report_type === "Simple Report"
? []
: formDataObject.regulated_products?.map((productId: any) => {
const product = allRegulatedProducts.find(
(p) => p.id === productId,
);
if (!product)
throw new Error(`Product with ID ${productId} not found`);
return product.name;
}),
};

const response = await actionHandler(endpoint, method, endpoint, {
Expand All @@ -93,18 +107,43 @@ export default function OperationReview({
}
};

// Function to handle changes in the form data
const onChangeHandler = (data: { formData: any }) => {
const updatedData = {
...data.formData,
// Modify the structure of form data here as needed
};

setFormDataState(updatedData); // Update the state with modified data
};

useEffect(() => {
if (!formData || !allActivities || !allRegulatedProducts) {
return;
}

const activities = formData.activities || [];
const products = formData.regulated_products || [];
const updatedFormData = {
...formData,
operation_report_type: reportType?.report_type || "Annual Report",
activities: formData.activities || [],
regulated_products: formData.regulated_products || [],
};

setFormDataState(updatedFormData);
}, [formData, reportType, allActivities, allRegulatedProducts]);

useEffect(() => {
setSchema((prevSchema) => ({
...prevSchema,
properties: {
...prevSchema.properties,
operation_report_type: {
type: "string",
title: "Please select what type of report you are filling",
enum: ["Annual Report", "Simple Report"],
default: formDataState?.operation_report_type || "Annual Report",
},
// Conditionally render fields based on report type
activities: {
type: "array",
title: "Reporting activities",
Expand All @@ -114,6 +153,10 @@ export default function OperationReview({
enumNames: allActivities.map((activity) => activity.name),
},
uniqueItems: true,
// Only show this field if report type is not simple
"ui:options": {
hidden: formDataState.operation_report_type === "Simple Report",
},
},
regulated_products: {
type: "array",
Expand All @@ -124,16 +167,20 @@ export default function OperationReview({
enumNames: allRegulatedProducts.map((product) => product.name),
},
uniqueItems: true,
// Only show this field if report type is not simple
"ui:options": {
hidden: formDataState.operation_report_type === "Simple Report",
},
},
operation_representative_name: {
type: "string",
title: "Operation representative",
enum: [formData.operation_representative_name || ""],
enum: [formDataState.operation_representative_name || ""],
},
operation_type: {
type: "string",
title: "Operation type",
enum: [formData.operation_type || ""],
enum: [formDataState.operation_type || ""],
},
date_info: {
type: "object",
Expand All @@ -142,18 +189,35 @@ export default function OperationReview({
},
},
}));
}, [allActivities, allRegulatedProducts, formDataState, reportingWindowEnd]);

const updatedFormData = {
...formData,
activities,
regulated_products: products,
useEffect(() => {
const updateUiSchema = () => {
const helperText =
formDataState?.operation_report_type === "Simple Report" ? (
<small>
Regulated or Reporting Operations should file a Simple Report if
their emissions have dropped below 10,000 tCO2e. They will continue
to report using the Simple Report form until they stop Schedule A
activities or stay under 10ktCO2e for three years. This does not
apply to Opt-ins.
</small>
) : null;

setUiSchema({
...operationReviewUiSchema,
operation_report_type: {
"ui:widget": "select", // Set the widget type
"ui:help": helperText,
},
});
};

setFormDataState(updatedFormData);
}, [allActivities, allRegulatedProducts, formData, reportingWindowEnd]);
// Call the function to update the UI schema
updateUiSchema();
}, [formDataState]); // Ensure the effect runs when formDataState changes

if (!formData) {
//we need to render another component which we would display if no version Id exist or we want to show an error
return <div>No version ID found(TBD)</div>;
}

Expand All @@ -168,11 +232,12 @@ export default function OperationReview({
]}
taskListElements={taskListElements}
schema={schema}
uiSchema={operationReviewUiSchema}
uiSchema={uiSchema}
formData={formDataState}
baseUrl={baseUrl}
cancelUrl={cancelUrl}
onSubmit={(data) => submitHandler(data, version_id)}
onChange={onChangeHandler} // Pass the onChange handler here
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { getReportingYear } from "@reporting/src/app/utils/getReportingYear";
import { getReportingOperation } from "@reporting/src/app/utils/getReportingOperation";
import { getAllActivities } from "@reporting/src/app/utils/getAllReportingActivities";
import { getAllRegulatedProducts } from "@reporting/src/app/utils/getAllRegulatedProducts";
import { getReportType } from "@reporting/src/app/utils/getReportType";

export default async function OperationReviewFormData({
version_id,
Expand All @@ -13,10 +14,12 @@ export default async function OperationReviewFormData({
const allActivities = await getAllActivities();
const allRegulatedProducts = await getAllRegulatedProducts();
const reportingYear = await getReportingYear();
const reportType = await getReportType(version_id);
return (
<OperationReview
formData={reportOperation}
version_id={version_id}
reportType={reportType}
allActivities={allActivities}
reportingYear={reportingYear}
allRegulatedProducts={allRegulatedProducts}
Expand Down
9 changes: 9 additions & 0 deletions bciers/apps/reporting/src/app/utils/getReportType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { actionHandler } from "@bciers/actions";
export async function getReportType(version_id: number) {
let response = await actionHandler(
`reporting/report-version/${version_id}/report-type`,
"GET",
`reporting/report-version/${version_id}/report-type`,
);
if (!response.error) return response;
}
19 changes: 14 additions & 5 deletions bciers/apps/reporting/src/data/jsonSchema/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,8 @@ export const operationReviewSchema: RJSFSchema = {
operation_report_type: {
type: "string",
title: "Please select what type of report are you filling",
enum: [
"Annual emissions report",
"Regulated partial year operation",
"Simple Report",
],
enum: ["Annual report", "Simple Report"],
default: "Annual report",
},
operation_representative_name: {
type: "string",
Expand All @@ -47,6 +44,10 @@ export const operationReviewSchema: RJSFSchema = {
},
operation_bcghgid: { type: "string", title: "BCGHG ID" },
bc_obps_regulated_operation_id: { type: "string", title: "BORO ID" },
registration_pupose: {
type: "string",
title: "Registration Purpose",
},
activities: {
type: "array",
title: "Reporting activities",
Expand Down Expand Up @@ -94,14 +95,21 @@ export const operationReviewUiSchema = {
"ui:widget": "select",
"ui:options": { style: { width: "100%", textAlign: "justify" } },
"ui:placeholder": "Report type",
"ui:disabled": true,
},
operation_bcghgid: {
"ui:options": commonUiOptions,
"ui:placeholder": "BCGHG ID",
"ui:disabled": true,
},
bc_obps_regulated_operation_id: {
"ui:options": commonUiOptions,
"ui:placeholder": "BORO ID",
"ui:disabled": true,
},

registration_pupose: {
"ui:placeholder": "Registration Purpose",
},
activities: {
"ui:widget": "MultiSelectWidget",
Expand All @@ -121,6 +129,7 @@ export const operationReviewUiSchema = {
"ui:placeholder": "Regulated products",
uniqueItems: true,
},

operation_representative_name: {
"ui:widget": "select",
"ui:options": commonUiOptions,
Expand Down
1 change: 1 addition & 0 deletions erd_diagrams/erd_reporting.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ ReportVersion {
DateTimeField archived_at
ForeignKey report
BooleanField is_latest_submitted
CharField report_type
CharField status
}
ReportPersonResponsible {
Expand Down

0 comments on commit f85fcc9

Please sign in to comment.