main.py 21 KB

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