Spaces:
Runtime error
Runtime error
| import { Request, Response } from 'express'; | |
| import { fetchBuildings, fetchPortfolio, fetchUnits } from '../../shared/services/propertyware.service'; | |
| import { logger } from '../../utils/logger'; | |
| import { syncUnitsDataFromUrlService, syncUnitsDataService } from '../../shared/services/units.service'; | |
| import PwPortfolio from '../../models/pwPortfolio'; | |
| import PwBuilding from '../../models/pwBuildings'; | |
| import PwUnit from '../../models/pwUnits'; | |
| export const syncUnitsData = async (req: Request, res: Response) => { | |
| try { | |
| const result = await syncUnitsDataService(); | |
| res.status(200).send(result); | |
| } catch (error) { | |
| logger.error('Error syncing Units'); | |
| logger.error(error); | |
| res.status(500).send((error as Error).message); | |
| } | |
| }; | |
| export const syncUnitsDataFromUrl = async (req: Request, res: Response) => { | |
| try { | |
| const result = await syncUnitsDataFromUrlService(); | |
| res.status(200).send(result); | |
| } catch (error) { | |
| logger.error('Error syncing Units from URL'); | |
| logger.error(error); | |
| res.status(500).send((error as Error).message); | |
| } | |
| }; | |
| export const LocationLookup = async (req: Request, res: Response) => { | |
| try { | |
| const unitsWithBuildingPortfolio = await PwUnit.findAll({ | |
| attributes: [['pw_id', 'id'], 'name'], | |
| include: [ | |
| { | |
| model: PwPortfolio, | |
| as: 'portfolio', | |
| attributes: [['pw_id', 'id'], 'name'], | |
| }, | |
| { | |
| model: PwBuilding, | |
| as: 'building', | |
| attributes: [['pw_id', 'id'], 'name'], | |
| }, | |
| ], | |
| }); | |
| const portfolios = transformUnitsToPortfolios(unitsWithBuildingPortfolio) | |
| res.json(portfolios); | |
| } catch (error) { | |
| logger.error('Error fetching location data:', error); | |
| logger.error(error); | |
| res.status(500).json({ error: 'An error occurred while fetching data' }); | |
| } | |
| }; | |
| function transformUnitsToPortfolios(units: any[]) { | |
| const portfolios: any[] = []; | |
| units.forEach(unit => { | |
| const { portfolio, building, id, name } = unit; | |
| let portfolioEntry = portfolios.find(p => p.id === portfolio.id); | |
| if (!portfolioEntry) { | |
| portfolioEntry = { id: portfolio.id, name: portfolio.name, buildings: [] }; | |
| portfolios.push(portfolioEntry); | |
| } | |
| let buildingEntry = portfolioEntry.buildings.find((b: { id: any; }) => b.id === building.id); | |
| if (!buildingEntry) { | |
| buildingEntry = { id: building.id, name: building.name, units: [] }; | |
| portfolioEntry.buildings.push(buildingEntry); | |
| } | |
| buildingEntry.units.push({ id, name }); | |
| }); | |
| return portfolios; | |
| } | |