diff --git a/pyaccuwage/__init__.py b/pyaccuwage/__init__.py index 4691cee..01fef45 100644 --- a/pyaccuwage/__init__.py +++ b/pyaccuwage/__init__.py @@ -88,6 +88,33 @@ def dumps(records): fp.seek(0) return fp.read() +def json_dumps(records): + import json + import model + import decimal + + class JSONEncoder(json.JSONEncoder): + def default(self, o): + if hasattr(o, 'toJSON') and callable(getattr(o, 'toJSON')): + return o.toJSON() + + elif isinstance(o, decimal.Decimal): + return str(o.quantize(decimal.Decimal('0.01'))) + + return super(JSONEncoder, self).default(o) + + return json.dumps(records, cls=JSONEncoder, indent=2) + + +def json_loads(s, record_classes): + import json + + def object_hook(o): + return {'object_hook':str(o)} + #def default(self, o): + # return super(JSONDecoder, self).default(o) + + return json.loads(s, object_hook=object_hook) # THIS WAS IN CONTROLLER, BUT UNLESS WE # REALLY NEED A CONTROLLER CLASS, IT'S SIMPLER @@ -104,6 +131,7 @@ def validate_required_records(records): while req_types: req = req_types[0] if req not in types: + from fields import ValidationError raise ValidationError("Record set missing required record: %s" % req) else: req_types.remove(req) diff --git a/pyaccuwage/fields.py b/pyaccuwage/fields.py index 960db3e..2f0658e 100644 --- a/pyaccuwage/fields.py +++ b/pyaccuwage/fields.py @@ -49,6 +49,19 @@ class Field(object): def parse(self, s): self.value = s.strip() + def toJSON(self): + data = self.get_data() + + return { + '__class__': self.__class__.__name__, + 'name': self.name, + 'maxLength': self.max_length, + 'required': self.required, + 'data': data, + 'value': self._value, + 'dataLength': len(data) + } + class TextField(Field): def validate(self): @@ -146,6 +159,9 @@ class BooleanField(Field): class MoneyField(Field): + def __init__(self, name=None, max_length=0, required=False): + super(MoneyField, self).__init__(name=name, uppercase=False, max_length=max_length, required=required) + def validate(self): if self.value == None and self.required: raise ValidationError("value required", field=self) diff --git a/pyaccuwage/model.py b/pyaccuwage/model.py index 05f2315..0a239a3 100644 --- a/pyaccuwage/model.py +++ b/pyaccuwage/model.py @@ -67,3 +67,9 @@ class Model(object): field.read(fp) + def toJSON(self): + return { + '__class__': self.__class__.__name__, + 'fields': self.get_sorted_fields() + } +