WorkAreaApiController.cs 122 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617
  1. using Dapper;
  2. using iTextSharp.text.pdf;
  3. using MassTransit;
  4. using Microsoft.AspNetCore.Authorization;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Extensions.Configuration;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Linq;
  10. using Npgsql;
  11. using RabbitMQ.Client.Framing.Impl;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Data;
  15. using System.IO;
  16. using System.IO.Compression;
  17. using System.Linq;
  18. using System.Net;
  19. using System.Reflection.PortableExecutable;
  20. using System.Security.Cryptography;
  21. using System.Security.Principal;
  22. using System.Text.RegularExpressions;
  23. using System.Threading.Tasks;
  24. using System.Xml.Linq;
  25. using WK_KLI_LAPS_COMMONTOOL_Service.App_Data;
  26. using WK_KLI_LAPS_COMMONTOOL_Service.Models;
  27. using static MassTransit.Logging.LogCategoryName;
  28. namespace WK_KLI_LAPS_COMMONTOOL_Service.Controllers.WorkArea
  29. {
  30. [Route("api/[controller]")]
  31. [ApiController]
  32. public class WorkAreaApiController : ControllerBase
  33. {
  34. CommonRepository oCommonRepository = new CommonRepository();
  35. WorkAreaService oWorkAreaService = new WorkAreaService();
  36. string baseurl = Startup.Configuration.GetValue<string>("AppSettings:serverroot");
  37. [AllowAnonymous]
  38. [HttpPost("getCheckout")]
  39. public IActionResult getCheckout([FromBody] object data)
  40. {
  41. try
  42. {
  43. var _list = oWorkAreaService.getCheckout(data);
  44. return Ok(_list);
  45. }
  46. catch (Exception ex)
  47. {
  48. oCommonRepository.ErrorLog(ex);
  49. // return error message if there was an exception
  50. return BadRequest(new { message = ex.Message });
  51. }
  52. }
  53. [AllowAnonymous]
  54. [HttpPost("usrstagemove")]
  55. public IActionResult usrstagemove([FromBody] lottraninfo data)
  56. {
  57. try
  58. {
  59. var _list = oWorkAreaService.usrstagemove(data);
  60. return Ok(_list);
  61. }
  62. catch (Exception ex)
  63. {
  64. oCommonRepository.ErrorLog(ex);
  65. // return error message if there was an exception
  66. return BadRequest(new { message = ex.Message });
  67. }
  68. }
  69. [AllowAnonymous]
  70. [HttpPost("getJobDetails")]
  71. public IActionResult getJobDetails([FromBody] object data)
  72. {
  73. var _list = oWorkAreaService.getJobDetails(data);
  74. return Ok(_list);
  75. }
  76. [AllowAnonymous]
  77. [HttpPost("getLotDetailsComments")]
  78. public IActionResult getLotDetailsComments([FromBody] object data)
  79. {
  80. var _list = oWorkAreaService.getLotDetailsComments(data);
  81. return Ok(_list);
  82. }
  83. [HttpPost("getLotDetailsOCR")]
  84. public IActionResult GetLotDetailsOCR([FromBody] JobRequest request)
  85. {
  86. if (request == null || request.JobId <= 0)
  87. return BadRequest("Invalid job ID");
  88. string serverinfo = string.Empty;
  89. var resultObj = oWorkAreaService.getLotDetailsOCR(request.JobId);
  90. // Convert to int safely
  91. int tranid = 0;
  92. if (resultObj != null)
  93. {
  94. // If resultObj is a list and you want the first item:
  95. var list = resultObj as IEnumerable<object>;
  96. if (list != null && list.Any())
  97. {
  98. tranid = Convert.ToInt32(list.First());
  99. }
  100. serverinfo = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
  101. }
  102. return Ok(serverinfo);
  103. }
  104. [HttpGet("DownloadFile")]
  105. public async Task<IActionResult> DownloadFile([FromQuery] string path, [FromQuery] string title, [FromQuery] string jobid)
  106. {
  107. if (string.IsNullOrWhiteSpace(path))
  108. return BadRequest("Folder path is required.");
  109. try
  110. {
  111. // ✅ Validate allowed network base path
  112. string allowedBasePath = @"\\pdynxfs\OEB_xml";
  113. if (!path.StartsWith(allowedBasePath, StringComparison.OrdinalIgnoreCase))
  114. return BadRequest("Access to this path is not allowed.");
  115. // ✅ Append subfolder if needed
  116. path = Path.Combine(path, "IN");
  117. if (!Directory.Exists(path))
  118. return NotFound("Folder not found.");
  119. // ✅ Fallback title
  120. if (string.IsNullOrWhiteSpace(title))
  121. title = "Download";
  122. var zipFileName = $"{title}.zip";
  123. // ✅ Use application temp folder instead of system temp
  124. string tempBase = Path.Combine(System.AppContext.BaseDirectory, "TempZips");
  125. Directory.CreateDirectory(tempBase); // ensure exists
  126. var tempZipPath = Path.Combine(tempBase, zipFileName);
  127. // ✅ Remove existing temp ZIP (if any)
  128. if (System.IO.File.Exists(tempZipPath))
  129. System.IO.File.Delete(tempZipPath);
  130. // ✅ Impersonate with granted folder permission
  131. using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  132. {
  133. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  134. await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
  135. {
  136. // Step 1: Create ZIP (no compression = faster)
  137. ZipFile.CreateFromDirectory(path, tempZipPath, CompressionLevel.NoCompression, includeBaseDirectory: true);
  138. await Task.CompletedTask; // keep async signature clean
  139. });
  140. }
  141. // Step 2: Stream ZIP asynchronously to response
  142. Response.ContentType = "application/zip";
  143. Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{zipFileName}\"");
  144. await using (var stream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  145. {
  146. await stream.CopyToAsync(Response.Body);
  147. }
  148. // Step 3: Delete temporary ZIP
  149. try
  150. {
  151. System.IO.File.Delete(tempZipPath);
  152. }
  153. catch
  154. {
  155. // ignore file delete issues
  156. }
  157. return new EmptyResult(); // response already written
  158. }
  159. catch (Exception ex)
  160. {
  161. // ✅ Log the error
  162. oCommonRepository.addlog(new
  163. {
  164. errormessage = "Error: " + ex.Message,
  165. createdby = 0,
  166. controller = "WorkAreaApi: DownloadFile"
  167. }, "errorlog");
  168. return StatusCode(500, $"Error while downloading folder: {ex.Message}");
  169. }
  170. }
  171. [HttpPost]
  172. public object PostValidateQA(Fields fields)
  173. {
  174. //DBContext db = new DBContext();
  175. //db.CheckLogin();
  176. var json = new List<object>();
  177. //try
  178. //{
  179. // BLDatamanipulation db_ = new BLDatamanipulation();
  180. // DataTable svrpath = db_.GetDataTable(db, string.Format("select * from usr_server_path_info({0},'serverinfo')", fields.transid), null);
  181. // string serverpath = svrpath.Rows[0]["serverpath"].ToString();
  182. // serverpath = "\\\\" + serverpath.Replace("/", "\\");
  183. // string serveroutpath = System.IO.Path.Combine(serverpath, "OUT");
  184. // string serverinpath = System.IO.Path.Combine(serverpath, "IN");
  185. // var ext = new List<string> { ".pdf", ".xml" };
  186. // if (Directory.Exists(serveroutpath) && Directory.Exists(serverinpath))
  187. // {
  188. // List<string> infile = Directory.GetFiles(serverinpath, "*.*", SearchOption.AllDirectories)
  189. // .Where(s => ext.Contains(Path.GetExtension(s).ToLower())).Select(x => Path.GetFileName(x)).ToList();
  190. // List<string> outfile = Directory.GetFiles(serveroutpath, "*.*", SearchOption.AllDirectories)
  191. // .Where(s => ext.Contains(Path.GetExtension(s).ToLower())).Select(x => Path.GetFileName(x)).ToList();
  192. // List<string> exept = infile.Except(outfile).ToList();
  193. // if (exept.Count > 0)
  194. // {
  195. // json.Add(JObject.Parse("{\"success\":false}"));
  196. // json.Add(JObject.Parse("{\"log\":\"Please completed QA process then proceed.\"}"));
  197. // }
  198. // else
  199. // {
  200. // if (File.Exists(Path.Combine(serveroutpath, "error.txt")))
  201. // {
  202. // json.Add(JObject.Parse("{\"success\":false}"));
  203. // json.Add(JObject.Parse("{\"log\":\"Please clear the validation error then proceed.\"}"));
  204. // }
  205. // else
  206. // json.Add(JObject.Parse("{\"success\":true}"));
  207. // }
  208. // }
  209. // else { json.Add(JObject.Parse("{\"success\":false}")); json.Add(JObject.Parse("{\"log\":\"Please completed QA process then proceed.\"}")); }
  210. //}
  211. //catch (Exception ex)
  212. //{
  213. // json.Add(JObject.Parse("{\"success\":false}"));
  214. // json.Add(JObject.Parse("{\"log\":\"Process failed. " + ex.Message + "\"}"));
  215. //}
  216. return json;
  217. }
  218. //raji
  219. [Authorize]
  220. [HttpPost("savefilechecker")]
  221. public object savefilechecker()
  222. {
  223. bool dirvalidate = false;
  224. bool filevalidate = false;
  225. string message = "";
  226. try
  227. {
  228. //var json =[];
  229. var httpRequest = HttpContext.Request.Form;
  230. string filepath = string.Empty;
  231. string actualdirectory = string.Empty;
  232. string filepath_name = string.Empty;
  233. string lottitles = string.Empty;
  234. string jobtitle = string.Empty;
  235. string dirName = string.Empty;
  236. //int charIndex = 0;
  237. string retmsg = string.Empty;
  238. string jobid = Request.Form["jobid"].ToString();
  239. string kvpmode = Request.Form["kvpmode"].ToString();
  240. string kvpvalue = Request.Form["kvpvalue"].ToString();
  241. string tranid = Request.Form["tranid"].ToString();
  242. string serverinfo = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
  243. string serverpath = Path.Combine(serverinfo, "OUT");
  244. string templatefileserverpath = string.Empty;
  245. var titleqry = oWorkAreaService.spfiletypevalidation(tranid.ToString(), jobid);
  246. var titleqry_jsonList = new List<string>();
  247. if (titleqry != null)
  248. {
  249. var titleqry_filetype = JsonConvert.DeserializeObject<object>(titleqry.ToString());
  250. JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
  251. lottitles = titleqry_a_filetype[0]["titlecur"].ToString();
  252. jobtitle = titleqry_a_filetype[0]["jobtitle"].ToString();
  253. lottitles = lottitles.Replace("-img", "");
  254. lottitles = lottitles.Replace("-txt", "");
  255. }
  256. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
  257. {
  258. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  259. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  260. {
  261. if (httpRequest.Files.Count > 0)
  262. {
  263. if (!Directory.Exists(serverpath))
  264. {
  265. Directory.CreateDirectory(serverpath);
  266. }
  267. if (!string.IsNullOrEmpty(kvpmode) && !string.IsNullOrEmpty(kvpvalue))
  268. {
  269. if (kvpmode == "file")
  270. {
  271. filepath = Directory.GetDirectories(serverpath, lottitles, SearchOption.TopDirectoryOnly).FirstOrDefault();
  272. if (!string.IsNullOrEmpty(filepath) && Directory.Exists(filepath))
  273. {
  274. dirvalidate = true;
  275. }
  276. else
  277. {
  278. //dirvalidate = true;
  279. if (!Directory.Exists(Path.Combine(serverpath, lottitles)))
  280. {
  281. Directory.CreateDirectory(Path.Combine(serverpath, lottitles));
  282. dirvalidate = true;
  283. }
  284. }
  285. for (int i = 0; i < httpRequest.Files.Count; i++)
  286. {
  287. var outfile = httpRequest.Files[i];
  288. dirName = "";
  289. dirName = Path.GetDirectoryName(outfile.FileName);
  290. if (dirName == "")
  291. {
  292. filepath_name = Path.GetFileNameWithoutExtension(outfile.FileName);
  293. if (kvpvalue == "_Redacted")
  294. {
  295. filevalidate = true;
  296. if (!filepath_name.ToString().EndsWith(kvpvalue) || !filepath_name.ToLower().Contains(lottitles.ToLower()))
  297. {
  298. filevalidate = false;
  299. }
  300. }
  301. else if (filepath_name.ToString().EndsWith(kvpvalue))
  302. {
  303. filevalidate = true;
  304. break;
  305. }
  306. }
  307. }
  308. }
  309. else
  310. {
  311. filevalidate = true;
  312. actualdirectory = string.Empty;
  313. actualdirectory = Path.Combine(serverpath, jobtitle + kvpvalue);
  314. string visf_folder = string.Empty;
  315. string[] extensionFilters = new string[] { kvpvalue };
  316. visf_folder = Directory.GetDirectories(serverpath, "*.*", SearchOption.TopDirectoryOnly)
  317. .Where(filename => extensionFilters.Any(x =>
  318. filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
  319. if (!string.IsNullOrEmpty(visf_folder))
  320. {
  321. dirvalidate = true;
  322. }
  323. else
  324. {
  325. if (!Directory.Exists(actualdirectory))
  326. {
  327. Directory.CreateDirectory(actualdirectory);
  328. dirvalidate = true;
  329. }
  330. }
  331. }
  332. //}
  333. if (kvpmode == "file")
  334. {
  335. if (filevalidate == false)
  336. {
  337. message = "" + kvpvalue + " file missing please check";
  338. }
  339. else
  340. {
  341. if (dirvalidate == false)
  342. {
  343. message = "file is not placed properly in lotname against job";
  344. }
  345. }
  346. }
  347. else
  348. {
  349. if (dirvalidate == false)
  350. {
  351. message = "" + kvpvalue + " folder missing against job.Please Check";
  352. }
  353. }
  354. }
  355. //else
  356. //{
  357. // message = "Unknown stage processor.please check";
  358. // var json = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
  359. // return json;
  360. //}
  361. }
  362. });
  363. }
  364. var json1 = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
  365. return json1;
  366. }
  367. catch (Exception ex)
  368. {
  369. message = ex.Message;
  370. dirvalidate = false;
  371. filevalidate = false;
  372. var json = new { dirresult = dirvalidate, fileresults = filevalidate, Message = message };
  373. return json;
  374. }
  375. }
  376. //rajii
  377. [Authorize]
  378. [HttpPost]
  379. public object PostUpdatelot_transaction(Fields fields)
  380. {
  381. //DBContext db = new DBContext();
  382. //db.CheckLogin();
  383. //long transactionid = fields.transid;
  384. //string option = fields.option;
  385. //string comment = fields.comment;
  386. //if (fields.fields != "null")
  387. //{
  388. // BLDatamanipulation db_ = new BLDatamanipulation();
  389. // List<NpgsqlParameter> parms = new List<NpgsqlParameter>();
  390. // db_.InsertQuery(db, "update lot_master set lotmastermetafields = '" + fields.fields + "' where lotid in (select a.lotid from lot_transaction a where a.transactionid = " + fields.transid + ")", parms);
  391. // db_.InsertQuery(db, "update lot_transaction set lotmetafields = '" + fields.fields + "' where transactionid = " + fields.transid + "", parms);
  392. //}
  393. //lot_tran_info lotinfo = new lot_tran_info();
  394. //lotinfo.p_tranid = transactionid.ToString();
  395. //lotinfo.p_userid = (HttpContext.Current.Session["UserID"] as string);
  396. //lotinfo.p_option = option;
  397. //lotinfo.p_holdreason = comment;
  398. //if (option == "checkout")
  399. // Checkout_transaction(lotinfo);
  400. //else if (option == "hold")
  401. // getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "I", "hold", "0", lotinfo.p_holdreason);
  402. //else if (option == "checkin")
  403. // getCheckout(lotinfo.p_tranid, lotinfo.p_userid, "P", "hold", "0", lotinfo.p_holdreason);
  404. return "Done";
  405. }
  406. public void TriggerMail(string tranid, string ordernumber, string nxttranid)
  407. {
  408. try
  409. {
  410. if (ordernumber == "1")
  411. {
  412. System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_PM?tranid=", tranid, "&sflag=", "1")));
  413. System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_Ack?tranid=", tranid, "&sflag=", "2")));
  414. }
  415. else if (ordernumber == "2")
  416. {
  417. System.Threading.Tasks.Parallel.Invoke(() => SendMailRequest(string.Join("", baseurl, "/api/DashboardApi/Postmail_SignOff?tranid=", nxttranid, "&jobworkflowid=", 0, "&sflag=", "2", "&curtranid=", tranid)));
  418. }
  419. }
  420. catch (Exception ex)
  421. {
  422. var data_input = new
  423. {
  424. errormessage = "Error: " + ex.Message,
  425. createdby = 0,
  426. controller = "UploaderApi: Downloader"
  427. };
  428. oCommonRepository.addlog(data_input, "errorlog");
  429. }
  430. }
  431. public void SendMailRequest(string apiUrl)
  432. {
  433. try
  434. {
  435. HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
  436. authRequest.ContentType = "application/xml";
  437. authRequest.Method = "POST";
  438. authRequest.ContentLength = 0;
  439. WebResponse authResponseTwitter = authRequest.GetResponse();
  440. }
  441. catch (Exception ex)
  442. {
  443. var data_input = new
  444. {
  445. errormessage = "Error: " + ex.Message,
  446. createdby = 0,
  447. controller = "UploaderApi: Downloader"
  448. };
  449. oCommonRepository.addlog(data_input, "errorlog");
  450. }
  451. }
  452. [HttpPost]
  453. public object getbronsdetails(string jobid)
  454. {
  455. //DBContext db = new DBContext();
  456. //db.CheckLogin();
  457. //string qry = "select * from getbronsbyid(@p_job) as json";
  458. //var data = db.Database.SqlQuery<jsonvalue>(qry, new Npgsql.NpgsqlParameter { ParameterName = "@p_job", Value = Convert.ToInt64(jobid) }).ToList();
  459. var json = new List<object>();
  460. //foreach (var item in data)
  461. //{
  462. // json.Add(JObject.Parse(item.json));
  463. //}
  464. return json;
  465. }
  466. [HttpPost]
  467. public object isdeleted(string jobid, string lotid)
  468. {
  469. //DBContext db = new DBContext();
  470. //db.CheckLogin();
  471. //var menudetails = db.Database.SqlQuery<jsonvalue>("select json_build_object('articalstatus', wa.article_status)as json from wkb_articleinfo wa inner join lot_master lm on lm.jobid=wa.jobid and lm.lotid=wa.lotid where lm.jobid=@jobid and lm.lotid=@lotid",
  472. // new Npgsql.NpgsqlParameter { ParameterName = "@jobid", Value = jobid }, new Npgsql.NpgsqlParameter { ParameterName = "@lotid", Value = lotid }).ToList();
  473. var json = new List<object>();
  474. //foreach (var item in menudetails)
  475. //{
  476. // json.Add(JObject.Parse(item.json));
  477. //}
  478. return json;
  479. }
  480. [HttpPost("test")]
  481. public object test()
  482. {
  483. return "done";
  484. }
  485. //[HttpPost]
  486. //public object getAllbronsdetails(string jobid_BUP)
  487. //{
  488. // DBContext db = new DBContext();
  489. // db.CheckLogin();
  490. // string qry = "select * from getbronsNewbyid(@p_job) as json";
  491. // var data = db.Database.SqlQuery<jsonvalue>(qry, new Npgsql.NpgsqlParameter { ParameterName = "@p_job", Value = Convert.ToInt64(jobid_BUP) }
  492. // ).ToList();
  493. // return data;
  494. //}
  495. //[HttpPost]
  496. //public object loadweblink(string jobid_o, long tranid)
  497. //{
  498. // DBContext db = new DBContext();
  499. // db.CheckLogin();
  500. // var json = new List<object>();
  501. // string jobid = getjobid(tranid);
  502. // BLDatamanipulation db12 = new BLDatamanipulation();
  503. // DataTable dt2 = db12.GetDataTable(db, "select isignoreable,websiteurl from wkb_job_details a where a.jobid = " + jobid + "", null);
  504. // if (dt2.Rows.Count > 0)
  505. // {
  506. // string isignore = dt2.Rows[0]["isignoreable"].ToString().ToLower();
  507. // string websiteurl = dt2.Rows[0]["websiteurl"].ToString().ToLower();
  508. // json.Add(JObject.Parse("{\"isignoreable\":'" + isignore + "',\"websiteurl\":'" + websiteurl + "'}"));
  509. // }
  510. // return json;
  511. //}
  512. public string getjobid(long p_tranid)
  513. {
  514. try
  515. {
  516. //DataTable svrpath = getdatatable("usr_server_path_info", new List<Npgsql.NpgsqlParameter>(){ new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = p_tranid },
  517. // new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = "serverinfo" }});
  518. return "";// svrpath.Rows[0]["jobid"].ToString();
  519. }
  520. catch (Exception ex)
  521. {
  522. return string.Join("", "Error : ", ex.Message.ToString());
  523. }
  524. }
  525. //[HttpPost]
  526. //public object Checkout_transaction(lot_tran_info lotinfo)
  527. //{
  528. // var trans_id = lotinfo.p_tranid;
  529. // var checkout = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_only", "0", lotinfo.p_holdreason);
  530. // if (checkout.Count > 0)
  531. // {
  532. // foreach (var item in checkout)
  533. // {
  534. // JobWorkflow_ obj = JsonConvert.DeserializeObject<JobWorkflow_>(item.json);
  535. // List<StageData> lst = new List<StageData>();
  536. // //******************* Get Next Stage Details **************
  537. // lst = getNextStageDetails(obj.jobid, obj.jobworkflowid);
  538. // //*******************
  539. // List<StageData> newList = lst
  540. // .Where(m => m.CURRENT == obj.jobworkflowid)
  541. // .ToList();
  542. // //******************* To Check Next Stage
  543. // foreach (var items in newList)
  544. // {
  545. // var next_workflow_id = "";
  546. // if (items.NEXT != null)
  547. // next_workflow_id = items.NEXT;
  548. // else if (items.PARALLEL != null)
  549. // next_workflow_id = items.PARALLEL;
  550. // else if (items.MOVEBACKNO != null)
  551. // next_workflow_id = items.MOVEBACKNO;
  552. // else if (items.MOVEBACKYES != null)
  553. // next_workflow_id = items.MOVEBACKYES;
  554. // //*******************
  555. // if (next_workflow_id != null)
  556. // {
  557. // next_workflow_id = next_workflow_id.Trim();
  558. // List<StageData> checkParallalList = lst
  559. // .Where(m => m.NEXT == next_workflow_id || m.PARALLEL == next_workflow_id || m.MOVEBACKYES == next_workflow_id || m.MOVEBACKNO == next_workflow_id)
  560. // .ToList();
  561. // if (checkParallalList.Count > 0)
  562. // {
  563. // var if_check_parallel = true;
  564. // //***************** Only One Next Stage
  565. // if (checkParallalList.Count == 1)
  566. // {
  567. // var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
  568. // var json = new List<transout>();
  569. // foreach (var checkout_next_item in checkout_next)
  570. // json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.json));
  571. // sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid);
  572. // }
  573. // //***************** More than One Next Stage
  574. // else
  575. // {
  576. // foreach (var item_checkParallalList in checkParallalList)
  577. // {
  578. // //***************** To Check All Parallal stage are completed or put Wait
  579. // var checkout_check_parallel = getCheckout(trans_id, lotinfo.p_userid, "C", "checkout_parallel_check", item_checkParallalList.CURRENT);
  580. // if (checkout_check_parallel.Count > 0)
  581. // {
  582. // foreach (var parallel_item in checkout_check_parallel)
  583. // {
  584. // JobWorkflow_ parallel_item_obj = JsonConvert.DeserializeObject<JobWorkflow_>(parallel_item.json);
  585. // if (parallel_item_obj.lotstatus == "P" || parallel_item_obj.lotstatus == "R" || parallel_item_obj.lotstatus == "W" || parallel_item_obj.lotstatus == "" || parallel_item_obj.lotstatus == null)
  586. // {
  587. // if_check_parallel = false;
  588. // }
  589. // }
  590. // }
  591. // }
  592. // if (if_check_parallel == true)
  593. // {
  594. // var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "R", "checkout_next", next_workflow_id, lotinfo.p_holdreason);
  595. // var json = new List<transout>();
  596. // foreach (var checkout_next_item in checkout_next)
  597. // json.Add(JsonConvert.DeserializeObject<transout>(checkout_next_item.json));
  598. // sendmail(lotinfo, json[0].p_tranid, obj.jobworkflowid.ToString());
  599. // }
  600. // else
  601. // { var checkout_next = getCheckout(trans_id, lotinfo.p_userid, "W", "checkout_next", next_workflow_id, lotinfo.p_holdreason); }
  602. // }
  603. // }
  604. // }
  605. // //*******************
  606. // }
  607. // }
  608. // }
  609. // return "Done";
  610. //}
  611. //public List<jsonvalue> getCheckout(string trans_id, string p_userid, string status, string option, string jobworkflowid, string p_comments = "")
  612. //{
  613. // DBContext db1 = new DBContext();
  614. // return db1.Database.SqlQuery<jsonvalue>("select * from usr_lot_tran_update_v2(@p_tranid,@p_userid,@p_status,@p_option,@jobworkflowid,@p_comments) as json",
  615. // new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = trans_id },
  616. // new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = p_userid },
  617. // new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = status },
  618. // new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = option },
  619. // new Npgsql.NpgsqlParameter { ParameterName = "@p_comments", Value = p_comments },
  620. // new Npgsql.NpgsqlParameter { ParameterName = "@jobworkflowid", Value = jobworkflowid }).ToList();
  621. // //List<Npgsql.NpgsqlParameter> Parmtr = new List<NpgsqlParameter>();
  622. // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_tranid", Value = trans_id });
  623. // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_userid", Value = p_userid });
  624. // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_status", Value = status });
  625. // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@p_option", Value = option });
  626. // //Parmtr.Add(new Npgsql.NpgsqlParameter { ParameterName = "@jobworkflowid", Value = jobworkflowid });
  627. // //string json = db.getdataJson("usr_lot_tran_update_v2", Parmtr);
  628. // //return Newtonsoft.Json.JsonConvert.DeserializeObject<List<JobWorkflow_>>(string.Join("", json));
  629. //}
  630. public List<StageData> getNextStageDetails(string jobid, string jobworkflowid)
  631. {
  632. //BLDatamanipulation db = new BLDatamanipulation();
  633. //DBContext dbcontext_ = new DBContext();
  634. //string qry1 = @"select concat((case when jm.nextstage is not null and jm.movebackstage is null
  635. // then
  636. // concat('CURRENT:',cast(jm.jobworkflowid as text),',NEXT:',cast(nextjm.jobworkflowid as text)
  637. // ,case when (select count(1) from job_workflow_master where parallelstage=jm.nextstage)>0
  638. // then (select string_agg(concat(chr(10),',CURRENT:',cast(jm.jobworkflowid as text),',PARALLEL:',cast(jobWorkflowID as text)), '') from job_workflow_master where parallelstage=jm.nextstage)
  639. // else '' end)
  640. // else concat('CURRENT:',cast(jm.jobworkflowid as text)) end )
  641. // , (case when backjm.jobworkflowid is null then '' else concat(chr(10),',MOVEBACKYES:',cast(backjm.jobworkflowid as text),chr(10),',MOVEBACKNO:',cast(nextjm.jobworkflowid as text),
  642. // case when (select count(1) from job_workflow_master where parallelstage=nextjm.jobworkflowid)>0 then
  643. // (select concat(chr(10),'CURRENT:',cast(jm.jobworkflowid as text),'MOVEBACKNO:',cast(jobWorkflowID as text)) from job_workflow_master where parallelstage=nextjm.jobworkflowid) else '' end) end)) as Flowchart
  644. // from job_workflow_master jm
  645. // inner join stage_type_master st on st.stagetypeid=jm.stage_type
  646. // left join job_workflow_master nextjm on nextjm.jobworkflowid =jm.nextstage
  647. // left join job_workflow_master backjm on backjm.jobworkflowid =jm.movebackstage
  648. // where jm.jobid=" + jobid + " and jm.active=1 order by jm.stageorder";
  649. List<StageData> lst = new List<StageData>();
  650. //System.Data.DataTable data1 = db.GetDataTable(dbcontext_, qry1, null);
  651. //if (data1.Rows.Count > 0)
  652. //{
  653. // for (int i = 0; i <= data1.Rows.Count - 1; i++)
  654. // {
  655. // var splite = data1.Rows[i][0].ToString().Split(',');
  656. // if (splite.Length > 0)
  657. // {
  658. // var current = "";
  659. // foreach (string word in splite)
  660. // {
  661. // var stemp = ""; StageData st = new StageData();
  662. // var innersplite = word.ToString().Split(':');
  663. // for (int j = 0; j <= innersplite.Length; j++)
  664. // {
  665. // if (innersplite[0] == "CURRENT")
  666. // current = innersplite[1].Trim();
  667. // }
  668. // for (int j = 0; j <= innersplite.Length; j++)
  669. // {
  670. // st.CURRENT = current;
  671. // if (innersplite[0] == "CURRENT")
  672. // stemp = "CURRENT";
  673. // else if (innersplite[0] == "NEXT")
  674. // st.NEXT = innersplite[1].Trim();
  675. // else if (innersplite[0] == "PARALLEL")
  676. // st.PARALLEL = innersplite[1].Trim();
  677. // else if (innersplite[0] == "MOVEBACKNO")
  678. // st.MOVEBACKNO = innersplite[1].Trim();
  679. // else if (innersplite[0] == "MOVEBACKYES")
  680. // st.MOVEBACKYES = innersplite[1].Trim();
  681. // }
  682. // if (stemp != "CURRENT")
  683. // lst.Add(st);
  684. // }
  685. // }
  686. // }
  687. //}
  688. return lst;
  689. }
  690. public void sendmail(lot_tran_info lotinfo, string nexttranval, string jobworkflowid)
  691. {
  692. // (HttpContext.Current.Session["UserID"] as string)
  693. long userId_t = Convert.ToInt64("4"); // need to add logged in userid
  694. RabbitMq sendmsg = new RabbitMq();
  695. sendmsg.SendMqMail(lotinfo.p_tranid.ToString(), jobworkflowid.ToString(), "2", nexttranval.ToString(), userId_t.ToString());
  696. //var JobMetaFields = GetJobMetaData(nexttranval.ToString(), lotinfo.p_tranid.ToString(), jobworkflowid);
  697. //Postmail_SignOff(nexttranval, jobworkflowid, "", lotinfo.p_tranid.ToString(), JobMetaFields);
  698. //TriggerMail(lotinfo.p_tranid.ToString(), "2", nexttranval);
  699. //System.Threading.Thread.Sleep(100);
  700. //TriggerMail(lotinfo.p_tranid.ToString(), "1", (HttpContext.Current.Session["UserID"] as string));
  701. }
  702. public List<jobmetafields> GetJobMetaData(string tranid, string completedtranid, string jobworkflowid)
  703. {
  704. //DBContext db = new DBContext();
  705. //BLDatamanipulation db1 = new BLDatamanipulation();
  706. var finalout = new List<jobmetafields>();
  707. //var workflowid = "";
  708. //var completed_workflowid = ""; var job_id = "";
  709. //DataTable dt = db1.GetDataTable(db, "select wfdid,jobid from job_workflow_master a where a.jobworkflowid = " + jobworkflowid + "", null);
  710. //if (dt.Rows.Count > 0)
  711. //{
  712. // completed_workflowid = dt.Rows[0]["wfdid"].ToString();
  713. // job_id = dt.Rows[0]["jobid"].ToString();
  714. //}
  715. //var str = "select b.jobmetafields as jobworkflow_metafields,b.wfdid,c.lotmastermetafields as lot_metafields from lot_transaction a left outer join job_workflow_master b on a.jobworkflowid = b.jobworkflowid left outer join lot_master c on c.lotid = a.lotid where a.transactionid = @tranid";
  716. //var jobmeta = db.Database.SqlQuery<lot_tran_metafields>(str, new Npgsql.NpgsqlParameter { ParameterName = "@tranid", Value = tranid }).ToList();
  717. //if (jobmeta.Count > 0)
  718. //{
  719. // //jobworkflow_metafields
  720. // var jobworkflow_metafields = new List<jobmetafields>();
  721. // var lotmastermetafields = new List<jobmetafields>();
  722. // foreach (var item in jobmeta)
  723. // {
  724. // if (item.jobworkflow_metafields != null)
  725. // {
  726. // dynamic json = JsonConvert.DeserializeObject(item.jobworkflow_metafields);
  727. // workflowid = item.wfdid.ToString();
  728. // for (int i = 0; i < json.Count; i++)
  729. // {
  730. // var jdata = new jobmetafields();
  731. // foreach (var s in json[i])
  732. // {
  733. // if (s.Name == "name")
  734. // jdata.name = string.Join(",", s);
  735. // else if (s.Name == "type")
  736. // jdata.type = string.Join(",", s);
  737. // else if (s.Name == "value")
  738. // jdata.value = string.Join(",", s);
  739. // else if (s.Name == "workflowdid")
  740. // jdata.workflowdid = string.Join(",", s);
  741. // else if (s.Name == "label")
  742. // jdata.label = string.Join(",", s);
  743. // }
  744. // jobworkflow_metafields.Add(jdata);
  745. // }
  746. // //lotmastermetafields
  747. // dynamic json_ = JsonConvert.DeserializeObject(item.lot_metafields);
  748. // for (int i = 0; i < json_.Count; i++)
  749. // {
  750. // var jdata = new jobmetafields();
  751. // foreach (var s in json_[i])
  752. // {
  753. // if (s.Name == "name")
  754. // jdata.name = string.Join(",", s);
  755. // else if (s.Name == "type")
  756. // jdata.type = string.Join(",", s);
  757. // else if (s.Name == "value")
  758. // jdata.value = string.Join(",", s);
  759. // else if (s.Name == "workflowdid")
  760. // jdata.workflowdid = string.Join(",", s);
  761. // else if (s.Name == "label")
  762. // jdata.label = string.Join(",", s);
  763. // }
  764. // lotmastermetafields.Add(jdata);
  765. // }
  766. // }
  767. // }
  768. // var completed_field = (from job in jobworkflow_metafields
  769. // join lot in lotmastermetafields on new { job.workflowdid, job.name } equals new { lot.workflowdid, lot.name } //where lot.workflowdid == completed_workflowid
  770. // select new
  771. // {
  772. // lot.name,
  773. // lot.type,
  774. // job.label,
  775. // lot.workflowdid,
  776. // lot.value,
  777. // lot.status
  778. // }).ToList();
  779. // var current_field = (from job in jobworkflow_metafields
  780. // where job.workflowdid == workflowid
  781. // select new
  782. // {
  783. // job.name,
  784. // job.type,
  785. // job.label,
  786. // job.workflowdid,
  787. // job.value,
  788. // job.status
  789. // }).ToList();
  790. // foreach (var item in completed_field)
  791. // {
  792. // var stemp = new jobmetafields();
  793. // stemp.name = item.name;
  794. // stemp.type = item.type;
  795. // stemp.label = item.label.Replace("$$JobNo", job_id);
  796. // stemp.workflowdid = item.workflowdid;
  797. // stemp.value = item.value;
  798. // stemp.status = "Completed";
  799. // finalout.Add(stemp);
  800. // }
  801. // foreach (var item in current_field)
  802. // {
  803. // var stemp = new jobmetafields();
  804. // stemp.name = item.name;
  805. // stemp.type = item.type;
  806. // stemp.label = item.label;
  807. // stemp.workflowdid = item.workflowdid;
  808. // stemp.value = item.value;
  809. // stemp.status = "Current";
  810. // finalout.Add(stemp);
  811. // }
  812. //}
  813. return finalout;
  814. }
  815. private void CreateZip(string directoryPathToZip, string outputZipFileName)
  816. {
  817. //try
  818. //{
  819. // if (File.Exists(outputZipFileName))
  820. // File.Delete(outputZipFileName);
  821. // using (ZipFile outputZip = new ZipFile(outputZipFileName))
  822. // {
  823. // outputZip.AddDirectory(directoryPathToZip);
  824. // outputZip.Save();
  825. // }
  826. //}
  827. //catch (Exception ex)
  828. //{ }
  829. }
  830. [Authorize]
  831. [HttpPost("saveOutputFile")]
  832. public object saveOutputFile()
  833. {
  834. try
  835. {
  836. var httpRequest = HttpContext.Request.Form;
  837. string filepath = string.Empty;
  838. string dirName = string.Empty;
  839. int charIndex = 0;
  840. string lottitles = string.Empty;
  841. string jobtitle = string.Empty;
  842. string filepath_name = string.Empty;
  843. string projectsubtitle = string.Empty;
  844. // string currentstagename = string.Empty;
  845. string retmsg = string.Empty;
  846. bool lottitle_ = false;
  847. string jobid = Request.Form["jobid"].ToString();
  848. string tranid = Request.Form["tranid"].ToString();
  849. string pdid = Request.Form["pdid"].ToString();
  850. string kvpmode = Request.Form["kvpmode"].ToString();
  851. string kvpvalue = Request.Form["kvpvalue"].ToString();
  852. string fileID = Request.Form["fileID"].ToString();
  853. string totalchunk = Request.Form["totalChunks"].ToString();
  854. string filename = Request.Form["filename"].ToString();
  855. string currentstagename = Request.Form["currentstagename"].ToString();
  856. string merged_lot = string.Empty;
  857. string templatefileserverpath = string.Empty;
  858. var titleqry = oWorkAreaService.spfiletypevalidation(tranid.ToString(), jobid);
  859. var titleqry_jsonList = new List<string>();
  860. if (currentstagename == "OCR1")
  861. {
  862. //if (file == null || file.Length == 0)
  863. // return BadRequest("No file uploaded.");
  864. // Read PDF bytes directly from the uploaded file
  865. var file = HttpContext.Request.Form.Files.FirstOrDefault();
  866. if (file == null || file.Length == 0)
  867. return BadRequest("No file uploaded.");
  868. // ✅ Check file extension
  869. if (!file.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
  870. return BadRequest("Only PDF files are supported.");
  871. try
  872. {
  873. using (var memoryStream = new MemoryStream())
  874. {
  875. file.CopyTo(memoryStream);
  876. memoryStream.Position = 0; // ✅ Reset stream before reading
  877. // ✅ Validate PDF structure using iTextSharp
  878. using (PdfReader reader = new PdfReader(memoryStream))
  879. {
  880. Dictionary<string, string> info = reader.Info;
  881. string producer = info.ContainsKey("Producer") ? info["Producer"] : "Not available";
  882. string creator = info.ContainsKey("Creator") ? info["Creator"] : "Not available";
  883. // ✅ Check if it’s ABBYY FineReader
  884. if ((producer?.IndexOf("ABBYY", StringComparison.OrdinalIgnoreCase) >= 0) ||
  885. (creator?.IndexOf("ABBYY", StringComparison.OrdinalIgnoreCase) >= 0))
  886. {
  887. return Ok(new
  888. {
  889. Message = "Valid PDF. Created using ABBYY FineReader.",
  890. Producer = producer,
  891. Creator = creator
  892. });
  893. }
  894. else
  895. {
  896. return BadRequest(new
  897. {
  898. Message = "Invalid PDF. Not created using ABBYY FineReader.",
  899. Producer = producer,
  900. Creator = creator
  901. });
  902. }
  903. }
  904. }
  905. }
  906. catch (iTextSharp.text.exceptions.InvalidPdfException ex)
  907. {
  908. // 🚫 Handle “PDF signature not found” case
  909. return BadRequest("Uploaded file is not a valid PDF or is corrupted.");
  910. }
  911. catch (Exception ex)
  912. {
  913. // 🧩 Handle other unexpected errors
  914. return StatusCode(500, "An error occurred while validating the file: " + ex.Message);
  915. }
  916. }
  917. if (titleqry != null)
  918. {
  919. var titleqry_filetype = JsonConvert.DeserializeObject<object>(titleqry.ToString());
  920. JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
  921. lottitles = titleqry_a_filetype[0]["titlecur"].ToString();
  922. merged_lot = titleqry_a_filetype[0]["merged_lot"].ToString();
  923. jobtitle = titleqry_a_filetype[0]["jobtitle"].ToString();
  924. projectsubtitle = titleqry_a_filetype[0]["project_subtitle"].ToString();
  925. }
  926. //if (httpRequest.Files.Count > 0)
  927. // {
  928. string serverinfo = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
  929. string serverinpath = Path.Combine(serverinfo, "IN");
  930. string serverpath = Path.Combine(serverinfo, "OUT");
  931. var filetype = oWorkAreaService.getFileTypeOutput(tranid);
  932. var jsonList = new List<string>();
  933. var uploadExtentionList = new List<string>();
  934. string resultList = string.Empty;
  935. if (filetype != null)
  936. {
  937. var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
  938. JArray a_filetype = JArray.Parse(i_filetype.ToString());
  939. foreach (var a in a_filetype)
  940. {
  941. JObject obj_filetype = JObject.Parse(a.ToString());
  942. jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
  943. }
  944. }
  945. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
  946. {
  947. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  948. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  949. {
  950. if (!Directory.Exists(serverpath))
  951. {
  952. Directory.CreateDirectory(serverpath);
  953. }
  954. string finalFilePath = Path.Combine(serverpath, filename);
  955. string chunkFolder = Path.Combine("TempUploads", tranid.ToString());
  956. using (var finalStream = new FileStream(finalFilePath, FileMode.Create))
  957. {
  958. for (int i = 0; i < Convert.ToInt64(totalchunk); i++)
  959. {
  960. string partPath = Path.Combine(chunkFolder, $"{i}.part");
  961. using (var partStream = new FileStream(partPath, FileMode.Open))
  962. {
  963. partStream.CopyTo(finalStream);
  964. }
  965. }
  966. }
  967. Directory.Delete(chunkFolder, true);
  968. });
  969. }
  970. /*if (jsonList.Count != 0 && jsonList[0].ToString() != ".*")
  971. {
  972. for (int i = 0; i < httpRequest.Files.Count; i++)
  973. {
  974. var outfile = httpRequest.Files[i];
  975. uploadExtentionList.Add(Path.GetExtension(outfile.FileName));
  976. }
  977. //var jsonlist_filter = jsonList.Except(uploadExtentionList).ToArray();
  978. var extentionlist_filter = uploadExtentionList.Except(jsonList).ToArray();
  979. for (int i = 0; i < extentionlist_filter.Length; i++)
  980. {
  981. resultList = string.Concat(resultList, extentionlist_filter[i], ",");
  982. }
  983. if (!string.IsNullOrEmpty(resultList))
  984. {
  985. return Ok("Extra files with extension '" + resultList.TrimEnd(',') + "' are not allowed kindly remove it and then proceed.");
  986. }
  987. }*/
  988. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
  989. {
  990. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  991. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  992. {
  993. // using (ServerInfo.GrantFolderPermission imp = new ServerInfo.GrantFolderPermission(jobid))
  994. // {
  995. if (!Directory.Exists(serverpath))
  996. {
  997. Directory.CreateDirectory(serverpath);
  998. }
  999. var curr_stageid = oWorkAreaService.getCurrentStage(tranid);
  1000. string current_stageid = "";
  1001. if (curr_stageid != null)
  1002. {
  1003. var i_curr_stageid = JsonConvert.DeserializeObject<object>(curr_stageid.ToString());
  1004. JArray a_curr_stageid = JArray.Parse(i_curr_stageid.ToString());
  1005. JObject obj_curr_stageid = JObject.Parse(a_curr_stageid[0].ToString());
  1006. current_stageid = obj_curr_stageid["stageid"].ToString();
  1007. }
  1008. if (string.IsNullOrEmpty(kvpmode) && string.IsNullOrEmpty(kvpvalue))
  1009. {
  1010. for (int i = 0; i < httpRequest.Files.Count; i++)
  1011. {
  1012. var outfile = httpRequest.Files[i];
  1013. dirName = Path.GetDirectoryName(outfile.FileName);
  1014. if (jsonList.Count > 0)
  1015. {
  1016. if (jsonList.Count == 1 && jsonList[0].ToString() == ".*")
  1017. {
  1018. if (dirName.Contains("\\"))
  1019. {
  1020. charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
  1021. dirName = dirName.Substring(charIndex + 1);
  1022. filepath = Path.Combine(serverpath, dirName, Path.GetFileName(outfile.FileName));
  1023. }
  1024. else
  1025. {
  1026. filepath = Path.Combine(serverpath, Path.GetFileName(outfile.FileName));
  1027. }
  1028. if (!Directory.Exists(Path.GetDirectoryName(filepath)))
  1029. {
  1030. Directory.CreateDirectory(Path.GetDirectoryName(filepath));
  1031. }
  1032. using (var stream = new FileStream(filepath, FileMode.Create))
  1033. {
  1034. outfile.CopyTo(stream);
  1035. }
  1036. }
  1037. else
  1038. {
  1039. if (jsonList.Contains(Path.GetExtension(outfile.FileName).ToLower()))
  1040. {
  1041. if (dirName.Contains("\\"))
  1042. {
  1043. charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
  1044. dirName = dirName.Substring(charIndex + 1);
  1045. filepath = Path.Combine(serverpath, dirName, Path.GetFileName(outfile.FileName));
  1046. }
  1047. else
  1048. {
  1049. filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
  1050. }
  1051. if (!Directory.Exists(Path.GetDirectoryName(filepath)))
  1052. {
  1053. Directory.CreateDirectory(Path.GetDirectoryName(filepath));
  1054. }
  1055. using (var stream = new FileStream(filepath, FileMode.Create))
  1056. {
  1057. outfile.CopyTo(stream);
  1058. }
  1059. // outfile.SaveAs(filepath);
  1060. }
  1061. }
  1062. }
  1063. else
  1064. {
  1065. if (dirName.Contains("\\"))
  1066. {
  1067. charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
  1068. dirName = dirName.Substring(charIndex + 1);
  1069. filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
  1070. }
  1071. else
  1072. {
  1073. filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
  1074. }
  1075. if (!Directory.Exists(Path.GetDirectoryName(filepath)))
  1076. {
  1077. Directory.CreateDirectory(Path.GetDirectoryName(filepath));
  1078. }
  1079. // outfile.SaveAs(filepath);
  1080. using (var stream = new FileStream(filepath, FileMode.Create))
  1081. {
  1082. outfile.CopyTo(stream);
  1083. }
  1084. }
  1085. }
  1086. }
  1087. else
  1088. {
  1089. lottitles = lottitles.Replace("-img", "");
  1090. lottitles = lottitles.Replace("-txt", "");
  1091. for (int i = 0; i < httpRequest.Files.Count; i++)
  1092. {
  1093. var outfile = httpRequest.Files[i];
  1094. dirName = Path.GetDirectoryName(outfile.FileName);
  1095. if (kvpmode == "file")
  1096. {
  1097. if (dirName.Contains("\\"))
  1098. {
  1099. charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
  1100. dirName = dirName.Substring(charIndex + 1);
  1101. filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
  1102. }
  1103. else
  1104. {
  1105. filepath_name = Path.GetFileNameWithoutExtension(outfile.FileName);
  1106. if (filepath_name.ToString().EndsWith(kvpvalue))
  1107. {
  1108. filepath = Path.Combine(serverpath.ToString(), lottitles, Path.GetFileName(outfile.FileName));
  1109. }
  1110. else
  1111. {
  1112. filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
  1113. }
  1114. }
  1115. }
  1116. else
  1117. {
  1118. if (dirName.Contains("\\"))
  1119. {
  1120. charIndex = dirName.Contains("\\") ? dirName.IndexOf('\\') : 0;
  1121. dirName = dirName.Substring(charIndex + 1);
  1122. filepath = Path.Combine(serverpath.ToString(), dirName, Path.GetFileName(outfile.FileName));
  1123. }
  1124. else
  1125. {
  1126. filepath_name = Path.GetExtension(outfile.FileName);
  1127. if (filepath_name.ToString().EndsWith(".txt"))
  1128. {
  1129. filepath = Path.Combine(serverpath.ToString(), jobtitle + kvpvalue, Path.GetFileName(outfile.FileName));
  1130. }
  1131. else
  1132. {
  1133. filepath = Path.Combine(serverpath.ToString(), Path.GetFileName(outfile.FileName));
  1134. }
  1135. }
  1136. }
  1137. if (!Directory.Exists(Path.GetDirectoryName(filepath)))
  1138. {
  1139. Directory.CreateDirectory(Path.GetDirectoryName(filepath));
  1140. }
  1141. // outfile.SaveAs(filepath);
  1142. using (var stream = new FileStream(filepath, FileMode.Create))
  1143. {
  1144. outfile.CopyTo(stream);
  1145. }
  1146. }
  1147. }
  1148. //}
  1149. });
  1150. }
  1151. // }
  1152. return Ok(1);
  1153. }
  1154. catch (Exception ex)
  1155. {
  1156. var data_input = new
  1157. {
  1158. errormessage = "Error: " + ex.Message,
  1159. createdby = 0,
  1160. controller = "UploaderApi: Downloader"
  1161. };
  1162. oCommonRepository.addlog(data_input, "errorlog");
  1163. return null;
  1164. }
  1165. }
  1166. [HttpPost("chunk")]
  1167. public async Task<IActionResult> UploadChunk([FromForm] IFormFile filechunk,
  1168. [FromForm] string fileId,
  1169. [FromForm] int index,
  1170. [FromForm] int tranid)
  1171. {
  1172. try
  1173. {
  1174. var dir = Path.Combine("TempUploads", tranid.ToString());
  1175. Directory.CreateDirectory(dir);
  1176. var chunkPath = Path.Combine(dir, $"{index}.part");
  1177. using (var stream = new FileStream(chunkPath, FileMode.Create, FileAccess.Write))
  1178. {
  1179. await filechunk.CopyToAsync(stream);
  1180. }
  1181. return Ok(new { success = true });
  1182. }
  1183. catch (Exception ex)
  1184. {
  1185. return Ok(ex.Message);
  1186. }
  1187. }
  1188. // [Authorize]
  1189. [HttpGet("GetAllFilesForDownload")]
  1190. public List<FileDetails> GetAllFilesForDownload(int jobid, int tranid)
  1191. {
  1192. List<FileDetails> AllFiles = new List<FileDetails>();
  1193. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
  1194. {
  1195. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1196. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  1197. {
  1198. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  1199. System.Console.WriteLine(useri.Name);
  1200. string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
  1201. serverpath = Path.Combine(serverpath, "IN");
  1202. var filetype = oWorkAreaService.getFileTypeInput(tranid.ToString());
  1203. var jsonList = new List<string>();
  1204. string[] inputfiles;
  1205. if (filetype != null)
  1206. {
  1207. var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
  1208. JArray a_filetype = JArray.Parse(i_filetype.ToString());
  1209. foreach (var a in a_filetype)
  1210. {
  1211. JObject obj_filetype = JObject.Parse(a.ToString());
  1212. jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
  1213. }
  1214. }
  1215. if (jsonList.Count() == 1 && jsonList[0].ToString().Contains(".*"))
  1216. {
  1217. inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).ToArray();
  1218. }
  1219. else
  1220. {
  1221. inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1222. if (inputfiles.Length == 0)
  1223. {
  1224. inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).ToArray();
  1225. //inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1226. }
  1227. }
  1228. foreach (var item in inputfiles)
  1229. {
  1230. FileDetails filedetails = new FileDetails();
  1231. filedetails.FileName = Path.GetFileName(item);
  1232. filedetails.FilePath = item;
  1233. AllFiles.Add(filedetails);
  1234. }
  1235. });
  1236. }
  1237. return AllFiles;
  1238. }
  1239. // [Authorize]
  1240. [HttpGet("GetAllOutputFiles")]
  1241. public List<FileDetails> GetAllOutputFiles(int jobid, int tranid)
  1242. {
  1243. List<FileDetails> AllFiles = new List<FileDetails>();
  1244. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
  1245. {
  1246. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1247. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  1248. {
  1249. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  1250. System.Console.WriteLine(useri.Name);
  1251. var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
  1252. var jsonList = new List<string>();
  1253. string[] inputfiles;
  1254. if (filetype != null)
  1255. {
  1256. var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
  1257. JArray a_filetype = JArray.Parse(i_filetype.ToString());
  1258. foreach (var a in a_filetype)
  1259. {
  1260. JObject obj_filetype = JObject.Parse(a.ToString());
  1261. jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
  1262. }
  1263. }
  1264. // using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(jobid.ToString()))
  1265. // {
  1266. string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
  1267. serverpath = Path.Combine(serverpath, "OUT");
  1268. string[] outputfiles = null;
  1269. if (Directory.Exists(serverpath))
  1270. {
  1271. //outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
  1272. outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1273. }
  1274. else
  1275. {
  1276. AllFiles = null;
  1277. }
  1278. if (outputfiles.Length == 0)
  1279. {
  1280. // outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
  1281. outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1282. }
  1283. foreach (var item in outputfiles)
  1284. {
  1285. FileDetails filedetails = new FileDetails();
  1286. filedetails.FileName = Path.GetFileName(item);
  1287. filedetails.FilePath = item;
  1288. AllFiles.Add(filedetails);
  1289. }
  1290. });
  1291. }
  1292. // }
  1293. return AllFiles;
  1294. }
  1295. // [Authorize]
  1296. [HttpGet("GetAllOutFilesForDownload")]
  1297. public List<FileDetails> GetAllOutFilesForDownload(int jobid, int tranid)
  1298. {
  1299. List<FileDetails> AllFiles = new List<FileDetails>();
  1300. string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
  1301. serverpath = Path.Combine(serverpath, "OUT");
  1302. var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
  1303. var jsonList = new List<string>();
  1304. if (filetype != null)
  1305. {
  1306. var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
  1307. JArray a_filetype = JArray.Parse(i_filetype.ToString());
  1308. foreach (var a in a_filetype)
  1309. {
  1310. JObject obj_filetype = JObject.Parse(a.ToString());
  1311. jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
  1312. }
  1313. }
  1314. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
  1315. {
  1316. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1317. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  1318. {
  1319. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  1320. System.Console.WriteLine(useri.Name);
  1321. string[] inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly)
  1322. .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1323. if (inputfiles.Length == 0)
  1324. {
  1325. inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories)
  1326. .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1327. }
  1328. foreach (var item in inputfiles)
  1329. {
  1330. FileDetails filedetails = new FileDetails();
  1331. filedetails.FileName = Path.GetFileName(item);
  1332. filedetails.FilePath = item;
  1333. AllFiles.Add(filedetails);
  1334. }
  1335. });
  1336. }
  1337. return AllFiles;
  1338. }
  1339. // [Authorize]
  1340. [HttpPost("downloadInputFiles")]
  1341. public IActionResult downloadInputFiles(dynamic fileData)
  1342. {
  1343. string jobid = fileData.jobid.ToString();
  1344. string tranid = fileData.tranid.ToString();
  1345. string type = fileData.type.ToString();
  1346. string pdid = fileData.pdid.ToString();
  1347. string code = fileData.code.ToString();
  1348. string jobtitle = fileData.jobtitle.ToString();
  1349. string serverpath;
  1350. string zipname = string.Empty;
  1351. var jsonList = new List<string>();
  1352. string filepath = string.Empty;
  1353. string[] inputfiles;
  1354. //string current_stagename = db1.GetDataTable(db, @"select jw.stagename_alias from lot_transaction lt
  1355. // inner join job_workflow_master jw on jw.jobworkflowid = lt.jobworkflowid
  1356. // where lt.transactionid = '" + tranid + "'", null).Rows[0][0].ToString();
  1357. // if (type == "stage")
  1358. // {
  1359. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  1360. {
  1361. serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
  1362. serverpath = Path.Combine(serverpath, "IN");
  1363. zipname = jobtitle + "_" + tranid + ".zip";
  1364. var filetype = oWorkAreaService.getFileTypeInput(tranid);
  1365. if (filetype != null)
  1366. {
  1367. var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
  1368. JArray a_filetype = JArray.Parse(i_filetype.ToString());
  1369. foreach (var a in a_filetype)
  1370. {
  1371. JObject obj_filetype = JObject.Parse(a.ToString());
  1372. jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
  1373. }
  1374. }
  1375. var curr_stageid = oWorkAreaService.getCurrentStage(tranid);
  1376. string current_stageid = "";
  1377. if (curr_stageid != null)
  1378. {
  1379. var i_curr_stageid = JsonConvert.DeserializeObject<object>(curr_stageid.ToString());
  1380. JArray a_curr_stageid = JArray.Parse(i_curr_stageid.ToString());
  1381. JObject obj_curr_stageid = JObject.Parse(a_curr_stageid[0].ToString());
  1382. current_stageid = obj_curr_stageid["stageid"].ToString();
  1383. }
  1384. if (jsonList.Count > 0)
  1385. {
  1386. string zipPath = Path.Combine(serverpath, zipname + ".zip");
  1387. string tempFolderName = "temp_" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
  1388. string tempPath = Path.Combine(serverpath, tempFolderName);
  1389. if (!Directory.Exists(tempPath))
  1390. Directory.CreateDirectory(tempPath);
  1391. if (jsonList.Count == 1 && jsonList[0].ToString() == ".*")
  1392. {
  1393. ZipFile.CreateFromDirectory(tempPath, zipPath);
  1394. filepath = zipPath;
  1395. Directory.Delete(tempPath, true);
  1396. if (filepath != "" || filepath.Length > 0)
  1397. {
  1398. byte[] file = System.IO.File.ReadAllBytes(filepath);
  1399. System.IO.File.Delete(filepath);
  1400. return Ok(new { File = file });
  1401. }
  1402. else
  1403. {
  1404. return BadRequest(new { message = "File notfound" });
  1405. }
  1406. }
  1407. else
  1408. {
  1409. inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1410. if (inputfiles.Length == 0)
  1411. {
  1412. inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories)
  1413. .Where(x => jsonList.Contains(Path.GetExtension(x.ToString()).ToLower())).ToArray();
  1414. }
  1415. byte[] fileBytes = null;
  1416. using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
  1417. {
  1418. using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
  1419. {
  1420. foreach (string f in inputfiles)
  1421. {
  1422. // add the item name to the zip
  1423. System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
  1424. // add the item bytes to the zip entry by opening the original file and copying the bytes
  1425. using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
  1426. {
  1427. using (System.IO.Stream entryStream = zipItem.Open())
  1428. {
  1429. originalFileMemoryStream.CopyTo(entryStream);
  1430. }
  1431. }
  1432. }
  1433. }
  1434. fileBytes = memoryStream.ToArray();
  1435. return Ok(new { File = fileBytes });
  1436. // return Ok(new { File = File(fileBytes, "application/zip", zipname) });
  1437. }
  1438. }
  1439. }
  1440. else { return BadRequest(new { message = "File notfound" }); }
  1441. // }
  1442. }
  1443. }
  1444. // [Authorize]
  1445. [HttpPost("DownloadInOutFiles")]
  1446. public async Task<IActionResult> DownloadInOutFiles([FromBody] filedownload fileData)
  1447. {
  1448. string jobid = fileData.jobid.ToString() ?? "";
  1449. string tranid = fileData.tranid.ToString() ?? "";
  1450. string pdid = fileData.pdid.ToString() ?? "";
  1451. string option = fileData.option.ToString() ?? "";
  1452. string jobtitle = fileData.jobtitle.ToString() ?? "";
  1453. if (string.IsNullOrWhiteSpace(tranid))
  1454. return BadRequest("Transaction ID is required.");
  1455. try
  1456. {
  1457. // ✅ Step 1: Build server path
  1458. string serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
  1459. if (!string.IsNullOrWhiteSpace(option))
  1460. serverpath = Path.Combine(serverpath, option);
  1461. if (!Directory.Exists(serverpath))
  1462. return NotFound("Source folder not found.");
  1463. // ✅ Step 2: Prepare ZIP name
  1464. string zipFileName = (!string.IsNullOrEmpty(option) && (option.Contains("IN") || option.Contains("OUT")))
  1465. ? $"{jobtitle}_{tranid}_{option}.zip"
  1466. : $"{jobtitle}_{tranid}.zip";
  1467. // ✅ Step 3: Create app-specific temporary folder (not C:\Windows\Temp)
  1468. string tempBase = Path.Combine(System.AppContext.BaseDirectory, "TempZips");
  1469. Directory.CreateDirectory(tempBase); // ensure it exists
  1470. string tempZipPath = Path.Combine(tempBase, zipFileName);
  1471. // Clean existing temp file if present
  1472. if (System.IO.File.Exists(tempZipPath))
  1473. System.IO.File.Delete(tempZipPath);
  1474. // ✅ Step 4: Use impersonation to access the server folder
  1475. using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  1476. {
  1477. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1478. await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
  1479. {
  1480. // Create ZIP under impersonated context (no compression = faster)
  1481. ZipFile.CreateFromDirectory(serverpath, tempZipPath, CompressionLevel.NoCompression, includeBaseDirectory: true);
  1482. await Task.CompletedTask; // keep async signature clean
  1483. });
  1484. }
  1485. // ✅ Step 5: Stream ZIP to client
  1486. Response.ContentType = "application/zip";
  1487. Response.Headers.Add("Content-Disposition", $"attachment; filename=\"{zipFileName}\"");
  1488. await using (var zipStream = new FileStream(tempZipPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
  1489. {
  1490. await zipStream.CopyToAsync(Response.Body);
  1491. }
  1492. // ✅ Step 6: Clean up temporary ZIP safely
  1493. try
  1494. {
  1495. System.IO.File.Delete(tempZipPath);
  1496. }
  1497. catch
  1498. {
  1499. // ignore cleanup errors
  1500. }
  1501. return new EmptyResult(); // response already written
  1502. }
  1503. catch (Exception ex)
  1504. {
  1505. // ✅ Step 7: Log and return error
  1506. oCommonRepository.addlog(new
  1507. {
  1508. errormessage = "Error: " + ex.Message,
  1509. createdby = 0,
  1510. controller = "WorkAreaApi: DownloadInOutFiles"
  1511. }, "errorlog");
  1512. return StatusCode(500, $"Error while downloading files: {ex.Message}");
  1513. }
  1514. }
  1515. //public async Task<IActionResult> DownloadInOutFiles([FromBody] filedownload fileData)
  1516. //{
  1517. // try
  1518. // {
  1519. // string jobid = fileData.jobid.ToString() ?? "";
  1520. // string tranid = fileData.tranid.ToString() ?? "";
  1521. // string pdid = fileData.pdid.ToString() ?? "";
  1522. // string option = fileData.option.ToString() ?? "";
  1523. // string jobtitle = fileData.jobtitle.ToString() ?? "";
  1524. // // Build server path
  1525. // string serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
  1526. // serverpath = Path.Combine(serverpath, option);
  1527. // // Build ZIP filename
  1528. // string zipname = (option.Contains("IN") || option.Contains("OUT"))
  1529. // ? $"{jobtitle}_{tranid}_{option}.zip"
  1530. // : $"{jobtitle}_{tranid}.zip";
  1531. // DirectoryInfo dirinfo = new DirectoryInfo(serverpath);
  1532. // if (!dirinfo.Exists)
  1533. // return NotFound("Source folder not found.");
  1534. // // Create in-memory zip (streamed, not loaded fully)
  1535. // var memoryStream = new MemoryStream();
  1536. // using (var permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  1537. // {
  1538. // WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1539. // await WindowsIdentity.RunImpersonated(newId.AccessToken, async () =>
  1540. // {
  1541. // using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
  1542. // {
  1543. // foreach (var file in dirinfo.GetFiles("*.*", SearchOption.AllDirectories))
  1544. // {
  1545. // string relativePath = file.FullName.Substring(dirinfo.FullName.Length + 1);
  1546. // var entry = archive.CreateEntry(relativePath, CompressionLevel.Fastest);
  1547. // using var entryStream = entry.Open();
  1548. // using var fileStream = System.IO.File.OpenRead(file.FullName);
  1549. // await fileStream.CopyToAsync(entryStream);
  1550. // }
  1551. // }
  1552. // });
  1553. // }
  1554. // memoryStream.Position = 0; // reset stream for reading
  1555. // // Return the zip file to Angular
  1556. // return File(memoryStream, "application/zip", zipname);
  1557. // }
  1558. // catch (Exception ex)
  1559. // {
  1560. // oCommonRepository.addlog(new
  1561. // {
  1562. // errormessage = "Error: " + ex.Message,
  1563. // createdby = 0,
  1564. // controller = "WorkAreaApi: DownloadInOutFiles"
  1565. // }, "errorlog");
  1566. // return BadRequest(new { message = "Error: " + ex.Message });
  1567. // }
  1568. //}
  1569. //public IActionResult DownloadInOutFiles(filedownload fileData)
  1570. //{
  1571. // try
  1572. // {
  1573. // // Extract file data from the request
  1574. // string jobid = fileData.jobid.ToString();
  1575. // string tranid = fileData.tranid.ToString();
  1576. // string pdid = fileData.pdid.ToString();
  1577. // string option = fileData.option.ToString();
  1578. // string jobtitle = fileData.jobtitle.ToString();
  1579. // string serverpath;
  1580. // // Get the server path based on the transaction ID and other parameters
  1581. // serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
  1582. // serverpath = Path.Combine(serverpath, option);
  1583. // // Generate the zip file name
  1584. // string zipname = string.Empty;
  1585. // if (option.Contains("IN") || option.Contains("OUT"))
  1586. // {
  1587. // zipname = $"{jobtitle}_{tranid}_{option}.zip";
  1588. // }
  1589. // else
  1590. // {
  1591. // zipname = $"{jobtitle}_{tranid}.zip";
  1592. // }
  1593. // // Get the directory info for the given path
  1594. // System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo(serverpath);
  1595. // // Check if the directory exists
  1596. // if (!dirinfo.Exists)
  1597. // {
  1598. // return BadRequest(new { message = "Directory does not exist." });
  1599. // }
  1600. // // Create a list of file entries from the directory, including subdirectories
  1601. // FileInfo[] inputfiles = dirinfo.GetFiles("*.*", SearchOption.AllDirectories);
  1602. // if (inputfiles.Length == 0)
  1603. // {
  1604. // return BadRequest(new { message = "No files found in the directory." });
  1605. // }
  1606. // byte[] fileBytes = null;
  1607. // using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
  1608. // {
  1609. // using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
  1610. // {
  1611. // foreach (FileInfo file in inputfiles)
  1612. // {
  1613. // // Create a zip entry for each file while maintaining the folder structure
  1614. // string relativePath = file.FullName.Substring(dirinfo.FullName.Length + 1); // Get relative path of the file
  1615. // System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(relativePath);
  1616. // // Open the original file and copy its contents into the zip entry
  1617. // using (System.IO.Stream originalFileStream = file.OpenRead())
  1618. // {
  1619. // using (System.IO.Stream entryStream = zipItem.Open())
  1620. // {
  1621. // originalFileStream.CopyTo(entryStream);
  1622. // }
  1623. // }
  1624. // }
  1625. // }
  1626. // // Convert memory stream to byte array
  1627. // fileBytes = memoryStream.ToArray();
  1628. // }
  1629. // // Return the zip file as byte array
  1630. // return Ok(new { File = fileBytes });
  1631. // // Alternatively, you can return the file directly as:
  1632. // // return File(fileBytes, "application/zip", zipname);
  1633. // }
  1634. // catch (Exception ex)
  1635. // {
  1636. // // Log the error
  1637. // var data_input = new
  1638. // {
  1639. // errormessage = "Error: " + ex.Message,
  1640. // createdby = 0,
  1641. // controller = "UploaderApi: Downloader"
  1642. // };
  1643. // oCommonRepository.addlog(data_input, "errorlog");
  1644. // // Return an error message
  1645. // return BadRequest(new { message = "An error occurred while processing the files." });
  1646. // }
  1647. //}
  1648. //public IActionResult DownloadInOutFiles(filedownload fileData)
  1649. //{
  1650. // try
  1651. // {
  1652. // string jobid = fileData.jobid.ToString();
  1653. // string tranid = fileData.tranid.ToString();
  1654. // string pdid = fileData.pdid.ToString();
  1655. // string option = fileData.option.ToString();
  1656. // string jobtitle = fileData.jobtitle.ToString();
  1657. // string serverpath;
  1658. // serverpath = oWorkAreaService.GetServerPath(tranid, false, "serverinfo");
  1659. // serverpath = Path.Combine(serverpath, option);
  1660. // string zipname = string.Empty;
  1661. // if (option.IndexOf("IN") != -1 || option.IndexOf("OUT") != -1)
  1662. // {
  1663. // zipname = jobtitle + "_" + tranid + "_" + option + ".zip";
  1664. // }
  1665. // else
  1666. // {
  1667. // zipname = jobtitle + "_" + tranid + ".zip";
  1668. // }
  1669. // string[] inputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly).ToArray();
  1670. // byte[] fileBytes = null;
  1671. // using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
  1672. // {
  1673. // using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
  1674. // {
  1675. // foreach (string f in inputfiles)
  1676. // {
  1677. // // add the item name to the zip
  1678. // System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
  1679. // // add the item bytes to the zip entry by opening the original file and copying the bytes
  1680. // using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
  1681. // {
  1682. // using (System.IO.Stream entryStream = zipItem.Open())
  1683. // {
  1684. // originalFileMemoryStream.CopyTo(entryStream);
  1685. // }
  1686. // }
  1687. // }
  1688. // }
  1689. // fileBytes = memoryStream.ToArray();
  1690. // return Ok(new { File = fileBytes });
  1691. // // return Ok(new { File = File(fileBytes, "application/zip", zipname) });
  1692. // }
  1693. // }
  1694. // catch (Exception ex)
  1695. // {
  1696. // var data_input = new
  1697. // {
  1698. // errormessage = "Error: " + ex.Message,
  1699. // createdby = 0,
  1700. // controller = "UploaderApi: Downloader"
  1701. // };
  1702. // oCommonRepository.addlog(data_input, "errorlog");
  1703. // return BadRequest(new { message = "File notfound" });
  1704. // }
  1705. //}
  1706. [HttpGet("ValidateOutFileExist")]
  1707. public object ValidateOutFileExist(int jobid, int tranid, string stagename_alias, int projectdefinitionid, string lottitle)
  1708. {
  1709. List<FileDetails> AllFiles = new List<FileDetails>();
  1710. string[] outputfiles = null;
  1711. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString()))
  1712. {
  1713. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1714. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  1715. {
  1716. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  1717. System.Console.WriteLine(useri.Name);
  1718. // using (ServerInfo.GrantFolderPermission permit = new ServerInfo.GrantFolderPermission(jobid.ToString()))
  1719. // {
  1720. string serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
  1721. serverpath = Path.Combine(serverpath, "OUT");
  1722. if (Directory.Exists(serverpath))
  1723. {
  1724. outputfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.AllDirectories);
  1725. }
  1726. else
  1727. {
  1728. AllFiles = null;
  1729. }
  1730. });
  1731. }
  1732. if (outputfiles.Length == 0)
  1733. {
  1734. var json = new { result = false };
  1735. return json;
  1736. }
  1737. else
  1738. {
  1739. if (stagename_alias == "LARE Review")
  1740. {
  1741. int htmlFilesCount = outputfiles.Count(file => file.EndsWith(".html", StringComparison.OrdinalIgnoreCase));
  1742. if (htmlFilesCount == 0)
  1743. {
  1744. var json = new { result = false };
  1745. return json;
  1746. }
  1747. else
  1748. {
  1749. var json = new { result = true };
  1750. return json;
  1751. }
  1752. }
  1753. else if (
  1754. (stagename_alias == "Redaction and Styling"
  1755. || stagename_alias == "OCR and Styling")
  1756. && projectdefinitionid == 366
  1757. )
  1758. {
  1759. int htmlFilesCount = outputfiles.Count(file => file.Contains(lottitle, StringComparison.OrdinalIgnoreCase) &&
  1760. file.EndsWith(".xml", StringComparison.OrdinalIgnoreCase));
  1761. if (htmlFilesCount == 0)
  1762. {
  1763. var json = new { result = false };
  1764. return json;
  1765. }
  1766. else
  1767. {
  1768. var json = new { result = true };
  1769. return json;
  1770. }
  1771. }
  1772. else if (stagename_alias == "Redaction and Styling" && projectdefinitionid == 364)
  1773. {
  1774. int htmlFilesCount = outputfiles.Count(file => file.EndsWith("_Redacted.pdf", StringComparison.OrdinalIgnoreCase));
  1775. if (htmlFilesCount == 0)
  1776. {
  1777. var json = new { result = false };
  1778. return json;
  1779. }
  1780. else
  1781. {
  1782. var json = new { result = true };
  1783. return json;
  1784. }
  1785. }
  1786. else
  1787. {
  1788. var json = new { result = true };
  1789. return json;
  1790. }
  1791. }
  1792. }
  1793. // [Authorize]
  1794. //[AllowAnonymous]
  1795. [HttpPost("getdispatchid")]
  1796. public object getdispatchid(long jobid, long tranid, long lotid, string projectsubtitle)
  1797. {
  1798. int jobWorkflowId = 0;
  1799. int dispatchtranid = 0;
  1800. int Allocationtranid = 0;
  1801. string[] inputfiles;
  1802. try
  1803. {
  1804. using (IDbConnection dbConnection = ConnectionBase.Connection)
  1805. {
  1806. dbConnection.Open();
  1807. string query = @"
  1808. SELECT lt.transactionid
  1809. FROM tbllottransaction lt
  1810. JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
  1811. WHERE jwd.stagename_alias = 'Dispatch' AND jwd.jobid = @jobid order by lt.starttime desc limit(1)";
  1812. var result = dbConnection.QueryFirstOrDefault<int>(query, new { jobid = jobid });
  1813. if (result != 0)
  1814. {
  1815. dispatchtranid = result; // store the transactionid or use it further
  1816. }
  1817. string updateQuerys = @"
  1818. UPDATE tbllottransaction
  1819. SET lotstatus = 'W'
  1820. WHERE transactionid = @transactionid ;
  1821. ";
  1822. int rowsAffecteds = dbConnection.Execute(updateQuerys, new { transactionid = dispatchtranid });
  1823. if (projectsubtitle == "LN_BPM")
  1824. {
  1825. string querys = @"
  1826. SELECT lt.transactionid
  1827. FROM tbllottransaction lt
  1828. JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
  1829. WHERE jwd.stagename_alias = 'Allocation' AND jwd.jobid = @jobid AND lt.lotstatus='F' order by lt.starttime desc limit(1) ";
  1830. var result1 = dbConnection.QueryFirstOrDefault<int>(querys, new { jobid = jobid });
  1831. if (result1 != 0)
  1832. {
  1833. Allocationtranid = result1; // store the transactionid or use it further
  1834. }
  1835. string updateQuery = @"
  1836. UPDATE tbllottransaction
  1837. SET active = '0'
  1838. WHERE transactionid = @transactionid ;
  1839. ";
  1840. int rowsAffected = dbConnection.Execute(updateQuery, new { transactionid = Allocationtranid });
  1841. }
  1842. else
  1843. {
  1844. string querys = @"
  1845. SELECT lt.transactionid
  1846. FROM tbllottransaction lt
  1847. JOIN tbljobworkflowdefinition jwd ON jwd.jobworkflowid = lt.jobworkflowid
  1848. WHERE jwd.stagename_alias = 'XML Review' AND jwd.jobid = @jobid AND lt.lotstatus='F' order by lt.starttime desc limit(1) ";
  1849. var result1 = dbConnection.QueryFirstOrDefault<int>(querys, new { jobid = jobid });
  1850. if (result1 != 0)
  1851. {
  1852. Allocationtranid = result1; // store the transactionid or use it further
  1853. }
  1854. string updateQuery = @"
  1855. UPDATE tbllottransaction
  1856. SET active = '0'
  1857. WHERE transactionid = @transactionid ;
  1858. ";
  1859. int rowsAffected = dbConnection.Execute(updateQuery, new { transactionid = Allocationtranid });
  1860. }
  1861. }
  1862. string redactserverinfo = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
  1863. string serverpaths = Path.Combine(redactserverinfo, "IN");
  1864. inputfiles = Directory.GetFiles(serverpaths, "*.pdf", SearchOption.AllDirectories).ToArray();
  1865. foreach (var file in inputfiles)
  1866. {
  1867. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid.ToString()))
  1868. {
  1869. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1870. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  1871. {
  1872. // using (ServerInfo.GrantFolderPermission imp = new ServerInfo.GrantFolderPermission(jobid))
  1873. string serverinfo = oWorkAreaService.GetServerPath(dispatchtranid.ToString(), false, "serverinfo");
  1874. string serverpath = Path.Combine(serverinfo, "IN");
  1875. string destinationFilePath = Path.Combine(serverinfo, "IN", Path.GetFileName(file));
  1876. if (!Directory.Exists(serverpath))
  1877. {
  1878. Directory.CreateDirectory(serverpath);
  1879. }
  1880. //string destinationFilePath = Path.Combine(serverpath, Path.GetFileName(file));
  1881. // try
  1882. // {
  1883. System.IO.File.Copy(file, destinationFilePath, true);
  1884. // }
  1885. });
  1886. }
  1887. }
  1888. }
  1889. catch (Exception ex)
  1890. {
  1891. return Ok(new { jobid = ex.Message });
  1892. }
  1893. return Ok(new { jobid = jobid }); // or any other return value you need
  1894. }
  1895. [HttpPost]
  1896. [Route("forwardstage")]
  1897. public IActionResult forwardstage([FromBody] JObject data)
  1898. {
  1899. Guid id = Guid.NewGuid();
  1900. //int next_tranid = InsertLotTransaction(Convert.ToInt32(data1.Rows[0]["lotid"].ToString()), AIstage.ToString(), Path.GetFileNameWithoutExtension(inpath), tranid);
  1901. // var _listlt = oWorkAreaService.usrLotTransactionInsert(data.p_userid, data.p_lotid, data.p_jobworkflowid, id.ToString(), "insertlottransactiondetailonly");
  1902. long tranid = 0;
  1903. // Safely parse properties from JObject
  1904. int userid = data["p_userid"]?.ToObject<int>() ?? 0;
  1905. long lotid = data["p_lotid"]?.ToObject<long>() ?? 0;
  1906. // long jobworkflowid = Convert.ToInt32(data.p_jobworkflowid) + 1;
  1907. // using (IDbConnection dbConnection = ConnectionBase.Connection)
  1908. // {
  1909. // dbConnection.Open();
  1910. // string querys = @"
  1911. //SELECT jobworkflowid
  1912. //FROM tbljobworkflowdefinition
  1913. //WHERE jobid = @jobid
  1914. //AND stagename_alias='HTML Generation'";
  1915. // var jobworkflow = dbConnection.Query<int>(querys, new { jobid = data.p_jobid }).ToList();
  1916. // string sQry = "insert_lot_transaction_details_only";
  1917. // using (var cmd = new NpgsqlCommand(sQry, (NpgsqlConnection)dbConnection))
  1918. // {
  1919. // cmd.CommandType = CommandType.StoredProcedure;
  1920. // //cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = Convert.ToInt64(jobworkflow) });
  1921. // if (jobworkflow != null && jobworkflow.Any())
  1922. // {
  1923. // cmd.Parameters.Add(new NpgsqlParameter("p_jobworkflowid", NpgsqlTypes.NpgsqlDbType.Bigint)
  1924. // {
  1925. // Value = Convert.ToInt64(jobworkflow.First())
  1926. // });
  1927. // }
  1928. // cmd.Parameters.Add(new NpgsqlParameter("p_lotid", NpgsqlTypes.NpgsqlDbType.Bigint) { Value = lotid });
  1929. // cmd.Parameters.Add(new NpgsqlParameter("p_lotkey", NpgsqlTypes.NpgsqlDbType.Uuid) { Value = Guid.Parse(id.ToString()) });
  1930. // object result = cmd.ExecuteScalar();
  1931. // // Replace modcommon.nz with your own null check or conversion
  1932. // if (result == null || result == DBNull.Value)
  1933. // {
  1934. // tranid = 0; // or default value you want
  1935. // }
  1936. // else
  1937. // {
  1938. // tranid = Convert.ToInt64(result);
  1939. // }
  1940. // }
  1941. // long transactionId = Convert.ToInt64(data.p_tranid);
  1942. // string query = @"Update tbllottransaction set lotstatus='F' where transactionid=@transactionid"
  1943. // ;
  1944. // var lotIds = dbConnection.Query<int>(query, new { transactionid = transactionId }).ToList();
  1945. // }
  1946. // var _listlt = oWorkAreaService.usrLotTransactionInsert(userid, lotid, jobworkflowid, id.ToString(), "insertlottransactiondetailonly");
  1947. //string nextstage_serverpath = oCommonRepository.GetServerPath(data.p_tranid.ToString(), "serverinfo",true);
  1948. //RabbitMq sendmsg = new RabbitMq(_requestClient);
  1949. //sendmsg.SendMq_StageComplete(tranid.ToString(), "0", "checkin_apps", "server", "", "A", "");
  1950. return Ok("Success");
  1951. }
  1952. //[Authorize]
  1953. [HttpPost("DownloadSingleFile")]
  1954. public IActionResult DownloadSingleFile(filedownload fileData)
  1955. {
  1956. try
  1957. {
  1958. string type = fileData.type.ToString();
  1959. string path = fileData.path.ToString();
  1960. string jobid = fileData.jobid.ToString();
  1961. byte[] fileBytes = null;
  1962. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  1963. {
  1964. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1965. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  1966. {
  1967. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  1968. fileBytes = System.IO.File.ReadAllBytes(path);
  1969. string fileName = Path.GetFileName(path);
  1970. });
  1971. }
  1972. return Ok(new { File = fileBytes });
  1973. }
  1974. catch (Exception ex)
  1975. {
  1976. var data_input = new
  1977. {
  1978. errormessage = "Error: " + ex.Message,
  1979. createdby = 0,
  1980. controller = "UploaderApi: Downloader"
  1981. };
  1982. oCommonRepository.addlog(data_input, "errorlog");
  1983. throw;
  1984. }
  1985. }
  1986. // [Authorize]
  1987. [HttpPost("DownloadSingleOutFile")]
  1988. public IActionResult DownloadSingleOutFile(filedownload fileData)
  1989. {
  1990. try
  1991. {
  1992. string type = fileData.type.ToString();
  1993. string path = fileData.path.ToString();
  1994. string jobid = fileData.jobid.ToString();
  1995. byte[] fileBytes = null;
  1996. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  1997. {
  1998. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  1999. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  2000. {
  2001. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  2002. fileBytes = System.IO.File.ReadAllBytes(path);
  2003. string fileName = Path.GetFileName(path);
  2004. });
  2005. }
  2006. return Ok(new { File = fileBytes });
  2007. }
  2008. catch (Exception ex)
  2009. {
  2010. var data_input = new
  2011. {
  2012. errormessage = "Error: " + ex.Message,
  2013. createdby = 0,
  2014. controller = "UploaderApi: Downloader"
  2015. };
  2016. oCommonRepository.addlog(data_input, "errorlog");
  2017. throw;
  2018. }
  2019. }
  2020. // [Authorize]
  2021. [HttpPost("RemoveIOFiles")]
  2022. public object RemoveIOFiles(dynamic fileData)
  2023. {
  2024. string path = fileData.path.ToString();
  2025. string jobid = fileData.jobid.ToString();
  2026. try
  2027. {
  2028. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  2029. {
  2030. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  2031. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  2032. {
  2033. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  2034. System.IO.File.Delete(path);
  2035. });
  2036. }
  2037. var json = new { result = true, filename = Path.GetFileName(path) };
  2038. return json;
  2039. }
  2040. catch (Exception ex)
  2041. {
  2042. var data_input = new
  2043. {
  2044. errormessage = "Error: " + ex.Message,
  2045. createdby = 0,
  2046. controller = "UploaderApi: Downloader"
  2047. };
  2048. oCommonRepository.addlog(data_input, "errorlog");
  2049. var json = new { result = false, filename = Path.GetFileName(path) };
  2050. return json;
  2051. }
  2052. }
  2053. // [Authorize]
  2054. [HttpPost("DownloadFolder")]
  2055. public IActionResult DownloadFolder(dynamic fileData)
  2056. {
  2057. try
  2058. {
  2059. string jobid = fileData.jobid.ToString();
  2060. string FolderPath = fileData.path.ToString();
  2061. string tranid = fileData.tranid.ToString();
  2062. string jobtitle = fileData.jobtitle.ToString();
  2063. string zipname = string.Empty;
  2064. byte[] fileBytes = null;
  2065. bool fail = false;
  2066. zipname = jobtitle + "_" + tranid + ".zip";
  2067. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", "", "", jobid))
  2068. {
  2069. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  2070. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  2071. {
  2072. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  2073. if (Directory.Exists(FolderPath))
  2074. {
  2075. string[] inputfiles = Directory.GetFiles(FolderPath, "*.*", SearchOption.TopDirectoryOnly).ToArray();
  2076. using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
  2077. {
  2078. using (System.IO.Compression.ZipArchive zip = new System.IO.Compression.ZipArchive(memoryStream, System.IO.Compression.ZipArchiveMode.Create, true))
  2079. {
  2080. foreach (string f in inputfiles)
  2081. {
  2082. // add the item name to the zip
  2083. System.IO.Compression.ZipArchiveEntry zipItem = zip.CreateEntry(Path.GetFileName(f) + "." + Path.GetExtension(f));
  2084. // add the item bytes to the zip entry by opening the original file and copying the bytes
  2085. using (System.IO.MemoryStream originalFileMemoryStream = new System.IO.MemoryStream(System.IO.File.ReadAllBytes(f)))
  2086. {
  2087. using (System.IO.Stream entryStream = zipItem.Open())
  2088. {
  2089. originalFileMemoryStream.CopyTo(entryStream);
  2090. }
  2091. }
  2092. }
  2093. }
  2094. fileBytes = memoryStream.ToArray();
  2095. }
  2096. }
  2097. else
  2098. {
  2099. fail = true;
  2100. }
  2101. });
  2102. }
  2103. if (!fail) { return Ok(new { File = File(fileBytes, "application/zip", zipname) }); }
  2104. else
  2105. {
  2106. return BadRequest(new { message = "Folder notfound" });
  2107. }
  2108. }
  2109. catch (Exception ex)
  2110. {
  2111. var data_input = new
  2112. {
  2113. errormessage = "Error: " + ex.Message,
  2114. createdby = 0,
  2115. controller = "UploaderApi: Downloader"
  2116. };
  2117. oCommonRepository.addlog(data_input, "errorlog");
  2118. return BadRequest(new { message = "Folder notfound" });
  2119. }
  2120. }
  2121. [HttpGet("GetOutfileExtension")]
  2122. public object GetOutfileExtension(long tranid)
  2123. {
  2124. var filetype = oWorkAreaService.getFileTypeOutput(tranid.ToString());
  2125. var jsonList = new List<string>();
  2126. if (filetype != null)
  2127. {
  2128. var i_filetype = JsonConvert.DeserializeObject<object>(filetype.ToString());
  2129. JArray a_filetype = JArray.Parse(i_filetype.ToString());
  2130. foreach (var a in a_filetype)
  2131. {
  2132. JObject obj_filetype = JObject.Parse(a.ToString());
  2133. jsonList.Add(obj_filetype["filetype"].ToString().ToLower());
  2134. }
  2135. }
  2136. return Ok(jsonList);
  2137. }
  2138. [HttpGet("getOutfileupdated")]
  2139. public object getOutfileupdated(long tranid, string option)
  2140. {
  2141. using (CommonRepository.GrantFolderPermission permit = new CommonRepository.GrantFolderPermission("", tranid.ToString(), "", ""))
  2142. {
  2143. WindowsIdentity newId = permit.GetImpartunate().AllowAccesstoServer();
  2144. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  2145. {
  2146. WindowsIdentity useri = WindowsIdentity.GetCurrent();
  2147. string renamedvalue = string.Empty;
  2148. string anyfiles = string.Empty;
  2149. string anyfolder = string.Empty;
  2150. var renametype = oWorkAreaService.getFilerenameInput(tranid.ToString());
  2151. var titleqry_jsonList = new List<string>();
  2152. if (renametype != null)
  2153. {
  2154. var titleqry_filetype = JsonConvert.DeserializeObject<object>(renametype.ToString());
  2155. JArray titleqry_a_filetype = JArray.Parse(titleqry_filetype.ToString());
  2156. renamedvalue = titleqry_a_filetype[0]["filename"].ToString();
  2157. string serverpath;
  2158. serverpath = oWorkAreaService.GetServerPath(tranid.ToString(), false, "serverinfo");
  2159. serverpath = Path.Combine(serverpath, option);
  2160. if (Directory.Exists(serverpath))
  2161. {
  2162. string[] folderextensionFilters = new string[] { ".pdf", ".visf" };
  2163. string[] allfolder = Directory.GetDirectories(serverpath, "*.*", SearchOption.TopDirectoryOnly)
  2164. .Where(filename => folderextensionFilters.Any(x =>
  2165. filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).ToArray();
  2166. if (allfolder.Count() > 1)
  2167. {
  2168. foreach (var folder in allfolder)
  2169. {
  2170. anyfolder = string.Empty;
  2171. anyfolder = folder;
  2172. if (anyfolder.Contains(".pdf"))
  2173. {
  2174. anyfiles = string.Empty;
  2175. anyfiles = Directory.GetFiles(anyfolder, "*.pdf", SearchOption.TopDirectoryOnly).FirstOrDefault();
  2176. if (!string.IsNullOrEmpty(anyfiles) && System.IO.File.Exists(anyfiles))
  2177. {
  2178. string destinationPath = Path.Combine(anyfolder, renamedvalue + Path.GetExtension(anyfiles));
  2179. System.IO.File.Move(anyfiles, destinationPath, true);
  2180. }
  2181. }
  2182. else
  2183. {
  2184. anyfiles = Directory.GetFiles(anyfolder, "*.txt", SearchOption.TopDirectoryOnly).Where(x => !x.EndsWith("_Validation_report.txt")).FirstOrDefault();
  2185. if (!string.IsNullOrEmpty(anyfiles) && System.IO.File.Exists(anyfiles))
  2186. {
  2187. string destinationPath = Path.Combine(anyfolder, renamedvalue + Path.GetExtension(anyfiles));
  2188. System.IO.File.Move(anyfiles, destinationPath, true);
  2189. }
  2190. }
  2191. }
  2192. }
  2193. anyfiles = string.Empty;
  2194. anyfiles = Directory.GetFiles(serverpath, "*.docx", SearchOption.TopDirectoryOnly).FirstOrDefault();
  2195. if (!string.IsNullOrEmpty(anyfiles))
  2196. {
  2197. string destinationPath = Path.Combine(serverpath, renamedvalue + Path.GetExtension(anyfiles));
  2198. System.IO.File.Move(anyfiles, destinationPath, true);
  2199. }
  2200. //string actulavlue = Startup.Configuration.GetValue<string>("AppSettings:QA_File_type");
  2201. //actulavlue = Regex.Replace(actulavlue, @"&quot;", "\"", RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Singleline);
  2202. //string[] extensionFilters = new string[] { ".pdf", ".docx", ".zip" };
  2203. //string anyfiles = Directory.GetFiles(serverpath, "*.*", SearchOption.TopDirectoryOnly)
  2204. // .Where(filename => extensionFilters.Any(x =>
  2205. // filename.EndsWith(x, StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
  2206. //if (!string.IsNullOrEmpty(anyfiles))
  2207. //{
  2208. // try
  2209. // {
  2210. // string destinationPath = Path.Combine(serverpath, renamedvalue+Path.GetExtension(anyfiles));
  2211. // System.IO.File.Move(anyfiles, destinationPath, true);
  2212. // }
  2213. // catch(Exception ex)
  2214. // {
  2215. // }
  2216. //}
  2217. }
  2218. }
  2219. });
  2220. }
  2221. return Ok(1);
  2222. }
  2223. [AllowAnonymous]
  2224. [HttpPost("pushback")]
  2225. public IActionResult PushBack([FromForm] PushBackRequest request)
  2226. {
  2227. try
  2228. {
  2229. // Get base server path
  2230. string serverinfo = oWorkAreaService
  2231. .GetServerPath(request.tranid.ToString(), false, "serverinfo");
  2232. // Combine folder paths
  2233. string outFolderPath = Path.Combine(serverinfo, "OUT");
  2234. string inFolderPath = Path.Combine(serverinfo, "IN");
  2235. using (CommonRepository.GrantFolderPermission permit =
  2236. new CommonRepository.GrantFolderPermission("", "", "", request.jobid.ToString()))
  2237. {
  2238. WindowsIdentity newId = permit.GetImpartunate()?.AllowAccesstoServer();
  2239. if (newId == null)
  2240. return StatusCode(500, "Impersonation failed");
  2241. WindowsIdentity.RunImpersonated(newId.AccessToken, () =>
  2242. {
  2243. // Delete OUT folder files
  2244. if (Directory.Exists(outFolderPath))
  2245. {
  2246. var outFiles = Directory.GetFiles(outFolderPath);
  2247. foreach (var file in outFiles)
  2248. {
  2249. System.IO.File.Delete(file);
  2250. }
  2251. }
  2252. // Delete IN folder files
  2253. if (Directory.Exists(inFolderPath))
  2254. {
  2255. var inFiles = Directory.GetFiles(inFolderPath);
  2256. foreach (var file in inFiles)
  2257. {
  2258. System.IO.File.Delete(file);
  2259. }
  2260. }
  2261. });
  2262. }
  2263. var result = oWorkAreaService.PushBack(request);
  2264. return Ok(result);
  2265. }
  2266. catch (Exception ex)
  2267. {
  2268. return StatusCode(500, ex.Message);
  2269. }
  2270. }
  2271. [AllowAnonymous]
  2272. [HttpPost("workflowdecision")]
  2273. public IActionResult workflowdecision([FromBody] object data)
  2274. {
  2275. var _list = oWorkAreaService.workflowdecision(data);
  2276. return Ok(_list);
  2277. }
  2278. public class JobRequest
  2279. {
  2280. public long JobId { get; set; }
  2281. }
  2282. public class PushBackRequest
  2283. {
  2284. public long jobid { get; set; }
  2285. public long lotid { get; set; }
  2286. public long tranid { get; set; }
  2287. public string lottitle { get; set; }
  2288. }
  2289. }
  2290. }