app.py 6.3 KB

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