-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSegment.py
73 lines (61 loc) · 2.6 KB
/
Segment.py
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
from Element import Element
from Settings import CurrentSettings
class Segment(object):
def __init__(self):
self.fieldCount = 0
self.fields = []
self.id = Element()
self.element_separator = CurrentSettings.element_separator
self.segment_terminator = CurrentSettings.segment_terminator
self.sub_element_separator = CurrentSettings.sub_element_separator
def validate(self, report):
"""
Validate the segment by validating all elements.
:param report: the validation report to append errors.
"""
for field in self.fields:
field.validate(report)
def format_as_edi(self, document_configuration):
"""Format the segment into an EDI string"""
self.element_separator = document_configuration.element_separator
self.segment_terminator = document_configuration.segment_terminator
self.sub_element_separator = document_configuration.sub_element_separator
return str(self)
def __str__(self):
"""Return the segment as a string"""
out = ""
if self.__all_fields_empty():
return out
out = self.__get_fields_as_string(out)
return out
def __all_fields_empty(self):
"""determine if all fields are empty"""
for field in self.fields:
if field.content != "":
return False
return True
def __get_fields_as_string(self, out):
"""processes all the fields in the segment and returns the string representation"""
for index, field in enumerate(self.fields):
if field.content:
out += str(field)
out = self.__add_separators_to_fields(index, out)
out = self.__add_segment_terminator(out)
return out
def __add_separators_to_fields(self, index, out):
"""adds field separators to all the element strings"""
if index < self.fieldCount:
#if the next field is required add the separator
if self.fields[index + 1].required:
out += self.element_separator
#if the next field is optional but has content add the separator
elif self.fields[index + 1].content:
out += self.element_separator
#finally if the next field is not the last element add the separator
elif index + 1 != self.fieldCount:
out += self.element_separator
return out
def __add_segment_terminator(self, out):
"""Adds the segment terminator to the segment string"""
out += self.segment_terminator
return out