main.py 23 KB

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