Advertisement
GLASHATAY_007

Untitled

Mar 25th, 2024
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.14 KB | None | 0 0
  1. CREATE OR REPLACE FUNCTION "public"."dwh_contract_kgntv_func"()
  2. RETURNS TABLE("contractid" int4, "requestid" int4, "lotid" int4, "requestyear" int4, "first_fin_year" int4, "first_fin_cont_year" int4, "first_fin_cont_year_fact" int4, "contractrnk" varchar, "contractchangenumber" varchar, "modification" varchar, "contractversion" int4, "ordertypename" text, "ordertypecode" int4, "stagetitle" varchar, "stageid" int4, "stagenumber" numeric, "contractnoticenumber" varchar, "datelastchange" timestamptz, "customerid" int4, "customername" varchar, "customerinn" varchar, "customerkpp" varchar, "suppliername" varchar, "supplierinn" varchar, "supplierkpp" varchar, "suppliersmp" int4, "suppliersmpsmp" int4, "suppliersmpsonco" int4, "supplierinvalid" int4, "suppliercriminal" int4, "supplierstatus" varchar, "supplierphone" varchar, "supplierokopf" varchar, "supplierokpo" varchar, "supplierfio" varchar, "supplieremail" varchar, "supplieradress" varchar, "supplieraddress_fact" varchar, "suppliertype" varchar, "grbsname" varchar, "grbsid" int4, "grbscode" varchar, "perc_size" numeric, "perc_rub_size" numeric, "modification_docnum" varchar, "penaltiesamount" varchar, "contractcreatedate" timestamptz, "contractsigndate" timestamptz, "contractnumber" varchar, "contractsubject" varchar, "contractfullprice" numeric, "contract_price_signing" numeric, "contractactualpaid" numeric, "contractplaneexecdate" timestamptz, "contractactualexecdate" timestamptz, "contractrejectdate" timestamptz, "first_notice_date" timestamp, "first_try_notice_date" timestamp, "last_notice_date" timestamp, "last_try_notice_date" timestamp, "contractrejectreason" varchar, "contractrejectbase" varchar, "contractoneexecreason" varchar, "resultprotocol" varchar, "paidfromregister" numeric, "protocoldate" timestamptz, "finsource" varchar, "warranty_requirements" varchar, "warranty_case" varchar, "foreignpref" int4, "penalties" int4, "ispublic" int4, "import_uuid" varchar, "detail_parent_id" int4, "cancel_document_params" varchar, "is_concluded_in_e_shop" varchar, "special_contract_type" int4, "contract_execution_start_date" timestamptz, "price_type" varchar, "document_date" timestamptz, "contract_modification_reasons" varchar, "modif_reason_documents" varchar, "drugs_purchase" int4, "fulfilment_sum_rur" numeric, "violation_deadlines" int4, "name" varchar, "violation_reasons_not_21" varchar, "amount_of_penalty" varchar, "penalty_write_off_information" int4, "penalty_sum" numeric, "fulfilment_sum" numeric, "preference_smp_sonco" int4, "preference_invalid" int4, "preference_ugolov" int4, "oktmo" varchar, "supply_impossible" int4, "rtc_price" numeric, "acceptance_doc" int4) AS $BODY$
  3. #variable_conflict use_column
  4. begin
  5.  
  6. -- создаем временную таблицу first_fin
  7. Create Temp Table first_fin
  8. (
  9. lot_id int4 PRIMARY KEY,
  10. year_ int4
  11. )
  12. ;
  13.  
  14. -- заполняем времнную таблицу first_fin
  15. Insert into first_fin
  16. Select
  17. l.id lot_id,
  18. min(pvtp.name) year_
  19. From gpospb.lots l
  20. Inner Join gpospb.po_finances pf On (pf.lot_id = l.id)
  21. Inner Join gpospb.po_account pa On (pa.id = pf.po_account_id)
  22. Inner Join gpospb.po_budget pb On (pb.id = pa.po_budget_id)
  23. Inner Join gpospb.po_vocab_time_periods pvtp On pvtp.id = pb.po_period_id
  24. Group by l.id
  25. ;
  26.  
  27. -- создаем временную таблицу first_fin_cont
  28. Create Temp Table first_fin_cont
  29. (
  30. lot_id int4 PRIMARY KEY,
  31. year_plan int4,
  32. year_fact int4
  33. )
  34. ;
  35.  
  36. -- заполняем времнную таблицу first_fin_cont
  37. Insert into first_fin_cont
  38. Select
  39. pf.lot_id,
  40. Min(Case
  41. When pf.type = 1 Then pvtp.name
  42. Else null End) year_plan,
  43. Min(Case
  44. When pf.type = 2 Then pvtp.name
  45. Else Null End) year_fact
  46. From gpospb.cm_contract_finances pf
  47. Inner Join gpospb.po_account pa On (pa.id = pf.po_account_id and pf.actual is true)
  48. Inner Join gpospb.po_exp_account pea On (pea.id = pa.po_exp_account_id and pea.actual = true)
  49. Inner Join gpospb.gpo_vocab_budget_links gvbl On ((gvbl.budget_type)::text = (pea.budget_type)::text)
  50. Inner Join gpospb.gpo_list_budget glb On ((glb.code)::text = (gvbl.gpo_budget_type_code)::text)
  51. Inner Join gpospb.po_budget pb On (pb.id = pa.po_budget_id and pb.actual = true)
  52. Inner Join gpospb.po_vocab_time_periods pvtp On (pvtp.id = pb.po_period_id)
  53. Inner Join gpospb.cm_contract_stages ccs On (ccs.id = pf.stage_id and ccs.actual = true)
  54. Group By pf.lot_id
  55. ;
  56.  
  57. -- создаем временную таблицу supplieradress
  58. Create Temp Table supplieradress
  59. (
  60. contragent_id int4 PRIMARY KEY,
  61. address_nahozh varchar(4000),
  62. adress varchar(4000)
  63. )
  64. ;
  65.  
  66. -- заполняем времнную таблицу supplieradress
  67. Insert into supplieradress
  68. Select
  69. contragent_id,
  70. max(Case
  71. When address_type = 1
  72. Then Coalesce(index::text, '') ||' ' ||Coalesce(region, '') ||' ' || Coalesce(settlement, '') ||' ' || Coalesce(city, '') || ' ' || Coalesce(street, '') || ' ' || Coalesce(house, '')
  73. When address_type = 3
  74. Then Coalesce(foreign_region, '') ||' ' || Coalesce(foreign_settlement, '') ||' ' || Coalesce(foreign_city, '') || ' ' || Coalesce(foreign_street, '') || ' ' || Coalesce(foreign_house, '')
  75. Else Null
  76. end) address_nahozh,
  77. max(Case
  78. When address_type =2
  79. Then Coalesce(index::text, '') ||' ' ||Coalesce(region, '') ||' ' || Coalesce(settlement, '') ||' ' || Coalesce(city, '') || ' ' || Coalesce(street, '') || ' ' || Coalesce(house, '')
  80. Else Null
  81. End) adress
  82. From gpospb.addresses
  83. Where actual = true --And region Is Not Null And coalesce(Index::text,city) Is Not NULL 20/11/23
  84. Group by contragent_id
  85. ;
  86.  
  87. -- создаем временную таблицу fins
  88. Create Temp Table fins
  89. (
  90. lot_id int4 PRIMARY KEY,
  91. sources varchar(10000)
  92. )
  93. ;
  94.  
  95. -- заполняем времнную таблицу fins
  96. Insert into fins
  97. Select
  98. pf.lot_id,
  99. string_agg(Distinct glb.name, ', ') sources
  100. From gpospb.cm_contract_finances pf
  101. Inner Join gpospb.po_account pa On (pa.id = pf.po_account_id And pf.type = 1 and pf.actual is true)
  102. Inner Join gpospb.po_exp_account pea On (pea.id = pa.po_exp_account_id)
  103. Inner Join
  104. (Select
  105. Min(gpo_budget_type_code) gpo_budget_type_code,
  106. budget_type
  107. From gpospb.gpo_vocab_budget_links
  108. Where actual Is true
  109. Group by budget_type
  110. )gvbl On ((gvbl.budget_type)::text = (pea.budget_type)::text)
  111. Inner Join gpospb.gpo_list_budget glb On ((glb.code) =(gvbl.gpo_budget_type_code))
  112. Group by pf.lot_id
  113. ;
  114.  
  115. -- создаем временную таблицу ccf_p
  116. Create Temp Table ccf_p
  117. (
  118. amount numeric(15,2),
  119. fulfilment_sum_rur numeric(21,2),
  120. fulfilment_sum numeric(21,2),
  121. lot_id int4 PRIMARY KEY,
  122. acceptance_doc int4
  123. )
  124. ;
  125.  
  126. -- заполняем времнную таблицу ccf_p
  127. Insert into ccf_p
  128. Select
  129. Sum(cm_contract_finances.amount) As amount,
  130. Sum(cm_contract_finances.fulfilment_sum_rur) As fulfilment_sum_rur,
  131. Sum(cm_contract_finances.fulfilment_sum) As fulfilment_sum,
  132. cm_contract_finances.lot_id,
  133. max(CASE
  134. WHEN acceptance_doc IS TRUE THEN 1
  135. ELSE 0 END
  136. ) AS acceptance_doc
  137. From gpospb.cm_contract_finances
  138. Where cm_contract_finances.type = 2 and cm_contract_finances.actual is true
  139. Group By cm_contract_finances.lot_id
  140. ;
  141.  
  142. -- создаем временную таблицу firstnotice
  143. Create Temp Table firstnotice
  144. (
  145. id int4 PRIMARY KEY,
  146. date_ timestamp(6),
  147. successdate timestamp(6),
  148. date_max timestamp(6),
  149. successdate_max timestamp(6)
  150. )
  151. ;
  152.  
  153. -- заполняем времнную таблицу firstnotice
  154. Insert into firstnotice
  155. Select
  156. cc.id,
  157. Min(o.date_created) date_,
  158. Min(Case
  159. When o.success = true
  160. Then o.date_created
  161. End) successdate,
  162. Max(o.date_created) date_max,
  163. Max(Case
  164. When o.success = true
  165. Then o.date_created
  166. End) successdate_max
  167. From gpospb.oos_messages o
  168. Inner Join gpospb.cm_contracts cc On cc.lot_id = o.lot_id and cc.id = o.contract_id And o.type = 'contract' And cc.import_uuid Is Null -- and o.success = true
  169. Group By cc.id
  170. ;
  171.  
  172. -- создаем временную таблицу Join_lots
  173. Create Temp Table Join_lots
  174. (
  175. lot_id int4 PRIMARY KEY,
  176. procedure_id int4,
  177. registry_number varchar(32)
  178. )
  179. ;
  180.  
  181. -- заполняем времнную таблицу Join_lots
  182. Insert into Join_lots
  183. Select
  184. pol.lot_id,
  185. l.procedure_id,
  186. p.registry_number registry_number
  187. From gpospb.po_lots pol
  188. Inner Join gpospb.lots l On (l."id" = pol.consolidate_lot_id And pol.consolidate_lot_id Is Not Null)
  189. Inner Join gpospb.procedures p On (p."id" = l.procedure_id)
  190. ;
  191.  
  192. -- создаем временную таблицу ccpen
  193. Create Temp Table ccpen
  194. (
  195. doc_number text,
  196. doc_date varchar(100),
  197. amount int4,
  198. amount_of_penalty varchar(1000),
  199. penalty_write_off_information int4,
  200. penalty_sum numeric(15,2),
  201. cm_contract_id int4 PRIMARY KEY
  202. )
  203. ;
  204.  
  205. -- заполняем времнную таблицу ccpen
  206. Insert into ccpen
  207. Select doc_number,
  208. doc_date,
  209. amount,
  210. amount_of_penalty,
  211. penalty_write_off_information,
  212. penalty_sum,
  213. cm_contract_id
  214. From (
  215. Select string_agg(translate(ltrim(to_char(cpwoi.amount_of_penalty,'999G999G999G990D00')),',.',' ,'),'; ' order by cp.cm_contract_id) as amount_of_penalty --размер неустойки (штрафа, пени), по которой осуществлено списание штрафных санкций (если несколько списаний, то указано через ;)
  216. ,sum(cpwoi.amount_of_penalty) penalty_sum --сумма всех списанных штрафных санкций по контракту
  217. ,cm_contract_id
  218. ,max(f.penalty_write_off_information)penalty_write_off_information
  219. ,Coalesce(min(amount *(Case
  220. When currency_name = 'RUB'
  221. Then 1
  222. Else currency_rate
  223. End)),0
  224. )amount,
  225. Coalesce(to_char(min(doc_date), 'DD.MM.YYYY'), '') doc_date,
  226. Coalesce(min(doc_number), '') doc_number
  227. From gpospb.cm_contract_penalties cp
  228. Left join (select penalty_id,case when penalty_write_off_information='t' then 1 else 0 end penalty_write_off_information From gpospb.cm_contract_penalty_write_off_informations) f ON f.penalty_id = cp.id
  229. LEFT Join gpospb.cm_contract_penalty_write_off_informations AS cpwoi ON cpwoi.penalty_id = cp.id
  230. Group By cm_contract_id
  231. )a
  232. ;
  233.  
  234. -- создаем временную таблицу lc
  235. Create Temp Table lc
  236. (
  237. lot_id int4 PRIMARY KEY
  238. )
  239. ;
  240.  
  241. -- заполняем времнную таблицу lc
  242. Insert into lc
  243. Select
  244. lot_id
  245. From gpospb.lot_customers
  246. Where actual = true
  247. Group By lot_id
  248. ;
  249.  
  250. -- создаем временную таблицу ccss_pvss
  251. Create Temp Table ccss_pvss
  252. (
  253. contract_id int4 PRIMARY KEY,
  254. status int4
  255. )
  256. ;
  257.  
  258. -- заполняем времнную таблицу ccss_pvss
  259. Insert into ccss_pvss
  260. Select ccss.contract_id, max(ccss.status)status
  261. From gpospb.cm_contract_supplier_status ccss -- On (/*ccss.supplier_id=cc.supplier_id and */ccss.contract_id=cc.id)
  262. group by ccss.contract_id
  263. ;
  264.  
  265. -- создаем временную таблицу grbs
  266. Create Temp Table grbs
  267. (
  268. id int4 PRIMARY KEY,
  269. full_name varchar(2000),
  270. inn varchar(20),
  271. kpp varchar(20),
  272. code varchar(255)
  273. )
  274. ;
  275.  
  276. -- заполняем времнную таблицу grbs
  277. Insert into grbs
  278. Select c_grbs.id,c_grbs.full_name,c_grbs.inn,c_grbs.kpp,gcgrbs.code
  279. From gpospb.contragents c_grbs
  280. Left Join gpospb.gpospb_contragents gcgrbs On (gcgrbs.contragent_id = c_grbs.id)
  281. ;
  282.  
  283. -- создаем временную таблицу vps_nks
  284. Create Temp Table vps_nks
  285. (
  286. ps_id int4 PRIMARY KEY,
  287. full_name varchar(255),
  288. id int4,
  289. naumen_id numeric
  290. )
  291. ;
  292.  
  293. /*Select ps.id As ps_id, vps.full_name, vps.id, nks.naumen_id
  294. From gpospb.procedure_steps ps
  295. Inner Join gpospb.vocab_procedure_steps vps On (vps.pseudo::text = ps.step_id::text and vps.actual = true)
  296. Left Join gpospb.site.naumen_kgntv_stages nks On (nks.kgntv_id = vps.id )
  297. */
  298.  
  299. -- заполняем времнную таблицу vps_nks
  300. Insert into vps_nks
  301. Select
  302. ps.id As ps_id, vps.full_name, vps.id, nks.naumen_id
  303. From gpospb.lots l
  304. Inner Join gpospb.procedure_steps ps On (ps.id = l.current_step)
  305. Inner Join gpospb.vocab_procedure_steps vps On (vps.pseudo::text = ps.step_id::text and vps.actual = true)
  306. Left Join site.naumen_kgntv_stages nks On (nks.kgntv_id = vps.id )
  307. ;
  308.  
  309. -- создаем временную таблицу vpt_nkp
  310. Create Temp Table vpt_nkp
  311. (
  312. id int4 PRIMARY KEY,
  313. name varchar(55),
  314. naumen_name text,
  315. naumen_code int4
  316. )
  317. ;
  318.  
  319. -- заполняем времнную таблицу vpt_nkp
  320. Insert into vpt_nkp
  321. Select vpt.id, vpt.name, nkp.naumen_name, nkp.naumen_code
  322. From gpospb.vocab_procedure_types vpt
  323. Left Join site.naumen_kgntv_placingtypes nkp on (nkp.kgntv_id = vpt.id )
  324. ;
  325.  
  326. -- создаем временную таблицу ppr
  327. Create Temp Table ppr
  328. (
  329. lot_id int4,
  330. preference_short_name varchar(200),
  331. preference_id int4,
  332. actual bool
  333. )
  334. ;
  335.  
  336. -- заполняем времнную таблицу ppr
  337. Insert into ppr
  338. Select pr.lot_id, pr.preference_short_name, pr.preference_id,pr.actual
  339. From gpospb.po_preferences pr
  340. Join gpospb.po_list_purchase_preferences plpp on plpp.id=pr.preference_id and plpp.actual='true'
  341. ;
  342.  
  343. -- Очищаем данные основной таблицы
  344. Truncate table public.dwh_contract_kgntv_func
  345. ;
  346.  
  347.  
  348. -- Вставляем данные в основную таблицу
  349. Insert into public.dwh_contract_kgntv_func (contractid, requestid, lotid, requestyear, first_fin_year, first_fin_cont_year, first_fin_cont_year_fact, contractrnk, contractchangenumber, modification, contractversion, ordertypename,
  350. ordertypecode, stagetitle, stageid, stagenumber, contractnoticenumber,
  351. datelastchange, customerid, customername, customerinn, customerkpp, suppliername, supplierinn, supplierkpp, suppliersmp, suppliersmpsmp, suppliersmpsonco, supplierinvalid, suppliercriminal, supplierstatus,
  352. supplierphone, supplierokopf, supplierokpo, supplierfio,
  353. supplieremail,
  354. supplieradress, supplieraddress_fact, suppliertype, grbsname, grbsid, grbscode, perc_size, perc_rub_size, modification_docnum, penaltiesamount, contractcreatedate, contractsigndate, contractnumber, contractsubject, contractfullprice, contract_price_signing,
  355. contractactualpaid, contractplaneexecdate, contractactualexecdate, contractrejectdate, first_notice_date, first_try_notice_date, last_notice_date, last_try_notice_date, contractrejectreason,
  356. contractrejectbase,
  357. contractoneexecreason, resultprotocol, paidfromregister, protocoldate, finsource, warranty_requirements, warranty_case, foreignpref, penalties,
  358. ispublic,
  359. import_uuid, detail_parent_id,
  360. cancel_document_params, is_concluded_in_e_shop, special_contract_type, contract_execution_start_date, price_type, document_date,
  361. contract_modification_reasons,
  362. modif_reason_documents,
  363. drugs_purchase,
  364. fulfilment_sum_rur,
  365. violation_deadlines, name,
  366. violation_reasons_not_21,
  367. amount_of_penalty,
  368. penalty_write_off_information,
  369. penalty_sum, fulfilment_sum,
  370. preference_smp_sonco,
  371. preference_invalid,
  372. preference_ugolov
  373. ,oktmo
  374. ,supply_impossible,
  375. rtc_price,
  376. acceptance_doc)
  377. Select
  378. cc.id As contractid,
  379. pr.id As requestid,
  380. l.id As lotid,
  381. Case
  382. When f_pvtp.name Is Not Null
  383. Then f_pvtp.name
  384. Else first_fin.year_
  385. End As requestyear,
  386. first_fin.year_ first_fin_year,
  387. first_fin_cont.year_plan first_fin_cont_year,
  388. first_fin_cont.year_fact first_fin_cont_year_fact,
  389. cc.contract_rnk As contractrnk,
  390. (((cc.contract_number) ::text || '/'::text) ||
  391. Case
  392. When(cc.version_number Is Null)
  393. Then 0
  394. Else cc.version_number
  395. End) As contractchangenumber,
  396. substr(Case
  397. When modification_type = 1
  398. Then 'Изменение контракта \ '
  399. When modification_type = 2
  400. Then 'Корректировка ошибок \ '
  401. End || case when l.id =3460911 then null else modification_description end, 0, 1000) ::text modification,
  402. cc.version_number contractversion,
  403. Case
  404. When vpt_nkp.naumen_name Is Null
  405. Then vpt_nkp.name
  406. Else vpt_nkp.naumen_name
  407. End ordertypename,
  408. Case
  409. When vpt_nkp.naumen_code Is Null
  410. Then vpt_nkp.id+100
  411. Else vpt_nkp.naumen_code End ordertypecode,
  412. --nks.kgntv_name As stagetitle,
  413. substr(vps_nks.full_name, 0, 128) stagetitle,
  414. vps_nks.id /*nks.kgntv_id*/ As stageid,
  415. vps_nks.naumen_id As stagenumber,
  416. Case
  417. When Length(Coalesce(pr.registry_number,Join_lots.registry_number)) <> 19
  418. Then Null
  419. Else (Coalesce(pr.registry_number,Join_lots.registry_number))
  420. End contractnoticenumber,
  421. cc.date_last_edit As datelastchange,
  422. Case When pp.delegated is true Then grbs.id ELse c.id End As customerid,
  423. Case When pp.delegated is true Then upper(grbs.full_name) Else upper(c.full_name) End As customername,
  424. Case When pp.delegated is true Then grbs.inn Else c.inn End As customerinn,
  425. Case When pp.delegated is true Then grbs.kpp Else c.kpp End As customerkpp,
  426. Case
  427. When s.full_name Is Not Null
  428. Then s.full_name
  429. Else cmscn.supplier_full_name
  430. End As suppliername,
  431. s.inn As supplierinn,
  432. s.kpp As supplierkpp,
  433. Case
  434. When s.small_biz = true Or s.is_social = true or ccss_pvss.status In ('30','31') Or ccss_pvss.status In ('40','41')
  435. Then 1
  436. Else 0
  437. End As suppliersmp,
  438. Case
  439. When s.small_biz = true Or ccss_pvss.status In ('30','31')
  440. Then 1
  441. Else 0
  442. End As suppliersmpsmp,
  443. Case
  444. When s.is_social = true Or ccss_pvss.status In ('40','41')
  445. Then 1
  446. Else 0
  447. End As suppliersmpsonco,
  448. Case
  449. When s.is_disabled_people = true Or ccss_pvss.status = '20'
  450. Then 1
  451. Else 0
  452. End As supplierinvalid,
  453. Case
  454. When s.is_penal_system = true Or ccss_pvss.status = '10'
  455. Then 1
  456. Else 0
  457. End suppliercriminal,
  458. Case
  459. When ccss_pvss.status = '10' Then 'Учреждение и предприятие уголовно-исполнительной системы'
  460. When ccss_pvss.status = '20' Then 'Организация инвалидов'
  461. When ccss_pvss.status = '30' Then 'Субъект малого предпринимательства'
  462. When ccss_pvss.status = '31' Then 'Поставщик (подрядчик, исполнитель), который в соответствии с контрактом обязан привлечь к исполнению контракта субподрядчиков,соисполнителей из числа субъектов малого предпринимательства'
  463. When ccss_pvss.status = '40' Then 'Социально-ориентированная некоммерческая организация'
  464. When ccss_pvss.status = '41' Then 'Поставщик (подрядчик, исполнитель), который в соответствии с контрактом обязан привлечь к исполнению контракта субподрядчиков,соисполнителей из числа социально ориентированных некоммерческих организаций' Else '0'
  465. End As supplierstatus, --статус поставщика
  466. s.phone As supplierphone,
  467. s.okopf As supplierokopf,-- окопф поставщика от 31.05.2021
  468. s.okpo As supplierokpo,-- окпо поставщика от 31.05.2021
  469. s.contact_fio supplierfio, -- фио поставщика
  470. s.email supplieremail, -- э-почта поставщика
  471. supplieradress.adress As supplieradress,
  472. substr(supplieradress.address_nahozh, 0, 2000) As supplieraddress_fact,-- адрес местонахождения (фактический) поставщика от 01.06.2021
  473. sp.name As suppliertype,
  474. upper(grbs.full_name) As grbsname,
  475. grbs.id As grbsid,
  476. "substring"((grbs.code) ::text, 1, 2) As grbscode,
  477. cc.perc_size,
  478. cc.perc_rub_size,
  479. substr(cc.modification_docnum, 0, 1000) modification_docnum,
  480. Case
  481. When ccpen.amount > 0
  482. Then(ccpen.amount::text || ' от ' || ccpen.doc_date || ' № ' || ccpen.doc_number)
  483. Else '0'
  484. End penaltiesamount,
  485. cc.date_add As contractcreatedate,
  486. cc.date_sign As contractsigndate,
  487. cc.contract_number As contractnumber,
  488. substr(l.subject, 0, 2500) As contractsubject,
  489. cc.contract_amount As contractfullprice,
  490. -- cc.contract_price_signing, -- поле цена контракта, заполняется при наличии РНК
  491. coalesce(cc.contract_price_signing, cc.contract_amount) as contract_price_signing, -- 25.03.2022 в случае отсутствия РНК (но контракт заключен в ЭМ), берем цену контракта из contract_amount
  492. ccf_p.amount As contractactualpaid,
  493. cc.date_execute As contractplaneexecdate,
  494. cc.date_close_fact As contractactualexecdate,
  495. cc.date_cancel As contractrejectdate,
  496. firstnotice.successdate first_notice_date,
  497. firstnotice.date_ first_try_notice_date,
  498. firstnotice.successdate_max last_notice_date,
  499. firstnotice.date_max last_try_notice_date,
  500. -- clctr.name As contractrejectreason,
  501. "substring"(cc.cancel_document_params, 1, 128) as contractrejectreason, -- 10.03.22 поле причина расторжения контракта
  502. clctr.name as contractrejectbase, -- 10.03.22 поле основание расторжения контракта
  503. -- "substring"(coalesce(cc.cancel_document_params ,clctr.name ), 1, 128) as contractrejectreason, -- 28.01.21 поле причина расторжения контракта в случае пустого значения заполняется основанием расторжения контракта
  504. substr(plcssr.name, 0, 1000) contractoneexecreason,
  505. substr(cc.contractdoc_name, 0, 2000) As resultprotocol,
  506. cc.exec_paid_from_product_list paidfromregister,
  507. cc.protocol_date protocoldate,
  508. fins.sources As finsource,
  509. Case
  510. When ccqgi.warranty_requirements_text Is Not Null
  511. Then 'да'
  512. Else 'нет'
  513. End warranty_requirements,--признак наличия гарантийных обязательств от 31.05.2021
  514. Case
  515. When ccqgi.warranty_requirements_text Is Not Null And ccqgi.published Is True
  516. Then 'да'
  517. Else 'нет'
  518. End warranty_case,--признак наступления гарантийного случая от 31.05.2021
  519. Case
  520. When ppr_inostr.preference_short_name ='RBK44'
  521. Then 1
  522. Else 0
  523. End foreignpref,
  524. Case
  525. When ccpen.cm_contract_id Is Not Null
  526. Then 1
  527. Else 0 End penalties,
  528. Case
  529. When length(cc.contract_rnk)=13
  530. Then 1
  531. Else 0 End ispublic,
  532. cc.import_uuid,
  533. pp.detail_parent_id, --id родительской процецедуры
  534. substr(cc.cancel_document_params, 0, 2000)cancel_document_params,--Реквизиты документа по расторжению контракта
  535. Case
  536. When cc.external_id Is Not Null Or Coalesce(is_concluded_in_e_shop,false)=true
  537. Then True
  538. Else Null
  539. End::char is_concluded_in_e_shop,--Признак заключения контракта в ЭМ
  540. --cc.is_concluded_in_e_shop::char is_concluded_in_e_shop--Признак заключения контракта в ЭМ
  541. --pl.purchase_code pg_ikz, -- ИКЗ Плана-графика
  542. --pl.purchase_code_in_plan pz_ikz, -- ИКЗ Плана закупок
  543. --l.plan_position_number pg_rn -- РН позиции Плана-графика
  544. cc.special_contract_type,
  545. pl.contract_execution_start_date,
  546. Case
  547. When cc.price_type ='P'
  548. Then 'Цена контракта'
  549. When cc.price_type ='OP'
  550. Then 'Ориентировочное значение цены контракта'
  551. When cc.price_type ='MP'
  552. Then 'Максимальное значение цены контракта' --Способ указания цены контракта
  553. End price_type,
  554. cc.document_date document_date, --Дата документа, являющегося основанием от 25.01.2021
  555. creason.name contract_modification_reasons, --Причина изменения условий контракта/договора от 25.01.2021
  556. cdocuments.name modif_reason_documents, --Наименование документа основания внесения изменений от 25.01.2021
  557. Case
  558. When pl.drugs_purchase Is True
  559. Then 1
  560. Else 0
  561. End drugs_purchase, --лекарственные препараты 31.05.2021
  562. ccf_p.fulfilment_sum_rur --Стоимость исполненных поставщиком обязательств, руб 31.05.2021
  563. ,cc.violation_deadlines--Причина принятия бюджетных обязательств в нарушение срока
  564. ,substr(dd.name, 0, 1000) as name --Причина принятия бюджетных обязательств в нарушение срока (описание)
  565. ,substr(cc.violation_deadlines_description, 0, 1000) as violation_reasons_not_21 --Причины, не установленные пунктом 21 постановления Правительства №42
  566. ,ccpen.amount_of_penalty --размер неустойки (штрафа, пени), по которой осуществлено списание штрафных санкций
  567. ,ccpen.penalty_write_off_information --Флаг актуальности по информации об осуществлении списания штрафных санкций
  568. ,ccpen.penalty_sum --сумма всех списанных штрафных санкций по контракту
  569. ,ccf_p.fulfilment_sum --Стоимость исполненных обязательств 29.08.2022
  570. ,Case
  571. When ppr_smp_sonco.preference_short_name in ('PVS33044','MP44')
  572. Then 1
  573. Else 0
  574. End As preference_smp_sonco -- признак наличия преимуществ для СМП и социально ориентированных некоммерческих организаций
  575. ,Case
  576. When ppr_inv.preference_short_name ='IN44'
  577. Then 1
  578. Else 0
  579. End As preference_invalid -- признак наличия преимуществ для организаций инвалидов
  580. ,Case
  581. When ppr_ug.preference_short_name ='UG44'
  582. Then 1
  583. Else 0
  584. End As preference_ugolov -- признак наличия преимуществ для учреждений уголовно-исполнительной системы
  585. ,s.oktmo -- октмо
  586. ,Case
  587. When pl.supply_impossible is true
  588. Then 1
  589. Else 0
  590. End As supply_impossible, -- Признак заключения контракта с неопределенным объемом товаров, работ, услуг
  591. cc.rtc_price, -- Цена за право заключения контракта
  592. ccf_p.acceptance_doc --флаг документа о приемке
  593. From gpospb.cm_contracts cc
  594. Inner Join gpospb.lots l On (l.id = cc.lot_id And l.actual = true And (cc.contract_rnk Is Not Null Or cc.external_id Is Not Null) and cc.id not in (150039,81681,70830,91739,104632,215242,216796,217707,217712,217795,219368,240051,624804))
  595. Inner Join gpospb.procedures pr On (l.procedure_id = pr.id And pr.actual = true)
  596. Inner Join gpospb.po_procedures pp On (pp.procedure_id = pr.id)
  597. Inner Join vps_nks On (vps_nks.ps_id = l.current_step)
  598. Inner Join lc On (lc.lot_id = l.id)
  599. Inner Join gpospb.contragents c On (c.id = cc.contract_customer)
  600. Inner Join gpospb.contragents s On (s.id = cc.supplier_id)
  601. Left join ccss_pvss on ccss_pvss.contract_id=cc.id
  602. Left Join gpospb.po_lots pl on pl.lot_id = l.id
  603. Left Join gpospb.po_vocab_time_periods f_pvtp On (f_pvtp.id = pp.finance_time_period_id)
  604. Left Join first_fin On (first_fin.lot_id = l.id)
  605. Left Join first_fin_cont On (first_fin_cont.lot_id = l.id)
  606. Left Join vpt_nkp On (vpt_nkp.id = pr.procedure_type)
  607. Left Join gpospb.cm_contract_supplier_names cmscn On (cc.id=cmscn.contract_id)
  608. Left Join supplieradress On (supplieradress.contragent_id = s.id)
  609. Left Join gpospb.po_list_org_hierarchy ploh On (ploh.contragent_id = cc.contract_customer and ploh.parent_type = 1 and ploh.actual = true)
  610. Left join grbs On (grbs.id = ploh.parent_contragent_id)
  611. Left Join fins On (fins.lot_id = l.id)
  612. Left Join ccf_p On (ccf_p.lot_id = l.id)
  613. Left Join ppr as ppr_smp_sonco On ppr_smp_sonco.lot_id = l.id and ppr_smp_sonco.preference_short_name in ('PVS33044','MP44') and ppr_smp_sonco.actual is true
  614. Left Join ppr as ppr_inv On ppr_inv.lot_id = l.id and ppr_inv.preference_short_name ='IN44' and ppr_inv.actual is true
  615. Left Join ppr as ppr_ug On ppr_ug.lot_id = l.id and ppr_ug.preference_short_name ='UG44' and ppr_ug.actual is true
  616. Left Join ppr as ppr_inostr On ppr_inostr.lot_id = l.id and ppr_inostr.preference_short_name ='RBK44' and ppr_inostr.actual is true
  617. Left Join firstnotice On (firstnotice.id = cc.id)
  618. Left Join gpospb.cm_list_contract_termination_reasons clctr On (clctr.id = cc.cancel_reason and clctr.actual = true)
  619. Left Join gpospb.po_list_contract_single_supplier_reasons plcssr On (pp.basis_for_single_supplier = plcssr.code)
  620. Left Join gpospb.supplier_profiles sp On (sp."id" = s.supplier_profile_id)
  621. Left Join Join_lots On Join_lots.lot_id = l.id
  622. Left Join ccpen On (ccpen.cm_contract_id = cc.id)
  623. Left Join gpospb.cm_list_contract_modification_reasons creason On (creason.code=cc.modification_base)
  624. Left Join gpospb.cm_list_contract_modif_reason_documents cdocuments On (cdocuments.code=cc.modification_base_doc)
  625. Left Join gpospb.cm_contract_quality_guarantee_info ccqgi on c.id=ccqgi.contract_id
  626. left Join gpospb.cm_vocab_conclusion_violation_of_deadlines dd on dd.id=cc.violation_deadlines and dd.actual is TRUE
  627. /*WHERE (Case
  628. When f_pvtp.name Is Not Null
  629. Then f_pvtp.name
  630. Else first_fin.year_
  631. END) in ('2017','2018','2019','2020','2021','2022','2023')*/
  632.  
  633.  
  634. -- Order By l.id a
  635. ;
  636.  
  637. --Удаляем промежуточные тб.
  638. Drop table first_fin;
  639. Drop table first_fin_cont;
  640. Drop table supplieradress;
  641. Drop table fins;
  642. Drop table ccf_p;
  643. Drop table firstnotice;
  644. Drop table Join_lots;
  645. Drop table ccpen;
  646. Drop table lc;
  647. Drop table ccss_pvss;
  648. Drop table grbs;
  649. Drop table vps_nks;
  650. Drop table vpt_nkp;
  651. Drop table ppr;
  652.  
  653. --Возвращаем данные
  654. return query select * From public.dwh_contract_kgntv_func;
  655. end;
  656. $BODY$
  657. LANGUAGE plpgsql VOLATILE
  658. COST 100
  659. ROWS 1e+06
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement