@@ -275,6 +275,26 @@ class CompanySerializer(PermittedFieldsModelSerializer):
275
275
have to enter company numbers for UK establishments manually.
276
276
"""
277
277
278
+ # TODO: delete after the migration to address and registered address is completed
279
+ ADDRESS_FIELDS_MAPPING = {
280
+ 'trading' : {
281
+ 'address_1' : 'trading_address_1' ,
282
+ 'address_2' : 'trading_address_2' ,
283
+ 'address_town' : 'trading_address_town' ,
284
+ 'address_county' : 'trading_address_county' ,
285
+ 'address_postcode' : 'trading_address_postcode' ,
286
+ 'address_country' : 'trading_address_country' ,
287
+ },
288
+ 'registered' : {
289
+ 'address_1' : 'registered_address_1' ,
290
+ 'address_2' : 'registered_address_2' ,
291
+ 'address_town' : 'registered_address_town' ,
292
+ 'address_county' : 'registered_address_county' ,
293
+ 'address_postcode' : 'registered_address_postcode' ,
294
+ 'address_country' : 'registered_address_country' ,
295
+ },
296
+ }
297
+
278
298
default_error_messages = {
279
299
'invalid_uk_establishment_number_prefix' : ugettext_lazy (
280
300
'This must be a valid UK establishment number, beginning with BR.' ,
@@ -382,8 +402,47 @@ def validate(self, data):
382
402
'headquarter_type' : message ,
383
403
})
384
404
405
+ self ._populate_address_fields (combiner , data )
406
+
385
407
return data
386
408
409
+ def _populate_address_fields (self , combiner , data ):
410
+ """
411
+ Populates the address_* fields with the values from trading address or
412
+ registered address whichever is defined.
413
+
414
+ It's only triggered when any of the address fields are specified so that we don't
415
+ accidentally run this logic when changing any other field.
416
+ Doing this will allow us to implement a variant that updates the addresses
417
+ in a different way.
418
+
419
+ TODO: delete after the migration to address and registered address is completed
420
+ """
421
+ all_address_field_names = {
422
+ field
423
+ for mapping in self .ADDRESS_FIELDS_MAPPING .values ()
424
+ for field in mapping .values ()
425
+ }
426
+
427
+ # was any address field specified?
428
+ if not all_address_field_names & data .keys ():
429
+ return
430
+
431
+ trading_fields_mapping = Company .TRADING_ADDRESS_VALIDATION_MAPPING
432
+
433
+ has_valid_trading_address = all (
434
+ combiner .get_value (field_name )
435
+ for field_name , rules in trading_fields_mapping .items ()
436
+ if rules ['required' ]
437
+ )
438
+
439
+ mapping_source = 'trading' if has_valid_trading_address else 'registered'
440
+
441
+ mapping = self .ADDRESS_FIELDS_MAPPING [mapping_source ]
442
+ for target_field_name , source_field_name in mapping .items ():
443
+ target_value = combiner .get_value (source_field_name )
444
+ data [target_field_name ] = target_value
445
+
387
446
def validate_headquarter_type (self , headquarter_type ):
388
447
"""Raises an exception if company is a global hq and has subsidiaries."""
389
448
if self .instance is None :
0 commit comments