Skip to content

Commit

Permalink
Fix: LCFS - Fuel Code error shows when inputting Fuel Production colu…
Browse files Browse the repository at this point in the history
…mns #1961
  • Loading branch information
prv-proton committed Feb 12, 2025
1 parent 3a71a9a commit c523f38
Show file tree
Hide file tree
Showing 5 changed files with 150 additions and 69 deletions.
57 changes: 57 additions & 0 deletions backend/lcfs/web/api/fuel_code/repo.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import structlog
from fastapi import Depends
from sqlalchemy import and_, or_, select, func, text, update, distinct, desc, asc
from sqlalchemy.sql.functions import coalesce
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload, contains_eager

Expand Down Expand Up @@ -512,6 +513,62 @@ async def get_contact_email_by_company_and_name(
)
return (await self.db.execute(query)).scalars().all()

@repo_handler
async def get_fp_facility_location_by_name(
self,
city: Optional[str] = None,
province: Optional[str] = None,
country: Optional[str] = None,
) -> List[str]:
"""
Fetch fuel production locations dynamically based on provided filters.
- If `city` is provided → Returns "city, province, country"
- If `province` is provided → Returns "province, country"
- If `country` is provided → Returns "country"
"""
# Start building the query
stmt = select()

if city:
stmt = stmt.add_columns(
func.concat(
coalesce(FuelCode.fuel_production_facility_city, ""),
", ",
coalesce(FuelCode.fuel_production_facility_province_state, ""),
", ",
coalesce(FuelCode.fuel_production_facility_country, ""),
).label("location")
).filter(FuelCode.fuel_production_facility_city.ilike(f"%{city}%"))

elif province:
stmt = stmt.add_columns(
func.concat(
coalesce(FuelCode.fuel_production_facility_province_state, ""),
", ",
coalesce(FuelCode.fuel_production_facility_country, ""),
).label("location")
).filter(
FuelCode.fuel_production_facility_province_state.ilike(f"%{province}%")
)

elif country:
stmt = stmt.add_columns(
coalesce(FuelCode.fuel_production_facility_country, "").label(
"location"
)
).filter(FuelCode.fuel_production_facility_country.ilike(f"%{country}%"))

else:
return [] # If no filter is provided, return an empty list.

# Ensure uniqueness and limit results
stmt = stmt.distinct().limit(10)

# Execute query
result = await self.db.execute(stmt)
return [row[0] for row in result.unique().all()]

@repo_handler
async def get_distinct_fuel_codes_by_code(
self, fuel_code: str, prefix: str
Expand Down
6 changes: 5 additions & 1 deletion backend/lcfs/web/api/fuel_code/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ async def search_contact_email(self, company, contact_name, contact_email):
company, contact_name, contact_email
)

@service_handler
async def search_fp_facility_location(self, city, province, country):
return await self.repo.get_fp_facility_location_by_name(city, province, country)

@service_handler
async def get_table_options(self) -> TableOptionsSchema:
"""
Expand All @@ -65,7 +69,7 @@ async def get_table_options(self) -> TableOptionsSchema:
fuel_code_prefixes = await self.repo.get_fuel_code_prefixes()
latest_fuel_codes = await self.repo.get_latest_fuel_codes()
field_options_results = await self.repo.get_fuel_code_field_options()
fp_locations = await self.repo.get_fp_locations()
fp_locations = []
facility_nameplate_capacity_units = [unit.value for unit in QuantityUnitsEnum]

# Use a set to remove duplicates
Expand Down
18 changes: 18 additions & 0 deletions backend/lcfs/web/api/fuel_code/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,21 @@ async def search_table_options_strings(
prefix: Optional[str] = Query(
None, alias="prefix", description="Prefix for filtering options"
),
fp_city: Optional[str] = Query(
None,
alias="fpCity",
description="Fuel production facility city for suggestions",
),
fp_province: Optional[str] = Query(
None,
alias="fpProvince",
description="Fuel production facility province for suggestions",
),
fp_country: Optional[str] = Query(
None,
alias="fpCountry",
description="Fuel production facility country for suggestions",
),
distinct_search: Optional[bool] = Query(
False,
alias="distinctSearch",
Expand Down Expand Up @@ -104,6 +119,9 @@ async def search_table_options_strings(
)
return await service.search_contact_name(company, contact_name)
return await service.search_company(company)
elif fp_city or fp_province or fp_country:
logger.info("Searching fuel production facility location")
return await service.search_fp_facility_location(fp_city, fp_province, fp_country)
else:
raise ValueError("Invalid parameters provided for search")

Expand Down
13 changes: 13 additions & 0 deletions frontend/src/components/BCDataGrid/BCGridEditor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,18 @@ export const BCGridEditor = ({
}
}
}
const onCellFocused = (params) => {
if (params.column) {
// Ensure the focused column is always visible
this.gridApi.ensureColumnVisible(params.column)

// Scroll to make focused cell align to left
const leftPos = params.column.getLeftPosition()
if (leftPos !== null) {
this.gridApi.horizontalScrollTo(leftPos)
}
}
}

const handleAddRowsClick = (event) => {
setAnchorEl(event.currentTarget)
Expand Down Expand Up @@ -299,6 +311,7 @@ export const BCGridEditor = ({
getRowId={(params) => params.data.id}
onCellClicked={onCellClicked}
onCellEditingStopped={handleOnCellEditingStopped}
onCellFocused={onCellFocused}
autoHeight={true}
{...props}
/>
Expand Down
125 changes: 57 additions & 68 deletions frontend/src/views/FuelCodes/AddFuelCode/_schema.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -409,38 +409,32 @@ export const fuelCodeColDefs = (optionsData, errors, isCreate, canEdit) => [
editable: canEdit,
headerComponent: canEdit ? RequiredHeader : undefined,
headerName: i18n.t('fuelCode:fuelCodeColLabels.fuelProductionFacilityCity'),
cellEditor: AutocompleteCellEditor,
cellEditor: AsyncSuggestionEditor,
suppressKeyboardEvent,
cellDataType: 'text',
cellRenderer: createCellRenderer('fuelProductionFacilityCity'),
cellEditorParams: {
onDynamicUpdate: (val, params) => params.api.stopEditing(),
noLabel: true,
options: [
...new Map(
optionsData.fpLocations.map((location) => [
location.fuelProductionFacilityCity,
location.fuelProductionFacilityCity
])
).values()
],
multiple: false,
disableCloseOnSelect: false,
freeSolo: true,
openOnFocus: true
},
cellEditorParams: (params) => ({
queryKey: 'fuel-production-city-search',
queryFn: async ({ queryKey, client }) => {
let path = apiRoutes.fuelCodeSearch
path += 'fpCity=' + queryKey[1]
const response = await client.get(path)
return response.data
},
title: 'fuelProductionFacilityCity',
enabled: true
}),
minWidth: 325,
valueSetter: (params) => {
params.data.fuelProductionFacilityCity = params.newValue
if (!params.newValue) return false

const location = optionsData.fpLocations.find(
(location) => location.fuelProductionFacilityCity === params.newValue
)

params.data.fuelProductionFacilityProvinceState =
location?.fuelProductionFacilityProvinceState
params.data.fuelProductionFacilityCountry =
location?.fuelProductionFacilityCountry
// Split the newValue by comma and trim spaces
const [city = '', province = '', country = ''] = params.newValue
.split(',')
.map((val) => val.trim())
params.data.fuelProductionFacilityCity = city
params.data.fuelProductionFacilityProvinceState = province
params.data.fuelProductionFacilityCountry = country

return true
}
Expand All @@ -452,36 +446,33 @@ export const fuelCodeColDefs = (optionsData, errors, isCreate, canEdit) => [
headerName: i18n.t(
'fuelCode:fuelCodeColLabels.fuelProductionFacilityProvinceState'
),
cellEditor: AutocompleteCellEditor,
cellEditor: AsyncSuggestionEditor,
suppressKeyboardEvent,
cellDataType: 'text',
cellRenderer: createCellRenderer('fuelProductionFacilityProvinceState'),
cellEditorParams: {
onDynamicUpdate: (val, params) => params.api.stopEditing(),
noLabel: true,
options: [
...new Map(
optionsData.fpLocations.map((location) => [
location.fuelProductionFacilityProvinceState,
location.fuelProductionFacilityProvinceState
])
).values()
],
multiple: false,
disableCloseOnSelect: false,
freeSolo: true,
openOnFocus: true
},
cellEditorParams: (params) => ({
queryKey: 'fuel-production-province-search',
queryFn: async ({ queryKey, client }) => {
let path = apiRoutes.fuelCodeSearch
path += 'fpProvince=' + queryKey[1]
const response = await client.get(path)
return response.data
},
title: 'fuelProductionFacilityProvinceState',
enabled: true
}),
minWidth: 325,
valueSetter: (params) => {
params.data.fuelProductionFacilityProvinceState = params.newValue
if (!params.newValue) return false // Handle empty values safely

const location = optionsData.fpLocations.find(
(location) =>
location.fuelProductionFacilityProvinceState === params.newValue
)
params.data.fuelProductionFacilityCountry =
location?.fuelProductionFacilityCountry
// Split the newValue by comma and trim spaces
const [province = '', country = ''] = params.newValue
.split(',')
.map((val) => val.trim())

// Assign the values to the respective fields
params.data.fuelProductionFacilityProvinceState = province
params.data.fuelProductionFacilityCountry = country

return true
}
Expand All @@ -493,25 +484,21 @@ export const fuelCodeColDefs = (optionsData, errors, isCreate, canEdit) => [
headerName: i18n.t(
'fuelCode:fuelCodeColLabels.fuelProductionFacilityCountry'
),
cellEditor: AutocompleteCellEditor,
cellEditor: AsyncSuggestionEditor,
suppressKeyboardEvent,
cellDataType: 'text',
cellRenderer: createCellRenderer('fuelProductionFacilityCountry'),
cellEditorParams: {
noLabel: true,
options: [
...new Map(
optionsData.fpLocations.map((location) => [
location.fuelProductionFacilityCountry,
location.fuelProductionFacilityCountry
])
).values()
],
multiple: false,
disableCloseOnSelect: false,
freeSolo: true,
openOnFocus: true
},
cellEditorParams: (params) => ({
queryKey: 'fuel-production-country-search',
queryFn: async ({ queryKey, client }) => {
let path = apiRoutes.fuelCodeSearch
path += 'fpCountry=' + queryKey[1]
const response = await client.get(path)
return response.data
},
title: 'fuelProductionFacilityCountry',
enabled: true
}),
minWidth: 325
},
{
Expand Down Expand Up @@ -563,7 +550,8 @@ export const fuelCodeColDefs = (optionsData, errors, isCreate, canEdit) => [
marginTop: '0.7rem'
},
cellEditorParams: {
options: optionsData?.transportModes?.map((obj) => obj.transportMode) || [],
options:
optionsData?.transportModes?.map((obj) => obj.transportMode) || [],
multiple: true,
openOnFocus: true,
disableCloseOnSelect: true
Expand All @@ -588,7 +576,8 @@ export const fuelCodeColDefs = (optionsData, errors, isCreate, canEdit) => [
marginTop: '0.7rem'
},
cellEditorParams: {
options: optionsData?.transportModes.map((obj) => obj.transportMode) || [],
options:
optionsData?.transportModes.map((obj) => obj.transportMode) || [],
multiple: true,
openOnFocus: true,
disableCloseOnSelect: true
Expand Down

0 comments on commit c523f38

Please sign in to comment.