app.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import json
  2. import os
  3. from flask import Flask, request, jsonify
  4. from flask_cors import CORS
  5. from functools import wraps
  6. _url_prefix = os.environ.get("URL_PREFIX", "room").strip("/")
  7. _port = os.environ.get("FLASK_PORT", "5000").strip()
  8. _debug = os.environ.get("FLASK_DEBUG", "").strip()
  9. _here = os.path.dirname(__file__)
  10. DEBUG = True if _debug else False
  11. URL_PREFIX = f"/{_url_prefix}" if _url_prefix else ""
  12. PORT = int(_port)
  13. app = Flask(__name__)
  14. CORS(app)
  15. # Config
  16. with open(os.path.join(_here, "config.json")) as f:
  17. CONFIG = json.load(f)
  18. if not CONFIG or 'services' not in CONFIG or 'global' not in CONFIG:
  19. raise ValueError('CONFIG: Missing services or global')
  20. SERVICES = CONFIG['services']
  21. GLOBAL = CONFIG['global']
  22. if not GLOBAL or 'taxes' not in GLOBAL or 'sales' not in GLOBAL['taxes']:
  23. raise ValueError('GLOBAL: Missing sales tax')
  24. SALES_TAX = GLOBAL['taxes']['sales']
  25. DEFAULT_SERVICE = next(iter(SERVICES))
  26. # Formatters
  27. def dollar_fmt(value: float) -> str:
  28. return "{:.2f}".format(round(value, 2))
  29. def title_fmt(value: str) -> str:
  30. return value.replace('_', ' ').title()
  31. def details_fmt(details: dict) -> dict:
  32. fmt = {}
  33. for k, v in details.items():
  34. fmt[title_fmt(k)] = dollar_fmt(v)
  35. return fmt
  36. # Request handlers
  37. def _request(request) -> dict:
  38. _req = request.get_json(silent=True) or request.args
  39. _data = { 'service_key': None }
  40. if 'service' in _req:
  41. _data['service_key'] = str(_req['service']).lower().strip()
  42. if 'amount' in _req:
  43. _data['amount'] = float(_req['amount'])
  44. for k in [ 'service_key', 'amount' ]:
  45. if k not in _data or not _data[k]:
  46. raise ValueError(k)
  47. _data['service'] = SERVICES.get(_data['service_key'])
  48. if _data['service'] is None:
  49. raise ValueError('service')
  50. _data['details'] = {}
  51. return _data
  52. def _response(**data) -> str:
  53. _dict = { 'service_key' : data['service_key'] }
  54. for k in [ 'listed', 'retail', 'net' ]:
  55. if data.get(k) is not None:
  56. _dict[k] = dollar_fmt(data.get(k))
  57. if data.get('details') is not None:
  58. _dict['details'] = details_fmt(data.get('details'))
  59. return jsonify(_dict)
  60. def make_handler(*transforms):
  61. def handler():
  62. try:
  63. data = _request(request)
  64. except (TypeError, ValueError):
  65. return jsonify({'error': 'Invalid or missing parameters'}), 400
  66. for transform in transforms:
  67. transform(data)
  68. return _response(**data)
  69. return handler
  70. # Actual math
  71. def _n2l(data: dict) -> None:
  72. svc = data['service']
  73. det = data['details']
  74. net = data['net'] if data.get('net') else data['amount']
  75. comm_rate = svc.get('fees', {}).get('commission', 0)
  76. wrong_rate = svc.get('taxes', {}).get('wrong', SALES_TAX)
  77. listed = (net / (1 - comm_rate - SALES_TAX + wrong_rate))
  78. if 'fees' in svc and 'commission' in svc['fees']:
  79. det['commission'] = listed * comm_rate
  80. if 'taxes' in svc and 'wrong' in svc['taxes']:
  81. det['wrong_tax'] = listed * wrong_rate
  82. det['sales_tax'] = listed * SALES_TAX
  83. det['wrong_tax_loss'] = det['sales_tax'] - det['wrong_tax']
  84. data['listed'] = round(listed, 2)
  85. def _l2n(data: dict) -> None:
  86. svc = data['service']
  87. det = data['details']
  88. net = data['listed'] if data.get('listed') else data['amount']
  89. if 'fees' in svc and 'commission' in svc['fees']:
  90. det['commission'] = net * svc['fees']['commission']
  91. if 'taxes' in svc and 'wrong' in svc['taxes']:
  92. det['sales_tax'] = net * SALES_TAX
  93. det['wrong_tax'] = net * svc['taxes']['wrong']
  94. det['wrong_tax_loss'] = det['sales_tax'] - det['wrong_tax']
  95. for k in [ 'commission', 'wrong_tax_loss' ]:
  96. if k in det:
  97. net -= det[k]
  98. data['net'] = round(net,2)
  99. def _l2r(data: dict) -> None:
  100. svc = data['service']
  101. det = data['details']
  102. retail = data['listed'] if data.get('listed') else data['amount']
  103. if 'fees' in svc and 'client_fee' in svc['fees']:
  104. det['client_fee'] = retail * svc['fees']['client_fee']
  105. retail += det['client_fee']
  106. if 'taxes' in svc and 'wrong' in svc['taxes']:
  107. det['wrong_tax'] = retail * svc['taxes']['wrong']
  108. retail += det['wrong_tax']
  109. else:
  110. det['sales_tax'] = retail * SALES_TAX
  111. retail += det['sales_tax']
  112. if 'taxes' in svc and 'flat_tax' in svc['taxes']:
  113. det['service_tax'] = svc['taxes']['flat_tax']
  114. retail += det['service_tax']
  115. data['retail'] = round(retail, 2)
  116. def _r2l(data: dict) -> None:
  117. svc = data['service']
  118. det = data['details']
  119. listed = data['retail'] if data.get('retail') else data['amount']
  120. if 'taxes' in svc and 'flat_tax' in svc['taxes']:
  121. det['service_tax'] = svc['taxes']['flat_tax']
  122. listed -= det['service_tax']
  123. if 'taxes' in svc and 'wrong' in svc['taxes']:
  124. det['wrong_tax'] = listed - (listed / (1 + svc['taxes']['wrong']))
  125. listed -= det['wrong_tax']
  126. else:
  127. det['sales_tax'] = listed - (listed / (1 + SALES_TAX))
  128. listed -= det['sales_tax']
  129. if 'fees' in svc and 'client_fee' in svc['fees']:
  130. det['client_fee'] = listed - (listed / (1 + svc['fees']['client_fee']))
  131. listed -= det['client_fee']
  132. data['listed'] = round(listed, 2)
  133. # Routing
  134. routes = [
  135. ('net_to_list', _n2l),
  136. ('list_to_net', _l2n),
  137. ('list_to_retail', _l2r),
  138. ('retail_to_list', _r2l),
  139. ('net_to_retail', _n2l, _l2r),
  140. ('retail_to_net', _r2l, _l2n),
  141. ]
  142. for route_def in routes:
  143. endpoint, *transforms = route_def
  144. handler = make_handler(*transforms)
  145. # Flask requires unique function names
  146. handler.__name__ = endpoint
  147. app.add_url_rule(
  148. f"{URL_PREFIX}/{endpoint}",
  149. endpoint=endpoint,
  150. view_func=handler,
  151. methods=['GET', 'POST']
  152. )
  153. @app.route(f"{URL_PREFIX}/services", methods=['GET'])
  154. def list_services():
  155. return jsonify([
  156. {'key': key, 'name': cfg['name']}
  157. for key, cfg in SERVICES.items()
  158. ])
  159. # Main app
  160. if __name__ == '__main__':
  161. app.run(debug=DEBUG, port=PORT)