main.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  1. import xml.etree.ElementTree as ET
  2. from typing import Union
  3. from fastapi import FastAPI
  4. import os
  5. import uuid
  6. import re
  7. import zipfile
  8. import json
  9. from fastapi.middleware.cors import CORSMiddleware
  10. from fastapi.middleware.gzip import GZipMiddleware
  11. import base64
  12. from pydantic import BaseModel
  13. from subdir import service
  14. from subdir import db
  15. from subdir import util
  16. import xml.dom.minidom as MD
  17. import numpy as np
  18. from fastapi.staticfiles import StaticFiles
  19. from pymongo import AsyncMongoClient
  20. client = AsyncMongoClient()
  21. from fastapi.responses import FileResponse
  22. from fastapi import WebSocket, WebSocketDisconnect
  23. from fastapi import UploadFile
  24. class ConnectionManager:
  25. """Class defining socket events"""
  26. def __init__(self):
  27. """init method, keeping track of connections"""
  28. self.active_connections = []
  29. async def connect(self, websocket: WebSocket):
  30. """connect event"""
  31. await websocket.accept()
  32. self.active_connections.append(websocket)
  33. async def send_personal_message(self, message: str, websocket: WebSocket):
  34. """Direct Message"""
  35. await websocket.send_text(message)
  36. def disconnect(self, websocket: WebSocket):
  37. """disconnect event"""
  38. self.active_connections.remove(websocket)
  39. app = FastAPI()
  40. origins = [
  41. "http://localhost.tiangolo.com",
  42. "https://localhost.tiangolo.com",
  43. "http://localhost",
  44. "http://localhost:9002",
  45. "http://127.0.0.1:9002",
  46. ]
  47. app.add_middleware(
  48. CORSMiddleware,
  49. allow_origins=["*"],
  50. allow_credentials=True,
  51. allow_methods=["*"],
  52. allow_headers=["*"],
  53. )
  54. ##app.add_middleware(GZipMiddleware, minimum_size=1000, compresslevel=5)
  55. ##app.mount("/static", StaticFiles(directory="front/dist"), name="static")
  56. ##manager = ConnectionManager()
  57. class Info(BaseModel):
  58. name: str
  59. class DingeshuRequest(BaseModel):
  60. value: int
  61. class DingeXilieRequest(BaseModel):
  62. value: int
  63. id: str
  64. class SingleDingeXilieRequest(BaseModel):
  65. zhuanye: int
  66. debh: str
  67. class InfoWithID(BaseModel):
  68. name: str
  69. id: str
  70. class Tiaojia(BaseModel):
  71. biao_id: str
  72. bh: str
  73. bm: str
  74. mingcheng: str
  75. danwei: str
  76. jiage: str
  77. glf: str
  78. lr: str
  79. bz: int
  80. class SearchDe(BaseModel):
  81. zhuanye: str
  82. text: str
  83. class UpdateZjcs(BaseModel):
  84. biao_id: str
  85. bh: str
  86. mc: str
  87. fl: str
  88. @app.post("/outline2")
  89. async def read_root2(info: Info):
  90. return await db.getOutline(client, info.name)
  91. @app.post("/detail2")
  92. async def read_detail2(info: Info):
  93. return await db.getDetail(client, info.name)
  94. @app.post("/baojiahuizong2/")
  95. async def read_bjhz2(info: InfoWithID):
  96. raw = await db.getBjhz(client, info.name, info.id)
  97. raw2 = []
  98. for entry in raw:
  99. if "__children" in entry:
  100. entry["_children"] = entry["__children"]
  101. for grandchild in entry["_children"]:
  102. if "__children" in grandchild:
  103. grandchild['_children'] = grandchild['__children']
  104. del grandchild['__children']
  105. del entry["__children"]
  106. raw2.append(entry)
  107. return raw2
  108. @app.post("/guifeishuijin2/")
  109. async def read_gfsj2(info: InfoWithID):
  110. raw = await db.getGfsj(client, info.name, info.id)
  111. raw2 = []
  112. for entry in raw:
  113. if "__children" in entry:
  114. entry["_children"] = entry["__children"]
  115. del entry["__children"]
  116. raw2.append(entry)
  117. return raw2
  118. @app.post("/qitaxiangmu2/")
  119. async def read_qtxm2(info: InfoWithID):
  120. raw = await db.getQtxm(client, info.name, info.id)
  121. raw2 = []
  122. for entry in raw:
  123. if "__children" in entry:
  124. entry["_children"] = entry["__children"]
  125. del entry["__children"]
  126. raw2.append(entry)
  127. return raw2
  128. @app.post("/zygczgj/")
  129. async def zygczgj(info: InfoWithID):
  130. return await db.getZygczgj(client, info.name, info.id)
  131. @app.post("/zanliejine2/")
  132. async def read_zlje2(info: InfoWithID):
  133. return await db.getZlje(client, info.name, info.id)
  134. @app.post("/jirigong2/")
  135. async def read_jrg2(info: InfoWithID):
  136. return await db.getJrg(client, info.name, info.id)
  137. @app.post("/zongchengbaofuwufei2/")
  138. async def read_zcbfwf2(info: InfoWithID):
  139. return await db.getZcbfwf(client, info.name, info.id)
  140. @app.post("/fabaorengongyingcailiao2/")
  141. async def read_fbrgycl2(info: InfoWithID):
  142. return await db.getFbrgycl(client, info.name, info.id)
  143. @app.post("/rencaijihuizong2/")
  144. async def read_rcjhz2(info: InfoWithID):
  145. return await db.getRcjhz(client, info.name, info.id)
  146. @app.post("/qingdanxiangmu2/")
  147. async def read_qdxm2(info: InfoWithID):
  148. return await db.getQdxm(client, info.name, info.id)
  149. class Item(BaseModel):
  150. bh: str
  151. bt: str
  152. name: str
  153. class Rcj(BaseModel):
  154. bh: str
  155. bt: str
  156. bm: str
  157. name: str
  158. class Dercj(BaseModel):
  159. bh: str
  160. bt: str
  161. qdbm: str
  162. debm: str
  163. name: str
  164. class Zjcs(BaseModel):
  165. bh: str
  166. name: str
  167. @app.post("/qingdanmingxi/")
  168. async def read_qdmx(item : Item):
  169. return await db.getQdmx(client, item.name, item.bh, item.bt)
  170. @app.post("/qingdanrcj/")
  171. async def read_rcj(item : Rcj):
  172. if item.bt == "Djcs":
  173. return await db.getDjcsQingdanrcj(client, item.name, item.bh, item.bt, item.bm)
  174. return await db.getQingdanrcj(client, item.name, item.bh, item.bt, item.bm)
  175. @app.post("/qingdantuijian/")
  176. async def read_tuijian(item : Rcj):
  177. return service.getQingdanTuijian(item.bh, item.bt, item.bm)
  178. @app.post("/dingercj/")
  179. async def read_dercj(item : Dercj):
  180. if item.bt == "Djcs":
  181. return await db.getDjcsDingercj(client, item.name, item.bh, item.bt, item.qdbm, item.debm)
  182. return await db.getDingercj(client, item.name, item.bh, item.bt, item.qdbm, item.debm)
  183. @app.post("/zjcs/")
  184. async def read_zjcs(item : Zjcs):
  185. raw = await db.getZjcs(client, item.name, item.bh)
  186. raw2 = []
  187. for entry in raw:
  188. if "__children" in entry:
  189. entry["_children"] = entry["__children"]
  190. del entry["__children"]
  191. raw2.append(entry)
  192. return raw2
  193. @app.post("/djcs/")
  194. async def read_djcs(item : Zjcs):
  195. raw = await db.getDjcs(client, item.name, item.bh)
  196. raw2 = []
  197. for entry in raw:
  198. if "__children" in entry:
  199. entry["_children"] = entry["__children"]
  200. del entry["__children"]
  201. raw2.append(entry)
  202. return raw2
  203. @app.post("/files2/")
  204. async def read_files2():
  205. result = await db.list_files(client)
  206. return result
  207. @app.post("/deleteFile/")
  208. async def delete(r: Info):
  209. result = await db.delete_files(client, r.name)
  210. return result
  211. @app.post("/des/")
  212. async def read_des(r: DingeshuRequest):
  213. result = service.getDes(r.value)
  214. if r.value == 30:
  215. result.append({
  216. "id": "2075",
  217. "key" : "2075",
  218. "value" : "2075",
  219. "label" : "安装费用",
  220. "title" : "安装费用",
  221. "children" : [
  222. {
  223. "id": "2076",
  224. "key" : "2076",
  225. "value" : "2076",
  226. "label" : "脚手架搭拆费",
  227. "title" : "脚手架搭拆费",
  228. "children" : []
  229. },
  230. {
  231. "id": "2077",
  232. "key" : "2077",
  233. "value" : "2077",
  234. "label" : "施工超高增加费",
  235. "title" : "施工超高增加费",
  236. "children" : []
  237. },
  238. {
  239. "id": "2078",
  240. "key" : "2078",
  241. "value" : "2078",
  242. "label" : "安装生产同时增加费",
  243. "title" : "安装生产同时增加费",
  244. "children" : []
  245. },
  246. {
  247. "id": "2079",
  248. "key" : "2079",
  249. "value" : "2079",
  250. "label" : "有害环境操作增加费",
  251. "title" : "有害环境操作增加费",
  252. "children" : []
  253. },
  254. {
  255. "id": "2080",
  256. "key" : "2080",
  257. "value" : "2080",
  258. "label" : "高层建筑增加费",
  259. "title" : "高层建筑增加费",
  260. "children" : [
  261. {
  262. "id": "2081",
  263. "key" : "2081",
  264. "value" : "2081",
  265. "label" : "第四册",
  266. "title" : "第四册",
  267. "children" : []
  268. },
  269. {
  270. "id": "2082",
  271. "key" : "2082",
  272. "value" : "2082",
  273. "label" : "第五册",
  274. "title" : "第五册",
  275. "children" : []
  276. },
  277. {
  278. "id": "2083",
  279. "key" : "2083",
  280. "value" : "2083",
  281. "label" : "第七册",
  282. "title" : "第七册",
  283. "children" : []
  284. },
  285. {
  286. "id": "2084",
  287. "key" : "2084",
  288. "value" : "2084",
  289. "label" : "第九册",
  290. "title" : "第九册",
  291. "children" : []
  292. },
  293. {
  294. "id": "2085",
  295. "key" : "2085",
  296. "value" : "2085",
  297. "label" : "第十册",
  298. "title" : "第十册",
  299. "children" : []
  300. },
  301. {
  302. "id": "2086",
  303. "key" : "2086",
  304. "value" : "2086",
  305. "label" : "第十一册",
  306. "title" : "第十一册",
  307. "children" : []
  308. },
  309. ]
  310. },
  311. {
  312. "id": "2087",
  313. "key" : "2087",
  314. "value" : "2087",
  315. "label" : "系统调试费",
  316. "title" : "系统调试费",
  317. "children" : []
  318. },
  319. ]
  320. })
  321. return result
  322. @app.post("/pbs/")
  323. async def read_pbs(r: DingeshuRequest):
  324. result = service.getPbs(r.value)
  325. #print(result)
  326. result.insert(0, {"id": "0","key": "0", "label": "全部", "title": "全部"})
  327. return result
  328. @app.post("/pbxl/")
  329. async def read_pbxl(r: Info):
  330. result = service.getPbxl(r.name)
  331. #print(result)
  332. return result
  333. @app.post("/cankao/")
  334. async def cankao():
  335. result = service.getCankao()
  336. #print(result)
  337. return result
  338. @app.post("/qufei/")
  339. async def read_qufei(r: Info):
  340. return await db.getQufei(client, r.name)
  341. @app.post("/dexilie/")
  342. async def read_dexilie(r: DingeXilieRequest):
  343. if r.value == 30 and int(r.id) > 2074:
  344. return service.getDeXilie_azfy(r.value, r.id)
  345. result = service.getDeXilie(r.value, r.id)
  346. #print(result)
  347. return result
  348. @app.post("/singledexilie/")
  349. async def read_singledexilie(r: SingleDingeXilieRequest):
  350. if r.debh.startswith("D") :
  351. return json.dumps({
  352. "reverse": "None",
  353. "rgde": None,
  354. "jxde": None,
  355. "clde": None,
  356. "actual_zhuanye": r.zhuanye,
  357. "bz_selected": {"BZBH": {}},
  358. "bz_selected2": {"BZBH": {}}
  359. }, ensure_ascii=False)
  360. if "-F" in r.debh:
  361. return service.read_singledexilie_azfy(r.debh)
  362. r_debh = r.debh.split("#")[0]
  363. result1, result2, rgde, jxde, clde, bz_selected, bz_selected2, actual_zhuanye= service.getSingleDeXilie(r.zhuanye, r_debh)
  364. print("get result ***************************************")
  365. if result1:
  366. result3 = json.loads(result1)
  367. else:
  368. result3 = {}
  369. result3["reverse"] = str(result2)
  370. result3["rgde"] = rgde
  371. result3["jxde"] = jxde
  372. result3["clde"] = clde
  373. result3["actual_zhuanye"] = actual_zhuanye
  374. if bz_selected != None:
  375. result3["bz_selected"] = json.loads(bz_selected)
  376. else:
  377. result3["bz_selected"] = {"BZBH": {}}
  378. if bz_selected2 != None:
  379. result3["bz_selected2"] = json.loads(bz_selected2)
  380. else:
  381. result3["bz_selected2"] = {"BZBH": {}}
  382. if "[" in r_debh:
  383. position3 = r_debh.find("*")
  384. coef = 1
  385. if position3 == -1:
  386. pass
  387. else:
  388. coef = r_debh[1 + position3:]
  389. print(coef)
  390. tail = 0
  391. for i in range(0, len(coef) + 1):
  392. if i == len(coef):
  393. tail = i
  394. break
  395. if coef[i] > '9' or coef[i] < '0':
  396. tail = i
  397. break
  398. if tail == 0:
  399. print("1113111")
  400. result3["reverse"] = 'None'
  401. return json.dumps(result3, ensure_ascii=False)
  402. coef = int(coef[0:tail])
  403. position1 = r_debh.find("[")
  404. position2 = r_debh.find("]")
  405. if position2 == -1:
  406. print("1121111")
  407. result3["reverse"] = 'None'
  408. return json.dumps(result3, ensure_ascii=False)
  409. if r_debh[position1-1] == "+":
  410. pass
  411. elif r_debh[position1-1] == "-":
  412. coef = -coef
  413. else:
  414. print("111111")
  415. result3["reverse"] = 'None'
  416. return json.dumps(result3, ensure_ascii=False)
  417. debh = r_debh[position1+1: position2]
  418. if result3['GLDE']: ##csv文件里的字段,表示这个定额有没有配套的增减定额
  419. hit = False
  420. for key, value in result3['GLDE'].items():
  421. if value == debh:
  422. hit = True
  423. if not hit:
  424. result3["reverse"] = 'None'
  425. return json.dumps(result3, ensure_ascii=False)
  426. else:
  427. result3["reverse"] = 'None'
  428. return json.dumps(result3, ensure_ascii=False)
  429. result1_, result2_, rgde_, jxde_, clde_, bz_selected_, bz_selected2_, actual_zhuanye_ = service.getSingleDeXilie(r.zhuanye, debh)
  430. if result1_:
  431. util.mergerg(rgde, rgde_, coef)
  432. util.mergejx(jxde, jxde_, coef)
  433. util.mergecl(clde, clde_, coef)
  434. result3["rgde"] = rgde
  435. result3["jxde"] = jxde
  436. result3["clde"] = clde
  437. item_ = None
  438. for item in result3['DW'].keys():
  439. item_ = item
  440. result3['DEBH'] = {item_: util.cleanBM(r_debh)}
  441. else:
  442. result3["reverse"] = 'None'
  443. return json.dumps(result3, ensure_ascii=False)
  444. @app.post("/save/")
  445. async def save(r: Info):
  446. data = json.loads(r.name)
  447. ##print(data)
  448. return await db.save(client, data)
  449. @app.post("/savedjcs/")
  450. async def savedjcs(r: Info):
  451. data = json.loads(r.name)
  452. ##print(data)
  453. return await db.savedjcs(client, data)
  454. @app.post("/applyFL/")
  455. async def applyFL(r: InfoWithID):
  456. data = json.loads(r.name)
  457. print(data)
  458. return await db.applyFL(client, r.id, data)
  459. @app.post("/tiaojia/")
  460. async def tiaojia(r: Tiaojia):
  461. ##return []
  462. glf = r.glf
  463. lr = r.lr
  464. if r.glf == '':
  465. glf = '0'
  466. if r.lr == "":
  467. lr = '0'
  468. return await db.tiaojia(client, r.biao_id, r.bh, r.bm, r.mingcheng, r.danwei, r.jiage, glf, lr, r.bz)
  469. @app.post("/searchde/")
  470. async def searchde(r: SearchDe):
  471. ##return []
  472. return await db.searchde(client, r.zhuanye, r.text)
  473. @app.post("/updatezjcs/")
  474. async def updatezjcs(r: UpdateZjcs):
  475. ##return []
  476. return await db.updatezjcs(client, r.biao_id, r.bh, r.mc, r.fl)
  477. @app.post("/upload/")
  478. async def upload(file: UploadFile):
  479. if file.filename.endswith('13jz') or file.filename.endswith("13jt"):
  480. content = await file.read()
  481. string = content.decode('utf-8')
  482. await resolve(string)
  483. return [file.filename]
  484. elif file.filename.endswith("jszf"):
  485. content = await file.read()
  486. string = content.decode('utf-8')
  487. root = ET.fromstring(string)
  488. for child in root:
  489. print(child)
  490. if child.tag == "ZBFileContent":
  491. base64_bytes = child.text.encode("ascii")
  492. sample_string_bytes = base64.b64decode(base64_bytes)
  493. tmp = str(uuid.uuid4())
  494. os.mkdir(os.path.join("tmp", tmp))
  495. with open(tmp, "wb") as file_:
  496. file_.write(sample_string_bytes)
  497. with zipfile.ZipFile(tmp, 'r') as zip_ref:
  498. zip_ref.extractall(os.path.join("tmp", tmp))
  499. dir_list = os.listdir(os.path.join("tmp", tmp))
  500. print(dir_list)
  501. for entry in dir_list:
  502. if entry.endswith("13jz"):
  503. with open(os.path.join("tmp", tmp, entry), 'r') as f:
  504. await resolve(f.read())
  505. return [file.filename]
  506. else:
  507. return [file.filename]
  508. @app.get("/download/{item_id}")
  509. async def download_file(item_id):
  510. file_path = "export/contacts.xml.b"
  511. # Create the root element
  512. root = ET.Element("JingJiBiao")
  513. # Create a sub-element
  514. ##TouBiaoXx = ET.SubElement(root, "TouBiaoXx")
  515. await db.build(client, root, item_id)
  516. # Create the tree and write to a file
  517. tree = ET.ElementTree(root)
  518. tree.write("export/contacts.xml", encoding="utf-8")
  519. dom = MD.parse("export/contacts.xml")
  520. with open("export/contacts.xml.b", 'w') as f:
  521. f.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
  522. content = (dom.toprettyxml(indent=" "))
  523. content_ = content.split("\n")
  524. f.write("\n".join(content_[1:]))
  525. return FileResponse(file_path, media_type='application/octet-stream', filename="contacts.xml")
  526. async def resolve(data):
  527. await db.resolve(data, client)##manager.send_personal_message(f"You wrote: {data}", websocket)
  528. ##@app.websocket("/ws")
  529. ##async def websocket_endpoint(websocket: WebSocket):
  530. ## await manager.connect(websocket)
  531. ## try:
  532. ## while True:
  533. ## data = await websocket.receive_text()
  534. ## await resolve(websocket, data)
  535. ## ##await manager.broadcast(f"Client #{client_id} says: {data}")
  536. ## except WebSocketDisconnect:
  537. ## manager.disconnect(websocket)
  538. ## ##await manager.broadcast(f"Client left the chat")