app.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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 wrong_tax_loss(listed: float, wrong_tax: float, details: dict = None) -> float:
  60. if details is None:
  61. details = {}
  62. details['sales_tax'] = listed * SALES_TAX
  63. details['wrong_tax'] = listed * wrong_tax
  64. details['wrong_tax_loss'] = details['sales_tax'] - details['wrong_tax']
  65. return details['wrong_tax_loss']
  66. def _n2l(data: dict) -> None:
  67. svc = data['service']
  68. det = data['details']
  69. net = data['net'] if data.get('net') else data['amount']
  70. comm_rate = svc.get('fees', {}).get('commission', 0)
  71. wrong_rate = svc.get('taxes', {}).get('wrong', SALES_TAX)
  72. listed = (net / (1 - comm_rate - SALES_TAX + wrong_rate))
  73. if 'fees' in svc and 'commission' in svc['fees']:
  74. det['commission'] = listed * comm_rate
  75. if 'taxes' in svc and 'wrong' in svc['taxes']:
  76. det['wrong_tax'] = listed * wrong_rate
  77. det['sales_tax'] = listed * SALES_TAX
  78. det['wrong_tax_loss'] = det['sales_tax'] - det['wrong_tax']
  79. data['listed'] = listed
  80. def _l2n(data: dict) -> None:
  81. svc = data['service']
  82. det = data['details']
  83. net = data['listed'] if data.get('listed') else data['amount']
  84. if 'fees' in svc and 'commission' in svc['fees']:
  85. det['commission'] = net * svc['fees']['commission']
  86. if 'taxes' in svc and 'wrong' in svc['taxes']:
  87. det['sales_tax'] = net * SALES_TAX
  88. det['wrong_tax'] = net * svc['taxes']['wrong']
  89. det['wrong_tax_loss'] = det['sales_tax'] - det['wrong_tax']
  90. for k in [ 'commission', 'wrong_tax_loss' ]:
  91. if k in det:
  92. net -= det[k]
  93. data['net'] = net
  94. def _l2r(data: dict) -> None:
  95. svc = data['service']
  96. det = data['details']
  97. retail = data['listed'] if data.get('listed') else data['amount']
  98. if 'fees' in svc and 'client_fee' in svc['fees']:
  99. det['client_fee'] = retail * svc['fees']['client_fee']
  100. retail += det['client_fee']
  101. if 'taxes' in svc and 'wrong' in svc['taxes']:
  102. det['wrong_tax'] = retail * svc['taxes']['wrong']
  103. retail += det['wrong_tax']
  104. else:
  105. det['sales_tax'] = retail * SALES_TAX
  106. retail += det['sales_tax']
  107. if 'taxes' in svc and 'flat_tax' in svc['taxes']:
  108. det['service_tax'] = svc['taxes']['flat_tax']
  109. retail += det['service_tax']
  110. data['retail'] = retail
  111. def _r2l(data: dict) -> None:
  112. svc = data['service']
  113. det = data['details']
  114. listed = data['retail'] if data.get('retail') else data['amount']
  115. if 'taxes' in svc and 'flat_tax' in svc['taxes']:
  116. det['service_tax'] = svc['taxes']['flat_tax']
  117. listed -= det['service_tax']
  118. if 'taxes' in svc and 'wrong' in svc['taxes']:
  119. det['wrong_tax'] = listed - (listed / (1 + svc['taxes']['wrong']))
  120. listed -= det['wrong_tax']
  121. else:
  122. det['sales_tax'] = listed - (listed / (1 + SALES_TAX))
  123. listed -= det['sales_tax']
  124. if 'fees' in svc and 'client_fee' in svc['fees']:
  125. det['client_fee'] = listed - (listed / (1 + svc['fees']['client_fee']))
  126. listed -= det['client_fee']
  127. data['listed'] = listed
  128. # Routing
  129. @app.route(f"{URL_PREFIX}/services", methods=['GET'])
  130. def list_services():
  131. return jsonify([
  132. {'key': key, 'name': cfg['name']}
  133. for key, cfg in SERVICES.items()
  134. ])
  135. @app.route(f"{URL_PREFIX}/net_to_list", methods=['GET', 'POST'])
  136. def net_to_list():
  137. try:
  138. data = _request(request)
  139. except (TypeError, ValueError):
  140. return jsonify({'error': 'Invalid or missing parameters'}), 400
  141. _n2l(data)
  142. return _response(**data)
  143. @app.route(f"{URL_PREFIX}/list_to_net", methods=['GET', 'POST'])
  144. def list_to_net():
  145. try:
  146. data = _request(request)
  147. except (TypeError, ValueError):
  148. return jsonify({'error': 'Invalid or missing parameters'}), 400
  149. _l2n(data)
  150. return _response(**data)
  151. @app.route(f"{URL_PREFIX}/list_to_retail", methods=['GET', 'POST'])
  152. def list_to_retail():
  153. try:
  154. data = _request(request)
  155. except (TypeError, ValueError):
  156. return jsonify({'error': 'Invalid or missing parameters'}), 400
  157. _l2r(data)
  158. return _response(**data)
  159. @app.route(f"{URL_PREFIX}/retail_to_list", methods=['GET', 'POST'])
  160. def retail_to_list():
  161. try:
  162. data = _request(request)
  163. except (TypeError, ValueError):
  164. return jsonify({'error': 'Invalid or missing parameters'}), 400
  165. _r2l(data)
  166. return _response(**data)
  167. @app.route(f"{URL_PREFIX}/net_to_retail", methods=['GET', 'POST'])
  168. def net_to_retail():
  169. try:
  170. data = _request(request)
  171. except (TypeError, ValueError):
  172. return jsonify({'error': 'Invalid or missing parameters'}), 400
  173. _n2l(data)
  174. _l2r(data)
  175. return _response(**data)
  176. @app.route(f"{URL_PREFIX}/retail_to_net", methods=['GET', 'POST'])
  177. def retail_to_net():
  178. try:
  179. data = _request(request)
  180. except (TypeError, ValueError):
  181. return jsonify({'error': 'Invalid or missing parameters'}), 400
  182. _r2l(data)
  183. _l2n(data)
  184. return _response(**data)
  185. # Main app
  186. if __name__ == '__main__':
  187. app.run(debug=DEBUG, port=PORT)