buildings.js 12.9 KB
Newer Older
abergavenny's avatar
abergavenny committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import { validationResult } from 'express-validator'

import { Building, Management, Simulation, User } from '../db/index.js'
import { getUserFromRequest, success, warning } from '../helpers/index.js'
import { executeSimulation, getInformation } from '../services/external.js'

import { ResponseCode } from '../ENUMS.js'

export const createBuilding = async (req, res) => {
  const validationErrors = validationResult(req)

  if (!validationErrors.isEmpty()) {
    return warning(res, { code: ResponseCode.ValidationError })
  }

  const { accessor } = getUserFromRequest(req)
  const { buildingAddress, buildingGmlId, buildingName, buildingPrefix } = req.body

  const mgmt = await Management.findOne()

  if (mgmt.prefixList.indexOf(buildingPrefix) !== -1) {
    return warning(res, { code: ResponseCode.PrefixUnavailable })
  }

  await mgmt.prefixList.push(buildingPrefix)
  await mgmt.save()

  const result = await Building.create({
    prefix: buildingPrefix,
    name: buildingName,
    address: buildingAddress,
    gmlid: buildingGmlId || null,
    owner: accessor
  })

  if (result) {
    const user = await User.findById(accessor)
    user.ofBuilding = result._id
    user.save()

    return success(res, { code: ResponseCode.Created, id: result._id })
  }

  warning(res, { code: ResponseCode.NotCreated })
}

export const getApartments = async (req, res) => {
  const validationErrors = validationResult(req)

  if (!validationErrors.isEmpty()) {
    return warning(res, { code: ResponseCode.ValidationError })
  }

  const { id } = req.params

  const result = await Building.findOne({ _id: id }).select('apartments.name apartments.image apartments.linkedTo apartments.owner')

  if (result) {
    return success(res, { data: result.apartments })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const getBuilding = async (req, res) => {
  const validationErrors = validationResult(req)

  if (!validationErrors.isEmpty()) {
    return warning(res, { code: ResponseCode.ValidationError })
  }

  const { accessor, role } = getUserFromRequest(req)
  const { id } = req.params

  let result

  if (role === 'administrator') {
    result = await Building.findOne({ _id: id, owner: accessor }).select('_id name address data apartments gmlid prefix createdAt')
  } else {
    result = await Building.findOne({ _id: id, 'apartments.owner': accessor }).select('_id name address data apartments gmlid prefix createdAt')
  }

  if (result) {
    return success(res, { data: result })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const getBuildings = async (req, res) => {
  const { accessor } = getUserFromRequest(req)

  const result = await Building.find({ owner: accessor }).select('_id name address data apartments gmlid setupCompleted prefix createdAt')

  if (result) {
    return success(res, { data: result })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const getSimulation = async (req, res) => {
  const { id } = req.params
  const { gmlId } = req.query

  const building = await Building.findById(id)

  if (building) {
    const simulationId = gmlId || building.gmlId

    if (gmlId) {
      await Building.findByIdAndUpdate({ _id: building._id }, { gmlId })
    }

    if (simulationId) {
      const prefetched = await getInformation(simulationId)

      // DEVINFO Hier könnte das Object für ein Request an die CS-T-API verändert werden.
      // Wenn keine GML-Id in der Datenbank gespeichert wurden, kann über die API eine angefügt werden.
      // Es wird ein Request zur Abfrage bestehender Information für die ausgewählt GML-Id ausgeführt.
      // Die entsprechenden Object-Keys werden im Standard-Request-Body durch die neuen Daten ersetzt
      // Request 1: /api/v1/buildings/<building_id>/simulations/run
      // Request 2: /api/v1/buildings/<building_id>/simulations/run?gmlId=<gml_id>
      // Example Id: DENW39AL1000nJfc
      const simData = {
        gmlId: simulationId,
        atticType: 'unknown',
        basementType: 'unknown',
        comparisonRenovationType: 'no',
        existingModuleArea: '0',
        existingModuleEfficiency: '15',
        renovationType: 'no',
        roofType: 'unknown',
        simulateModuleEfficiency: '15',
        typeOfEnergy: 'unknown',
        yearOfConstruction: '2000',
        ...prefetched
      }

      const simResult = await executeSimulation(simData)

      if (simResult) {
        const { successful, errorMessage, ...rest } = simResult

        await Simulation.create({
          buildingId: id,
          gmlId: simulationId,
          prefetched,
          result: rest
        })

        return success(res, {
          data: {
            successful,
            errorMessage,
            prefetched,
            result: rest
          }
        })
      }

      return warning(res, { code: ResponseCode.InvalidInput })
    }

    return warning(res, { code: ResponseCode.MissingParameter })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const getUsers = async (req, res) => {
  const { id } = req.params

  const result = await User.find({ linkedTo: id }).select('_id username')

  if (result) {
    return success(res, { data: result })
  }

  warning(res, { code: ResponseCode.UserNotFound })
}

export const updateBuilding = async (req, res) => {
  const { id } = req.params
  const { buildingAddress, gmlid, buildingName, buildingPrefix } = req.body

  const building = await Building.findById(id)

  if (building) {
    const updateQuery = {
      address: buildingAddress,
      gmlid,
      name: buildingName,
      updatedAt: Date.now()
    }

    if (building.prefix === null && !building.setupCompleted) {
      const mgmt = await Management.findOne()

      if (mgmt.prefixList.indexOf(buildingPrefix) !== -1) {
        return warning(res, { code: ResponseCode.PrefixUnavailable }, 200)
      }

      updateQuery.prefix = buildingPrefix
      updateQuery.setupCompleted = true

      await mgmt.prefixList.push(buildingPrefix)
      await mgmt.save()
    }

    const result = await Building.findByIdAndUpdate(building._id, updateQuery, { new: true, runValidators: true })

    if (result) {
      return success(res, { data: result })
    }
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const updateBuildingDataBasement = async (req, res) => {
  const validationErrors = validationResult(req)

  if (!validationErrors.isEmpty()) {
    return warning(res, { code: ResponseCode.ValidationError })
  }

  const { id } = req.params
  const { basementInsulatingMaterial, basementInsulatingMaterialThickness, basementRefurbishmentComment, heatedBasement, insulatedBasementCeiling, insulatedBasementFloor } = req.body

  const result = await Building.findByIdAndUpdate(id, {
    $set: {
      updatedAt: Date.now(),
      'data.basementInsulatingMaterial': basementInsulatingMaterial,
      'data.basementInsulatingMaterialThickness': basementInsulatingMaterialThickness,
      'data.basementRefurbishmentComment': basementRefurbishmentComment,
      'data.heatedBasement': heatedBasement,
      'data.insulatedBasementCeiling': insulatedBasementCeiling,
      'data.insulatedBasementFloor': insulatedBasementFloor
    }
  }, { new: true, runValidators: true })
    .select([
      'data.basementInsulatingMaterial',
      'data.basementInsulatingMaterialThickness',
      'data.basementRefurbishmentComment',
      'data.heatedBasement',
      'data.insulatedBasementCeiling',
      'data.insulatedBasementFloor'
    ])

  if (result) {
    return success(res, {
      code: ResponseCode.UpdateSuccess,
      data: result.data
    })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const updateBuildingDataCharacteristics = async (req, res) => {
  const validationErrors = validationResult(req)

  if (!validationErrors.isEmpty()) {
    return warning(res, { code: ResponseCode.ValidationError })
  }

  const { id } = req.params
  const { characteristicsComment, energyPerformanceCertificate, listedBuilding, livingSpace, numberOfFloors, yearOfConstruction } = req.body

  const result = await Building.findByIdAndUpdate(id, {
    $set: {
      updatedAt: Date.now(),
      'data.characteristicsComment': characteristicsComment,
      'data.energyPerformanceCertificate': energyPerformanceCertificate,
      'data.listedBuilding': listedBuilding,
      'data.livingSpace': livingSpace,
      'data.numberOfFloors': numberOfFloors,
      'data.yearOfConstruction': yearOfConstruction
    }
  }, { new: true, runValidators: true })
    .select([
      'data.characteristicsComment',
      'data.energyPerformanceCertificate',
      'data.listedBuilding',
      'data.livingSpace',
      'data.numberOfFloors',
      'data.yearOfConstruction'
    ])

  if (result) {
    return success(res, {
      code: ResponseCode.UpdateSuccess,
      data: result.data
    })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const updateBuildingDataFacade = async (req, res) => {
  const validationErrors = validationResult(req)

  if (!validationErrors.isEmpty()) {
    return warning(res, { code: ResponseCode.ValidationError })
  }

  const { id } = req.params
  const { buildingStructure, buildingStructureThickness, facadeInsulatingMaterial, facadeInsulatingMaterialThickness, facadeEast, facadeNorth, facadeRefurbishmentComment, facadeSouth, facadeWest } = req.body

  const result = await Building.findByIdAndUpdate(id, {
    $set: {
      updatedAt: Date.now(),
      'data.buildingStructure': buildingStructure,
      'data.buildingStructureThickness': buildingStructureThickness,
      'data.facadeInsulatingMaterial': facadeInsulatingMaterial,
      'data.facadeInsulatingMaterialThickness': facadeInsulatingMaterialThickness,
      'data.facadeEast': facadeEast,
      'data.facadeNorth': facadeNorth,
      'data.facadeRefurbishmentComment': facadeRefurbishmentComment,
      'data.facadeSouth': facadeSouth,
      'data.facadeWest': facadeWest
    }
  }, { new: true, runValidators: true })
    .select([
      'data.buildingStructure',
      'data.buildingStructureThickness',
      'data.facadeInsulatingMaterial',
      'data.facadeInsulatingMaterialThickness',
      'data.facadeEast',
      'data.facadeNorth',
      'data.facadeRefurbishmentComment',
      'data.facadeSouth',
      'data.facadeWest'
    ])

  if (result) {
    return success(res, {
      code: ResponseCode.UpdateSuccess,
      data: result.data
    })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const updateBuildingDataHeating = async (req, res) => {
  const validationErrors = validationResult(req)

  if (!validationErrors.isEmpty()) {
    return warning(res, { code: ResponseCode.ValidationError })
  }

  const { id } = req.params
  const { heatingConsumption, heatingInstallation, heatingInstallationComment, photovoltaic, photovoltaicArea, photovoltaicYield, pipeSystem, selfContainedCentralHeating, solarHeat, solarHeatArea } = req.body

  const result = await Building.findByIdAndUpdate(id, {
    $set: {
      updatedAt: Date.now(),
      'data.heatingConsumption': heatingConsumption,
      'data.heatingInstallation': heatingInstallation,
      'data.heatingInstallationComment': heatingInstallationComment,
      'data.photovoltaic': photovoltaic,
      'data.photovoltaicArea': photovoltaicArea,
      'data.photovoltaicYield': photovoltaicYield,
      'data.pipeSystem': pipeSystem,
      'data.selfContainedCentralHeating': selfContainedCentralHeating,
      'data.solarHeat': solarHeat,
      'data.solarHeatArea': solarHeatArea
    }
  }, { new: true, runValidators: true })
    .select([
      'data.heatingConsumption',
      'data.heatingInstallation',
      'data.heatingInstallationComment',
      'data.photovoltaic',
      'data.photovoltaicArea',
      'data.photovoltaicYield',
      'data.pipeSystem',
      'data.selfContainedCentralHeating',
      'data.solarHeat',
      'data.solarHeatArea'
    ])

  if (result) {
    return success(res, {
      code: ResponseCode.UpdateSuccess,
      data: result.data
    })
  }

  warning(res, { code: ResponseCode.NotFound })
}

export const updateBuildingDataRoof = async (req, res) => {
  const { id } = req.params
  const { clouding, flatRoof, heatedAttic, roofArea, roofInsulatingMaterial, roofInsulatingMaterialThickness, roofRefurbishmentComment } = req.body

  const result = await Building.findByIdAndUpdate(id, {
    $set: {
      updatedAt: Date.now(),
      'data.clouding': clouding,
      'data.flatRoof': flatRoof,
      'data.heatedAttic': heatedAttic,
      'data.roofArea': roofArea,
      'data.roofInsulatingMaterial': roofInsulatingMaterial,
      'data.roofInsulatingMaterialThickness': roofInsulatingMaterialThickness,
      'data.roofRefurbishmentComment': roofRefurbishmentComment
    }
  }, { new: true, runValidators: true })
    .select([
      'data.clouding',
      'data.flatRoof',
      'data.heatedAttic',
      'data.roofArea',
      'data.roofInsulatingMaterial',
      'data.roofInsulatingMaterialThickness',
      'data.roofRefurbishmentComment'
    ])

  if (result) {
    return success(res, {
      code: ResponseCode.UpdateSuccess,
      data: result.data
    })
  }

  warning(res, { code: ResponseCode.NotFound })
}