genjson_request.py 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577
  1. import os
  2. from typing import Optional
  3. from dataset.util import ResultIter
  4. from fastapi import FastAPI
  5. from fastapi.middleware.cors import CORSMiddleware
  6. from pytrends.request import TrendReq
  7. from datetime import tzinfo
  8. import datetime
  9. import mysql.connector
  10. from mysql.connector import Error
  11. from io import BytesIO
  12. from fastapi.responses import StreamingResponse
  13. import xlsxwriter
  14. import pandas as pd
  15. import dataset
  16. import json
  17. from pytube import extract
  18. import random
  19. import boto3
  20. from botocore.exceptions import ClientError
  21. import base64
  22. from pydantic import BaseModel
  23. from datetime import datetime
  24. from email.mime.multipart import MIMEMultipart
  25. from email.mime.text import MIMEText
  26. from email.mime.image import MIMEImage
  27. import jinja2
  28. app = FastAPI()
  29. origins = [
  30. "*"
  31. ]
  32. app.add_middleware(
  33. CORSMiddleware,
  34. allow_origins=origins,
  35. allow_credentials=True,
  36. allow_methods=["*"],
  37. allow_headers=["*"],
  38. )
  39. #https://m3.hhh.com.tw:18687/docs
  40. hhhMBPath = '../hhh-home-mb'
  41. hhhPCPath = '../hhh-home-pc'
  42. # db = dataset.connect(
  43. # 'mysql://hhh7796hhh:lYmWsu^ujcA1@hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com:3306/xoops?charset=utf8mb4')
  44. #2022/12/13 change
  45. db = dataset.connect( 'mysql://hhh7796hhh:lYmWsu^ujcA1@ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com:3306/xoops?charset=utf8mb4')
  46. def ExecuteQuery(isql):
  47. #2022/12/13 change
  48. #host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  49. connection = mysql.connector.connect(
  50. host='ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com',
  51. database='xoops',
  52. user='hhh7796hhh',
  53. password='lYmWsu^ujcA1',
  54. use_unicode=True,
  55. charset='utf8',
  56. collation='utf8_unicode_ci'
  57. )
  58. # connection.set_charset_collation('utf8','utf8_general_ci')
  59. cursor = connection.cursor(dictionary=True)
  60. cursor.execute(isql)
  61. if cursor.rowcount == -1:
  62. return cursor.fetchall()
  63. else:
  64. connection.commit()
  65. return cursor.rowcount
  66. def ExecuteCmd(isql):
  67. #2022/12/13 change
  68. #host='hhh-v57.cmab1ctkglka.ap-northeast-2.rds.amazonaws.com',
  69. connection = mysql.connector.connect(
  70. host='ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com',
  71. database='xoops',
  72. user='hhh7796hhh',
  73. password='lYmWsu^ujcA1'
  74. )
  75. cursor = connection.cursor(dictionary=True)
  76. cursor.execute(isql)
  77. print(cursor.rowcount)
  78. connection.commit()
  79. return None
  80. @app.get("/ExportExecuteDetail")
  81. async def ExportExecuteDetail():
  82. output = BytesIO()
  83. records = ExecuteQuery(""" select f.exf_id, num 合約, company 合約公司,lv1 大項目,lv2 執行項, contract_time 合約到期日,price 金額,sales_man 業務,quota 額度,creator 建立者,is_close 狀態,sdate 上架日期,edate 下架日期,f.note 備註,designer 設計師,mobile 手機,telete 電話,contract_person 聯絡人,detail_status 合約名稱,d.create_time 建立時間,d.update_time 更新時間,last_update 最後更新 from execute_form f
  84. left join execute_detail d on f.exf_id=d.exf_id
  85. where f.is_delete='N' order BY f.exf_id DESC, exd_id
  86. """)
  87. df = pd.DataFrame(list(records))
  88. writer = pd.ExcelWriter(output)
  89. df.to_excel(writer, sheet_name='bar')
  90. writer.save()
  91. """ workbook = xlsxwriter.Workbook(output)
  92. worksheet = workbook.add_worksheet()
  93. for cols in records:
  94. worksheet.write(0, 0, 'ISBN')
  95. worksheet.write(0, 1, 'Name')
  96. worksheet.write(0, 2, 'Takedown date')
  97. worksheet.write(0, 3, 'Last updated')
  98. workbook.close() """
  99. output.seek(0)
  100. headers = {
  101. 'Content-Disposition': 'attachment; filename="execute_detail_all.xlsx"'
  102. }
  103. return StreamingResponse(output, headers=headers, media_type='application/octet-stream')
  104. @app.get("/")
  105. def read_root():
  106. return {"Hello": "World"}
  107. @app.get("/movexoopstostage")
  108. def movexoopstostage(designerid: str = "0", caseid: str = "0"):
  109. ExecuteQuery(
  110. "replace INTO stage._hdesigner SELECT * FROM xoops._hdesigner WHERE hdesigner_id IN ('" + designerid.replace(',', "','")+"');")
  111. ExecuteQuery(
  112. "replace INTO stage._hcase SELECT * FROM xoops._hcase WHERE hcase_id IN ('"+caseid.replace(',', "','")+"');")
  113. ExecuteQuery(
  114. "replace INTO stage._hcase_img SELECT * FROM xoops._hcase_img WHERE hcase_id IN ('"+caseid.replace(',', "','")+"');")
  115. return {"success"}
  116. @app.get("/movepxoopstostage")
  117. def movepxoopstostage(brandid: str = "0", productid: str = "0"):
  118. ExecuteQuery(
  119. "replace INTO stage._hbrand SELECT * FROM xoops._hbrand WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  120. ExecuteQuery(
  121. "replace INTO stage._hbrand_page SELECT * FROM xoops._hbrand_page WHERE hbrand_id IN ('" + brandid.replace(',', "','")+"');")
  122. ExecuteQuery(
  123. "replace INTO stage._hproduct SELECT * FROM xoops._hproduct WHERE id IN ('"+productid.replace(',', "','")+"');")
  124. ExecuteQuery(
  125. "replace INTO stage._hproduct_img SELECT * FROM xoops._hproduct_img WHERE hproduct_id IN ('"+productid.replace(',', "','")+"');")
  126. return {"success"}
  127. @app.get("/movecxoopstostage")
  128. def movecxoopstostage(columnid: str = "0"):
  129. ExecuteQuery(
  130. "replace INTO stage._hcolumn SELECT * FROM xoops._hcolumn WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  131. ExecuteQuery(
  132. "replace INTO stage._hcolumn_img SELECT * FROM xoops._hcolumn_img WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  133. ExecuteQuery(
  134. "replace INTO stage._hcolumn_page SELECT * FROM xoops._hcolumn_page WHERE hcolumn_id IN ('" + columnid.replace(',', "','")+"');")
  135. return {"success"}
  136. @app.get("/genjson")
  137. def genjson(filename: str = "realtime.json"):
  138. jData = json.load(open(hhhMBPath+'/json/data.json', encoding='utf8'))
  139. records = ExecuteQuery("SELECT * FROM _had where (now() between start_time and end_time or ( start_time is null and end_time is null) or ( start_time = '0000-00-00 00:00:00' and end_time = '0000-00-00 00:00:00')) and onoff='1' and adtype like '首八大%' ")
  140. for x in jData:
  141. # 頂部輪播區-新刊頭
  142. if x['id'] == 0:
  143. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  144. WHERE adtype LIKE '新刊頭%'
  145. AND onoff='1'
  146. AND(NOW() BETWEEN start_time AND end_time OR(start_time='0000-00-00 00:00:00' and end_time='0000-00-00 00:00:00') or (start_time is null and end_time is NULL))
  147. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  148. x["data"] = []
  149. for c in records:
  150. a = {'imgUrl': c['mlo'], 'link': str(
  151. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  152. x["data"].append(a)
  153. # print(x["data"])
  154. # 主要輪播區-首八大
  155. if x['id'] == 1:
  156. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  157. WHERE adtype LIKE '首八大%'
  158. AND onoff='1'
  159. AND(NOW() BETWEEN start_time AND end_time OR(start_time='0000-00-00 00:00:00' and end_time='0000-00-00 00:00:00') or (start_time is null and end_time is NULL))
  160. ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)""")
  161. x["data"] = []
  162. for c in records:
  163. a = {'imgUrl': c['mlo'], 'link': str(
  164. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  165. x["data"].append(a)
  166. # print(x["data"])
  167. #tab區塊-最夯設計, 影音實錄, 專欄文章
  168. if x['id'] == 2:
  169. x["data"] = []
  170. records = ExecuteQuery("""SELECT caption TT ,cover IMG, CONCAT('https://hhh.com.tw/cases/detail/',hcase_id,'/') LK, short_desc txt
  171. from _hcase
  172. left join _hdesigner ON _hcase.hdesigner_id=_hdesigner.hdesigner_id
  173. WHERE
  174. _hcase.onoff='1' AND _hdesigner.onoff='1'
  175. AND(NOW() > sdate)
  176. ORDER BY hcase_id DESC
  177. LIMIT 3""")
  178. a = {'tab': '最夯設計', 'data': []}
  179. for c in records:
  180. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  181. 'title': c['TT'], 'description': c['txt']}
  182. a['data'].append(ad)
  183. x["data"].append(a)
  184. records = ExecuteQuery("""SELECT title TT,iframe IMG , CONCAT('https://hhh.com.tw/video-post.php?id=',hvideo_id) LK , name
  185. from _hvideo
  186. ORDER BY hvideo_id DESC
  187. LIMIT 4""")
  188. a = {'tab': '影音實錄', 'data': []}
  189. cnt = 0
  190. for c in records:
  191. if cnt == 0:
  192. cnt += 1
  193. continue
  194. tid = extract.video_id(c['IMG'])
  195. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  196. ad = {'imgUrl': timg, 'link': c['LK'],
  197. 'title': c['name'], 'description': c['TT']}
  198. a['data'].append(ad)
  199. x["data"].append(a)
  200. records = ExecuteQuery("""SELECT ctitle TT,clogo IMG, CONCAT('https://hhh.com.tw/columns/detail/',hcolumn_id,'/') LK, cdesc
  201. from _hcolumn
  202. WHERE onoff='1'
  203. AND NOW() > sdate
  204. ORDER BY hcolumn_id DESC
  205. LIMIT 3""")
  206. a = {'tab': '專欄文章', 'data': []}
  207. for c in records:
  208. ad = {'imgUrl': c['IMG'], 'link': c['LK'],
  209. 'title': c['TT'], 'description': c['cdesc']}
  210. a['data'].append(ad)
  211. x["data"].append(a)
  212. # print(x["data"])
  213. # 主題企劃區
  214. if x['id'] == 3:
  215. records = ExecuteQuery("""SELECT logo lo, CONCAT('https://hhh.com.tw/topic/detail/',htopic_id,'/') lk, `desc`, title FROM _htopic
  216. WHERE onoff = '1'
  217. ORDER BY htopic_id DESC limit 3""")
  218. x["data"] = []
  219. for c in records:
  220. a = {'imgUrl': c['lo'], 'link': str(
  221. c['lk']), 'video': 'false', 'description': c['desc'], 'title': c['title']}
  222. x["data"].append(a)
  223. # print(x["data"])
  224. # 編輯精選
  225. if x['id'] == 4:
  226. records = ExecuteQuery("""SELECT hcolumn_id, ctitle, clogo,cdesc
  227. FROM homepage_set
  228. LEFT JOIN _hcolumn ON mapping_id = hcolumn_id
  229. WHERE outer_set=8
  230. AND homepage_set.onoff='Y'
  231. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  232. ORDER BY inner_sort""")
  233. x["data"] = []
  234. for c in records:
  235. a = {'imgUrl': c['clogo'], 'link': "https://hhh.com.tw/columns/detail/" + str(
  236. c['hcolumn_id']) + "/", 'title': c['ctitle'], 'video': 'false', 'description': c['cdesc']}
  237. x["data"].append(a)
  238. # print(x["data"])
  239. # 首列表廣告
  240. if x['id'] == 5:
  241. records = ExecuteQuery("""SELECT adlogo lo,adlogo_mobile mlo, adhref lk, adlogo_mobile_webp lomwebp, adlogo_webp dwebp FROM _had
  242. WHERE adtype LIKE '首列表廣告%'
  243. AND onoff='1'
  244. AND(NOW() BETWEEN start_time AND end_time OR(start_time='0000-00-00 00:00:00' and end_time='0000-00-00 00:00:00') or (start_time is null and end_time is NULL))
  245. ORDER BY adtype""")
  246. x["data"] = []
  247. for c in records:
  248. a = {'imgUrl': c['mlo'], 'link': str(
  249. c['lk']), 'DimgUrl': c['lo'], 'webp': str(c['lomwebp']), 'Dwebp': str(c['dwebp'])}
  250. x["data"].append(a)
  251. # print(x["data"])
  252. # 來選好物區
  253. if x['id'] == 6:
  254. records = ExecuteQuery(
  255. "SELECT max_row from outer_site_set WHERE title='來選好貨'")
  256. maxrow = 1
  257. for c in records:
  258. maxrow = c['max_row']
  259. records = ExecuteQuery("""(SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) COLLATE utf8_general_ci caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) COLLATE utf8_general_ci J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) COLLATE utf8_general_ci short_desc
  260. , (case when theme_type='case' then CONCAT('https://hhh.com.tw/cases/detail/d/',mapping_id) when theme_type='column' then CONCAT('https://hhh.com.tw/columns/detail/',mapping_id) when theme_type='product' then CONCAT('https://hhh.com.tw/product-post.php?id=',mapping_id) when theme_type='video' then CONCAT('https://hhh.com.tw/video-post.php?id=',mapping_id) ELSE '' END) url
  261. -- SELECT *
  262. FROM homepage_set
  263. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  264. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  265. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  266. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  267. WHERE homepage_set.onoff='Y'
  268. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='來選好貨')
  269. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  270. ORDER BY outer_set, inner_sort)
  271. UNION
  272. (SELECT 'product', id, `name`, cover, NULL ,descr ,CONCAT('https://hhh.com.tw/product-post.php?id=',id) FROM _hproduct WHERE onoff='1' ORDER BY id DESC LIMIT """ + str(maxrow) + """)
  273. LIMIT """ + str(maxrow))
  274. x["data"] = []
  275. for c in records:
  276. #print(c)
  277. if c['iframe'] is None:
  278. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  279. c['J'] = c['J'].decode('utf8')
  280. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  281. c['caption'] = c['caption'].decode('utf8')
  282. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  283. c['short_desc'] = c['short_desc'].decode('utf8')
  284. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  285. 'description': c['short_desc'], 'video': 'false'}
  286. else:
  287. tid = extract.video_id(str(c['iframe']))
  288. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  289. ccaption = ""
  290. cdescription = ""
  291. if isinstance(c['caption'], bytearray):
  292. ccaption = str(c['caption'].decode('utf8'))
  293. else:
  294. ccaption = str(c['caption'])
  295. if c['short_desc'] is not None:
  296. if isinstance(c['short_desc'], bytes):
  297. cdescription = str(c['short_desc'].decode('utf8'))
  298. else:
  299. cdescription = str(c['short_desc'])
  300. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  301. 'description': cdescription, 'video': tid}
  302. x["data"].append(a)
  303. # print(x["data"])
  304. # 本週推薦
  305. if x['id'] == 7:
  306. records = ExecuteQuery(
  307. "SELECT max_row from outer_site_set WHERE title='本週推薦'")
  308. maxrow = 1
  309. for c in records:
  310. maxrow = c['max_row']
  311. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) short_desc
  312. , (case when theme_type='case' then CONCAT('https://hhh.com.tw/cases/detail/d/',mapping_id) when theme_type='column' then CONCAT('https://hhh.com.tw/columns/detail/',mapping_id) when theme_type='product' then CONCAT('https://hhh.com.tw/product-post.php?id=',mapping_id) when theme_type='video' then CONCAT('https://hhh.com.tw/video-post.php?id=',mapping_id) ELSE '' END) url
  313. -- SELECT *
  314. FROM homepage_set
  315. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  316. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  317. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  318. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  319. WHERE homepage_set.onoff='Y'
  320. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='本週推薦')
  321. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  322. ORDER BY outer_set, inner_sort
  323. LIMIT """ + str(maxrow))
  324. x["data"] = []
  325. for c in records:
  326. if c['iframe'] is None:
  327. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  328. c['J'] = c['J'].decode('utf8')
  329. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  330. c['caption'] = c['caption'].decode('utf8')
  331. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  332. c['short_desc'] = c['short_desc'].decode('utf8')
  333. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  334. 'description': c['short_desc'], 'video': 'false'}
  335. else:
  336. tid = extract.video_id(str(c['iframe']))
  337. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  338. ccaption = ""
  339. cdescription = ""
  340. if isinstance(c['caption'], bytearray):
  341. ccaption = str(c['caption'].decode('utf8'))
  342. else:
  343. ccaption = str(c['caption'])
  344. if c['short_desc'] is not None:
  345. if isinstance(c['short_desc'], bytes):
  346. cdescription = str(c['short_desc'].decode('utf8'))
  347. else:
  348. cdescription = str(c['short_desc'])
  349. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  350. 'description': cdescription, 'video': tid}
  351. x["data"].append(a)
  352. # print(x["data"])
  353. # 粉絲推薦
  354. if x['id'] == 8:
  355. records = ExecuteQuery(
  356. "SELECT max_row from outer_site_set WHERE title='粉絲推薦'")
  357. maxrow = 1
  358. for c in records:
  359. maxrow = c['max_row']
  360. records = ExecuteQuery("""SELECT theme_type, mapping_id, IFNULL(ifnull(ifnull(_hcase.caption,_hcolumn.ctitle),_hproduct.name),_hvideo.title) caption , IFNULL(ifnull(_hcase.cover,_hcolumn.clogo),_hproduct.cover) J, iframe , IFNULL(ifnull(ifnull(_hcase.short_desc,_hcolumn.cdesc),_hproduct.descr),_hvideo.`desc`) short_desc
  361. , (case when theme_type='case' then CONCAT('https://hhh.com.tw/cases/detail/d/',mapping_id) when theme_type='column' then CONCAT('https://hhh.com.tw/columns/detail/',mapping_id) when theme_type='product' then CONCAT('https://hhh.com.tw/product-post.php?id=',mapping_id) when theme_type='video' then CONCAT('https://hhh.com.tw/video-post.php?id=',mapping_id) ELSE '' END) url
  362. -- SELECT *
  363. FROM homepage_set
  364. left join _hcase ON _hcase.hcase_id=homepage_set.mapping_id AND theme_type='case'-- AND _hcase.onoff = '1'
  365. LEFT JOIN _hproduct ON mapping_id = _hproduct.id AND theme_type='product'-- AND _hproduct.onoff = '1'
  366. LEFT JOIN _hcolumn ON mapping_id = _hcolumn.hcolumn_id AND theme_type='column'-- AND _hcolumn.onoff = '1'
  367. LEFT JOIN _hvideo ON mapping_id = _hvideo.hvideo_id AND theme_type='video'
  368. WHERE homepage_set.onoff='Y'
  369. AND outer_set = (SELECT oss_id from outer_site_set WHERE title='粉絲推薦')
  370. AND(NOW() BETWEEN homepage_set.start_time AND homepage_set.end_time OR(homepage_set.start_time='0000-00-00 00:00:00' and homepage_set.end_time='0000-00-00 00:00:00') or (homepage_set.start_time is null and homepage_set.end_time is NULL))
  371. ORDER BY outer_set, inner_sort
  372. LIMIT """ + str(maxrow))
  373. x["data"] = []
  374. for c in records:
  375. if c['iframe'] is None:
  376. if isinstance(c['J'], bytearray) or isinstance(c['J'], bytes):
  377. c['J'] = c['J'].decode('utf8')
  378. if isinstance(c['caption'], bytearray) or isinstance(c['caption'], bytes):
  379. c['caption'] = c['caption'].decode('utf8')
  380. if isinstance(c['short_desc'], bytearray) or isinstance(c['short_desc'], bytes):
  381. c['short_desc'] = c['short_desc'].decode('utf8')
  382. a = {'imgUrl': c['J'], 'link': c['url'], 'title': c['caption'],
  383. 'description': c['short_desc'], 'video': 'false'}
  384. else:
  385. tid = extract.video_id(str(c['iframe']))
  386. timg = "https://img.youtube.com/vi/" + tid+"/hqdefault.jpg"
  387. ccaption = ""
  388. cdescription = ""
  389. if isinstance(c['caption'], bytearray):
  390. ccaption = str(c['caption'].decode('utf8'))
  391. else:
  392. ccaption = str(c['caption'])
  393. if c['short_desc'] is not None:
  394. if isinstance(c['short_desc'], bytes):
  395. cdescription = str(c['short_desc'].decode('utf8'))
  396. else:
  397. cdescription = str(c['short_desc'])
  398. a = {'imgUrl': timg, 'link': c['url'], 'title': ccaption,
  399. 'description': cdescription, 'video': tid}
  400. x["data"].append(a)
  401. # print(x["data"])
  402. if x['id'] == 9:
  403. records = ExecuteQuery(
  404. "SELECT id, (case when youtube_title = '' OR youtube_title IS NULL then (SELECT title FROM _hvideo ORDER BY hvideo_id DESC LIMIT 1) ELSE youtube_title END) T, (case when youtube_id = '' OR youtube_id IS NULL then (SELECT iframe FROM _hvideo ORDER BY hvideo_id DESC LIMIT 1) ELSE youtube_id end) Y FROM site_setup")
  405. for c in records:
  406. x['title'] = ""
  407. if isinstance(c['T'], bytearray):
  408. x['title'] = str(c['T'].decode('utf8'))
  409. else:
  410. x['title'] = str(c['T'])
  411. x['yt'] = extract.video_id(str(c['Y']))
  412. # print(id)
  413. if x['id'] == 10:
  414. records = ExecuteQuery(
  415. "SELECT all_search_tag ast FROM site_setup")
  416. x["data"] = []
  417. for c in records:
  418. x["data"] = c['ast'].split(',')
  419. # print(id)
  420. # print(jData)
  421. """ if not os.path.exists(hhhMBPath):
  422. os.mkdir(hhhMBPath)
  423. with open(hhhMBPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  424. json.dump(jData, f, ensure_ascii=False, indent=4)
  425. if not os.path.exists(hhhPCPath):
  426. os.mkdir(hhhPCPath)
  427. with open(hhhPCPath+'/json/' + filename, 'w', encoding='utf-8') as f:
  428. json.dump(jData, f, ensure_ascii=False, indent=4) """
  429. return jData
  430. @app.get("/gendesigner_list_six")
  431. def gendesigner_list_six(sort: str = "new", page: str="1",city: str = "0", county: str="0",region:str="0",dtype:str="0",dstyle:str="0",budget:str="0",arch:str="0",award:str="0",agent:str="0"):
  432. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  433. condition = ""
  434. if city != "0":
  435. condition+=""" and (t2.address like '%"""+city+"""%' or t3.address like '%"""+city+"""%') """
  436. if county != "0":
  437. condition+=""" and (t2.address like '%"""+county+"""%' or t3.address like '%"""+county+"""%') """
  438. if region != "0":
  439. condition+=""" and (t2.region like '%"""+region+"""%' or t2.region like '%不限%') """
  440. if dtype != "0":
  441. condition+=""" and (t2.type like '%"""+dtype+"""%' or t2.type like '%不限%') """
  442. if dstyle != "0":
  443. condition+=""" and (t2.style like '%"""+dstyle+"""%' or t2.style like '%不限%') """
  444. if arch != "0":
  445. condition+=""" and license!='' """
  446. if award !="0":
  447. condition+=""" and (t2.awards like '%亞洲設計獎%') """
  448. if agent !="0":
  449. condition+=""" and (t2.guarantee > 0) """
  450. if budget!="0":
  451. if budget==1:
  452. condition+=""" and (t2.min_budget>=0 and t2.min_budget<=1000000) """
  453. elif budget==2:
  454. condition+=""" and (t2.min_budget>=1000001 and t2.min_budget<=2000000) """
  455. elif budget==3:
  456. condition+=""" and (t2.min_budget>=2000001 and t2.min_budget<=3000000) """
  457. elif budget==4:
  458. condition+=""" and (t2.min_budget>=3000001 and t2.min_budget<=4000000) """
  459. elif budget==5:
  460. condition+=""" and (t2.min_budget>=4000001 and t2.min_budget<=5000000) """
  461. elif budget==6:
  462. condition+=""" and (t2.min_budget>=5000001)"""
  463. #jData = json.load(open(hhhMBPath+'/json/designer_list_six.json', encoding='utf8'))
  464. if condition=="":
  465. if page=="1":
  466. # records = db.query("""SELECT d.hdesigner_id,d.img_path,d.title,d.name,(select c.cover from _hcase c where c.hdesigner_id = d.hdesigner_id and c.onoff=1 ORDER BY c.corder ASC ,c.viewed DESC limit 1 ) as cover FROM _hdesigner d left join xoops.designer_branch b on b.designer_id = d.hdesigner_id left join xoops._hawards ha on ha.hdesigner_id = d.hdesigner_id where ha.onoff=1 and d.top="O" GROUP BY d.hdesigner_id Order By rand(); """)
  467. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 and t2.top_six="O" GROUP BY t2.hdesigner_id Order By rand(); """)
  468. else:
  469. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 and t2.top_six!="O" GROUP BY t2.hdesigner_id Order By"""+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page) - 2)*18+12)+""" ,6;""")
  470. else:
  471. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 """+condition+""" GROUP BY t2.hdesigner_id Order By """+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page) - 1)*18)+""" ,6;""")
  472. #print(records)
  473. #print(jData)
  474. jData = []
  475. for c in records:
  476. if "_hcase_img" in c["cover"]:
  477. cover=c["cover"].replace("_hcase_img","_hcase_img_orig")
  478. else:
  479. cover=c["cover"].replace("_hcase","_hcase_orig")
  480. jData.append({"hdesigner_id":str(c["hdesigner_id"]),"img_path":str(c["img_path"]),"name":c["name"],"title":c["title"],"cover":cover} )
  481. #for x,c in zip(jData,records):
  482. # x["hdesigner_id"] = str(c["hdesigner_id"])
  483. # x["img_path"] = str(c["img_path"])
  484. # x["name"] = c["name"]
  485. # x["title"] = c["title"]
  486. # x["cover"] = c["cover"]
  487. return jData
  488. @app.get("/gendesigner_list_twelve")
  489. def gendesigner_list_twelve(sort: str = "new", page: str="1",city: str = "0", county: str="0",region:str="0",dtype:str="0",dstyle:str="0",budget:str="0",arch:str="0",award:str="0",agent:str="0"):
  490. #jData = json.load(open(hhhMBPath+'/json/designer_list_twelve.json', encoding='utf8'))
  491. condition = ""
  492. if city != "0":
  493. condition+=""" and (t2.address like '%"""+city+"""%' or t3.address like '%"""+city+"""%') """
  494. if county != "0":
  495. condition+=""" and (t2.address like '%"""+county+"""%' or t3.address like '%"""+county+"""%') """
  496. if region != "0":
  497. condition+=""" and (t2.region like '%"""+region+"""%' or t2.region like '%不限%') """
  498. if dtype != "0":
  499. condition+=""" and (t2.type like '%"""+dtype+"""%' or t2.type like '%不限%') """
  500. if dstyle != "0":
  501. condition+=""" and (t2.style like '%"""+dstyle+"""%' or t2.style like '%不限%') """
  502. if arch != "0":
  503. condition+=""" and license!='' """
  504. if award !="0":
  505. condition+=""" and (t2.awards like '%亞洲設計獎%') """
  506. if agent !="0":
  507. condition+=""" and (t2.guarantee > 0) """
  508. if budget!="0":
  509. if budget==1:
  510. condition+=""" and (t2.min_budget>=0 and t2.min_budget<=1000000) """
  511. elif budget==2:
  512. condition+=""" and (t2.min_budget>=1000001 and t2.min_budget<=2000000) """
  513. elif budget==3:
  514. condition+=""" and (t2.min_budget>=2000001 and t2.min_budget<=3000000) """
  515. elif budget==4:
  516. condition+=""" and (t2.min_budget>=3000001 and t2.min_budget<=4000000) """
  517. elif budget==5:
  518. condition+=""" and (t2.min_budget>=4000001 and t2.min_budget<=5000000) """
  519. elif budget==6:
  520. condition+=""" and (t2.min_budget>=5000001)"""
  521. if condition=="":
  522. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 and t2.top_six!="O" GROUP BY t2.hdesigner_id Order By"""+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page)-1)*18)+""" ,12;""")
  523. else:
  524. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 """+condition+""" GROUP BY t2.hdesigner_id Order By"""+" "+("t1.sdate" if sort == 'new' else 't1.viewed')+""" DESC LIMIT"""+" "+str((int(page)-1)*18+6)+""" ,12;""")
  525. #print(records)
  526. #print(jData)
  527. #for x,c in zip(jData,records):
  528. # x["hdesigner_id"] = str(c["hdesigner_id"])
  529. # x["img_path"] = str(c["img_path"])
  530. # x["name"] = c["name"]
  531. # x["title"] = c["title"]
  532. # x["cover"] = c["cover"]
  533. jData = []
  534. for c in records:
  535. if "_hcase_img" in c["cover"]:
  536. cover=c["cover"].replace("_hcase_img","_hcase_img_orig")
  537. else:
  538. cover=c["cover"].replace("_hcase","_hcase_orig")
  539. jData.append({"hdesigner_id":str(c["hdesigner_id"]),"img_path":str(c["img_path"]),"name":c["name"],"title":c["title"],"cover":cover} )
  540. return jData
  541. @app.get("/gendesigner_list_all")
  542. def gendesigner_list_all(city: str = "0", county: str="0",region:str="0",dtype:str="0",dstyle:str="0",budget:str="0",arch:str="0",award:str="0",agent:str="0"):
  543. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  544. condition = ""
  545. if city != "0":
  546. condition+=""" and (t2.address like '%"""+city+"""%' or t3.address like '%"""+city+"""%') """
  547. if county != "0":
  548. condition+=""" and (t2.address like '%"""+county+"""%' or t3.address like '%"""+county+"""%') """
  549. if region != "0":
  550. condition+=""" and (t2.region like '%"""+region+"""%' or t2.region like '%不限%') """
  551. if dtype != "0":
  552. condition+=""" and (t2.type like '%"""+dtype+"""%' or t2.type like '%不限%') """
  553. if dstyle != "0":
  554. condition+=""" and (t2.style like '%"""+dstyle+"""%' or t2.style like '%不限%') """
  555. if arch != "0":
  556. condition+=""" and license!='' """
  557. if award !="0":
  558. condition+=""" and (t2.awards like '%亞洲設計獎%') """
  559. if agent !="0":
  560. condition+=""" and (t2.guarantee > 0) """
  561. if budget!="0":
  562. if budget==1:
  563. condition+=""" and (t2.min_budget>=0 and t2.min_budget<=1000000) """
  564. elif budget==2:
  565. condition+=""" and (t2.min_budget>=1000001 and t2.min_budget<=2000000) """
  566. elif budget==3:
  567. condition+=""" and (t2.min_budget>=2000001 and t2.min_budget<=3000000) """
  568. elif budget==4:
  569. condition+=""" and (t2.min_budget>=3000001 and t2.min_budget<=4000000) """
  570. elif budget==5:
  571. condition+=""" and (t2.min_budget>=4000001 and t2.min_budget<=5000000) """
  572. elif budget==6:
  573. condition+=""" and (t2.min_budget>=5000001)"""
  574. records = db.query("""SELECT t2.hdesigner_id,t2.img_path,t2.name,t2.title,(SELECT t1.cover from _hcase t1 where t1.hdesigner_id = t2.hdesigner_id and t1.onoff=1 ORDER BY t1.corder ASC ,t1.viewed DESC limit 1 ) as cover FROM _hdesigner t2 left JOIN _hcase t1 on t1.hdesigner_id=t2.hdesigner_id left JOIN designer_branch t3 on t1.hdesigner_id=t3.designer_id where t2.onoff=1 """+condition+""" GROUP BY t2.hdesigner_id;""")
  575. #print(records)
  576. #print(jData)
  577. jData = []
  578. for c in records:
  579. if "_hcase_img" in c["cover"]:
  580. cover=c["cover"].replace("_hcase_img","_hcase_img_orig")
  581. else:
  582. cover=c["cover"].replace("_hcase","_hcase_orig")
  583. jData.append({"hdesigner_id":str(c["hdesigner_id"]),"img_path":str(c["img_path"]),"name":c["name"],"title":c["title"],"cover":c["cover"]} )
  584. json.dumps(jData)
  585. #print(jData)
  586. #print(len(jData))
  587. return jData
  588. @app.get("/find_designer_show")
  589. def find_designer_show(cid:str ,type_use: str="computer"):
  590. condition = ""
  591. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  592. if type_use == "computer":
  593. records = db.query("""SELECT order_computer FROM _hdesigner where hdesigner_id="""+cid+""";""")
  594. jData = []
  595. for c in records:
  596. jData.append({"order_show_type":str(c["order_computer"])} )
  597. json.dumps(jData)
  598. else:
  599. records = db.query("""SELECT order_mb FROM _hdesigner where hdesigner_id="""+cid+""";""")
  600. jData = []
  601. for c in records:
  602. jData.append({"order_show_type":str(c["order_mb"])} )
  603. json.dumps(jData)
  604. #print(records)
  605. #print(jData)
  606. #print(jData)
  607. #print(len(jData))
  608. return jData
  609. @app.get("/find_total")
  610. def find_total(cid:str ,type_use: str):
  611. condition = ""
  612. if type_use=='case':
  613. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  614. records = db.query("""SELECT count(*) FROM _hcase c
  615. WHERE c.hdesigner_id = '""" + cid + """' AND c.onoff='1'; """ )
  616. elif type_use=='video':
  617. records = db.query("""SELECT count(*) FROM _hvideo v
  618. WHERE v.hdesigner_id = '""" + cid + """' AND display_datetime < NOW() ;""")
  619. elif type_use == 'column':
  620. records = db.query("""SELECT count(*) FROM _hcolumn c
  621. WHERE onoff=1 AND (c.hdesigner_ids LIKE '""" + cid + """,%' OR c.hdesigner_ids LIKE '%,""" + cid + """,%' OR c.hdesigner_ids LIKE '%,""" + cid + """' OR c.hdesigner_ids = '""" + cid + """') ;""")
  622. elif type_use == 'vr360':
  623. records = db.query("""SELECT count(*) FROM _hcase c
  624. WHERE c.hdesigner_id = '""" + cid + """' and istaging != '' AND c.onoff='1' ;""")
  625. jData = []
  626. for c in records:
  627. jData.append({"total":str(c["count(*)"])} )
  628. json.dumps(jData)
  629. #print(records)
  630. #print(jData)
  631. #print(jData)
  632. #print(len(jData))
  633. return jData
  634. @app.get("/find_user_favorite")
  635. def find_user_favorite(user_id: str ,cid:str, type_use: str="designer"):
  636. condition = ""
  637. #jData = json.load(open(hhhMBPath+'/json/designer_list_all.json', encoding='utf8'))
  638. records = db.query("""SELECT * FROM user_favorite where status=0 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  639. #print(records)
  640. #print(jData)
  641. jData = []
  642. for c in records:
  643. jData.append({"id":str(c["id"]),"user_id":str(c["user_id"]),"type":c["type"],"cid":c["table_id"],"create_time":str(c["create_time"]),"status":str(c["status"])} )
  644. json.dumps(jData)
  645. #print(jData)
  646. #print(len(jData))
  647. return jData
  648. # @app.post("/add_user_favorite")
  649. # def add_user_favorite(user_id: str ,cid:str, type_use: str="designer"):
  650. # records = db.query("""SELECT * FROM user_favorite where status=1 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  651. # jData = []
  652. # for c in records:
  653. # jData.append({"id":str(c["id"]),"user_id":str(c["user_id"]),"type":c["type"],"cid":c["table_id"],"create_time":str(c["create_time"]),"status":str(c["status"])} )
  654. # json.dumps(jData)
  655. # if len(jData)>0:
  656. # db.query("""UPDATE user_favorite SET status=0 WHERE user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""';""")
  657. # else:
  658. # records = db.query("""SELECT * FROM user_favorite where status=0 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  659. # jData = []
  660. # json.dumps(jData)
  661. # if len(jData)==0:
  662. # db.query("""INSERT INTO user_favorite (user_id, type, table_id) values ( """+user_id+""",'"""+type_use+"""',"""+cid+""");""")
  663. # db.commit()
  664. # return True
  665. # @app.post("/delete_user_favorite")
  666. # def delete_user_favorite(user_id: str ,cid:str, type_use: str="designer"):
  667. # records = db.query("""SELECT * FROM user_favorite where status=0 and user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""' ;""")
  668. # jData = []
  669. # for c in records:
  670. # jData.append({"id":str(c["id"]),"user_id":str(c["user_id"]),"type":c["type"],"cid":c["table_id"],"create_time":str(c["create_time"]),"status":str(c["status"])} )
  671. # json.dumps(jData)
  672. # if len(jData)>0:
  673. # db.query("""UPDATE user_favorite SET status=1 WHERE user_id="""+user_id+""" and table_id="""+cid+""" and type= '"""+type_use+"""';""")
  674. # return True
  675. #===================================================================================================================================
  676. @app.get("/gencase")
  677. def gencase(id: str = "14151", sort: str = "new", page: str="1"):
  678. jData = json.load(open(hhhMBPath+'/json/cases.json', encoding='utf8'))
  679. records = db.query("""SELECT *, c.style cstyle, c.style2 cstyle2 FROM _hcase c
  680. LEFT JOIN _hdesigner d ON c.hdesigner_id = d.hdesigner_id
  681. WHERE c.hcase_id = '""" + id + """' AND c.onoff='1' AND d.onoff='1' and c.sdate < now() """)
  682. #print(jData)
  683. for x in jData:
  684. tmpCaseDetail = []
  685. icount = 0
  686. for c in records:
  687. icount += 1
  688. #tmpCaseDetail.append({"CaseDetailImg": c["cimg"]})
  689. #x["CaseDetail"] = tmpCaseDetail
  690. if c != None:
  691. x["designerid"] = str(c["hdesigner_id"])
  692. x["CaseId"] = str(c["hcase_id"])
  693. x["Casetitle"] = c["caption"]
  694. x["CaseTeamName"] = c["name"]
  695. x["CaseCompany"] = c["title"]
  696. x["CaseCompanyAddress"] = c["address"]
  697. x["CaseCompanyTel"] = c["phone"]
  698. x["CaseCompanyEmail"] = c["mail"]
  699. x["CaseCompanyWeb"] = c["website"]
  700. x["CaseDate"] = str(c["sdate"])
  701. x["CaseViews"] = c["viewed"]
  702. x["CaseCoverImg"] = c["cover"]
  703. x["CaseImgAmount"] = icount
  704. x["CaseStyle"] = c["cstyle"]
  705. x["CaseHouse"] = c["layout"]
  706. x["CaseSize"] = c["area"]
  707. x["CaseProject"] = ""
  708. x["CaseDataMember"] = c["member"]
  709. x["CaseDataSize"] = c["area"]
  710. x["CaseDataStyle"] = c["cstyle"] + c["cstyle2"]
  711. x["CaseDataType"] = c["type"]
  712. x["CaseDataSituation"] = c["condition"]
  713. x["CaseDataImgProvide"] = c["provider"]
  714. x["CaseDataSpace"] = c["layout"]
  715. x["CaseDataMaterial"] = c["materials"]
  716. x["ContactFreeTel"] = c["service_phone"]
  717. x["ContactDesignerImg"] = c["img_path"]
  718. x["CasePageLink"] = ""
  719. x["CasePageprev"] = ""
  720. #x["CaseTag"]= []
  721. #相同設計師的個案
  722. sql = """SELECT * FROM _hcase c
  723. WHERE hdesigner_id = '""" + x["designerid"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  724. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  725. LIMIT """ + str((int(page) - 1)*12) + """,12
  726. """
  727. cases = db.query(sql)
  728. tmpOtherCases = []
  729. for other in cases:
  730. tmpOtherCase = {}
  731. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  732. tmpOtherCase["casesid"] = str(other["hcase_id"])
  733. tmpOtherCase["Views"] = other["viewed"]
  734. tmpOtherCase["ProfileImg"] = other["cover"]
  735. tmpTags = []
  736. for tag in other["tag"].split(','):
  737. tmpTags.append({"Tag": tag , "TagLink": "" })
  738. tmpOtherCase["ProfileTag"] = tmpTags
  739. tmpOtherCases.append(tmpOtherCase)
  740. x["DesignerProfile"] = tmpOtherCases
  741. #相同風格的個案
  742. sql = """SELECT * FROM _hcase c
  743. WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  744. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  745. LIMIT """ + str((int(page) - 1)*12) + """,12
  746. """
  747. cases = db.query(sql)
  748. tmpOtherCases = []
  749. for other in cases:
  750. tmpOtherCase = {}
  751. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  752. tmpOtherCase["casesid"] = str(other["hcase_id"])
  753. tmpOtherCase["Views"] = other["viewed"]
  754. tmpOtherCase["ProfileImg"] = other["cover"]
  755. tmpTags = []
  756. for tag in other["tag"].split(','):
  757. tmpTags.append({"Tag": tag , "TagLink": "" })
  758. tmpOtherCase["ProfileTag"] = tmpTags
  759. tmpOtherCases.append(tmpOtherCase)
  760. x["StyleProfile"] = tmpOtherCases
  761. #相同風格的RANDOM 10筆
  762. #cases = db.query("""SELECT * FROM _hcase c
  763. #WHERE style = '""" + x["CaseStyle"] + """' and hcase_id <> '""" + x["CaseId"] + """' and sdate < now() AND c.onoff='1'
  764. #ORDER BY RAND()
  765. #LIMIT 10
  766. #""")
  767. """ tmpOtherCases = []
  768. for other in cases:
  769. tmpOtherCase = {}
  770. tmpOtherCase["designerid"] = str(other["hdesigner_id"])
  771. tmpOtherCase["casesid"] = str(other["hcase_id"])
  772. tmpOtherCase["PortfoliolImg"] = other["cover"]
  773. tmpOtherCase["PortfoliolLink"] = ""
  774. tmpOtherCase["PortfoliolImgAlt"] = other["caption"]
  775. tmpOtherCases.append(tmpOtherCase)
  776. x["OtherStylePortfolio"]= tmpOtherCases """
  777. # print(x)
  778. # print(jData)
  779. """ if not os.path.exists(hhhMBPath):
  780. os.mkdir(hhhMBPath)
  781. with open(hhhMBPath+'/json/cases-' + id + '.json', 'w', encoding='utf-8') as f:
  782. json.dump(jData, f, ensure_ascii=False, indent=4) """
  783. return jData
  784. @app.get("/gendesigner")
  785. def gendesigner(id: str = "14151"):
  786. jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  787. records = db.query("""SELECT *, ci.name cimg FROM _hcase c
  788. LEFT JOIN _hcase_img ci ON c.hcase_id = ci.hcase_id
  789. LEFT JOIN _hdesigner d ON c.hdesigner_id = d.hdesigner_id
  790. WHERE d.hdesigner_id = '""" + id + """' AND c.onoff='1' AND d.onoff='1' """)
  791. # print(jData)
  792. for x in jData:
  793. tmpCaseDetail = []
  794. icount = 0
  795. for c in records:
  796. icount += 1
  797. # tmpCaseDetail.append({"CaseDetailImg":c["cimg"]})
  798. x["id"] = c["hdesigner_id"]
  799. x["BannerImg"] = c["background"]
  800. x["CompanyName"] = c["title"]
  801. x["DesignerName"] = c["name"]
  802. x["Designerimg"] = c["img_path"]
  803. x["Description"] = c["seo"]
  804. x["Approve"] = c["position"]
  805. x["Basics"] = [
  806. {"title": "免費專線:",
  807. "link": c["service_phone"], "data": c["service_phone"]},
  808. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  809. {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  810. {"title": "公司傳真:", "link": c["fax"], "data": c["fax"]},
  811. {"title": "公司地址:", "link": c["address"], "data": c["address"]},
  812. {"title": "電子信箱:", "link": c["mail"], "data": c["mail"]},
  813. {"title": "公司網址:", "link": c["website"], "data": c["website"]}
  814. ]
  815. x["FreeCall"] = c["service_phone"]
  816. x["ConsoleCall_1"] = c["phone"]
  817. x["ConsoleCall_2"] = c["phone"]
  818. x["Fax"] = c["fax"]
  819. x["Address"] = c["address"]
  820. x["Email"] = c["mail"]
  821. x["Web"] = c["website"]
  822. x["Branches"] = [
  823. {"title": "分公司地址:", "link": "台北市中山區林森北路50號4樓之一",
  824. "data": "台北市中山區林森北路50號4樓之一"},
  825. {"title": "分公司電話:", "link": "tel:02-2562-7755", "data": "02-2562-7755"},
  826. {"title": "分公司傳真:", "link": "tel:02-2562-7002", "data": "02-2562-7002"},
  827. {"title": "分公司地址:", "link": "上海市闵行区东川路2688号", "data": "上海市闵行区东川路2688号"}
  828. ]
  829. x["Budget"] = c["budget"]
  830. x["Square"] = c["area"]
  831. x["SpecialCase"] = c["special"]
  832. x["Charge"] = c["charge"]
  833. x["Pay"] = c["payment"]
  834. x["WorkLoc"] = c["region"]
  835. x["WorkType"] = c["type"]
  836. x["WorkStyle"] = c["style"]
  837. x["WorkBudget"] = c["budget"]
  838. x["Terms"] = [
  839. {"title": "接案預算:", "data": c["budget"]},
  840. {"title": "接案坪數:", "data": c["area"]},
  841. {"title": "特殊接案:", "data": c["special"]},
  842. {"title": "收費方式:", "data": c["charge"]},
  843. {"title": "付費方式:", "data": c["payment"]},
  844. {"title": "接案區域:", "data": c["region"]},
  845. {"title": "接案類型:", "data": c["type"]},
  846. {"title": "接案風格:", "data": c["style"]}
  847. ]
  848. x["scMedia"] = [
  849. {"name": "Facebook", "img": "https://hhh.com.tw/assets/images/rv_web/fb.svg",
  850. "link": c["fbpageurl"]},
  851. {"name": "Line", "img": "https://hhh.com.tw/assets/images/rv_web/line.svg",
  852. "link": c["line_link"]},
  853. {"name": "Wechat", "img": "https://hhh.com.tw/assets/images/rv_web/wechat.svg",
  854. "link": c["fbpageurl"]},
  855. {"name": "email", "img": "https://hhh.com.tw/assets/images/rv_web/share.svg",
  856. "link": c["mail"]},
  857. {"name": "Like", "img": "https://hhh.com.tw/assets/images/rv_web/like-o.svg", "link": ""}
  858. ]
  859. x["Content"] = [
  860. {
  861. "Title": "設計師作品",
  862. "mb_title": "作品",
  863. "Tabtag": "intro",
  864. "Display_mb": "true",
  865. "isActive": "true",
  866. "Carddata": [
  867. ]
  868. },
  869. {
  870. "Title": "設計師影音",
  871. "mb_title": "影音",
  872. "Tabtag": "video",
  873. "Display_mb": "true",
  874. "isActive": "true",
  875. "Carddata": [
  876. ]
  877. },
  878. {
  879. "Title": "設計師專欄",
  880. "mb_title": "專欄",
  881. "Tabtag": "columns",
  882. "Display_mb": "true",
  883. "isActive": "true",
  884. "Carddata": [
  885. ]
  886. },
  887. {
  888. "Title": "VR360",
  889. "mb_title": "",
  890. "Tabtag": "vr360",
  891. "Display_mb": "false",
  892. "isActive": "true",
  893. "Carddata": [
  894. ]
  895. },
  896. {
  897. "Title": "設計師公司簡介",
  898. "mb_title": "公司簡介",
  899. "Tabtag": "company",
  900. "Display_mb": "true",
  901. "isActive": "true",
  902. "Carddata": [
  903. ],
  904. "info": [
  905. {"title": "設計理念", "data": "空間設計的美學藝術,蔡岳儒總監更能將日式精闢的手工藝術融入台灣的設計與工程,更將留日所學發揚光大明確的把結構、 動線、收納、光線與品味融入建築、景觀與室內三大空間之中,藉由點線面展現出空間的獨特性,並賦予空間延續的生命活力。"},
  906. {"title": "公司統編", "data": "經濟部/財政部登記有案:54290717"},
  907. {"title": "相關經歷", "data": "蔡岳儒<br>◆現任/恆岳空間設計 主持設計師<br>◆學歷/東京デザイナー学院卒業<br>◆經歷/十餘年設計、工程經歷。"},
  908. {"title": "專業證照",
  909. "data": "建築師證書 高恒悌 (101) 專高建字第000013號<br>建築物室內裝修專業技術人員登記證 高恒悌 第40EC116787號"},
  910. {"title": "獲獎紀錄", "data": "2020年雪梨設計獎SYDNEY Design Awards GIOD-Quality Arena<br>2020年雪梨設計獎SYDNEY Design Awards SELECTION- Life Savoring"}
  911. ]
  912. }
  913. ]
  914. # print(x)
  915. # print(jData)
  916. """ if not os.path.exists(hhhMBPath):
  917. os.mkdir(hhhMBPath)
  918. with open(hhhMBPath+'/json/designers-' + id + '.json', 'w', encoding='utf-8') as f:
  919. json.dump(jData, f, ensure_ascii=False, indent=4) """
  920. return jData
  921. @app.get("/gencolumn")
  922. def gencolumn(id: str = "6392", sort: str = "new", page: str="1"):
  923. jData = json.load(open(hhhMBPath+'/json/Columns.json', encoding='utf8'))
  924. records = db.query("""SELECT * FROM _hcolumn c
  925. WHERE c.hcolumn_id = '""" + id + """' AND c.onoff='1' """)
  926. #print(id)
  927. for x in jData:
  928. icount = 0
  929. c = None
  930. for c in records:
  931. icount += 1
  932. if c != None:
  933. x["Columnsid"] = str(c["hcolumn_id"])
  934. x["Columnstitle"] = c["ctitle"]
  935. x["ColumnsCoverImg"] = c["clogo"]
  936. x["ColumnsDate"] = str(c["sdate"])
  937. x["ColumnsViews"] = str(c["viewed"])
  938. if page == "1":
  939. x["ColumnsContent"] = c["page_content"]
  940. tmpTags = []
  941. for tag in c["ctag"].split(','):
  942. tmpTags.append({"Tag": tag})
  943. x["ColumnsTag"] = tmpTags
  944. x["author_inf"] = c["extend_str"]
  945. #相同類別的最新12筆
  946. sql = """SELECT * FROM _hcolumn c
  947. WHERE (c.ctype like '%""" + str(c["ctype"]) + """%' and c.ctype_sub like '%""" + str(c["ctype_sub"]) + """%') and hcolumn_id <> '""" + str(c["hcolumn_id"]) + """' and sdate < now() AND c.onoff='1'
  948. ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  949. LIMIT """ + str((int(page) - 1)*12) + """,12
  950. """
  951. ctypes = db.query(sql)
  952. tmpOtherCols = []
  953. for other in ctypes:
  954. tmpOtherCol = {}
  955. tmpOtherCol["Columnsid"] = str(other["hcolumn_id"])
  956. tmpOtherCol["ColumnsCoverImg"] = other["clogo"]
  957. tmpOtherCol["Views"] = other["viewed"]
  958. tmpOtherCol["Columnstitle"] = other["ctitle"]
  959. tmpTags = []
  960. for tag in other["ctag"].split(','):
  961. tmpTags.append({"Tag": tag})
  962. tmpOtherCol["ColumnsTag"] = tmpTags
  963. tmpOtherCols.append(tmpOtherCol)
  964. x["OtherColumns"] = tmpOtherCols
  965. #print(x)
  966. # print(jData)
  967. """ if not os.path.exists(hhhMBPath):
  968. os.mkdir(hhhMBPath)
  969. with open(hhhMBPath+'/json/Columns-' + id + '.json', 'w', encoding='utf-8') as f:
  970. json.dump(jData, f, ensure_ascii=False, indent=4) """
  971. return jData
  972. @app.get("/getColumnAds")
  973. def getColumnAds():
  974. ads = []
  975. records = db.query("""SELECT adlogo_mobile imgUrl, adlogo DimgUrl, adhref link
  976. FROM _had hh
  977. WHERE adtype LIKE '專欄首大%'
  978. AND hh.onoff='1'
  979. and NOW() BETWEEN start_time AND end_time
  980. ORDER BY cast(SUBSTR(adtype, 4) AS DECIMAL) """)
  981. """ for x in records:
  982. ads.append(x) """
  983. ads.extend(records)
  984. rData = json.loads(json.dumps(ads))
  985. #print(json.dumps(ads))
  986. return rData
  987. """ if __name__ == "__main__":
  988. uvicorn.run(app, host="0.0.0.0", port=8000) """
  989. @app.get("/genemering")
  990. async def genemering():
  991. id_use = []
  992. ids = db.query("""SELECT hdesigner_id FROM _hdesigner d where d.emering=1 and d.onoff='1' order by rand();""")
  993. for c in ids:
  994. id_use.append(str(c["hdesigner_id"]))
  995. # with dataset.connect(connstr) as db:
  996. # jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  997. jData_all = []
  998. for id in id_use:
  999. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' ORDER BY sdate DESC LIMIT 6 """ )
  1000. cases_list = []
  1001. for case in cases:
  1002. tag_use = ''
  1003. if case['style']!='':
  1004. tag_use += case['style'].strip()
  1005. tag_use += ','
  1006. if case['style2']!='':
  1007. tag_use += case['style2'].strip()
  1008. tag_use += ','
  1009. if case['type']!='':
  1010. tag_use += case['type'].strip()
  1011. tag_use += ','
  1012. if case['condition']!='':
  1013. tag_use += case['condition'].strip()
  1014. tmpobj = {
  1015. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1016. "imgUrl": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1017. "title": case["caption"],
  1018. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1019. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1020. "views": case["viewed"],
  1021. "dateSort": str(case["sdate"])
  1022. }
  1023. cases_list.append(tmpobj)
  1024. records = db.query("""SELECT * FROM _hdesigner d WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  1025. for c in records:
  1026. if c["service_phone"]!='':
  1027. part1=c["service_phone"][0:4]
  1028. part2=c["service_phone"][4:7]
  1029. part3=c["service_phone"][7:10]
  1030. part4=c["service_phone"].split(',')[1]
  1031. service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  1032. else:
  1033. service_phone=''
  1034. jData={"hdesignerId":str(c["hdesigner_id"]),
  1035. "designerName":str(c["name"]),
  1036. "companyName": str(c["title"]),
  1037. 'designerBigImg':"./img/"+id,
  1038. "designerIdea":str(c["idea"]),
  1039. "website":str(c["website"]),
  1040. "servicePhone":service_phone,
  1041. "fbUrl":str(c["fbpageurl"]),
  1042. "cardData": cases_list
  1043. }
  1044. jData_all.append(jData)
  1045. json.dumps(jData_all)
  1046. return jData_all
  1047. from typing import List
  1048. @app.get("/genemering_case")
  1049. async def genemering_case():
  1050. id_use = []
  1051. ids = db.query("""SELECT hdesigner_id FROM _hdesigner d where d.emering=1 and d.onoff='1' order by rand();""")
  1052. for c in ids:
  1053. id_use.append(str(c["hdesigner_id"]))
  1054. # with dataset.connect(connstr) as db:
  1055. # jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  1056. jData_all = []
  1057. for id in id_use:
  1058. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' ORDER BY sdate DESC LIMIT 6 """ )
  1059. for case in cases:
  1060. tag_use = ''
  1061. if case['style']!='':
  1062. tag_use += case['style'].strip()
  1063. tag_use += ','
  1064. if case['style2']!='':
  1065. tag_use += case['style2'].strip()
  1066. tag_use += ','
  1067. if case['type']!='':
  1068. tag_use += case['type'].strip()
  1069. tag_use += ','
  1070. if case['condition']!='':
  1071. tag_use += case['condition'].strip()
  1072. tmpobj = {
  1073. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1074. "imgURL": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1075. "title": case["caption"],
  1076. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1077. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1078. "views": case["viewed"],
  1079. "dateSort": str(case["sdate"])
  1080. }
  1081. jData_all.append(tmpobj)
  1082. random.shuffle(jData_all)
  1083. json.dumps(jData_all)
  1084. return jData_all[0:6]
  1085. @app.get("/genemering_calculator_count")
  1086. async def genemering_calculator_count():
  1087. counts_use = []
  1088. counts = db.query("""SELECT count(1) FROM calculator;""")
  1089. for c in counts:
  1090. counts_use.append(str(c["count(1)"]))
  1091. return counts_use
  1092. class deco_request_detail(BaseModel):
  1093. id: str
  1094. name: str
  1095. email: str
  1096. phone: str
  1097. #detail
  1098. loc: str
  1099. h_class: str
  1100. # type: str
  1101. # budget: str
  1102. size: str
  1103. # bed_num: int
  1104. # liv_num: int
  1105. # bath_num: int
  1106. # style: str
  1107. # prefer_date: str
  1108. time_stamp: str
  1109. # gender: str
  1110. version: str
  1111. utmSource:str
  1112. utmMedium:str
  1113. utmCampaign:str
  1114. @app.post("/insert_calculator_request_A")
  1115. async def insert_calculator_request_A(req:deco_request_detail):
  1116. db_new = dataset.connect('mysql://hhh7796hhh:lYmWsu^ujcA1@ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com:3306/xoops?charset=utf8mb4')
  1117. db_new.query("""INSERT INTO calculator_request (name, phone, email,city,area,ca_type,source_web,marketing_consent,h_class,utm_source,utm_medium,utm_campaign) VALUES ('""" + req.name + """','""" + req.phone + """','""" + req.email + """','""" + req.loc + """', '""" + req.size + """', '""" + '無' + """', '""" + '全室裝修A' + """', '""" + '2' + """', '""" + req.h_class + """', '""" +str(req.utmSource)+ """', '""" + str(req.utmMedium)+ """', '""" + str(req.utmCampaign) + """');""")
  1118. db_new.commit()
  1119. ######寄給業務通知信###########################
  1120. # Replace sender@example.com with your "From" address.
  1121. # This address must be verified with Amazon SES.
  1122. iName = req.name
  1123. iPhone = req.phone
  1124. iEmail = req.email
  1125. iCity = req.loc
  1126. iArea = req.size
  1127. iHouse= req.h_class
  1128. iCtype = "無"
  1129. iSource = "全室裝修A"
  1130. #獲取當前時間
  1131. now = datetime.now()
  1132. #格式化時間
  1133. iDate = now.strftime("%Y.%m.%d %H:%M")
  1134. SENDER = "Gorgeous Space - Mailer <noreply@hhh.com.tw>"
  1135. # Replace recipient@example.com with a "To" address. If your account
  1136. # is still in the sandbox, this address must be verified.
  1137. #RECIPIENT = iRecipient
  1138. # RECIPIENTS = iRecipient.split(',')
  1139. # CCS = iSale_mail.split(',')
  1140. # RECIPIENTS = iRecipient.split(',')
  1141. #寄給業務
  1142. RECIPIENTS = ["miko@hhh.com.tw","lily_huang@hhh.com.tw","dori@hhh.com.tw","wesson@hhh.com.tw"]
  1143. #寄給開發
  1144. CCS=['oak@choozmo.com']
  1145. # CCS.append("hhh_edit@hhh.com.tw")
  1146. print(RECIPIENTS)
  1147. print(CCS)
  1148. ###之後要改成上面設計師email
  1149. # RECIPIENTS = ["may@hhh.com.tw","jennifer_kao@hhh.com.tw",]
  1150. #RECIPIENTS = ["hhh_edit@hhh.com.tw"]
  1151. #CCS = ["hhh_edit@hhh.com.tw"]
  1152. BCCS = []
  1153. # Specify a configuration set. If you do not want to use a configuration
  1154. # set, comment the following variable, and the
  1155. # ConfigurationSetName=CONFIGURATION_SET argument below.
  1156. #CONFIGURATION_SET = "ConfigSet"
  1157. # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
  1158. AWS_REGION = "us-east-1"
  1159. # The subject line for the email.
  1160. SUBJECT = "幸福空間 裝修需求預算通知 (來自"+iName+'-'+iPhone+")"
  1161. # The email body for recipients with non-HTML email clients.
  1162. # BODY_TEXT = ("\r\n" + iName + " 設計師 , 您好:\r\n我是幸福空間編輯 , 您的個案已經完成並上線!\r\n幸福空間已於"+ iSection +"將您的個案露出於幸福空間網站上"+"\r\n個案名稱 :"+ iCap+"\r\n\r\n"+ iImg+"\r\n\r\n網址: https://hhh.com.tw/cases/detail/d/"+iId+"/\r\n煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!\r\n------------------------------------------------------------\r\n 幸福空間股份有限公司\r\n E-mail : service@choozmo.com \r\n 幸福空間 : https://hhh.com.tw \r\n ")
  1163. # BODY_TEXT = ("\r\n" + " 以下為裝修需求")
  1164. BODY_TEXT = ""
  1165. BODY_HTML = """<html>
  1166. <head></head>
  1167. <body>
  1168. <p>以下為裝修需求 <br />
  1169. <p> 建立時間 : """ + iDate + "<br />姓名 : "+ iName +"<br />手機 : "+ iPhone+"<br />E-mail: "+ iEmail+"<br />縣市區域 : " + iCity +"<br />坪數 : "+ iArea+ "<br/>裝修類型:"+ iCtype+ "<br/>房屋類型:"+ iHouse+ "<br/>需求來源平台:"+ iSource +"<br/>"+"""
  1170. ------------------------------------------------------------<br/>
  1171. 幸福空間股份有限公司<br/>
  1172. E-mail : hhh_edit@hhh.com.tw <br/>
  1173. 幸福空間 : https://hhh.com.tw <br/>
  1174. </p>
  1175. </body>
  1176. </html>"""
  1177. # The character encoding for the email.
  1178. CHARSET = "UTF-8"
  1179. # Create a new SES resource and specify a region.
  1180. client = boto3.client('ses'
  1181. ,aws_access_key_id='AKIAQG3PJZCHXPCSTAJG'
  1182. ,aws_secret_access_key='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'
  1183. ,region_name=AWS_REGION)
  1184. # Try to send the email.
  1185. try:
  1186. #Provide the contents of the email.
  1187. response = client.send_email(
  1188. Destination={
  1189. 'ToAddresses': RECIPIENTS,
  1190. 'CcAddresses': CCS,
  1191. 'BccAddresses': BCCS
  1192. },
  1193. Message={
  1194. 'Body': {
  1195. 'Html': {
  1196. 'Charset': CHARSET,
  1197. 'Data': BODY_HTML,
  1198. },
  1199. 'Text': {
  1200. 'Charset': CHARSET,
  1201. 'Data': BODY_TEXT,
  1202. },
  1203. },
  1204. 'Subject': {
  1205. 'Charset': CHARSET,
  1206. 'Data': SUBJECT,
  1207. },
  1208. },
  1209. Source=SENDER,
  1210. # If you are not using a configuration set, comment or delete the
  1211. # following line
  1212. #ConfigurationSetName=CONFIGURATION_SET,
  1213. )
  1214. # Display an error if something goes wrong.
  1215. except ClientError as e:
  1216. print(e.response['Error']['Message'])
  1217. else:
  1218. print("Email sent! Message ID:"),
  1219. print(response['MessageId'])
  1220. return True
  1221. @app.post("/insert_calculator_request_B")
  1222. async def insert_calculator_request_A(req:deco_request_detail):
  1223. db_new = dataset.connect('mysql://hhh7796hhh:lYmWsu^ujcA1@ec2-3-35-26-49.ap-northeast-2.compute.amazonaws.com:3306/xoops?charset=utf8mb4')
  1224. db_new.query("""INSERT INTO calculator_request (name, phone, email,city,area,ca_type,source_web,marketing_consent,h_class,utm_source,utm_medium,utm_campaign) VALUES ('""" + req.name + """','""" + req.phone + """','""" + req.email + """','""" + req.loc + """', '""" + req.size + """', '""" + '無' + """', '""" + '全室裝修B' + """', '""" + '2' + """', '""" + req.h_class+ """', '""" +str(req.utmSource)+ """', '""" + str(req.utmMedium)+ """', '""" + str(req.utmCampaign) + """');""")
  1225. db_new.commit()
  1226. ######寄給業務通知信###########################
  1227. # Replace sender@example.com with your "From" address.
  1228. # This address must be verified with Amazon SES.
  1229. iName = req.name
  1230. iPhone = req.phone
  1231. iEmail = req.email
  1232. iCity = req.loc
  1233. iArea = req.size
  1234. iHouse= req.h_class
  1235. iCtype = "無"
  1236. iSource = "全室裝修B"
  1237. #獲取當前時間
  1238. now = datetime.now()
  1239. #格式化時間
  1240. iDate = now.strftime("%Y.%m.%d %H:%M")
  1241. SENDER = "Gorgeous Space - Mailer <noreply@hhh.com.tw>"
  1242. # Replace recipient@example.com with a "To" address. If your account
  1243. # is still in the sandbox, this address must be verified.
  1244. #RECIPIENT = iRecipient
  1245. # RECIPIENTS = iRecipient.split(',')
  1246. # CCS = iSale_mail.split(',')
  1247. # RECIPIENTS = iRecipient.split(',')
  1248. #寄給業務
  1249. RECIPIENTS = ["miko@hhh.com.tw","lily_huang@hhh.com.tw","dori@hhh.com.tw","wesson@hhh.com.tw"]
  1250. #寄給開發
  1251. CCS=['oak@choozmo.com']
  1252. # CCS.append("hhh_edit@hhh.com.tw")
  1253. print(RECIPIENTS)
  1254. print(CCS)
  1255. ###之後要改成上面設計師email
  1256. # RECIPIENTS = ["may@hhh.com.tw","jennifer_kao@hhh.com.tw",]
  1257. #RECIPIENTS = ["hhh_edit@hhh.com.tw"]
  1258. #CCS = ["hhh_edit@hhh.com.tw"]
  1259. BCCS = []
  1260. # Specify a configuration set. If you do not want to use a configuration
  1261. # set, comment the following variable, and the
  1262. # ConfigurationSetName=CONFIGURATION_SET argument below.
  1263. #CONFIGURATION_SET = "ConfigSet"
  1264. # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
  1265. AWS_REGION = "us-east-1"
  1266. # The subject line for the email.
  1267. SUBJECT = "幸福空間 裝修需求預算通知 (來自"+iName+'-'+iPhone+")"
  1268. # The email body for recipients with non-HTML email clients.
  1269. # BODY_TEXT = ("\r\n" + iName + " 設計師 , 您好:\r\n我是幸福空間編輯 , 您的個案已經完成並上線!\r\n幸福空間已於"+ iSection +"將您的個案露出於幸福空間網站上"+"\r\n個案名稱 :"+ iCap+"\r\n\r\n"+ iImg+"\r\n\r\n網址: https://hhh.com.tw/cases/detail/d/"+iId+"/\r\n煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!\r\n------------------------------------------------------------\r\n 幸福空間股份有限公司\r\n E-mail : service@choozmo.com \r\n 幸福空間 : https://hhh.com.tw \r\n ")
  1270. # BODY_TEXT = ("\r\n" + " 以下為裝修需求")
  1271. BODY_TEXT = ""
  1272. BODY_HTML = """<html>
  1273. <head></head>
  1274. <body>
  1275. <p>以下為裝修需求 <br />
  1276. <p> 建立時間 : """ + iDate + "<br />姓名 : "+ iName +"<br />手機 : "+ iPhone+"<br />E-mail: "+ iEmail+"<br />縣市區域 : " + iCity +"<br />坪數 : "+ iArea+ "<br/>裝修類型:"+ iCtype+ "<br/>房屋類型:"+ iHouse+ "<br/>需求來源平台:"+ iSource +"<br/>"+"""
  1277. ------------------------------------------------------------<br/>
  1278. 幸福空間股份有限公司<br/>
  1279. E-mail : hhh_edit@hhh.com.tw <br/>
  1280. 幸福空間 : https://hhh.com.tw <br/>
  1281. </p>
  1282. </body>
  1283. </html>"""
  1284. # The character encoding for the email.
  1285. CHARSET = "UTF-8"
  1286. # Create a new SES resource and specify a region.
  1287. client = boto3.client('ses'
  1288. ,aws_access_key_id='AKIAQG3PJZCHXPCSTAJG'
  1289. ,aws_secret_access_key='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'
  1290. ,region_name=AWS_REGION)
  1291. # Try to send the email.
  1292. try:
  1293. #Provide the contents of the email.
  1294. response = client.send_email(
  1295. Destination={
  1296. 'ToAddresses': RECIPIENTS,
  1297. 'CcAddresses': CCS,
  1298. 'BccAddresses': BCCS
  1299. },
  1300. Message={
  1301. 'Body': {
  1302. 'Html': {
  1303. 'Charset': CHARSET,
  1304. 'Data': BODY_HTML,
  1305. },
  1306. 'Text': {
  1307. 'Charset': CHARSET,
  1308. 'Data': BODY_TEXT,
  1309. },
  1310. },
  1311. 'Subject': {
  1312. 'Charset': CHARSET,
  1313. 'Data': SUBJECT,
  1314. },
  1315. },
  1316. Source=SENDER,
  1317. # If you are not using a configuration set, comment or delete the
  1318. # following line
  1319. #ConfigurationSetName=CONFIGURATION_SET,
  1320. )
  1321. # Display an error if something goes wrong.
  1322. except ClientError as e:
  1323. print(e.response['Error']['Message'])
  1324. else:
  1325. print("Email sent! Message ID:"),
  1326. print(response['MessageId'])
  1327. return True
  1328. class CalculatorRequest(BaseModel):
  1329. name: str
  1330. phone: str
  1331. email: str
  1332. city: str
  1333. area: str
  1334. ca_type: str
  1335. source: str
  1336. marketing_consent: str
  1337. h_class: str
  1338. utmSource:str
  1339. utmMedium:str
  1340. utmCampaign:str
  1341. # @app.post("/insert_calculator_request")
  1342. # async def insert_calculator_request(name: str = "test", phone: str = "0987654321", email: str="oak@choozmo.com",city:str="台北",area:str="20",ca_type:str="輕裝修",source:str="官網",marketing_consent:str="1",h_class:str="無"):
  1343. @app.post("/insert_calculator_request")
  1344. async def insert_calculator_request(request: CalculatorRequest):
  1345. name = request.name
  1346. phone = request.phone
  1347. email = request.email
  1348. city = request.city
  1349. area = request.area
  1350. ca_type = request.ca_type
  1351. source = request.source
  1352. marketing_consent = request.marketing_consent
  1353. h_class = request.h_class
  1354. utm_source = request.utmSource
  1355. utm_medium = request.utmMedium
  1356. utm_campaign= request.utmCampaign
  1357. db.query("""INSERT INTO calculator_request (name, phone, email,city,area,ca_type,source_web,marketing_consent,h_class,utm_source,utm_medium,utm_campaign) VALUES ('""" + name + """','""" + phone + """','""" + email + """','""" + city + """', '""" + area + """', '""" + ca_type + """', '""" + source + """', '""" + marketing_consent + """', '""" + h_class+ """', '""" +str(utm_source)+ """', '""" + str(utm_medium)+ """', '""" + str(utm_campaign) + """');""")
  1358. db.commit()
  1359. if ca_type=="輕裝修":
  1360. price = 43000*float(area)
  1361. k1 = price*0.3
  1362. k2 = price*0.36
  1363. k3 = price*0.22
  1364. k4 = price*0.12
  1365. jData = {"city":str(city),
  1366. "area":str(area),
  1367. "ca_type": str(ca_type),
  1368. "basic_engineering":k1,
  1369. "hardware_engineering":k2,
  1370. "decorated_home":k3,
  1371. "home_appliances":k4
  1372. }
  1373. json.dumps(jData)
  1374. elif ca_type=="全室裝修":
  1375. price1 = 63000*float(area)
  1376. k1 = price1*0.3
  1377. k2 = price1*0.36
  1378. k3 = price1*0.22
  1379. k4 = price1*0.12
  1380. price2 = 98000*float(area)
  1381. k5 = price2*0.3
  1382. k6 = price2*0.36
  1383. k7 = price2*0.22
  1384. k8 = price2*0.12
  1385. price3 = 163000*float(area)
  1386. k9 = price3*0.3
  1387. k10 = price3*0.36
  1388. k11 = price3*0.22
  1389. k12 = price3*0.12
  1390. jData = {"city":str(city),
  1391. "area":str(area),
  1392. "ca_type": str(ca_type),
  1393. "type_basic":{
  1394. "basic_engineering":k1,
  1395. "hardware_engineering":k2,
  1396. "decorated_home":k3,
  1397. "home_appliances":k4
  1398. },
  1399. "type_advanced":{
  1400. "basic_engineering":k5,
  1401. "hardware_engineering":k6,
  1402. "decorated_home":k7,
  1403. "home_appliances":k8
  1404. },
  1405. "type_all":{
  1406. "basic_engineering":k9,
  1407. "hardware_engineering":k10,
  1408. "decorated_home":k11,
  1409. "home_appliances":k12
  1410. }
  1411. }
  1412. json.dumps(jData)
  1413. elif ca_type=="局部裝修":
  1414. jData = {"city":str(city),
  1415. "area":str(area),
  1416. "ca_type": str(ca_type),
  1417. "kitchen_renovation":"18-28",
  1418. "bathroom_refurbishment":"15-21",
  1419. "ceiling":"19-25",
  1420. "windows_and_doors":"13-24",
  1421. "floor_renewal":"18-29"
  1422. }
  1423. json.dumps(jData)
  1424. else:
  1425. jData = {}
  1426. json.dumps(jData)
  1427. return jData
  1428. @app.get("/genrequest")
  1429. async def genrequest():
  1430. id_use = []
  1431. ids = db.query("""SELECT hdesigner_id FROM _hdesigner d where d.emering=1 and d.onoff='1' order by rand();""")
  1432. for c in ids:
  1433. id_use.append(str(c["hdesigner_id"]))
  1434. # with dataset.connect(connstr) as db:
  1435. # jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  1436. jData_all = []
  1437. for id in id_use:
  1438. cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' ORDER BY sdate DESC LIMIT 6 """ )
  1439. cases_list = []
  1440. for case in cases:
  1441. tag_use = ''
  1442. if case['style']!='':
  1443. tag_use += case['style'].strip()
  1444. tag_use += ','
  1445. if case['style2']!='':
  1446. tag_use += case['style2'].strip()
  1447. tag_use += ','
  1448. if case['type']!='':
  1449. tag_use += case['type'].strip()
  1450. tag_use += ','
  1451. if case['condition']!='':
  1452. tag_use += case['condition'].strip()
  1453. tmpobj = {
  1454. "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1455. "imgUrl": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1456. "title": case["caption"],
  1457. "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1458. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1459. "views": case["viewed"],
  1460. "dateSort": str(case["sdate"])
  1461. }
  1462. cases_list.append(tmpobj)
  1463. records = db.query("""SELECT * FROM _hdesigner d WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  1464. for c in records:
  1465. if c["service_phone"]!='':
  1466. part1=c["service_phone"][0:4]
  1467. part2=c["service_phone"][4:7]
  1468. part3=c["service_phone"][7:10]
  1469. part4=c["service_phone"].split(',')[1]
  1470. service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  1471. else:
  1472. service_phone=''
  1473. jData={"hdesignerId":str(c["hdesigner_id"]),
  1474. "designerName":str(c["name"]),
  1475. "companyName": str(c["title"]),
  1476. 'designerBigImg':"./img/"+id,
  1477. "designerIdea":str(c["idea"]),
  1478. "website":str(c["website"]),
  1479. "servicePhone":service_phone,
  1480. "fbUrl":str(c["fbpageurl"]),
  1481. "cardData": cases_list
  1482. }
  1483. jData_all.append(jData)
  1484. json.dumps(jData_all)
  1485. return jData_all
  1486. #################################################################################################
  1487. # def GetList():
  1488. # #SELECT hcase_id,caption,name,sdate,mail,cover FROM _hcase c left join _hdesigner d on c.hdesigner_id = d.hdesigner_id where sdate= CURDATE();;
  1489. # #本週/粉絲/編輯推薦
  1490. # # records = db.query("""SELECT hs.start_time,hs.end_time, ifnull(ca.hdesigner_id,co.hdesigner_ids) hid, ca.hdesigner_id,co.hdesigner_ids, oss.title sec
  1491. # # ,dd.title, dd.name, dd.mail, ifnull(ca.cover,co.clogo) img
  1492. # # FROM homepage_set hs
  1493. # # LEFT JOIN outer_site_set oss ON oss.oss_id = hs.outer_set
  1494. # # left join _hcase ca ON ca.hcase_id = hs.mapping_id AND hs.theme_type='case'
  1495. # # LEFT JOIN _hcolumn co ON hs.mapping_id = co.hcolumn_id AND hs.theme_type='column'
  1496. # # LEFT JOIN _hdesigner dd ON dd.hdesigner_id = ifnull(ca.hdesigner_id,co.hdesigner_ids)
  1497. # # WHERE hs.theme_type IN ('case','column')
  1498. # # and start_time BETWEEN DATE_ADD(CURDATE(), INTERVAL-15 DAY) AND DATE_ADD(NOW(), INTERVAL-1 DAY)
  1499. # # ORDER BY hs.ps_id
  1500. # # """)
  1501. # records = db.query("""
  1502. # SELECT hcase_id,caption,name,sdate,mail,cover,sales_mail FROM _hcase c left join _hdesigner d on c.hdesigner_id = d.hdesigner_id where sdate= CURDATE() and c.onoff=1;
  1503. # """)
  1504. # mList = []
  1505. # for row in records:
  1506. # sMail = str(row['mail'])
  1507. # sName = str(row['name'])
  1508. # sCap = str(row['caption'])
  1509. # sSec = str(row['sdate'])
  1510. # sImg = str(row['cover'])
  1511. # sID = str(row['hcase_id'])
  1512. # sSales_mail = str(row['sales_mail'])
  1513. # # sDuration = row['start_time'].strftime("%Y/%m/%d") + '-' + row['end_time'].strftime("%Y/%m/%d")
  1514. # mList.append([sMail,sCap,sName,sSec,sImg,sID,sSales_mail])
  1515. # #首八大
  1516. # # records = db.query("""SELECT hh.start_time,hh.end_time, hh.hdesigner_id hid, '首頁大' sec
  1517. # # ,dd.title, dd.name, dd.mail, adlogo img
  1518. # # FROM _had hh
  1519. # # LEFT JOIN _hdesigner dd ON dd.hdesigner_id = hh.hdesigner_id
  1520. # # WHERE adtype LIKE '首八大%'
  1521. # # AND hh.onoff='1' AND dd.onoff = '1'
  1522. # # and start_time BETWEEN DATE_ADD(CURDATE(), INTERVAL-1 DAY) AND DATE_ADD(NOW(), INTERVAL-1 DAY)
  1523. # # -- AND(NOW() BETWEEN start_time AND end_time OR(start_time='0000-00-00 00:00:00' and end_time='0000-00-00 00:00:00') or (start_time is null and end_time is NULL))
  1524. # # ORDER BY cast(SUBSTR(adtype,4) AS DECIMAL)
  1525. # # """)
  1526. # # for row in records:
  1527. # # if str(row['hid']) != "":
  1528. # # sMail = row['mail']
  1529. # # sName = row['name']
  1530. # # sCom = row['title']
  1531. # # sSec = row['sec']
  1532. # # sImg = row['img']
  1533. # # sDuration = row['start_time'].strftime("%Y/%m/%d") + '-' + row['end_time'].strftime("%Y/%m/%d")
  1534. # # mList.append([sMail,sCom,sName,sDuration,sSec,sImg])
  1535. # return mList
  1536. #####################################################################################################################
  1537. #print(sMail,sCom,sName,sDuration,sSec)
  1538. @app.post("/SendMail_to_sales")
  1539. async def SendMail_to_sales(request: CalculatorRequest):
  1540. # Replace sender@example.com with your "From" address.
  1541. # This address must be verified with Amazon SES.
  1542. iName = request.name
  1543. iPhone = request.phone
  1544. iEmail = request.email
  1545. iCity = request.city
  1546. iArea = request.area
  1547. iCtype = request.ca_type
  1548. iSource = request.source
  1549. #獲取當前時間
  1550. now = datetime.now()
  1551. #格式化時間
  1552. iDate = now.strftime("%Y.%m.%d %H:%M")
  1553. iHouse="無"
  1554. SENDER = "Gorgeous Space - Mailer <noreply@hhh.com.tw>"
  1555. # Replace recipient@example.com with a "To" address. If your account
  1556. # is still in the sandbox, this address must be verified.
  1557. #RECIPIENT = iRecipient
  1558. # RECIPIENTS = iRecipient.split(',')
  1559. # CCS = iSale_mail.split(',')
  1560. # RECIPIENTS = iRecipient.split(',')
  1561. #寄給業務
  1562. #RECIPIENTS = ["miko@hhh.com.tw","lily_huang@hhh.com.tw","dori@hhh.com.tw","wesson@hhh.com.tw"]
  1563. RECIPIENTS = ["agent@hhh.com.tw"]
  1564. #寄給開發
  1565. #CCS=["oak@choozmo.com"]
  1566. CCS=[]
  1567. # CCS.append("hhh_edit@hhh.com.tw")
  1568. print(RECIPIENTS)
  1569. print(CCS)
  1570. ###之後要改成上面設計師email
  1571. # RECIPIENTS = ["may@hhh.com.tw","jennifer_kao@hhh.com.tw",]
  1572. #RECIPIENTS = ["hhh_edit@hhh.com.tw"]
  1573. #CCS = ["hhh_edit@hhh.com.tw"]
  1574. BCCS = []
  1575. # Specify a configuration set. If you do not want to use a configuration
  1576. # set, comment the following variable, and the
  1577. # ConfigurationSetName=CONFIGURATION_SET argument below.
  1578. #CONFIGURATION_SET = "ConfigSet"
  1579. # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
  1580. AWS_REGION = "us-east-1"
  1581. # The subject line for the email.
  1582. SUBJECT = "幸福空間 裝修需求預算通知 (來自"+iName+'-'+iPhone+")"
  1583. # The email body for recipients with non-HTML email clients.
  1584. # BODY_TEXT = ("\r\n" + iName + " 設計師 , 您好:\r\n我是幸福空間編輯 , 您的個案已經完成並上線!\r\n幸福空間已於"+ iSection +"將您的個案露出於幸福空間網站上"+"\r\n個案名稱 :"+ iCap+"\r\n\r\n"+ iImg+"\r\n\r\n網址: https://hhh.com.tw/cases/detail/d/"+iId+"/\r\n煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!\r\n------------------------------------------------------------\r\n 幸福空間股份有限公司\r\n E-mail : service@choozmo.com \r\n 幸福空間 : https://hhh.com.tw \r\n ")
  1585. # BODY_TEXT = ("\r\n" + " 以下為裝修需求")
  1586. BODY_TEXT = ""
  1587. # :\r\n我是幸福空間編輯 , 您的個案已經完成並上線!\r\n幸福空間已於"+ iSection +"將您的個案露出於幸福空間網站上"+"\r\n個案名稱 :"+ iCap+"\r\n網址: https://hhh.com.tw/cases/detail/d/"+iId+"/\r\n煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!\r\n------------------------------------------------------------\r\n 幸福空間股份有限公司\r\n E-mail : hhh_edit@hhh.com.tw \r\n 幸福空間 : https://hhh.com.tw \r\n ")
  1588. # The HTML body of the email.
  1589. # BODY_HTML = """<html>
  1590. # <head></head>
  1591. # <body>
  1592. # <p>""" + iName + " 設計師 , 您好:<br />我是幸福空間編輯 , 您的個案已經完成並上線!<br />幸福空間已於"+ iSection + "將您的個案露出於幸福空間網站上<br />個案名稱 :"+ iCap+"<br /><br /><img style='width:40%' src='" + iImg + """' /><br /><br />網址: <a href='https://hhh.com.tw/cases/detail/d/"""+iId+"""/' target='_blank'>https://hhh.com.tw/cases/detail/d/"""+iId+"""/</a><br/>
  1593. # 煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!<br/>
  1594. # ------------------------------------------------------------<br/>
  1595. # 幸福空間股份有限公司<br/>
  1596. # E-mail : service@choozmo.com <br/>
  1597. # 幸福空間 : https://hhh.com.tw <br/>
  1598. # </p>
  1599. # </body>
  1600. # </html>"""
  1601. # 读取图片并编码为Base64字符串
  1602. with open('/var/www/html/hhh/genjson/request_template/mailhead.jpg', 'rb') as img_file:
  1603. img_data = img_file.read()
  1604. img_base64 = base64.b64encode(img_data).decode('utf-8')
  1605. #print(img_data)
  1606. BODY_HTML = """<html>
  1607. <head></head>
  1608. <body>
  1609. <img src="https://hhh.com.tw/HHH/calculator_request/img/mailhead.jpg" width="800" height="53" alt="Image" usemap="#image-map">
  1610. <map name="image-map">
  1611. <area target="_blank" alt="幸福空間" title="幸福空間" href="https://hhh.com.tw/" coords="13,8,154,56"
  1612. shape="rect">
  1613. <area target="_blank" alt="Facebook" title="Facebook" href="https://www.facebook.com/hhhfb"
  1614. coords="731,32,24" shape="circle">
  1615. <area target="_blank" alt="YouTube" title="YouTube" href="https://www.youtube.com/user/gorgeousspace"
  1616. coords="751,33,25" shape="circle">
  1617. </map>
  1618. <p>以下為裝修需求 <br />
  1619. <p> 建立時間 : """ + iDate + "<br />姓名 : "+ iName +"<br />手機 : "+ iPhone+"<br />E-mail: "+ iEmail+"<br />縣市區域 : " + iCity +"<br />坪數 : "+ iArea+ "<br/>裝修類型:"+ iCtype+ "<br/>房屋類型:"+ iHouse+ "<br/>需求來源平台:"+ iSource +"<br/>"+"""
  1620. ------------------------------------------------------------<br/>
  1621. 幸福空間股份有限公司<br/>
  1622. E-mail : agent@hhh.com.tw <br/>
  1623. 幸福空間 : https://hhh.com.tw <br/>
  1624. </p>
  1625. </body>
  1626. </html>"""
  1627. # The character encoding for the email.
  1628. CHARSET = "UTF-8"
  1629. # 创建邮件对象
  1630. msg = MIMEMultipart('alternative')
  1631. msg['Subject'] = SUBJECT
  1632. msg['From'] = SENDER
  1633. msg['To'] = ', '.join(RECIPIENTS)
  1634. msg['Cc'] = ', '.join(CCS)
  1635. # 添加图片附件
  1636. #img_attachment = MIMEImage(img_data)
  1637. #img_attachment.add_header('Content-Disposition', 'inline', filename='mailhead.jpg')
  1638. #img_attachment.add_header('Content-ID', '<image_cid>')
  1639. #msg.attach(img_attachment)
  1640. # 创建邮件的HTML部分
  1641. html_part = MIMEText(BODY_HTML, 'html','utf-8')
  1642. print(html_part)
  1643. msg.attach(html_part)
  1644. # Create a new SES resource and specify a region.
  1645. client = boto3.client('ses'
  1646. ,aws_access_key_id='AKIAQG3PJZCHXPCSTAJG'
  1647. ,aws_secret_access_key='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'
  1648. ,region_name=AWS_REGION)
  1649. # Try to send the email.
  1650. try:
  1651. response = client.send_raw_email(
  1652. Source=SENDER,
  1653. Destinations=RECIPIENTS + CCS + BCCS,
  1654. RawMessage={'Data': msg.as_string()}
  1655. )
  1656. # #Provide the contents of the email.
  1657. # response = client.send_email(
  1658. # Destination={
  1659. # 'ToAddresses': RECIPIENTS,
  1660. # 'CcAddresses': CCS,
  1661. # 'BccAddresses': BCCS
  1662. # },
  1663. # Message={
  1664. # 'Body': {
  1665. # 'Html': {
  1666. # 'Charset': CHARSET,
  1667. # 'Data': BODY_HTML,
  1668. # },
  1669. # 'Text': {
  1670. # 'Charset': CHARSET,
  1671. # 'Data': BODY_TEXT,
  1672. # },
  1673. # },
  1674. # 'Subject': {
  1675. # 'Charset': CHARSET,
  1676. # 'Data': SUBJECT,
  1677. # },
  1678. # },
  1679. # Source=SENDER,
  1680. # # If you are not using a configuration set, comment or delete the
  1681. # # following line
  1682. # #ConfigurationSetName=CONFIGURATION_SET,
  1683. # )
  1684. # # Display an error if something goes wrong.
  1685. except ClientError as e:
  1686. print(e.response['Error']['Message'])
  1687. else:
  1688. print("Email sent! Message ID:"),
  1689. print(response['MessageId'])
  1690. return True
  1691. @app.post("/SendMail_to_customer")
  1692. # async def SendMail_to_customer(iRecipient:str,iSale_mail:str, iDate:str,iPhone:str, iName:str, iCity:str, iArea:str,iCtype:str,iEmail:str):
  1693. async def SendMail_to_customer(request: CalculatorRequest):
  1694. # Replace sender@example.com with your "From" address.
  1695. # This address must be verified with Amazon SES.
  1696. SENDER = "Gorgeous Space - Mailer <noreply@hhh.com.tw>"
  1697. # Replace recipient@example.com with a "To" address. If your account
  1698. # is still in the sandbox, this address must be verified.
  1699. #RECIPIENT = iRecipient
  1700. iName = request.name
  1701. iPhone = request.phone
  1702. iEmail = request.email
  1703. iCity = request.city
  1704. iArea = request.area
  1705. iCtype = request.ca_type
  1706. #獲取當前時間
  1707. now = datetime.now()
  1708. #格式化時間
  1709. iDate = now.strftime("%Y.%m.%d %H:%M")
  1710. iHouse="無"
  1711. # RECIPIENTS = iRecipient.split(',')
  1712. # CCS = iSale_mail.split(',')
  1713. #寄給填寫email
  1714. RECIPIENTS = []
  1715. RECIPIENTS.append(iEmail)
  1716. #寄給開發
  1717. #CCS=['oak@choozmo.com']
  1718. CCS=[]
  1719. CCS.append("agent@hhh.com.tw")
  1720. print(RECIPIENTS)
  1721. print(CCS)
  1722. ###之後要改成上面設計師email
  1723. # RECIPIENTS = ["may@hhh.com.tw","jennifer_kao@hhh.com.tw",]
  1724. #RECIPIENTS = ["hhh_edit@hhh.com.tw"]
  1725. #CCS = ["hhh_edit@hhh.com.tw"]
  1726. BCCS = []
  1727. # Specify a configuration set. If you do not want to use a configuration
  1728. # set, comment the following variable, and the
  1729. # ConfigurationSetName=CONFIGURATION_SET argument below.
  1730. #CONFIGURATION_SET = "ConfigSet"
  1731. # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
  1732. AWS_REGION = "us-east-1"
  1733. # The subject line for the email.
  1734. SUBJECT = "幸福空間 裝修需求預算通知 (來自"+iName+'-'+iPhone+")"
  1735. # The email body for recipients with non-HTML email clients.
  1736. # BODY_TEXT = ("\r\n" + iName + " 設計師 , 您好:\r\n我是幸福空間編輯 , 您的個案已經完成並上線!\r\n幸福空間已於"+ iSection +"將您的個案露出於幸福空間網站上"+"\r\n個案名稱 :"+ iCap+"\r\n\r\n"+ iImg+"\r\n\r\n網址: https://hhh.com.tw/cases/detail/d/"+iId+"/\r\n煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!\r\n------------------------------------------------------------\r\n 幸福空間股份有限公司\r\n E-mail : service@choozmo.com \r\n 幸福空間 : https://hhh.com.tw \r\n ")
  1737. # BODY_TEXT = ("\r\n" + " 以下為裝修需求")
  1738. BODY_TEXT = ""
  1739. # :\r\n我是幸福空間編輯 , 您的個案已經完成並上線!\r\n幸福空間已於"+ iSection +"將您的個案露出於幸福空間網站上"+"\r\n個案名稱 :"+ iCap+"\r\n網址: https://hhh.com.tw/cases/detail/d/"+iId+"/\r\n煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!\r\n------------------------------------------------------------\r\n 幸福空間股份有限公司\r\n E-mail : hhh_edit@hhh.com.tw \r\n 幸福空間 : https://hhh.com.tw \r\n ")
  1740. # The HTML body of the email.
  1741. # BODY_HTML = """<html>
  1742. # <head></head>
  1743. # <body>
  1744. # <p>""" + iName + " 設計師 , 您好:<br />我是幸福空間編輯 , 您的個案已經完成並上線!<br />幸福空間已於"+ iSection + "將您的個案露出於幸福空間網站上<br />個案名稱 :"+ iCap+"<br /><br /><img style='width:40%' src='" + iImg + """' /><br /><br />網址: <a href='https://hhh.com.tw/cases/detail/d/"""+iId+"""/' target='_blank'>https://hhh.com.tw/cases/detail/d/"""+iId+"""/</a><br/>
  1745. # 煩請您上網查收點閱,若有需要增刪修改之處,還請不吝提出指教,謝謝!<br/>
  1746. # ------------------------------------------------------------<br/>
  1747. # 幸福空間股份有限公司<br/>
  1748. # E-mail : service@choozmo.com <br/>
  1749. # 幸福空間 : https://hhh.com.tw <br/>
  1750. # </p>
  1751. # </body>
  1752. # </html>"""
  1753. BODY_HTML = """<html>
  1754. <head></head>
  1755. <body>
  1756. <img src="https://hhh.com.tw/HHH/calculator_request/img/mailhead.jpg" width="800" height="53" alt="Image" usemap="#image-map">
  1757. <map name="image-map">
  1758. <area target="_blank" alt="幸福空間" title="幸福空間" href="https://hhh.com.tw/" coords="13,8,154,56"
  1759. shape="rect">
  1760. <area target="_blank" alt="Facebook" title="Facebook" href="https://www.facebook.com/hhhfb"
  1761. coords="731,32,24" shape="circle">
  1762. <area target="_blank" alt="YouTube" title="YouTube" href="https://www.youtube.com/user/gorgeousspace"
  1763. coords="751,33,25" shape="circle">
  1764. </map>
  1765. <p>親愛的"""+iName+""",<br />
  1766. <p> 非常感謝您在幸福空間官網留下您的裝修需求。<br/> 以下是您填寫的資訊:<br/>"""+ "<br />建立時間: "+ iDate + "<br />姓名 : "+ iName +"<br />手機 : "+ iPhone+"<br />E-mail: "+ iEmail+"<br />縣市區域 : " + iCity +"<br />坪數 : "+ iArea+ "<br/>裝修類型:"+ iCtype+ "<br/>"+"""
  1767. <br/>
  1768. 幸福經紀人將後續與您聯繫,以便確認您的需求,<br/>
  1769. 並向您推薦最適合的裝修方案。<br/>
  1770. <br/>
  1771. 歡迎您至幸福空間官網參考更多設計風格案例作品<br/>
  1772. <br/>
  1773. </p>
  1774. <img src="https://hhh.com.tw/HHH/calculator_request/img/mailfooter.jpg" width="800" height="600" alt="Image" usemap="#image-map1">
  1775. <map name="image-map1">
  1776. <area shape="rect" coords="64,88,388,242" href="https://hhh.com.tw/photos/lists/modern-style/" target="_blank" />
  1777. <!-- 右上 -->
  1778. <area shape="rect" coords="412,91,733,239" href="https://hhh.com.tw/photos/lists/nordic-style/" target="_blank" />
  1779. <!-- 左下 -->
  1780. <area shape="rect" coords="64,266,387,413" href="https://hhh.com.tw/photos/lists/american-style/" target="_blank" />
  1781. <!-- 右下 -->
  1782. <area shape="rect" coords="419,265,730,410" href="https://hhh.com.tw/photos/lists/mashup-style/" target="_blank" />
  1783. <area shape="rect" coords="0,422,795,596" href="https://event.hhh.com.tw/agent/" target="_blank" />
  1784. </map>
  1785. </body>
  1786. </html>"""
  1787. # The character encoding for the email.
  1788. CHARSET = "UTF-8"
  1789. # Create a new SES resource and specify a region.
  1790. client = boto3.client('ses'
  1791. ,aws_access_key_id='AKIAQG3PJZCHXPCSTAJG'
  1792. ,aws_secret_access_key='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'
  1793. ,region_name=AWS_REGION)
  1794. # Try to send the email.
  1795. try:
  1796. #Provide the contents of the email.
  1797. response = client.send_email(
  1798. Destination={
  1799. 'ToAddresses': RECIPIENTS,
  1800. 'CcAddresses': CCS,
  1801. 'BccAddresses': BCCS
  1802. },
  1803. Message={
  1804. 'Body': {
  1805. 'Html': {
  1806. 'Charset': CHARSET,
  1807. 'Data': BODY_HTML,
  1808. },
  1809. 'Text': {
  1810. 'Charset': CHARSET,
  1811. 'Data': BODY_TEXT,
  1812. },
  1813. },
  1814. 'Subject': {
  1815. 'Charset': CHARSET,
  1816. 'Data': SUBJECT,
  1817. },
  1818. },
  1819. Source=SENDER,
  1820. # If you are not using a configuration set, comment or delete the
  1821. # following line
  1822. #ConfigurationSetName=CONFIGURATION_SET,
  1823. )
  1824. # Display an error if something goes wrong.
  1825. except ClientError as e:
  1826. print(e.response['Error']['Message'])
  1827. else:
  1828. print("Email sent! Message ID:"),
  1829. print(response['MessageId'])
  1830. return True
  1831. # for item in GetList():
  1832. # #print(item)
  1833. # SendMail(item[0],item[1],item[2],item[3],item[4],item[5],item[6])
  1834. # with dataset.connect(connstr) as db:
  1835. # jData = json.load(open(hhhMBPath+'/json/designers.json', encoding='utf8'))
  1836. # cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1' ORDER BY sdate DESC LIMIT 6 """ )
  1837. # cases_list = []
  1838. # for case in cases:
  1839. # tag_use = ''
  1840. # if case['style']!='':
  1841. # tag_use += case['style'].strip()
  1842. # tag_use += ','
  1843. # if case['style2']!='':
  1844. # tag_use += case['style2'].strip()
  1845. # tag_use += ','
  1846. # if case['type']!='':
  1847. # tag_use += case['type'].strip()
  1848. # tag_use += ','
  1849. # if case['condition']!='':
  1850. # tag_use += case['condition'].strip()
  1851. # tmpobj = {
  1852. # "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  1853. # "imgURL": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  1854. # "title": case["caption"],
  1855. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  1856. # # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  1857. # "views": case["viewed"],
  1858. # "dateSort": str(case["sdate"])
  1859. # }
  1860. # cases_list.append(tmpobj)
  1861. # records = db.query("""SELECT * FROM _hdesigner d WHERE d.hdesigner_id = '""" + id + """' AND d.onoff='1' """)
  1862. # jData = []
  1863. # for c in records:
  1864. # if c["service_phone"]!='':
  1865. # part1=c["service_phone"][0:4]
  1866. # part2=c["service_phone"][4:7]
  1867. # part3=c["service_phone"][7:10]
  1868. # part4=c["service_phone"].split(',')[1]
  1869. # service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  1870. # else:
  1871. # service_phone=''
  1872. # jData.append({"hdesigner_id":str(c["hdesigner_id"]),
  1873. # "DesignerName":str(c["name"]),
  1874. # "CompanyName": str(c["title"]),
  1875. # 'Designerbigimg':"./img/"+id,
  1876. # "DesignerIdea":str(c["idea"]),
  1877. # "Website":str(c["website"]),
  1878. # "Service_phone":service_phone,
  1879. # "FB_url":str(c["fbpageurl"]),
  1880. # "Carddata": cases_list
  1881. # })
  1882. # json.dumps(jData)
  1883. # return jData
  1884. # check_len=[]
  1885. # for c in records:
  1886. # check_len.append(c)
  1887. # if len(check_len)==0:
  1888. # return []
  1889. # # print(jData)
  1890. # for x in jData:
  1891. # tmpCaseDetail = []
  1892. # icount = 0
  1893. # for c in records:
  1894. # icount += 1
  1895. # # tmpCaseDetail.append({"CaseDetailImg":c["cimg"]})
  1896. # if page == "1":
  1897. # x["id"] = c["hdesigner_id"]
  1898. # x["BannerImg"] = c["background"]
  1899. # x["BannerImg_mobile"] = c['background_mobile']
  1900. # x["CompanyName"] = c["title"]
  1901. # x["DesignerName"] = c["name"]
  1902. # x["Designerimg"] = c["img_path"]
  1903. # x["Description"] = c["seo"]
  1904. # x["Approve"] = c["position"]
  1905. # x["FB_link"] = c["fbpageurl"]
  1906. # # x["order_computer"] = c["order_computer"]
  1907. # # x["order_mb"] = c["order_mb"]
  1908. # if c["service_phone"]!='':
  1909. # part1=c["service_phone"][0:4]
  1910. # part2=c["service_phone"][4:7]
  1911. # part3=c["service_phone"][7:10]
  1912. # part4=c["service_phone"].split(',')[1]
  1913. # service_phone = part1+'-'+part2+'-'+part3+'#'+part4
  1914. # else:
  1915. # service_phone=''
  1916. # phone_list=[]
  1917. # for k1 in c["phone"].split(','):
  1918. # phone_list.append({"title": "諮詢專線:", "link":'tel:'+k1, "data":k1})
  1919. # x["Basics"] = []
  1920. # if service_phone!='':
  1921. # x["Basics"].append({"title": "免費專線:","link": 'tel:'+c["service_phone"], "data": service_phone})
  1922. # for k2 in phone_list:
  1923. # x["Basics"].append(k2)
  1924. # if len(c["fax"])!=0:
  1925. # x["Basics"].append({"title": "公司傳真:", "link": "fax:"+c["fax"], "data": c["fax"]})
  1926. # if len(c["address"])!=0:
  1927. # x["Basics"].append({"title": "公司地址:", "link": "https://www.google.com/search?q="+c["address"], "data": c["address"]})
  1928. # if len(c["mail"])!=0:
  1929. # x["Basics"].append({"title": "電子信箱:", "link": "mailto:"+c["mail"], "data": c["mail"]})
  1930. # if len(c["website"])!=0:
  1931. # x["Basics"].append({"title": "公司網址:", "link": c["website"], "data": c["website"]})
  1932. # blog_list=re.findall(r'href="(.*?)"',c["blog"])
  1933. # if len(blog_list)==0:
  1934. # blog_list=re.findall(r'http.*',c["blog"])
  1935. # if len(blog_list)!=0:
  1936. # for k3 in blog_list:
  1937. # x["Basics"].append({"title": "其他連結:", "link": k3, "data": k3})
  1938. # # x["Basics"] = [
  1939. # # {"title": "免費專線:","link": 'tel:'+c["service_phone"], "data": service_phone},
  1940. # # # {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  1941. # # {"title": "諮詢專線:", "link": c["phone"], "data": c["phone"]},
  1942. # # {"title": "公司傳真:", "link": c["fax"], "data": c["fax"]},
  1943. # # {"title": "公司地址:", "link": c["address"], "data": c["address"]},
  1944. # # {"title": "電子信箱:", "link": c["mail"], "data": c["mail"]},
  1945. # # {"title": "公司網址:", "link": c["website"], "data": c["website"]}
  1946. # # ]
  1947. # x["FreeCall"] = c["service_phone"]
  1948. # x["ConsoleCall_1"] = c["phone"]
  1949. # x["ConsoleCall_2"] = c["phone"]
  1950. # x["Fax"] = c["fax"]
  1951. # x["Address"] = c["address"]
  1952. # x["Email"] = c["mail"]
  1953. # x["Web"] = c["website"]
  1954. # x["Branches"] = []
  1955. # branches = db.query("""SELECT * FROM designer_branch br
  1956. # WHERE br.designer_id = '""" + id + """' """)
  1957. # for branch in branches:
  1958. # tmpobj = {
  1959. # "title": branch["title"],
  1960. # "address": branch["address"],
  1961. # "address_link" : "https://www.google.com/search?q="+branch["address"],
  1962. # "tel": branch["tel"],
  1963. # "tel_link": "tel:"+branch["tel"],
  1964. # "fax": branch["fax"],
  1965. # "fax_link": "fax:"+branch["fax"]
  1966. # }
  1967. # x["Branches"].append(tmpobj)
  1968. # x["Budget"] = c["budget"]
  1969. # x["Square"] = c["area"]
  1970. # x["SpecialCase"] = c["special"]
  1971. # x["Charge"] = c["charge"]
  1972. # x["Pay"] = c["payment"]
  1973. # x["WorkLoc"] = c["region"]
  1974. # x["WorkType"] = c["type"]
  1975. # x["WorkStyle"] = c["style"]
  1976. # x["WorkBudget"] = c["budget"]
  1977. # x["Terms"] = []
  1978. # if c["budget"]!='':
  1979. # x["Terms"].append({"title": "接案預算:", "data": c["budget"]})
  1980. # if c["area"]!='':
  1981. # x["Terms"].append({"title": "接案坪數:", "data": c["area"]})
  1982. # if c["special"]!='':
  1983. # x["Terms"].append({"title": "特殊接案:", "data": c["special"]})
  1984. # if c["charge"]!='':
  1985. # x["Terms"].append({"title": "收費方式:", "data": c["charge"]})
  1986. # if c["payment"]!='':
  1987. # x["Terms"].append({"title": "付費方式:", "data": c["payment"]})
  1988. # if c["region"]!='':
  1989. # x["Terms"].append({"title": "接案區域:", "data": c["region"]})
  1990. # if c["type"]!='':
  1991. # x["Terms"].append({"title": "接案類型:", "data": c["type"]})
  1992. # if c["style"]!='':
  1993. # x["Terms"].append({"title": "接案風格:", "data": c["style"]})
  1994. # x["scMedia"] = [
  1995. # {"name": "Facebook", "img": "https://hhh.com.tw/assets/images/rv_web/fb.svg",
  1996. # "link": c["fbpageurl"]},
  1997. # {"name": "Line", "img": "https://hhh.com.tw/assets/images/rv_web/line.svg",
  1998. # "link": c["line_link"]},
  1999. # {"name": "Wechat", "img": "https://hhh.com.tw/assets/images/rv_web/wechat.svg",
  2000. # "link": c["fbpageurl"]},
  2001. # {"name": "email", "img": "https://hhh.com.tw/assets/images/rv_web/share.svg",
  2002. # "link": c["mail"]},
  2003. # {"name": "Like", "img": "https://hhh.com.tw/assets/images/rv_web/like-o.svg", "link": ""}
  2004. # ]
  2005. # x_info = []
  2006. # if len(c["idea"])!=0:
  2007. # x_info.append({"title": "設計理念", "data": c["idea"]})
  2008. # if len(c["taxid"])!=0:
  2009. # x_info.append( {"title": "公司統編", "data": c["taxid"]})
  2010. # if len(c["career"])!=0:
  2011. # x_info.append({"title": "相關經歷", "data": c["career"]})
  2012. # if len(c["license"])!=0:
  2013. # x_info.append( {"title": "專業證照", "data": c["license"].replace('\r\n','<br />')})
  2014. # if len(c["awards"])!=0:
  2015. # x_info.append( {"title": "獲獎紀錄", "data": c["awards"].replace('\r\n','<br />')})
  2016. # x["Content"] = [
  2017. # {
  2018. # "Title": "設計師作品",
  2019. # "mb_title": "作品",
  2020. # "Tabtag": "intro",
  2021. # "Display_mb": "true",
  2022. # "isActive": "true",
  2023. # "Carddata": [],
  2024. # "total_all":0
  2025. # },
  2026. # {
  2027. # "Title": "設計師影音",
  2028. # "mb_title": "影音",
  2029. # "Tabtag": "video",
  2030. # "Display_mb": "true",
  2031. # "isActive": "true",
  2032. # "Carddata": [],
  2033. # "total_all":0
  2034. # },
  2035. # {
  2036. # "Title": "設計師專欄",
  2037. # "mb_title": "專欄",
  2038. # "Tabtag": "columns",
  2039. # "Display_mb": "true",
  2040. # "isActive": "true",
  2041. # "Carddata": [],
  2042. # "total_all":0
  2043. # },
  2044. # {
  2045. # "Title": "VR360",
  2046. # "mb_title": "VR",
  2047. # "Tabtag": "vr360",
  2048. # "Display_mb": "false",
  2049. # "isActive": "true",
  2050. # "Carddata": [],
  2051. # "total_all":0
  2052. # },
  2053. # {
  2054. # "Title": "設計師公司簡介",
  2055. # "mb_title": "公司簡介",
  2056. # "Tabtag": "company",
  2057. # "Display_mb": "true",
  2058. # "isActive": "true",
  2059. # "Carddata": [],
  2060. # "info":x_info
  2061. # # "info": [
  2062. # # {"title": "設計理念", "data": c["idea"]},
  2063. # # {"title": "公司統編", "data": c["taxid"]},
  2064. # # {"title": "相關經歷", "data": c["career"]},
  2065. # # {"title": "專業證照", "data": c["license"]},
  2066. # # {"title": "獲獎紀錄", "data": c["awards"]}
  2067. # # ]
  2068. # }
  2069. # ]
  2070. # records = db.query("""SELECT count(1) FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1'; """ )
  2071. # for c in records:
  2072. # x["Content"][0]["total_all"] = str(c["count(1)"])
  2073. # records = db.query("""SELECT count(1) FROM _hvideo v WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW() and iframe<>'' ;""")
  2074. # for c in records:
  2075. # x["Content"][1]["total_all"] = str(c["count(1)"])
  2076. # records = db.query("""SELECT count(1) FROM _hcolumn c WHERE onoff=1 AND (c.hdesigner_ids LIKE '""" + id + """,%' OR c.hdesigner_ids LIKE '%,""" + id + """,%' OR c.hdesigner_ids LIKE '%,""" + id + """' OR c.hdesigner_ids = '""" + id + """') ;""")
  2077. # for c in records:
  2078. # x["Content"][2]["total_all"] = str(c["count(1)"])
  2079. # records = db.query("""SELECT count(1) FROM _hcase c WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1' ;""")
  2080. # for c in records:
  2081. # x["Content"][3]["total_all"] = str(c["count(1)"])
  2082. # # 設計師作品
  2083. # x["Content"][0]["Carddata"] = []
  2084. # cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate,style,style2,type,`condition` FROM _hcase c
  2085. # WHERE c.hdesigner_id = '""" + id + """' AND c.onoff='1'
  2086. # ORDER BY """ + ("sdate" if sort == 'new' else 'corder ASC,viewed') + """ DESC
  2087. # LIMIT """ + str((int(page) - 1)*12) + """,12
  2088. # """)
  2089. # for case in cases:
  2090. # tag_use = ''
  2091. # if case['style']!='':
  2092. # tag_use += case['style'].strip()
  2093. # tag_use += ','
  2094. # if case['style2']!='':
  2095. # tag_use += case['style2'].strip()
  2096. # tag_use += ','
  2097. # if case['type']!='':
  2098. # tag_use += case['type'].strip()
  2099. # tag_use += ','
  2100. # if case['condition']!='':
  2101. # tag_use += case['condition'].strip()
  2102. # tmpobj = {
  2103. # "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  2104. # "imgURL": case["cover"].replace('/_hcase/', '/_hcase_orig/').replace('/_hcase_img/', '/_hcase_img_orig/'),
  2105. # "title": case["caption"],
  2106. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in tag_use.split(',')],
  2107. # # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/case/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  2108. # "views": case["viewed"],
  2109. # "dateSort": str(case["sdate"])
  2110. # }
  2111. # x["Content"][0]["Carddata"].append(tmpobj)
  2112. # # 設計師影音
  2113. # # https://i.ytimg.com/vi/y6VmaLC7O9Y/hqdefault.jpg
  2114. # x["Content"][1]["Carddata"] = []
  2115. # videos = db.query("""SELECT tag_vpattern,iframe,title,hvideo_id,viewed,display_datetime FROM _hvideo v
  2116. # WHERE v.hdesigner_id = '""" + id + """' AND display_datetime < NOW() and iframe<>''
  2117. # ORDER BY """ + ("hvideo_id" if sort == 'new' else 'viewed') + """ DESC
  2118. # LIMIT """ + str((int(page) - 1)*12) + """,12
  2119. # """)
  2120. # for video in videos:
  2121. # print(str(video['iframe']))
  2122. # tmpobj = {
  2123. # "url": "https://hhh.com.tw/video-post.php?id="+str(video['hvideo_id']),
  2124. # "imgURL": "https://i.ytimg.com/vi/" + extract.video_id(html.unescape(str(video['iframe'])))+"/hqdefault.jpg",
  2125. # "title": video["title"],
  2126. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/video/{}-keyword/".format(tag)} for tag in video["tag_vpattern"].split(',')],
  2127. # "views": video["viewed"],
  2128. # "dateSort": str(video["display_datetime"])
  2129. # }
  2130. # x["Content"][1]["Carddata"].append(tmpobj)
  2131. # # 設計師專欄
  2132. # x["Content"][2]["Carddata"] = []
  2133. # columns = db.query("""SELECT Ctag,clogo,ctitle,hcolumn_id,viewed,sdate FROM _hcolumn c
  2134. # WHERE onoff=1 AND (hdesigner_ids LIKE '""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """,%' OR hdesigner_ids LIKE '%,""" + id + """' OR hdesigner_ids = '""" + id + """')
  2135. # ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  2136. # LIMIT """ + str((int(page) - 1)*12) + """,12
  2137. # """)
  2138. # for column in columns:
  2139. # tmpobj = {
  2140. # "url": "https://hhh.com.tw/columns/detail/"+str(column['hcolumn_id']),
  2141. # "imgURL": column['clogo'],
  2142. # "title": column["ctitle"],
  2143. # "tag": [] if not column["Ctag"] else [{"name": tag, "link": "https://hhh.com.tw/search/lists/column/{}-keyword/".format(tag)} for tag in column["Ctag"].split(',')],
  2144. # "views": column["viewed"],
  2145. # "dateSort": str(column["sdate"])
  2146. # }
  2147. # x["Content"][2]["Carddata"].append(tmpobj)
  2148. # # VR360
  2149. # x["Content"][3]["Carddata"] = []
  2150. # cases = db.query("""SELECT tag,cover,caption,hcase_id,viewed,sdate FROM _hcase c
  2151. # WHERE c.hdesigner_id = '""" + id + """' and istaging != '' AND c.onoff='1'
  2152. # ORDER BY """ + ("sdate" if sort == 'new' else 'viewed') + """ DESC
  2153. # LIMIT """ + str((int(page) - 1)*12) + """,12
  2154. # """)
  2155. # for case in cases:
  2156. # tmpobj = {
  2157. # "url": "https://hhh.com.tw/cases/detail/d/"+str(case["hcase_id"]),
  2158. # "imgURL": case["cover"],
  2159. # "title": case["caption"],
  2160. # "tag": [{"name": tag, "link": "https://hhh.com.tw/search/lists/column/{}-keyword/".format(tag)} for tag in case["tag"].split(',')],
  2161. # "views": case["viewed"],
  2162. # "dateSort": str(case["sdate"])
  2163. # }
  2164. # x["Content"][3]["Carddata"].append(tmpobj)
  2165. # # 設計公司簡介
  2166. # #x["Content"][4]["Carddata"] = []
  2167. # #cases = db.query("")
  2168. # """ for case in cases:
  2169. # tmpobj = {
  2170. # "imgURL":case["cover"],
  2171. # "title":case["caption"],
  2172. # "tag":[{"name": tag, "link": ""} for tag in case["tag"].split(',')],
  2173. # "views":case["viewed"],
  2174. # "dateSort":str(case["sdate"])
  2175. # }
  2176. # x["Content"][4]["Carddata"].append(tmpobj) """
  2177. # # print(x)
  2178. # # print(jData)
  2179. # """ if not os.path.exists(hhhMBPath):
  2180. # os.mkdir(hhhMBPath)
  2181. # with open(hhhMBPath+'/json/designers-' + id + '.json', 'w', encoding='utf-8') as f:
  2182. # json.dump(jData, f, ensure_ascii=False, indent=4) """