ERP.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # 1229 Test
  2. # TODO 資料表是否會重複開啟? -> def?
  3. from logging import info
  4. from datetime import datetime
  5. from flask import Flask, render_template, request, jsonify
  6. import pymysql
  7. from flask_migrate import Migrate
  8. import time
  9. from app import create_app
  10. import pandas as pd
  11. import xlsxwriter
  12. app = Flask(__name__)
  13. # 首頁測試
  14. @app.route('/')
  15. def index():
  16. return render_template('index.html')
  17. # 使用者名稱測試
  18. @app.route('/user/<name>')
  19. def user(name):
  20. return render_template('hello.html', name=name)
  21. # 建立 BOM 表
  22. @app.route('/create_BOM', methods=['GET', 'POST'])
  23. def create_BOM():
  24. # 開啟本機 erp 資料庫
  25. mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='erp', charset='utf8')
  26. mycursor = mydb.cursor()
  27. # 獲取資料表內資料
  28. sql = '''SELECT 內部料號, 會計科目表.會計科目_名稱, 類別表.類別_名稱, 流水號, 供應商.公司, 名稱
  29. FROM (
  30. (零件表
  31. INNER JOIN 供應商
  32. ON 供應商.供應商 = 零件表.供應商
  33. )
  34. INNER JOIN 類別表
  35. ON 類別表.類別_編號 = 零件表.類別
  36. )
  37. INNER JOIN 會計科目表
  38. ON 會計科目表.會計科目_編號 = 零件表.會計科目
  39. '''
  40. mycursor.execute(sql)
  41. content = mycursor.fetchall()
  42. # 獲取欄位名稱
  43. sql = "SHOW FIELDS FROM 零件表"
  44. mycursor.execute(sql)
  45. labels = mycursor.fetchall()
  46. # print("labels: ", labels)
  47. # # labels: (('產品', 'varchar(4)', 'YES', '', None, ''), ('系統', 'varchar(5)', 'YES', '', None, ''),
  48. labels = [g[0] for g in labels]
  49. # print("labels: ", labels)
  50. # # labels: ['產品', '系統', '系統圖號', '狀態', '進貨狀態', '序號', '組序號',
  51. # 獲取會計科目欄位
  52. AccountingSubjects = "SELECT * FROM 會計科目表"
  53. mycursor.execute(AccountingSubjects)
  54. AccountingSubjects_data = mycursor.fetchall()
  55. # print("AccountingSubjects_data", AccountingSubjects_data)
  56. # # (('01', '成品'), ('02', '系統成品'), ('03', '模組半成品'), ('04', '零件'), ('05', '工具'))
  57. # 獲取類別欄位
  58. Category = "SELECT * FROM 類別表"
  59. mycursor.execute(Category)
  60. Category_data = mycursor.fetchall()
  61. # 獲取供應商欄位
  62. Supplier = "SELECT * FROM 供應商"
  63. mycursor.execute(Supplier)
  64. Supplier_data = mycursor.fetchall()
  65. # 獲取零件名稱
  66. Component = "SELECT 名稱 FROM 零件表"
  67. mycursor.execute(Component)
  68. Component_data = mycursor.fetchall()
  69. return render_template('create_BOM.html', title='建立 BOM 表', **locals())
  70. # 新增零件清單項目
  71. @app.route('/create_component_table_item', methods=['GET', 'POST'])
  72. def create_component_table_item():
  73. # 開啟本機 erp 資料庫
  74. mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='erp', charset='utf8')
  75. mycursor = mydb.cursor()
  76. # # --- 新增零件用 -----------------------------------------------------------------------------------------
  77. # 獲取會計科目欄位
  78. AccountingSubjects = "SELECT * FROM 會計科目表"
  79. mycursor.execute(AccountingSubjects)
  80. AccountingSubjects_data = mycursor.fetchall()
  81. # print("AccountingSubjects_data", AccountingSubjects_data)
  82. # # (('01', '成品'), ('02', '系統成品'), ('03', '模組半成品'), ('04', '零件'), ('05', '工具'))
  83. # 獲取類別欄位
  84. Category = "SELECT * FROM 類別表"
  85. mycursor.execute(Category)
  86. Category_data = mycursor.fetchall()
  87. # 獲取供應商欄位
  88. Supplier = "SELECT * FROM 供應商"
  89. mycursor.execute(Supplier)
  90. Supplier_data = mycursor.fetchall()
  91. # 獲取零件名稱
  92. Component = "SELECT 名稱 FROM 零件表"
  93. mycursor.execute(Component)
  94. Component_data = mycursor.fetchall()
  95. # # --- 新增會計科目項目用 -----------------------------------------------------------------------------------------
  96. accountingsubject_sql = 'SELECT 會計科目_編號 FROM 會計科目表 ORDER BY 會計科目_編號 DESC LIMIT 1'
  97. # print("accountingsubject_sql: ", accountingsubject_sql)
  98. mycursor.execute(accountingsubject_sql)
  99. content = mycursor.fetchall()
  100. try:
  101. # print("content: ", content[0][0], type(content[0][0]))
  102. new_as_sn = int(content[0][0])+1
  103. new_as_sn = '{0:02d}'.format(new_as_sn)
  104. except IndexError:
  105. new_as_sn = '01'
  106. # # --- 新增類別項目用 -----------------------------------------------------------------------------------------
  107. category_sql = 'SELECT 類別_編號 FROM 類別表 ORDER BY 類別_編號 DESC LIMIT 1'
  108. mycursor.execute(category_sql)
  109. content = mycursor.fetchall()
  110. try:
  111. new_ca_sn = int(content[0][0])+1
  112. new_ca_sn = '{0:02d}'.format(new_ca_sn)
  113. except IndexError:
  114. new_ca_sn = '01'
  115. # # --- 新增供應商項目用 -----------------------------------------------------------------------------------------
  116. supplier_sql = 'SELECT 供應商 FROM 供應商 ORDER BY 供應商 DESC LIMIT 1'
  117. mycursor.execute(supplier_sql)
  118. content = mycursor.fetchall()
  119. try:
  120. print("content[0][0][1:]: ", content[0][0][1:])
  121. new_su_sn = int(content[0][0][1:])+1
  122. new_su_sn = content[0][0][:1] + '{0:02d}'.format(new_su_sn)
  123. except IndexError:
  124. new_su_sn = 'T01'
  125. return render_template('create_component_table_item.html', title='新增零件', **locals())
  126. # ERP 測試 四層下拉式選單關聯
  127. @app.route('/drop_down_list', methods=['GET', 'POST'])
  128. def drop_down_list():
  129. conn = pymysql.connect(
  130. host='52.69.200.169',
  131. port=3306,
  132. user='coffee',
  133. password='skyeye',
  134. database='Coffee',
  135. charset='utf8'
  136. )
  137. cur = conn.cursor()
  138. #獲取欄位資料
  139. sql = "select * from product_info"
  140. cur.execute(sql)
  141. content = cur.fetchall()
  142. #獲取欄位名稱
  143. sql = "SHOW FIELDS FROM product_info"
  144. cur.execute(sql)
  145. labels = cur.fetchall()
  146. # print("labels: ", labels) # labels: (('產品', 'varchar(4)', 'YES', '', None, ''), ('系統', 'varchar(5)', 'YES', '', None, ''),
  147. labels = [g[0] for g in labels]
  148. # print("labels: ", labels) # labels: ['產品', '系統', '系統圖號', '狀態', '進貨狀態', '序號', '組序號',
  149. return render_template('drop_down_list.html', labels=labels, content=content)
  150. # ERP 測試
  151. @app.route('/search', methods=['GET', 'POST'])
  152. def search():
  153. # 開啟本機 erp 資料庫
  154. mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='erp', charset='utf8')
  155. mycursor = mydb.cursor()
  156. # 獲取欄位資料
  157. # sql = '''SELECT * FROM table_component_name'''
  158. sql = '''SELECT 內部料號, 會計科目表.會計科目_名稱, 類別表.類別_名稱, 流水號, 供應商.公司, 名稱
  159. FROM (
  160. (零件表
  161. INNER JOIN 供應商
  162. ON 供應商.供應商 = 零件表.供應商
  163. )
  164. INNER JOIN 類別表
  165. ON 類別表.類別_編號 = 零件表.類別
  166. )
  167. INNER JOIN 會計科目表
  168. ON 會計科目表.會計科目_編號 = 零件表.會計科目
  169. '''
  170. mycursor.execute(sql)
  171. content = mycursor.fetchall()
  172. #獲取欄位名稱
  173. sql = "SHOW FIELDS FROM 零件表"
  174. mycursor.execute(sql)
  175. labels = mycursor.fetchall()
  176. # print("labels: ", labels)
  177. # # labels: (('產品', 'varchar(4)', 'YES', '', None, ''), ('系統', 'varchar(5)', 'YES', '', None, ''),
  178. labels = [g[0] for g in labels]
  179. # print("labels: ", labels)
  180. # # labels: ['產品', '系統', '系統圖號', '狀態', '進貨狀態', '序號', '組序號',
  181. # 獲取會計科目欄位
  182. AccountingSubjects = "SELECT * FROM 會計科目表"
  183. mycursor.execute(AccountingSubjects)
  184. AccountingSubjects_data = mycursor.fetchall()
  185. # print("AccountingSubjects_data", AccountingSubjects_data)
  186. # # (('01', '成品'), ('02', '系統成品'), ('03', '模組半成品'), ('04', '零件'), ('05', '工具'))
  187. # 獲取類別欄位
  188. Category = "SELECT * FROM 類別表"
  189. mycursor.execute(Category)
  190. Category_data = mycursor.fetchall()
  191. # 獲取供應商欄位
  192. Supplier = "SELECT * FROM 供應商"
  193. mycursor.execute(Supplier)
  194. Supplier_data = mycursor.fetchall()
  195. # 獲取零件名稱
  196. Component = "SELECT 名稱 FROM 零件表"
  197. mycursor.execute(Component)
  198. Component_data = mycursor.fetchall()
  199. return render_template('search.html', title = 'ERP Search', **locals())
  200. # 找到 serial number 最大值後 +1
  201. @app.route('/sn_get/<AccountSubject>/<Category>', methods=['GET', 'POST'])
  202. def zn_get(AccountSubject, Category):
  203. # 開啟本機 erp 資料庫
  204. mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='erp', charset='utf8')
  205. mycursor = mydb.cursor()
  206. # 取得流水號最大值
  207. sql = 'SELECT 流水號 FROM 零件表 '
  208. sql += 'WHERE 會計科目 = "' + AccountSubject + '" AND 類別 = "' + Category + '" ORDER BY 流水號 DESC LIMIT 1'
  209. print("sql: ", sql)
  210. mycursor.execute(sql)
  211. content = mycursor.fetchall()
  212. try:
  213. print("content: ", content[0][0], type(content[0][0]))
  214. new_sn = int(content[0][0])+1
  215. new_sn = '{0:04d}'.format(new_sn)
  216. except IndexError:
  217. new_sn = '0001'
  218. return jsonify({"new_sn":new_sn})
  219. # 匯出 Excel
  220. @app.route('/export_excel/<BOM_company_id>', methods=['GET'])
  221. def export_excel(BOM_company_id):
  222. mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='erp', charset='utf8')
  223. mycursor = mydb.cursor()
  224. info = request.args.to_dict('sql')
  225. sql = info['sql']
  226. # print("sql: ", sql)
  227. mycursor.execute(sql)
  228. sql_data = mycursor.fetchall()
  229. sql_data = [g for g in sql_data]
  230. print("sql_data: ", sql_data)
  231. sql_data_new = [] # 外面的 LIST
  232. # BOM 表欄位名稱
  233. sql_field = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + BOM_company_id + "'"
  234. print("sql_field: ", sql_field)
  235. mycursor.execute(sql_field)
  236. sql_field = mycursor.fetchall()
  237. sql_field = [g for g in sql_field]
  238. F = []
  239. for f in range(0, len(sql_field)):
  240. F.append(sql_field[f][0])
  241. # 增加輸出 BOM 表易讀性, 增加 零件表.名稱
  242. F.insert(1, '名稱')
  243. sql_data_new.append(F)
  244. print("sql_data_new: ", sql_data_new)
  245. # BOM 表內容
  246. for i in range(0, len(sql_data)):
  247. J = [] # 裡面的 LIST
  248. for j in range(0, len(sql_data[i])):
  249. J.append(sql_data[i][j])
  250. sql_data_new.append(J)
  251. print("sql_data_new: ", sql_data_new, type(sql_data_new))
  252. # 匯出成 Excel
  253. df = pd.DataFrame(sql_data_new)
  254. writer = pd.ExcelWriter('C:/Users/USER/Downloads/BOM_' + str(BOM_company_id) + '_' + str(datetime.today().strftime("%m%d")) + '.xlsx', engine='xlsxwriter')
  255. df.to_excel(writer, sheet_name=BOM_company_id, encoding='utf8', header=None, index=False)
  256. writer.save()
  257. mydb.commit()
  258. return jsonify({"file_location":'C:/Users/USER/Downloads/BOM__' + str(BOM_company_id) + '_' + str(datetime.today().strftime("%m%d")) + '.xlsx'})
  259. # 從資料表找出符合篩選條件之資料
  260. @app.route('/sql_get', methods=['GET'])
  261. def sql_get():
  262. mydb = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='g53743001', database='erp', charset='utf8')
  263. mycursor = mydb.cursor()
  264. # 取得網頁傳回來的 SQL 指令
  265. # sql = "SELECT * FROM 零件表 WHERE 會計科目 = 04"
  266. info = request.args.to_dict('sql')
  267. sql = info['sql']
  268. # print("sql: ", sql)
  269. mycursor.execute(sql)
  270. sql_data = mycursor.fetchall()
  271. # 獲取欄位名稱
  272. # 拆解取得資料表資料
  273. # print("sql_data: ", sql_data)
  274. # # sql_data: (('04030001T01', '04', '03', '0001', 'T01', '電阻-18Ω'), ... )
  275. # Rita 這裡在測試日期格式修改, 優化後調整
  276. # if 'INNER JOIN 庫存表' in sql:
  277. # labels = []
  278. # for g in sql_data:
  279. # # timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
  280. # print("g[0]: ", g[0], type(g[0]), g[0].strftime("%Y-%m-%d %H:%M:%S"))
  281. # timeString = g[0].strftime("%Y-%m-%d %H:%M:%S")
  282. # print("timeString: ", timeString, type(timeString))
  283. # labels.append(timeString)
  284. # # labels.append(time.strftime("%Y-%m-%d %H:%M:%S"))
  285. # labels.append(g[1])
  286. # labels.append(g[2])
  287. # else:
  288. # labels = [g for g in sql_data]
  289. labels = [g for g in sql_data]
  290. # 取得欄位資料
  291. if 'INNER JOIN 規格表' in sql:
  292. sql_field = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '規格表'"
  293. elif 'INNER JOIN 庫存表' in sql:
  294. sql_field = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '庫存表' LIMIT 3"
  295. elif 'INNER JOIN 銷貨表' in sql:
  296. sql_field = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '銷貨表'"
  297. elif 'INNER JOIN 進貨表' in sql:
  298. sql_field = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '進貨表'"
  299. elif '`' in sql:
  300. table_name = sql[sql.find('`')+1:]
  301. table_name = table_name[:table_name.find('`')]
  302. sql_field = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + table_name + "'"
  303. else:
  304. sql_field = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '零件表'"
  305. mycursor.execute(sql_field)
  306. sql_field = mycursor.fetchall()
  307. mydb.commit()
  308. return jsonify({"sql_data":sql_data,
  309. "labels":labels,
  310. "sql_field":sql_field})
  311. #自動關閉所有未使用、掛著的連接
  312. @app.teardown_appcontext
  313. def shutdown_session(exception=None):
  314. # db.session.remove()
  315. pass
  316. if __name__ == '__main__':
  317. app.run(debug=False, threaded=True, port=5010)