main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. from asyncio.windows_events import NULL
  2. from time import sleep
  3. from app_logging import logger_name, init as init_logging
  4. import logging
  5. logger = logging.getLogger(logger_name)
  6. import requests,json
  7. import datetime
  8. import argparse
  9. init_logging()
  10. logger.debug(__name__)
  11. logger.info("")
  12. logger.info("")
  13. logger.info("")
  14. logger.info("------- welcome to Slash-Dolistripe -------")
  15. # Method to read config file settings
  16. logger.info(" --- -------------------------------------------------------------------------------- ---")
  17. logger.info(" --- ---------------------------------- ARG PHASE ----------------------------------- ---")
  18. logger.info(" --- -------------------------------------------------------------------------------- ---")
  19. parser = argparse.ArgumentParser()
  20. parser.add_argument("-v","--verbosity", help="increase output verbosity",action="store_true")
  21. parser.add_argument("-d","--dry", help="perform a dry run",action="store_true")
  22. parser.add_argument("-m","--mail", help="send invoice per mail to client",action="store_true")
  23. parser.add_argument("-p","--planned", help="trigger planned work to ",action="store_true")
  24. args = parser.parse_args()
  25. if args.verbosity:
  26. logger.info("Args : Debug Verbose Enabled")
  27. logger.setLevel(logging.DEBUG)
  28. else :
  29. logger.setLevel(logging.INFO)
  30. args = parser.parse_args()
  31. if args.dry:
  32. logger.info("Args : Dry Run Enabled")
  33. args = parser.parse_args()
  34. if args.mail:
  35. logger.info("Args : send invoice per Mails Enabled")
  36. logger.info(" --- -------------------------------------------------------------------------------- ---")
  37. logger.info(" --- ---------------------------------- CONF PHASE ---------------------------------- ---")
  38. logger.info(" --- -------------------------------------------------------------------------------- ---")
  39. logger.info("Reading Reference ConfIguration File")
  40. import configparser
  41. config = configparser.ConfigParser()
  42. config.optionxform = str # to make the read Case Sensitive
  43. config.read('references.conf')
  44. references_dict = config["list"]
  45. stripe_api_key = config["credentials"]["stripe_api_key"]
  46. dolibarr_username = config["credentials"]["dolibarr_username"]
  47. dolibarr_password = config["credentials"]["dolibarr_password"]
  48. if args.planned :
  49. dolibarr_planned_work_key = config["credentials"]["planned_work_key"]
  50. dolibarr_planned_work_cron_job_id = config["credentials"]["cron_job_id"]
  51. contact_mail = None
  52. if config.has_option("credentials", "contact_mail") :
  53. contact_mail = config["credentials"]["contact_mail"]
  54. logger.debug("contact mail in configuration is : " + contact_mail)
  55. logger.debug("Reading Stripe subscriptions references with CRM link to subscription contract")
  56. for reference in references_dict:
  57. logger.debug("link reference found : " + reference + " -> " + references_dict[reference])
  58. logger.info(" --- -------------------------------------------------------------------------------- ---")
  59. logger.info(" --- --------------------------------- STRIPE PHASE --------------------------------- ---")
  60. logger.info(" --- -------------------------------------------------------------------------------- ---")
  61. logger.info("testing connection to stripe...")
  62. import requests
  63. from requests.structures import CaseInsensitiveDict
  64. headers = CaseInsensitiveDict()
  65. headers["Accept"] = "application/json"
  66. headers["Authorization"] = "Bearer "+ stripe_api_key
  67. logger.debug("retrieving balance for test")
  68. r = requests.get("https://api.stripe.com/v1/balance", headers=headers)
  69. json_content = json.loads(r.text)
  70. logger.debug(json.dumps(json_content, indent=4 , ensure_ascii=False))
  71. assert r.status_code == 200
  72. logger.info("Stripe OK")
  73. logger.info("----------- Validating Stripe references and retrieving data -----------")
  74. class crm_linked_invoice :
  75. url : str
  76. date : datetime
  77. amount : float
  78. unpaid : bool = False
  79. class invoice_link :
  80. stripe_subscription_reference : str
  81. contract_number : int
  82. stripe_customer_ref : str
  83. stripe_customer_name : str
  84. stripe_customer_mail : str
  85. stripe_paid_amount : float
  86. stripe_epoch_date : int
  87. stripe_invoice_url : str
  88. stripe_invoice_number : str
  89. crm_contract_activated : bool = False
  90. crm_needs_new_invoice : bool = False
  91. crm_needs_update : bool = False
  92. crm_target_invoice : crm_linked_invoice
  93. invoice_links = set()
  94. for reference in references_dict:
  95. logger.info("retrieving Subscription data of " + reference)
  96. url = "https://api.stripe.com/v1/subscriptions/" + reference
  97. logger.debug("testing url : '" + url + "'")
  98. r = requests.get(url, headers=headers)
  99. assert r.status_code == 200
  100. subscription_json_data = json.loads(r.text)
  101. logger.debug("Subscription Data found : ")
  102. logger.debug(json.dumps(subscription_json_data, indent=4 , ensure_ascii=False))
  103. if subscription_json_data["status"] != "active" :
  104. logger.info("subscription not active, going to next")
  105. continue
  106. #retrieving customer data
  107. latest_invoice_reference = subscription_json_data["latest_invoice"]
  108. logger.debug("latest invoice reference found : " + latest_invoice_reference)
  109. url = "https://api.stripe.com/v1/invoices/" + latest_invoice_reference
  110. r = requests.get(url, headers=headers)
  111. assert r.status_code == 200
  112. latest_invoice_json_data = json.loads(r.text)
  113. logger.debug("latest invoice Data found : ")
  114. logger.debug(json.dumps(latest_invoice_json_data, indent=4, ensure_ascii=False))
  115. #TODO verfiy invoice status to "paid"
  116. link = invoice_link()
  117. link.stripe_subscription_reference = reference
  118. link.contract_number = references_dict[reference]
  119. link.stripe_paid_amount = float(float(latest_invoice_json_data["amount_paid"]) / 100 )
  120. link.stripe_epoch_date = latest_invoice_json_data["created"]
  121. link.stripe_customer_name = latest_invoice_json_data["customer_name"]
  122. link.stripe_customer_mail = latest_invoice_json_data["customer_email"]
  123. link.stripe_invoice_url = latest_invoice_json_data["hosted_invoice_url"]
  124. link.stripe_invoice_number = latest_invoice_json_data["number"]
  125. logger.info("latest invoice customer info : " + link.stripe_customer_name + " - " + link.stripe_customer_mail)
  126. logger.info("latest invoice paid amount : " + str(link.stripe_paid_amount) + latest_invoice_json_data["currency"])
  127. logger.info("latest invoice payment date : " + str(datetime.datetime.fromtimestamp(int(link.stripe_epoch_date))))
  128. logger.info("latest invoice url : " + link.stripe_invoice_url )
  129. # subscription reference - dolibarr contract reference - name - mail - amount - date of payment.
  130. invoice_links.add(link)
  131. logger.info(" ----------- Subscription Data OK")
  132. logger.info("Stripe Phase OK")
  133. logger.info(" --- -------------------------------------------------------------------------------- ---")
  134. logger.info(" --- -------------------------------- READ CRM PHASE -------------------------------- ---")
  135. logger.info(" --- -------------------------------------------------------------------------------- ---")
  136. from selenium import webdriver
  137. from selenium.webdriver.common.keys import Keys
  138. from selenium.webdriver.common.by import By
  139. import logging
  140. from selenium.webdriver.remote.remote_connection import LOGGER
  141. LOGGER.setLevel(logging.CRITICAL)
  142. logger.info("CRM Login")
  143. driver = webdriver.Edge()
  144. driver.get("https://crm.slashthd.fr/index.php")
  145. assert "Identifiant" in driver.title
  146. driver.find_element(By.NAME,"username").send_keys(str(dolibarr_username))
  147. pass_field = driver.find_element(By.NAME,"password")
  148. pass_field.send_keys(str(dolibarr_password))
  149. pass_field.send_keys(Keys.RETURN)
  150. logger.info(driver.title)
  151. assert "Accueil" in driver.title
  152. logger.info("login successful")
  153. current_date = datetime.datetime.now()
  154. if args.planned :
  155. logger.info("preparation phase : trigger planned work in CRM")
  156. work_url = "https://crm.slashthd.fr/public/cron/cron_run_jobs_by_url.php?securitykey=" + \
  157. dolibarr_planned_work_key + "&userlogin=" + dolibarr_username + "&id=" + str(dolibarr_planned_work_cron_job_id)
  158. driver.get(work_url)
  159. logger.info("temporization 1 sec....")
  160. sleep(1)
  161. # iterating over links63
  162. logger.info("iterating over invoice links")
  163. link : invoice_link
  164. for link in invoice_links :
  165. link.crm_contract_activated == False
  166. logger.debug("treating contract : " + link.contract_number)
  167. driver.get("https://crm.slashthd.fr/contrat/card.php?id=" + str(link.contract_number))
  168. logger.debug("testing if services are activated")
  169. #iterating service
  170. contract_lines = driver.find_elements(By.XPATH,"//div[contains(@id,'contrat-lines-container')]/div")
  171. logger.info(str(len(contract_lines)) + " service line found")
  172. for line in contract_lines :
  173. service_name = line.find_element(By.CLASS_NAME,"classfortooltip").text
  174. service_status = line.find_element(By.CLASS_NAME,"badge-status").text
  175. logger.info(service_name)
  176. logger.info(service_status)
  177. if "En service" in service_status :
  178. logger.debug("crm contract have at least one service activated")
  179. link.crm_contract_activated = True
  180. if link.crm_contract_activated == False:
  181. logger.info("the contract with number " + link.contract_number + " have all services disabled, SKIPPING CONTRACT")
  182. continue
  183. contract_links_table = driver.find_element(By.XPATH,'//table[@data-block="showLinkedObject"]')
  184. contract_links_elements = driver.find_elements(By.XPATH,'//tr[@data-element="facture"]')
  185. link.crm_needs_new_invoice = True
  186. if len(contract_links_elements) == 0 or contract_links_elements == None:
  187. link.crm_needs_new_invoice = False
  188. if not link.crm_contract_activated :
  189. link.crm_needs_new_invoice = False
  190. for element in contract_links_elements :
  191. current_invoice = crm_linked_invoice()
  192. current_invoice.url = element.find_element(By.CLASS_NAME, "linkedcol-name").find_element(By.TAG_NAME,"a").get_attribute("href")
  193. current_invoice.amount = float(element.find_element(By.CLASS_NAME, "linkedcol-amount").text.replace(',', "."))
  194. current_invoice.date = datetime.datetime.strptime(element.find_element(By.CLASS_NAME, "linkedcol-date").text, '%d/%m/%Y')
  195. if element.find_element(By.CLASS_NAME, "linkedcol-statut").find_element(By.TAG_NAME,"span").get_attribute("title") == "Impayée" :
  196. logger.debug("invoice is unpaid")
  197. current_invoice.unpaid = True
  198. logger.info("-----")
  199. logger.info("CRM linked invoice for customer : " + link.stripe_customer_name + " - " + link.stripe_customer_mail)
  200. logger.info("CRM linked invoice url : " + current_invoice.url)
  201. logger.info("CRM linked invoice date : " + str(current_invoice.amount))
  202. logger.info("CRM linked invoice amount : " + str(current_invoice.date))
  203. logger.info("CRM linked invoice unpaid ? : " + str(current_invoice.unpaid))
  204. logger.info("-----")
  205. stripe_date = datetime.datetime.fromtimestamp(link.stripe_epoch_date)
  206. #checking if new invoice is needed for the month
  207. if current_invoice.date.year == current_date.year :
  208. if current_invoice.date.month == current_date.month :
  209. logger.debug("invoice link does not need a new invoice for this month")
  210. link.crm_needs_new_invoice = False #TODO check all month since last invoice
  211. #checking if invoice is eligible to update
  212. if current_invoice.date.year == stripe_date.year :
  213. if current_invoice.date.month == stripe_date.month :
  214. if current_invoice.date.day <= stripe_date.day :
  215. if current_invoice.unpaid :
  216. if link.stripe_paid_amount == current_invoice.amount :
  217. logger.info("Current crm invoice is unpaid, and corresponding to same month and amount as stripe payment")
  218. logger.info(" ## Target invoice FOUND ! ##")
  219. link.crm_needs_update = True
  220. link.crm_target_invoice = current_invoice
  221. logger.info(" --- -------------------------------------------------------------------------------- ---")
  222. logger.info(" --- -------------------------------- SUMMARY PHASE --------------------------------- ---")
  223. logger.info(" --- -------------------------------------------------------------------------------- ---")
  224. logger.info("summary of actions")
  225. if len(invoice_links) == 0 :
  226. logger.info("## no action pending detected ##")
  227. action = False
  228. link : invoice_link
  229. for link in invoice_links :
  230. if link.crm_contract_activated :
  231. if link.crm_needs_update :
  232. action = True
  233. logger.info(" ## ------------------------------- ##")
  234. logger.info("@@ INVOICE UPDATE PENDING : ")
  235. logger.info("stripe invoice customer info : " + link.stripe_customer_name + " - " + link.stripe_customer_mail)
  236. logger.info("stripe invoice paid amount : " + str(link.stripe_paid_amount) + " " + latest_invoice_json_data["currency"])
  237. logger.info("stripe invoice payment date : " + str(datetime.datetime.fromtimestamp(int(link.stripe_epoch_date))))
  238. logger.info("CRM linked invoice url : " + link.crm_target_invoice.url)
  239. logger.info("CRM linked invoice date : " + str(link.crm_target_invoice.amount))
  240. logger.info("CRM linked invoice amount : " + str(link.crm_target_invoice.date))
  241. logger.info("CRM linked invoice unpaid ? : " + str(link.crm_target_invoice.unpaid))
  242. logger.info(" ## ------------------------------- ##")
  243. if link.crm_needs_new_invoice :
  244. Action = True
  245. logger.info(" ## ------------------------------- ##")
  246. logger.info("New Invoice Generation Pending")
  247. logger.info("invoice customer info : " + link.stripe_customer_name + " - " + link.stripe_customer_mail)
  248. date_string = format(current_date,'01/%m/%Y')
  249. logger.info("planned date : " + date_string)
  250. logger.info(" ## ------------------------------- ##")
  251. if not action :
  252. logger.info("## no action pending detected ##")
  253. if args.dry:
  254. driver.close()
  255. logger.info("dry run enabled, exiting here...")
  256. exit(0)
  257. logger.info(" --- -------------------------------------------------------------------------------- ---")
  258. logger.info(" --- -------------------------------- ACTION PHASE ---------------------------------- ---")
  259. logger.info(" --- -------------------------------------------------------------------------------- ---")
  260. for link in invoice_links :
  261. if link.crm_contract_activated :
  262. if link.crm_needs_update :
  263. logger.info(" ## ------ Creating Payment ------ ##")
  264. logger.info("stripe invoice customer info : " + link.stripe_customer_name + " - " + link.stripe_customer_mail)
  265. logger.info("stripe invoice paid amount : " + str(link.stripe_paid_amount) + " " + latest_invoice_json_data["currency"])
  266. logger.info("stripe invoice payment date : " + str(datetime.datetime.fromtimestamp(int(link.stripe_epoch_date))))
  267. logger.info("CRM linked invoice url : " + link.crm_target_invoice.url)
  268. logger.info("CRM linked invoice date : " + str(link.crm_target_invoice.amount))
  269. logger.info("CRM linked invoice amount : " + str(link.crm_target_invoice.date))
  270. logger.info("CRM linked invoice unpaid ? : " + str(link.crm_target_invoice.unpaid))
  271. driver.get(link.crm_target_invoice.url)
  272. pay_url = driver.find_element(By.XPATH, "//*[text()='Saisir règlement']").get_attribute("href")
  273. driver.get(pay_url)
  274. stripe_payment_date = datetime.datetime.fromtimestamp(int(link.stripe_epoch_date))
  275. date_string = format(stripe_payment_date,'{%d/%m/%Y}')
  276. driver.find_element(By.ID, "re").send_keys(date_string)
  277. driver.find_element(By.NAME, "comment").send_keys("Payment treated by automation - Slash-DoliStripe \n stripe invoice URL : " + link.stripe_invoice_url )
  278. driver.find_element(By.CLASS_NAME,'AutoFillAmout').click()
  279. driver.find_element(By.NAME, "num_paiement").send_keys(link.stripe_invoice_number)
  280. driver.find_element(By.XPATH,'//input[@value="Payer"]').click()
  281. driver.find_element(By.XPATH,'//input[@value="Valider"]').click()
  282. if args.mail:
  283. logger.info("sending email to client...")
  284. driver.find_element(By.XPATH, "//*[text()='Envoyer email']").click()
  285. driver.find_element(By.ID, "sendto").send_keys(link.stripe_customer_mail)
  286. if contact_mail is not None :
  287. driver.find_element(By.ID, "sendtocc").send_keys(contact_mail)
  288. driver.find_element(By.ID, "sendmail").click()
  289. logger.info(" --- -------------------------------------------------------------------------------- ---")
  290. logger.info(" --- -------------------------------- CLEANING PHASE -------------------------------- ---")
  291. logger.info(" --- -------------------------------------------------------------------------------- ---")
  292. driver.close()
  293. exit(0)