is_close_changed_notice.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. from enum import Enum
  2. import time
  3. from datetime import datetime
  4. from typing import Optional
  5. from pydantic import BaseModel
  6. from fastapi import FastAPI, Query, UploadFile, File
  7. from fastapi import FastAPI
  8. from fastapi.middleware.cors import CORSMiddleware
  9. import json
  10. import urllib.request
  11. import dataset,json
  12. import dataset
  13. from datetime import datetime, timedelta
  14. from email.mime.text import MIMEText
  15. from email.mime.image import MIMEImage
  16. from email.mime.multipart import MIMEMultipart
  17. from email.mime.base import MIMEBase
  18. from email.mime.application import MIMEApplication
  19. import os
  20. import boto3
  21. from botocore.exceptions import ClientError
  22. app = FastAPI()
  23. origins = [
  24. "http://139.162.121.30",
  25. "http://139.162.121.30:8002",
  26. ]
  27. app.add_middleware(
  28. CORSMiddleware,
  29. # allow_origins=origins,
  30. allow_origins=["*"],
  31. allow_credentials=True,
  32. allow_methods=["*"],
  33. allow_headers=["*"],
  34. )
  35. # 取得資料庫連線
  36. def get_db_connection():
  37. # Choozmo DB
  38. # db = dataset.connect("mysql://choozmo:pAssw0rd@db.ptt.cx:3306/hhh?charset=utf8mb4")
  39. # 測試機 DB
  40. db = dataset.connect('mysql://hhh7796hhh:lYmWsu^ujcA1@hhh-v57-cluster.cluster-cmab1ctkglka.ap-northeast-2.rds.amazonaws.com:3306/stage?charset=utf8mb4')
  41. # 正式機 DB
  42. # db = dataset.connect('mysql://hhh7796hhh:lYmWsu^ujcA1@hhh-v57-cluster.cluster-cmab1ctkglka.ap-northeast-2.rds.amazonaws.com:3306/xoops?charset=utf8mb4')
  43. return db
  44. # 寄送合約狀態修改Email通知
  45. def hhh_send_mail(email, subject, html):
  46. SENDER = "Gorgeous Space <noreply@hhh.com.tw>"
  47. RECIPIENT = email
  48. AWS_REGION = "us-east-1"
  49. CHARSET = "UTF-8"
  50. client = boto3.client('ses',region_name=AWS_REGION)
  51. try:
  52. msg = MIMEMultipart()
  53. msg["Subject"] = subject
  54. msg["From"] = "noreply@hhh.com.tw"
  55. msg["To"] = email
  56. # Set message body
  57. body = MIMEText(html, "html")
  58. msg.attach(body)
  59. response = client.send_raw_email(
  60. Source=msg["From"],
  61. Destinations=[msg["To"]],
  62. RawMessage={"Data": msg.as_string()}
  63. )
  64. print(response)
  65. # Display an error if something goes wrong.
  66. except ClientError as e:
  67. print(e.response['Error']['Message'])
  68. else:
  69. print("Email sent! Message ID:"),
  70. print(response['MessageId'])
  71. '''
  72. 原有狀態:
  73. N: 未結案
  74. Y: 已結案
  75. T: 未上線
  76. C: 轉約 (已刪除)
  77. 新增狀態:
  78. D: 續約
  79. E: 不續約延期
  80. F: 不續約需下線
  81. G: 已到期未續約
  82. '''
  83. @app.get("/is_close_changed_notice")
  84. async def is_close_changed_notice(exf_id: str = '', is_close: str = ''):
  85. # 取得資料庫連線
  86. db = get_db_connection()
  87. subject = ""
  88. # 取得合約資料
  89. q = "SELECT * \
  90. FROM execute_form \
  91. WHERE exf_id = " + exf_id
  92. q_result_count = len(list(db.query(q)))
  93. if q_result_count == 0: # 無合約資料
  94. return
  95. for r in db.query(q):
  96. # 判斷合約狀態是否有修改
  97. if is_close == r['is_close']: # 合約狀態未修改
  98. print ('合約狀態未修改,不須通知')
  99. print ('is_close = ' + is_close + ', r[is_close] = ' + r['is_close']) # test
  100. return
  101. else: # 合約狀態有修改
  102. print ('合約狀態有修改,須通知')
  103. subject = '[合約狀態修改]:' + r['company'] + ' (合約編號:' + r['num'] + ')_' + datetime.now().strftime("%Y-%m-%d %H:%M")
  104. html = """
  105. <!DOCTYPE html>
  106. <head>
  107. <meta charset="UTF-8">
  108. </head>
  109. <body>
  110. """
  111. if is_close == 'D':
  112. print('修改後狀態: 續約(D)')
  113. html += '<div>本合約狀態已修改為 <span style="color:red;">續約</span></div>'
  114. '''
  115. # 發送通知給負責業務、CRM、Kevin、Sam
  116. email_list = ['sam@hhh.com.tw','kevin.h@hhh.com.tw', 'miko@hhh.com.tw', 'mollie@hhh.com.tw', 'lynn@hhh.com.tw', 'zoe_lo@hhh.com.tw']
  117. # 負責業務
  118. print('負責業務: ' + r['sales_man'])
  119. email_list.append(r['sales_man'])
  120. # 取得執行單位Email清單
  121. q1 = "SELECT DISTINCT(execute_man) \
  122. FROM execute_detail \
  123. WHERE exf_id=" + exf_id
  124. q1_result_count = len(list(db.query(q1)))
  125. if q1_result_count > 0: # 有執行單位Email清單
  126. for r1 in db.query(q1):
  127. if r1['execute_man']:
  128. print('執行單位: ' + r1['execute_man'])
  129. email_list.append(r1['execute_man'])
  130. '''
  131. elif is_close == 'E':
  132. print('修改後狀態: 不續約延期(E)')
  133. html += '<div>本合約狀態已修改為 <span style="color:red;">不續約延期</span></div>'
  134. '''
  135. # 發送通知給負責業務、CRM、Kevin、Sam
  136. # 以變更後的合約日期來發送通知信
  137. email_list = ['sam@hhh.com.tw','kevin.h@hhh.com.tw', 'miko@hhh.com.tw', 'mollie@hhh.com.tw', 'lynn@hhh.com.tw', 'zoe_lo@hhh.com.tw']
  138. # 負責業務
  139. print('負責業務: ' + r['sales_man'])
  140. email_list.append(r['sales_man'])
  141. # 取得執行單位Email清單
  142. q1 = "SELECT DISTINCT(execute_man) \
  143. FROM execute_detail \
  144. WHERE exf_id=" + exf_id
  145. q1_result_count = len(list(db.query(q1)))
  146. if q1_result_count > 0: # 有執行單位Email清單
  147. for r1 in db.query(q1):
  148. if r1['execute_man']:
  149. print('執行單位: ' + r1['execute_man'])
  150. email_list.append(r1['execute_man'])
  151. '''
  152. elif is_close == 'F':
  153. print('修改後狀態: 不續約需下線(F)')
  154. html += '<div>本合約狀態已修改為 <span style="color:red;">不續約需下線</span></div>'
  155. '''
  156. # 發送通知通知給負責業務、CRM、財務部、Kevin、Sam
  157. email_list = ['sam@hhh.com.tw','kevin.h@hhh.com.tw', 'miko@hhh.com.tw', 'mollie@hhh.com.tw', 'lynn@hhh.com.tw', 'zoe_lo@hhh.com.tw', 'acct_team@hhh.com.tw']
  158. # 負責業務
  159. print('負責業務: ' + r['sales_man'])
  160. email_list.append(r['sales_man'])
  161. # 取得執行單位Email清單
  162. q1 = "SELECT DISTINCT(execute_man) \
  163. FROM execute_detail \
  164. WHERE exf_id=" + exf_id
  165. q1_result_count = len(list(db.query(q1)))
  166. if q1_result_count > 0: # 有執行單位Email清單
  167. for r1 in db.query(q1):
  168. if r1['execute_man']:
  169. print('執行單位: ' + r1['execute_man'])
  170. email_list.append(r1['execute_man'])
  171. '''
  172. elif is_close == 'G':
  173. print('修改後狀態: 已到期未續約(G)')
  174. html += '<div>本合約狀態已修改為 <span style="color:red;">已到期未續約</span></div>'
  175. '''
  176. # 發送通知給負責業務、Kevin、Sam
  177. email_list = ['sam@hhh.com.tw','kevin.h@hhh.com.tw']
  178. # 負責業務
  179. print('負責業務: ' + r['sales_man'])
  180. email_list.append(r['sales_man'])
  181. '''
  182. # 列出該合約底下所有執行項目(含已完成、未完成)
  183. q1 = "SELECT * \
  184. FROM execute_detail \
  185. WHERE exf_id=" + exf_id + \
  186. " ORDER BY execute_man"
  187. q1_result_count = len(list(db.query(q1)))
  188. if q1_result_count > 0: # 有執行項目
  189. html += "<br><table style='width:100%;border-collapse: collapse;' border='1'> \
  190. <tr style='text-align:left;'> \
  191. <th style='width:5%;'>#</th> \
  192. <th>大項目</th> \
  193. <th>執行項</th> \
  194. <th>單位</th> \
  195. <th>是否完成</th> \
  196. <th>完成人</th> \
  197. <th>備註</th> \
  198. <th>預計排程日期</th> \
  199. <th>第一次提醒日</th> \
  200. </tr>";
  201. idx = 1
  202. for r1 in db.query(q1):
  203. if r1['set_date'] is None:
  204. r1['set_date'] = '無'
  205. if r1['alert_date_1'] is None:
  206. r1['alert_date_1'] = '無'
  207. # 執行單位Email
  208. if r1['execute_man'] == 'hhh_edit@hhh.com.tw':
  209. r1['execute_man'] = '編輯採訪部'
  210. elif r1['execute_man'] == 'hhh_mk@hhh.com.tw':
  211. r1['execute_man'] = '行銷企劃部'
  212. elif r1['execute_man'] == 'hhh_web@hhh.com.tw':
  213. r1['execute_man'] = '網站工程部'
  214. elif r1['execute_man'] == 'hhh_video@hhh.com.tw':
  215. r1['execute_man'] = '影音企劃部'
  216. elif r1['execute_man'] == 'agent@hhh.com.tw':
  217. r1['execute_man'] = '幸福經紀人'
  218. elif r1['execute_man'] == 'hhh_admin@hhh.com.tw':
  219. r1['execute_man'] = '行政部'
  220. elif r1['execute_man'] == 'hhh_sales@hhh.com.tw':
  221. r1['execute_man'] = '業務部'
  222. html += "<tr><td>" + str(idx) + "</td><td>" + r1['lv1'] + "</td><td>" + r1['lv2'] + "</td><td>" + r1['execute_man'] + "</td><td>" + r1['is_complete'] + "</td><td>" + r1['complete_man'] + "</td><td>" + r1['note'] + "</td><td>" + str(r1['set_date']) + "</td><td>" + str(r1['alert_date_1']) + "</td></tr>"
  223. idx += 1
  224. html += "</table>"
  225. else:
  226. print ('修改後狀態: ' + is_close + ',不須通知')
  227. return
  228. html += "<div><br>幸福空間經營團隊敬上<br><br>※此信為系統自動寄送,請勿直接回信。謝謝!</div>"
  229. html += """
  230. </body>
  231. </html>
  232. """
  233. # Email清單
  234. email_list = ['mike@choozmo.com', 'stacy@choozmo.com']
  235. # 寄送合約狀態修改Email通知
  236. for email in email_list:
  237. hhh_send_mail(email, subject, html)