main.py 18 KB

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