Advertisement
Guest User

Untitled

a guest
Oct 15th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 86.76 KB | None | 0 0
  1. package com.bssys.sbns.dbo.rur.collectionletter
  2.  
  3. import com.bssys.sbns.DboConsts
  4. import com.bssys.sbns.crypto.SignService
  5. import com.bssys.sbns.dbo.audit.AuditDocumentUtils
  6. import com.bssys.sbns.dbo.clientadmin.*
  7. import com.bssys.sbns.dbo.common.*
  8. import com.bssys.sbns.dbo.common.client.RAccountScroller
  9. import com.bssys.sbns.dbo.common.correspondent.CorrespondentScroller
  10. import com.bssys.sbns.dbo.common.officials.Officials
  11. import com.bssys.sbns.dbo.common.orgselect.OrgSelectUtils
  12. import com.bssys.sbns.dbo.common.predicates.CurrentUserOrgPredicate
  13. import com.bssys.sbns.dbo.common.predicates.upc.CurrentUserOrgUPCType
  14. import com.bssys.sbns.dbo.permission.DBOPermission
  15. import com.bssys.sbns.dbo.rur.payment.PaymentPurposeScroller
  16. import com.bssys.sbns.dbo.rur.payment.R030Utils
  17. import com.bssys.sbns.dbo.rur.payment.R030VatCalculationRule
  18. import com.bssys.sbns.dbo.security.DBOAccessService
  19. import com.bssys.sbns.dbo.services.DboConfigService
  20. import com.bssys.sbns.dbo.utils.AccountByDefaultUtils
  21. import com.bssys.sbns.dbo.utils.AccountUtils
  22. import com.bssys.sbns.dbo.utils.CounterUtils
  23. import com.bssys.sbns.dbo.utils.DocUtils
  24. import com.bssys.sbns.entity.BIC
  25. import com.bssys.sbns.entity.Correspondent
  26. import com.bssys.sbns.entity.PaymentKind
  27. import com.bssys.sbns.hibernate.HibernateTemplate
  28. import com.bssys.sbns.licence.LicenceService
  29. import com.bssys.sbns.metadata.Const
  30. import com.bssys.sbns.metadata.MetaDataService
  31. import com.bssys.sbns.metadata.common.ColumnType
  32. import com.bssys.sbns.metadata.form.FormBaseScript
  33. import com.bssys.sbns.security.SessionManager
  34. import com.bssys.sbns.security.access.UPCFormValueContext
  35. import com.bssys.sbns.services.CounterService
  36. import com.bssys.sbns.services.DigestService
  37. import com.bssys.sbns.services.WidgetCreator
  38. import com.bssys.sbns.state.FormFieldState
  39. import com.bssys.sbns.state.GridRowData
  40. import com.bssys.sbns.statemachine.StateMachineService
  41. import com.bssys.sbns.userexit.*
  42. import com.bssys.sbns.utils.*
  43. import com.bssys.sbns.validation.ValidationError
  44. import com.bssys.sbns.validation.ValidationResult
  45. import org.apache.commons.lang.StringUtils
  46. import org.hibernate.criterion.DetachedCriteria
  47. import org.hibernate.criterion.Restrictions
  48.  
  49. import java.util.regex.Pattern
  50.  
  51. import static com.bssys.sbns.dbo.clientadmin.OrgCopyService.Fields.*
  52. import static com.bssys.sbns.localization.I18n.i18n
  53. import static com.bssys.sbns.userexit.BeanContextDbo.lawChangeConfigService
  54. import static com.bssys.sbns.userexit.BeanContextDbo.orgCopyService
  55.  
  56. class R050EditForm extends FormBaseScript {
  57. public static BigDecimal DEFAULT_VAT = 18
  58. public static final BigDecimal VAT20 = 20
  59. public static BigDecimal MIN_SUM_WITH_ADDRESS = 15000
  60. public static String MIN_SUM_ACCOUNT = "30111"
  61. protected static String PARAM_COPY_ORG_NAME = "copyOrgName"
  62. protected static String PARAM_COPY_ORG_DEF_VAL = "copy"
  63.  
  64. public static INN_IGNORE_DRAWER_STATUSES = ["03", "05", "19", "20", "22", "26"]
  65.  
  66. public static List<String> getInnIgnoreDrawerStatus() {
  67. return ["03", "05", "19", "20", "22", "26"]
  68. }
  69.  
  70. static final String SAVE_ACCOUNT_AS_DEFAULT = "_saveAccountAsDefault"
  71.  
  72. @Override
  73. def config() {
  74. form title: "Инкассовое поручение",
  75. enhancedSecurity: true,
  76. permissionTitle: "Инкассовое поручение (клиент)",
  77. restId: 'client/rur/collectionLetters',
  78.  
  79. helpTopic: "appCorreqts.winCollectionLetter.html",
  80. width: 75,
  81. documentTypeDesc: R050Desc.name,
  82.  
  83. toolbar: {
  84. toolbarButton DboConsts.SYS_ACTION_SAVE, DboConsts.SYS_ACTION_SAVE_NO_CLOSE, DboConsts.SYS_ACTION_SAVE_CREATE
  85. toolbarButton DboConsts.SYS_ACTION_CHECK
  86. DocUtils.defineSaveAndSignButton(this, R050Desc, R050NotificationDigest)
  87. DocUtils.definePrintButtonEditForm(this, R050Report)
  88. toolbarButton DboConsts.SYS_ACTION_HELP, DboConsts.SYS_ACTION_CLOSE
  89.  
  90. },
  91. extraFields: ["orgName", "orgId", "orgType", "accountId", "receiverBankName", "taxPeriodDay",
  92. "payerBankName", "payerBankCity", "payerBankSettlementType", "receiverBankCity", "receiverBankSettlementType",
  93. "branch"],
  94. fields: {
  95. tab id: "mainTab",
  96. label: "Основные поля",
  97. fields: {
  98. standardLayout id: "mainLayout", fields: {
  99. textField id: "docNumber",
  100. label: "Номер",
  101. width: 8,
  102. disabled: false,
  103. maxLength: 7,
  104. tooltip: "Номер инкассового поручения"
  105. dateField id: "docDate",
  106. disabled: false,
  107. label: "Дата",
  108. attachFlag: true,
  109. tooltip: "Дата составления инкассового поручения"
  110. label id: "blankLabel",
  111. label: ""
  112. selectField id: "paymentKind",
  113. label: " Вид платежа",
  114. refScroller: PaymentKindScroller,
  115. refField: "kind",
  116. width: 8,
  117. tooltip: "Способ отправки документа",
  118. defValue: "электронно",
  119. onChange: { FormFieldSubmitContext ctx ->
  120. if (ctx.isFormChanged()) {
  121. updatePaymentCode(ctx)
  122. }
  123. }
  124. deck id: "paymentCodeDeck",
  125. fields: {
  126. deckPane id: "isPaymentCode",
  127. fields: {
  128. textField id: "paymentCode",
  129. width: 2,
  130. disabled: true,
  131. tooltip: "Код вида платежа"
  132. }
  133. }
  134. selectField id: "drawerStatus",
  135. label: "Пок. статуса",
  136. tooltip: "Показатель статуса (101)",
  137. refScroller: PaymentTaxStatusCScroller,
  138. refField: "code",
  139. width: 17,
  140. onChange: { FormFieldSubmitContext ctx, BankUtils bankUtils ->
  141. onRequireTaxFieldsEnablingDisabling(ctx)
  142. if (ctx.isFormChanged()) {
  143. onSetEnabledINN(ctx);
  144. onRequireTaxFieldsChange(ctx.fields, true)
  145. receiverDataOnDrawerStatusChange(ctx, bankUtils)
  146. onRequirePayerNameEnable(ctx, bankUtils)
  147. }
  148. }
  149. }
  150. tableLayout resizableColumns: [1],
  151. fields: {
  152. label ""
  153. label label: "",
  154. newCell: true
  155. label label: "Сумма"
  156. moneyField id: "documentSum",
  157. width: 17,
  158. newCell: true,
  159. tooltip: "Сумма платежа",
  160. maxLength: 18,
  161. scale: 2,
  162. onChange: { FormFieldSubmitContext ctx, BankUtils bankUtils ->
  163. if (ctx.isFormChanged()) {
  164. onRequireVatRecount(ctx)
  165. }
  166. }
  167. label label: "",
  168. newCell: true,
  169. newLine: true
  170. label label: "",
  171. newCell: true
  172. label "НДС"
  173. moneyField id: "vatSum",
  174. disabled: true,
  175. width: 17,
  176. newCell: true,
  177. maxLength: 18,
  178. scale: 2,
  179. tooltip: "Величина НДС",
  180. onChange: { FormFieldSubmitContext ctx, BankUtils bankUtils ->
  181. if (ctx.isFormChanged()) {
  182. onRequireVatRecount(ctx)
  183. }
  184. }
  185.  
  186. label label: "",
  187. newCell: true,
  188. newLine: true
  189. label label: "",
  190. newCell: true
  191. numericField id: "vatRate",
  192. secondaryLabel: "%",
  193. width: 4,
  194. maxLength: 6,
  195. newCell: true,
  196. scale: 2,
  197. tooltip: "Ставка НДС в процентах",
  198. onChange: { FormFieldSubmitContext ctx, BankUtils bankUtils ->
  199. if (ctx.isFormChanged()) {
  200. onRequireVatRecount(ctx)
  201. }
  202. }
  203. selectField id: "vatCalculationRule",
  204. items: {
  205. // Отфильтровываем синтетическое значение, нужное только для рассчетов
  206. R030VatCalculationRule.values().findAll({ rule ->
  207. !rule.equals(R030VatCalculationRule.VatAddNoChange)
  208. }).each { rule ->
  209. item id: rule.name(), label: rule.name
  210. }
  211. },
  212. width: 11,
  213. tooltip: "Способ расчета НДС",
  214. onChange: { FormFieldSubmitContext ctx, BankUtils bankUtils ->
  215. if (ctx.isFormChanged()) {
  216. onRequireVatRecount(ctx)
  217. }
  218. }
  219. }
  220. separator "Плательщик"
  221.  
  222. tableLayout id: "payerTable", resizableColumns: [1],
  223. fields: {
  224. textField id: "payerINN",
  225. label: "ИНН/КИО",
  226. tooltip: "ИНН или КИО плательщика",
  227. refField: "inn",
  228. refScroller: CorrespondentScroller,
  229. refSearch: true,
  230. attachFlag: true,
  231. onRefSelect: { FormRefSelectContext ctx, BankUtils bankUtils ->
  232. onCorrespondentSelect(ctx.currentRow, ctx.fields, ctx.hibernateTemplate, bankUtils)
  233. fillPayerReq(ctx.fields, ctx.entity, bankUtils)
  234. onRequirePayerNameEnable(ctx, bankUtils)
  235. },
  236. maxLength: 12,
  237. width: 12,
  238. allowedChars: Const.ONLY_DIGITS
  239. newLine: true
  240.  
  241. miniButton icon: "ref_add.png",
  242. tooltip: "Добавить в справочник корреспондентов",
  243. attachFlag: true,
  244. onChange: addNewOfficials
  245. textField id: "payerKPP",
  246. label: "КПП",
  247. tooltip: "КПП плательщика (102) или '0'",
  248. maxLength: 9,
  249. width: 9
  250.  
  251. textField id: "payerName",
  252. tooltip: "Наименование плательщика. В начале обязательно должно содержать наименование по умолчанию. После него может содержать информацию об адресе плательщика.",
  253. width: 40,
  254. height: 4,
  255. rowSpan: 2,
  256. newLine: true,
  257. maxLength: 160
  258. label id: "afterPayerName", label: "",
  259. newLine: true
  260. label "Сч. №"
  261. textField id: "payerAccount",
  262. refField: "account",
  263. tooltip: "Счет плательщика",
  264. refScroller: CorrespondentScroller,
  265. refSearch: true,
  266. width: 17,
  267. overwriteInput: true,
  268. mask: "#####.###.#.###########",
  269. newCell: true,
  270. onRefInit: { FormRefInitContext<R050> ctx ->
  271. ctx.softFilter = ["org.id=:orgId", [orgId: ctx.entity.orgId]]
  272. },
  273. onRefSelect: { FormRefSelectContext ctx, BankUtils bankUtils ->
  274. onCorrespondentSelect(ctx.currentRow, ctx.fields, ctx.hibernateTemplate, bankUtils)
  275. fillPayerReq(ctx.fields, ctx.entity, bankUtils)
  276. onRequirePayerNameEnable(ctx, bankUtils)
  277. }
  278.  
  279. label label: "Банк плательщика",
  280. newLine: true
  281. textField id: "payerBankName",
  282. tooltip: "Наименование и местонахождение Банка плательщика",
  283. disabled: true,
  284. width: 40,
  285. height: 4,
  286. rowSpan: 2,
  287. field: null,
  288. newLine: true
  289. label label: "",
  290. newCell: true
  291. label label: "БИК"
  292. textField id: "payerBankBic",
  293. tooltip: "БИК Банка плательщика",
  294. refField: "bic",
  295. refScroller: BICScroller,
  296. refSearch: true,
  297. disabled: false,
  298. width: 10,
  299. newCell: true,
  300. attachFlag: true,
  301. onRefSelect: { FormRefSelectContext ctx, BankUtils bankUtils ->
  302. if (ctx.currentRow) {
  303. BIC bic = ctx.hibernateTemplate.get(BIC, ctx.currentRow)
  304. fillPayerReq(ctx.fields, ctx.entity, bankUtils)
  305. ctx.fields.payerBankCorrAccount.value = bic.corrAccount
  306. }
  307. }
  308. label label: "",
  309. newCell: true,
  310. newLine: true
  311. label label: "Сч. №"
  312. textField id: "payerBankCorrAccount",
  313. tooltip: "Корсчет Банка плательщика",
  314. disabled: true,
  315. width: 17,
  316. overwriteInput: true,
  317. mask: "#####.###.#.###########",
  318. newCell: true
  319. }
  320.  
  321. separator "Получатель"
  322.  
  323. tableLayout resizableColumns: [1],
  324. fields: {
  325. label label: "",
  326. newLine: true
  327. textField id: "receiverINN",
  328. label: "ИНН/КИО",
  329. tooltip: "ИНН/КИО получателя",
  330. disabled: true,
  331. attachFlag: true,
  332. maxLength: 12,
  333. width: 12
  334. selectField id: "receiverKPP",
  335. label: "КПП",
  336. tooltip: "КПП получателя (102) или '0'",
  337. maxLength: 9,
  338. strict: false,
  339. width: 9,
  340. items: {},
  341. onChange: { FormFieldSubmitContext ctx ->
  342. if (ctx.isFormChanged()) {
  343. //При изменении КПП добавляем поле не из списка в список
  344. //Иначе при сабмите формы оно пропадает
  345. Org org = ctx.hibernateTemplate.get(Org, ctx.entity.orgId)
  346. fillReceiverKppList(ctx.fields, org)
  347. }
  348. }
  349.  
  350. label label: "", newCell: true
  351. label "УИП "
  352. textField id: "code",
  353. tooltip: "УИП",
  354. maxLength: 25,
  355. width: 17,
  356. newCell: true
  357.  
  358. textField id: "receiverName",
  359. tooltip: "Наименование получателя",
  360. width: 40,
  361. height: 4,
  362. rowSpan: 2,
  363. maxLength: 160,
  364. newLine: true
  365. label label: "",
  366. newCell: true
  367. label "Сч. №"
  368. textField id: "receiverAccount",
  369. refField: "account",
  370. tooltip: "Счет получателя",
  371. refScroller: RAccountScroller,
  372. refSearch: true,
  373. onRefInit: { FormRefInitContext<R050> ctx ->
  374. ctx.softFilter << ["org.id=:orgId and accountState=:accountState",
  375. [orgId: ctx.entity.orgId, accountState: "OPEN"]]
  376. ctx.softFilter << ["accountType.shortName like 'р/с'"]
  377. // Передадим имя услуги, чтобы можно было выбрать только счета,
  378. // по которым предоставляется данная услуга.
  379. ctx.refParams.serviceName = R050Desc.name
  380. },
  381. width: 17,
  382. overwriteInput: true,
  383. mask: "#####.###.#.###########",
  384. newCell: true,
  385. onRefSelect: { FormRefSelectContext<R050> ctx, BankUtils bankUtils ->
  386. if (ctx.currentRow) {
  387. ctx.formChangedByField = false
  388. Account account = ctx.hibernateTemplate.get(Account, ctx.currentRow)
  389. if (account) {
  390. ctx.entity.accountId = account.id
  391. }
  392. onRequirePayerBankChange(ctx.fields as Map, ctx.entity, bankUtils,
  393. ctx.hibernateTemplate, ctx.currentRow, ctx as Map)
  394. }
  395.  
  396. },
  397. onChange: { FormFieldSubmitContext<R050> ctx, BankUtils bankUtils ->
  398. if (ctx.formChangedByField) {
  399. onRequirePayerBankChange(ctx.fields as Map, ctx.entity, bankUtils,
  400. ctx.hibernateTemplate, null, ctx as Map)
  401. }
  402. }
  403. miniButton id: SAVE_ACCOUNT_AS_DEFAULT,
  404. icon: 'gear_add.png',
  405. tooltip: 'Сохранить как счет по умолчанию',
  406. attachFlag: true,
  407. onChange: { FormFieldSubmitContext<R050> ctx,
  408. MetaDataService metaDataService ->
  409. if (ctx.isFormChanged()) {
  410. if (ctx.entity.orgId) {
  411. def docDesc = metaDataService.findDesc(DocumentTypeDesc, R050Desc.name)
  412.  
  413. String accId = StringUtils.isBlank(ctx.fields.payerAccount.value) ? null : ctx.entity.accountId
  414.  
  415. ctx.execute AccountByDefaultUtils.updateDefaultAccount.curry(
  416. ctx.entity.orgId,
  417. R050Desc.name,
  418. accId
  419. )
  420. def msg = accId == null ? i18n('Счет по умолчанию для документа "#1#" сброшен', docDesc.getName()) :
  421. i18n('Счет "#1#" сохранен в качестве счета по умолчанию для документа "#2#"',
  422. (ctx.hibernateTemplate.get(Account, accId) as Account).account,
  423. docDesc.getName()
  424. )
  425.  
  426. ctx.widgetCreator.showInformMessage(
  427. msg,
  428. i18n('Счет по умолчанию')
  429. )
  430. }
  431. }
  432. }
  433. label label: "",
  434. newLine: true
  435. label "Вид оп."
  436. textField id: "operationType",
  437. tooltip: "Вид операции",
  438. width: 3,
  439. newCell: true,
  440. disabled: true
  441. textField id: "paymentPriority",
  442. label: "Очер. пл.",
  443. tooltip: "Очередность платежа",
  444. disabled: false,
  445. refScroller: PaymentPriorityCScroller,
  446. refField: "code",
  447. width: 5,
  448. maxLength: 2
  449. label label: "Банк получателя",
  450. id: "recBankLabel",
  451. newLine: true
  452. textField id: "receiverBankName",
  453. tooltip: "Наименование и местонахождение Банка получателя",
  454. disabled: true,
  455. width: 40,
  456. newLine: true,
  457. height: 4,
  458. rowSpan: 2,
  459. field: null
  460. label label: "",
  461. newCell: true
  462. label "БИК"
  463. textField id: "receiverBankBic",
  464. tooltip: "БИК Банка получателя",
  465. disabled: true,
  466. maxLength: 9,
  467. width: 12,
  468. newCell: true
  469. label label: "",
  470. newCell: true,
  471. newLine: true
  472. label "Сч. №"
  473. textField id: "receiverBankCorrAccount",
  474. tooltip: "Корсчет Банка получателя",
  475. disabled: true,
  476. width: 17,
  477. overwriteInput: true,
  478. mask: "#####.###.#.###########",
  479. newCell: true
  480. }
  481.  
  482. separator "Назначение платежа"
  483.  
  484. standardLayout fields: {
  485. textField id: "paymentPurpose",
  486. tooltip: "Назначение платежа",
  487. maxLength: 210,
  488. height: 4,
  489. refScroller: PaymentPurposeScroller,
  490. refField: "purpose",
  491. onRefInit: { FormRefInitContext<R050> ctx ->
  492. ctx.softFilter = ["org.id=:orgId", [orgId: ctx.entity.orgId]]
  493. }
  494. }
  495.  
  496. separator id: "budgetpayment",
  497. label: "Бюджетный платеж"
  498.  
  499. tableLayout fields: {
  500. label label: "КБК",
  501. refLinkFor: "cbc"
  502. label label: "ОКТМО",
  503. newCell: true
  504. label label: "Осн. плт.",
  505. newCell: true
  506. selectField id: "taxOrCustoms",
  507. items: {
  508. item id: "Налог. период"
  509. item id: "Код тамож. органа"
  510. },
  511. tooltip: "Основание платежа",
  512. width: 12,
  513. newCell: true,
  514. onChange: { FormFieldSubmitContext ctx ->
  515. if (ctx.isFormChanged()) {
  516. ctx.fields.taxPeriodDeck.value = isTaxPeriod(ctx) ? "taxPeriodPanel1" : "taxPeriodPanel2"
  517. }
  518. }
  519. label label: "Ном. док.",
  520. newCell: true
  521. label label: "Дата док.",
  522. newCell: true
  523. label label: "Тип плт.",
  524. newCell: true
  525. textField id: "cbc",
  526. refField: "code",
  527. tooltip: "Код бюджетной классификации (1012212112) или '0'",
  528. refScroller: CBCScroller,
  529. width: 14,
  530. maxLength: 20,
  531. allowedChars: Const.ONLY_DIGITS,
  532. newLine: true
  533. textField id: "ocato",
  534. tooltip: "Указание кода ОКТМО обязательно при платежах на счета 40101. Для таможенных платежей допустимо указание значения \"0\"",
  535. width: 7,
  536. newCell: true,
  537. maxLength: 11
  538. selectField id: "payReason",
  539. tooltip: "Показатель основания платежа (106) или '0'",
  540. refScroller: PaymentReasonCScroller,
  541. refField: "code",
  542. width: 4,
  543. newCell: true
  544. deck id: "taxPeriodDeck",
  545. newCell: true,
  546. fields: {
  547. deckPane id: "taxPeriodPanel1",
  548. fields: {
  549. selectField id: "taxPeriodDay1",
  550. field: null,
  551. tooltip: "Показатель налогового периода (107): код или число даты или '0'",
  552. refScroller: TaxPeriodCScroller,
  553. refField: "code",
  554. width: 4,
  555. strict: false,
  556. maxLength: 2
  557. textField id: "taxPeriodMonth",
  558. tooltip: "Показатель налогового периода (107): код или месяц даты",
  559. width: 3,
  560. maxLength: 2
  561. textField id: "taxPeriodYear",
  562. tooltip: "Показатель налогового периода (107): год даты",
  563. width: 4,
  564. maxLength: 4,
  565. attachFlag: true
  566. }
  567. deckPane id: "taxPeriodPanel2",
  568. fields: {
  569. textField id: "taxPeriodDay2",
  570. tooltip: "Код таможенного органа",
  571. field: null,
  572. width: 10,
  573. maxLength: 8
  574. }
  575. }
  576. textField id: "taxDocNumber",
  577. tooltip: "Показатель номера документа (108) или '0'",
  578. width: 8,
  579. newCell: true,
  580. maxLength: 15
  581. textField id: "docDateDay",
  582. tooltip: "Показатель даты документа (109): число даты или '0'",
  583. width: 3,
  584. newCell: true,
  585. maxLength: 2
  586. textField id: "docDateMonth",
  587. tooltip: "Показатель даты документа (109): месяц даты",
  588. width: 3,
  589. attachFlag: true,
  590. maxLength: 2
  591. textField id: "docDateYear",
  592. tooltip: "Показатель даты документа (109): год даты",
  593. width: 4,
  594. attachFlag: true,
  595. maxLength: 4
  596. label ""
  597. selectField id: "chargeType",
  598. tooltip: "Показатель типа платежа (110) или '0'",
  599. refScroller: PaymentTypeCScroller,
  600. refField: "code",
  601. width: 10,
  602. newCell: true
  603. }
  604. }
  605. tab id: "infoTab",
  606. label: "Информация из банка",
  607. fields: {
  608. standardLayout fields: {
  609. dateField id: "bankAcceptDate",
  610. label: "Дата принятия/отказа",
  611. tooltip: "Дата принятия/отказа",
  612. disabled: true,
  613. newLine: true
  614.  
  615. dateField id: "operationDate",
  616. label: "Списано со счета плательщика",
  617. tooltip: "Дата списания со счета плательщика",
  618. disabled: true
  619.  
  620. dateField id: "deliveredTime",
  621. label: "Поступило в Банк плательщика",
  622. tooltip: "Дата поступления в банк плательщика",
  623. disabled: true,
  624. newLine: true
  625.  
  626. dateField id: "queueDate",
  627. label: "Дата помещения в картотеку",
  628. tooltip: "Дата помещения в картотеку",
  629. disabled: true
  630.  
  631. textField id: "bankMessageAuthor",
  632. label: "Исполнитель",
  633. tooltip: "Исполнитель",
  634. newLine: true,
  635. disabled: true
  636. }
  637. separator "Частичные платежи"
  638. label id: "partPaymentsBlankLabel",
  639. label: "",
  640. newLine: true
  641.  
  642. grid id: "partPayments",
  643. columns: {
  644. column id: "strNum",
  645. label: "№ част. платежа",
  646. type: ColumnType.NUMERIC,
  647. width: 10
  648. column id: "orderNumber",
  649. label: "Номер платежного ордера",
  650. type: ColumnType.NUMERIC,
  651. width: 15
  652. column id: "orderDate",
  653. label: "Дата платежного ордера",
  654. type: ColumnType.DATE,
  655. width: 15
  656. column id: "partPaymentSum",
  657. label: "Сумма частичного платежа",
  658. type: ColumnType.MONEY,
  659. width: 15
  660. column id: "paymentBalance",
  661. label: "Сумма остатка платежа",
  662. type: ColumnType.MONEY,
  663. width: 15
  664. }
  665. label id: "bankMessageBlankLabel",
  666. label: "",
  667. newLine: true
  668. textField id: "bankMessage",
  669. vertical: true,
  670. label: "Сообщение из банка",
  671. tooltip: "Отметки Банка плательщика",
  672. disabled: true,
  673. height: 10,
  674. newLine: true
  675. }
  676. },
  677. init: { FormInitContext<R050> ctx, DboConfigService configService ->
  678. ctx.entity.printed = false
  679. if (!DocUtils.isSavedForm(ctx)) {
  680. ctx.buttons[DboConsts.SYS_ACTION_PRINT].visible = false
  681. }
  682. ctx.fields.paymentCodeDeck.value = "isPaymentCode";
  683. updatePaymentCode(ctx);
  684.  
  685. def defaultAccountEnabled = configService.getEffectiveConfiguration(R050Service.R050_DEFAULT_ACCOUNT_ENABLED)
  686. ctx.fields[SAVE_ACCOUNT_AS_DEFAULT].disabled =
  687. ctx.operation == WidgetCreator.FormOperation.SHOW ||
  688. !defaultAccountEnabled || ctx.fields.payerAccount.disabled
  689.  
  690. ctx.execute DocUtils.disableSaveAndSignButton.curry(R050Desc)
  691. appendStateToTitle(ctx)
  692. },
  693. createAfter: { FormAfterContext ctx, BankUtils bankUtils, SignService signService, DBOAccessService accessService,
  694. LicenceService licenceService ->
  695. if (licenceService.checkLicenceFeature(R050LicenceFeature.COLLECTION_LETTER_COUNT)) {
  696. ctx.addCriticalError i18n("Произошла ошибка лицензирования, невозможно сохранить документ. Код причины: 0891. Обратитесь к администратору")
  697. }
  698. R050 doc = (R050) ctx.entity;
  699. List<Account> accounts = accessService.getAvailableAccounts()
  700. for (Account account : accounts) {
  701. if ((account.account == doc.payerAccount) && (account.bankBic == doc.payerBankBic)) {
  702. doc.accountId = account.id
  703. break;
  704. }
  705. }
  706.  
  707. doc.signCollection = signService.createSignCollection(R050SignDigest.name)
  708.  
  709. ctx.execute CounterUtils.updateYearCurrent.curry(DboConsts.R050_COUNTER_NAME, doc.orgId, doc.docNumber)
  710. },
  711. createBefore: { FormInitContext ctx, BankUtils bankUtils, DBOAccessService accessService ->
  712. Org org = ctx.execute(OrgSelectUtils.callOrgTypedServicedSelectForm.curry(OrganisationType.JURIDICAL, R050Desc.name)) as Org
  713. R050 doc = (R050) ctx.entity;
  714. doc.orgId = org.id
  715. doc.orgType = org.organisationType
  716. doc.orgName = org.name
  717. ctx.fields.docNumber.value = ctx.execute CounterUtils.generateYearNext.curry(DboConsts.R050_COUNTER_NAME, org.id)
  718.  
  719. Branch branch = bankUtils.getBranchByOrgServices(org, null)
  720. ctx.fields.docDate.value = bankUtils.getBranchCurrentDate(branch)
  721. doc.branch = branch
  722.  
  723. if (ctx.fields.paymentKind.items.rowId.contains("электронно")) {
  724. ctx.fields.paymentKind.value = "электронно"
  725. updatePaymentCode(ctx)
  726. }
  727.  
  728. ctx.fields.receiverName.value = org.name
  729. ctx.fields.receiverINN.value = org.inn
  730. ctx.fields.receiverKPP.value = org.defaultKpp?.kpp
  731. ctx.fields.vatRate.value = lawChangeConfigService.isVAT2019(R030Utils.getTimeZoneByOrg(ctx.entity.orgId, ctx.hibernateTemplate)) ?
  732. VAT20 : DEFAULT_VAT
  733. ctx.fields.vatCalculationRule.value = R030VatCalculationRule.Vat1.name()
  734. ctx.fields.operationType.value = "06"
  735.  
  736. initReceiverAccount(accessService, doc, ctx, bankUtils)
  737. onRequireTaxFieldsEnablingDisabling(ctx)
  738. onRequireTaxFieldsChange(ctx.fields)
  739. fillReceiverKppList(ctx.fields, org)
  740.  
  741. onRequireVatEnable(ctx)
  742. },
  743. editBefore: { FormInitContext<R050> ctx, BankUtils bankUtils ->
  744. if (isTaxPeriod(ctx)) {
  745. ctx.fields.taxPeriodDay1.value = ctx.entity.taxPeriodDay
  746. ctx.fields.taxPeriodDeck.value = "taxPeriodPanel1"
  747. } else {
  748. ctx.fields.taxPeriodDay2.value = ctx.entity.taxPeriodDay
  749. ctx.fields.taxPeriodDeck.value = "taxPeriodPanel2"
  750. }
  751. Org org = ctx.hibernateTemplate.get(Org, ctx.entity.orgId)
  752. if (ctx.operation != WidgetCreator.FormOperation.SHOW && !isBudgetInn(ctx) && (org != null && !org.federalTreasuryBody) && !(ctx.fields.drawerStatus.value in getInnIgnoreDrawerStatus())) {
  753. ctx.fields.receiverINN.value = org?.inn
  754. }
  755. String payerBankBic = ctx.fields.payerBankBic.value
  756. if (payerBankBic) {
  757. def payerBankInfo = bankUtils.getBankInfo(payerBankBic)
  758. if (payerBankInfo) {
  759. ctx.fields.payerBankName.value = bankUtils.getBankFullName(
  760. ctx.entity.payerBankName ?: payerBankInfo.get(BankUtils.BANK_NAME),
  761. ctx.entity.payerBankSettlementType ?: payerBankInfo.get(BankUtils.BANK_TNP),
  762. ctx.entity.payerBankCity ?: payerBankInfo.get(BankUtils.BANK_CITYORIG),
  763. )
  764. }
  765. }
  766. fillReceiverKppList(ctx.fields, org)
  767. String receiverBankBic = ctx.fields.receiverBankBic.value
  768. if (receiverBankBic) {
  769. def receiverBankInfo = bankUtils.getBankInfo(receiverBankBic)
  770. if (receiverBankInfo) {
  771. ctx.fields.receiverBankCorrAccount.value = receiverBankInfo.get(BankUtils.BANK_CORRACCOUNT)
  772. ctx.fields.receiverBankName.value = receiverBankInfo.get(BankUtils.BANK_FULLNAME)
  773. ctx.fields.receiverBankName.value = bankUtils.getBankFullName(
  774. ctx.entity.receiverBankName ?: receiverBankInfo.get(BankUtils.BANK_NAME),
  775. ctx.entity.receiverBankSettlementType ?: receiverBankInfo.get(BankUtils.BANK_TNP),
  776. ctx.entity.receiverBankCity ?: receiverBankInfo.get(BankUtils.BANK_CITYORIG),
  777. )
  778. } else {
  779. ctx.fields.receiverBankCorrAccount.value = null
  780. ctx.fields.receiverBankName.value = null
  781. }
  782. }
  783. onSetEnabledINN(ctx)
  784. onRequirePayerNameEnable(ctx, bankUtils)
  785. if (ctx.operation != WidgetCreator.FormOperation.SHOW) {
  786. def defaultVatRate = lawChangeConfigService.isVAT2019(R030Utils.getTimeZoneByOrg(ctx.entity.orgId, ctx.hibernateTemplate)) ?
  787. VAT20 : DEFAULT_VAT
  788. if (ctx.fields.vatRate.value != defaultVatRate) {
  789. onRequireVatRecount(ctx, defaultVatRate, false)
  790. } else {
  791. onRequireVatEnable(ctx)
  792. }
  793. }
  794. },
  795. copyBefore: { FormInitContext<R050> ctx, BankUtils bankUtils, DboConfigService configService ->
  796. orgCopyService.copyValues(ctx.entity, ctx.fields, this.mapping)
  797.  
  798. Org org = ctx.hibernateTemplate.get(Org, ctx.entity.orgId)
  799.  
  800. fillReceiverKppList(ctx.fields, org)
  801. if (!org.orgKpp.find { OrgKpp kpp -> kpp.kpp == ctx.entity.receiverKPP }) {
  802. ctx.fields.receiverKPP.value = null
  803. }
  804. ctx.entity.orgName = org.name
  805. def branch = bankUtils.getBranchByOrgServices(org, null)
  806. ctx.fields.docDate.value = bankUtils.getBranchCurrentDate(branch)
  807. ctx.fields.docNumber.value = ctx.execute CounterUtils.generateYearNext.curry(DboConsts.R050_COUNTER_NAME, org.id)
  808. ctx.fields.paymentCodeDeck.value = "isPaymentCode"
  809. updatePaymentCode(ctx)
  810.  
  811. if (org) {
  812. ctx.fields.receiverName.value = org.name
  813. ctx.fields.receiverINN.value = org.inn
  814. }
  815.  
  816. if (isTaxPeriod(ctx)) {
  817. ctx.fields.taxPeriodDay1.value = ctx.entity.taxPeriodDay
  818. ctx.fields.taxPeriodDeck.value = "taxPeriodPanel1"
  819. } else {
  820. ctx.fields.taxPeriodDay2.value = ctx.entity.taxPeriodDay
  821. ctx.fields.taxPeriodDeck.value = "taxPeriodPanel2"
  822. }
  823.  
  824. // найдем по БИК текущее наименования банка
  825. String payerBankBic = ctx.fields.payerBankBic.value
  826. if (payerBankBic) {
  827. def payerBankInfo = bankUtils.getBankInfo(payerBankBic)
  828. if (payerBankInfo) {
  829. ctx.fields.payerBankName.value = bankUtils.getBankFullName(
  830. ctx.entity.payerBankName ?: payerBankInfo.get(BankUtils.BANK_NAME),
  831. ctx.entity.payerBankSettlementType ?: payerBankInfo.get(BankUtils.BANK_TNP),
  832. ctx.entity.payerBankCity ?: payerBankInfo.get(BankUtils.BANK_CITYORIG),
  833. )
  834. } else {
  835. ctx.fields.payerBankName.value = ctx.entity.payerBankName
  836. }
  837. }
  838.  
  839. // Заполним руками, т.к. там стоит "field: null"
  840. ctx.fields.receiverBankName.value = ctx.entity.receiverBankName
  841.  
  842. //МПК. Работает только для сценария замена БИКа (без создания нового подразделения) и
  843. // без создания новых счетов (ключевание не меняется)
  844. DocUtils.changeBranchToCurrentAccountBranch(ctx, 'payerAccount', [
  845. ["dst": "payerBankBic", "src": "branch", "fields": "bic"],
  846. ["dst": "payerBankName", "src": "bic", "fields": BankUtils.BANK_FULLNAME],
  847. ["dst": "payerBankCorrAccount", "src": "bic", "fields": BankUtils.BANK_CORRACCOUNT],
  848. ["dst": "payerBankCity", "src": "bic", "fields": BankUtils.BANK_CITYORIG],
  849. ["dst": "payerBankSettlementType", "src": "bic", "fields": BankUtils.BANK_TNP]
  850. ], null, org, false, bankUtils)
  851. DocUtils.changeBranchToCurrentAccountBranch(ctx, 'receiverAccount', [
  852. ["dst": "receiverBankBic", "src": "branch", "fields": "bic"],
  853. ["dst": "receiverBankName", "src": "bic", "fields": BankUtils.BANK_FULLNAME],
  854. ["dst": "receiverBankCorrAccount", "src": "bic", "fields": BankUtils.BANK_CORRACCOUNT],
  855. ["dst": "receiverBankCity", "src": "bic", "fields": BankUtils.BANK_CITYORIG],
  856. ["dst": "receiverBankSettlementType", "src": "bic", "fields": BankUtils.BANK_TNP]
  857. ], null, org, true, bankUtils)
  858.  
  859. ctx.fields.bankAcceptDate.value = null
  860. ctx.fields.operationDate.value = null
  861. ctx.fields.bankMessage.value = null
  862. ctx.fields.bankMessageAuthor.value = null
  863. ctx.fields.deliveredTime.value = null
  864. R050 doc = (R050) ctx.entity
  865. doc.partPayments.clear()
  866.  
  867. onRequirePayerBankChange(ctx.fields, ctx.entity, bankUtils, ctx.hibernateTemplate, null, ctx.params, false)
  868. onSetEnabledINN(ctx)
  869. onRequirePayerNameEnable(ctx, bankUtils)
  870.  
  871. def defaultVatRate = lawChangeConfigService.isVAT2019(R030Utils.getTimeZoneByOrg(ctx.entity.orgId, ctx.hibernateTemplate)) ?
  872. VAT20 : DEFAULT_VAT
  873. if (ctx.fields.vatRate.value != defaultVatRate) {
  874. onRequireVatRecount(ctx, defaultVatRate, false)
  875. } else {
  876. onRequireVatEnable(ctx)
  877. }
  878. },
  879. complete: { FormAfterContext<R050> ctx, StateMachineService stateMachineService, BankUtils bankUtils, DBOAccessService accessService,
  880. MetaDataService metaDataService, DigestService digestService,
  881. CounterService counterService, ServiceUtils serviceUtils, SessionManager sessionManager ->
  882. R050 doc = (R050) ctx.entity;
  883. doc.lastModifyDate = DateUtils.getCurrentTime()
  884. doc.taxPeriodDay = isTaxPeriod(ctx) ? ctx.fields.taxPeriodDay1.value : ctx.fields.taxPeriodDay2.value
  885. ctx.execute DocUtils.updateStatus.curry(R050StateMachine)
  886. if (doc.bankMessage != ctx.fields.bankMessage.value) {
  887. ctx.fields.bankMessage.value = doc.bankMessage
  888. }
  889.  
  890. // запоминаем последний выбранный счет и организацию
  891. if (ctx.entity.orgId) {
  892. ctx.execute AccountByDefaultUtils.updateLastAccount.curry(
  893. ctx.entity.orgId,
  894. R050Desc.name,
  895. ctx.entity.accountId,
  896. R050Service.R050_LAST_ACCOUNT_ENABLED
  897. )
  898. }
  899.  
  900. ctx.execute AuditDocumentUtils.auditDocumentSave.curry(R050Desc)
  901. },
  902. upcTypes: [CurrentUserOrgUPCType.name],
  903. upc: { UPCFormValueContext<R050> ctx ->
  904. ctx.setUpcValue(CurrentUserOrgUPCType.name, ctx.entity.orgId)
  905. },
  906. roles: {
  907. role id: [DBOPermission.BANK_CLIENT, DBOPermission.OFFLINE_CLIENT],
  908. predicates: CurrentUserOrgPredicate.name,
  909. actions: [Const.SYS_ALL_ACTIONS]
  910. }
  911. }
  912.  
  913. protected def onRequireTaxFieldsEnablingDisabling(FormContext ctx) {
  914. if (ctx.operation != WidgetCreator.FormOperation.SHOW && ctx.fields.drawerStatus.value) {
  915. ctx.fields.cbc.disabled = false
  916. ctx.fields.taxOrCustoms.disabled = false
  917. ctx.fields.ocato.disabled = false
  918. ctx.fields.payReason.disabled = false
  919. ctx.fields.taxPeriodDay1.disabled = false
  920. ctx.fields.taxPeriodMonth.disabled = false
  921. ctx.fields.taxPeriodYear.disabled = false
  922. ctx.fields.taxPeriodDay2.disabled = false
  923. ctx.fields.taxDocNumber.disabled = false
  924. ctx.fields.docDateDay.disabled = false
  925. ctx.fields.docDateMonth.disabled = false
  926. ctx.fields.docDateYear.disabled = false
  927. ctx.fields.chargeType.disabled = false
  928. } else {
  929. ctx.fields.cbc.disabled = true
  930. ctx.fields.taxOrCustoms.disabled = true
  931. ctx.fields.ocato.disabled = true
  932. ctx.fields.payReason.disabled = true
  933. ctx.fields.taxPeriodDay1.disabled = true
  934. ctx.fields.taxPeriodMonth.disabled = true
  935. ctx.fields.taxPeriodYear.disabled = true
  936. ctx.fields.taxPeriodDay2.disabled = true
  937. ctx.fields.taxDocNumber.disabled = true
  938. ctx.fields.docDateDay.disabled = true
  939. ctx.fields.docDateMonth.disabled = true
  940. ctx.fields.docDateYear.disabled = true
  941. ctx.fields.chargeType.disabled = true
  942. }
  943. }
  944.  
  945. protected def onRequireTaxFieldsChange(Map<String, FormFieldState> fields, boolean resetAll = false) {
  946. if (fields.drawerStatus.value) {
  947. fields.taxOrCustoms.value = fields.taxOrCustoms.value ?: "Налог. период"
  948. } else {
  949. fields.cbc.value = ""
  950. fields.taxOrCustoms.value = ""
  951. fields.ocato.value = ""
  952. fields.taxPeriodMonth.value = ""
  953. fields.taxPeriodYear.value = ""
  954. fields.taxPeriodDay2.value = ""
  955. fields.docDateDay.value = ""
  956. fields.docDateMonth.value = ""
  957. fields.docDateYear.value = ""
  958. if (resetAll) {
  959. fields.payReason.value = ""
  960. fields.taxPeriodDay1.value = ""
  961. fields.chargeType.value = ""
  962. fields.taxDocNumber.value = ""
  963. }
  964. }
  965. }
  966.  
  967. protected def onSetEnabledINN(def ctx) {
  968. def disabled = !(ctx.fields.drawerStatus.value in getInnIgnoreDrawerStatus()) && !isBudgetInn(ctx)
  969. Org org = ctx.hibernateTemplate.get(Org, ctx.entity?.orgId)
  970. if (disabled) {
  971. disabled = !org?.federalTreasuryBody
  972. }
  973. ctx.fields.receiverINN.disabled = disabled || ctx.operation == WidgetCreator.FormOperation.SHOW
  974. if (disabled) {
  975. ctx.fields.receiverINN.value = ctx.operation == WidgetCreator.FormOperation.COPY ? org?.inn : ctx.entity.receiverINN
  976. }
  977. }
  978.  
  979. private static final def BUDGET_SYSTEM_ACCOUNTS = ["40101810[0-9]{12}", "40105810[0-9]{12}", "40201810[0-9]{12}",
  980. "40204810[0-9]{12}", "40302810[0-9]{12}", "40312810[0-9]{12}", "404[0-9]{2}810[0-9]{12}",
  981. "40501810[0-9]{5}2[0-9]{6}", "40503810[0-9]{5}4[0-9]{6}", "40601810[0-9]{5}1[0-9]{6}", "40601810[0-9]{5}3[0-9]{6}",
  982. "40501810[0-9]{5}2[0-9]{6}", "40503810[0-9]{5}4[0-9]{6}", "40601810[0-9]{5}1[0-9]{6}", "40601810[0-9]{5}3[0-9]{6}",
  983. "40603810[0-9]{5}4[0-9]{6}", "40701810[0-9]{5}1[0-9]{6}", "40701810[0-9]{5}3[0-9]{6}", "40703810[0-9]{5}4[0-9]{6}"]
  984.  
  985.  
  986. protected def isBudgetInn(def ctx) {
  987. return ctx.fields.drawerStatus?.value &&
  988. (ctx.fields.drawerStatus.value == '26' || ctx.fields.drawerStatus.value == '20' || ctx.fields.drawerStatus.value == '22') &&
  989. isBudgetSystemAccount(ctx.fields.receiverAccount?.value)
  990. }
  991.  
  992. public static boolean isBudgetSystemAccount(String account) {
  993. if (!AccountUtils.isValidAccount(account)) {
  994. return false
  995. }
  996. return BUDGET_SYSTEM_ACCOUNTS.any { account ==~ it }
  997. }
  998.  
  999.  
  1000. protected void initReceiverAccount(DBOAccessService accessService, R050 doc, FormInitContext ctx,
  1001. BankUtils bankUtils) {
  1002. String orgId = doc.orgId
  1003.  
  1004. List<Account> accounts = accessService.getAvailableAccounts()
  1005.  
  1006. def rAccounts = accounts.findAll({
  1007. it.currencyCode == '810' &&
  1008. it.org?.id == orgId &&
  1009. it.accountState == 'OPEN' &&
  1010. it.accountType?.shortName?.equalsIgnoreCase('р/с')
  1011. })
  1012.  
  1013. rAccounts = rAccounts.unique(true, { Account it -> it.id })
  1014.  
  1015. // получаем счёт по умолчанию или последний выбранный счет
  1016. Account defaultAccount = ctx.execute(
  1017. AccountByDefaultUtils.defOrLastAccount.curry(orgId, R050Desc.name, rAccounts,
  1018. R050Service.R050_DEFAULT_ACCOUNT_ENABLED, R050Service.R050_LAST_ACCOUNT_ENABLED
  1019. )
  1020. )
  1021.  
  1022. if (!defaultAccount && rAccounts.size() == 1) {
  1023. // если счета по умолчанию нет и рублевый счет один - при создании указываем его на форме
  1024. defaultAccount = rAccounts.get(0)
  1025. }
  1026.  
  1027. if (defaultAccount) {
  1028. def rAccountId = defaultAccount.id
  1029. doc.accountId = rAccountId
  1030. ctx.fields.receiverAccount.value = defaultAccount.account
  1031. onRequirePayerBankChange(ctx.fields, doc, bankUtils, ctx.hibernateTemplate, rAccountId, null)
  1032. }
  1033. }
  1034.  
  1035.  
  1036. protected def onRequirePayerBankChange(Map<String, FormFieldState> fields, R050 entity, BankUtils bankUtils,
  1037. HibernateTemplate hibernateTemplate,
  1038. Serializable accountId, Map<String, Serializable> contextParams,
  1039. boolean rewriteNotEmpty = true) {
  1040. Account account
  1041. if (accountId) {
  1042. account = hibernateTemplate.get(Account, accountId)
  1043. } else {
  1044. def val = fields.receiverAccount.value as String
  1045. def accounts = val ? bankUtils.findAccounts(val) : null
  1046. account = accounts ? (accounts.size() == 1 ? accounts.get(0) : accounts.find {
  1047. entity.orgId?.equals(it.org?.id)
  1048. }) : null
  1049.  
  1050. }
  1051. if (account) {
  1052. entity.accountId = account.id
  1053. def payerBankInfo = bankUtils.getBankInfo(account.bankBic)
  1054. if (payerBankInfo) {
  1055. fields.receiverBankBic.value = account.bankBic
  1056. fields.receiverBankName.value = payerBankInfo.get(BankUtils.BANK_FULLNAME);
  1057. fields.receiverBankCorrAccount.value = payerBankInfo.get(BankUtils.BANK_CORRACCOUNT);
  1058. entity.receiverBankName = payerBankInfo.get(BankUtils.BANK_NAME);
  1059. entity.receiverBankCity = payerBankInfo.get(BankUtils.BANK_CITYORIG)
  1060. entity.receiverBankSettlementType = payerBankInfo.get(BankUtils.BANK_TNP)
  1061. } else {
  1062. clearReceiverBank(fields, entity)
  1063. }
  1064.  
  1065. Org org = hibernateTemplate.get(Org, entity.orgId)
  1066. if (org) {
  1067. fillReceiverKppList(fields, org)
  1068. }
  1069.  
  1070. checkSameBank(fields)
  1071. } else {
  1072. clearReceiverBank(fields, entity)
  1073. entity.accountId = null
  1074. }
  1075. }
  1076.  
  1077. protected void clearReceiverBank(Map<String, FormFieldState> fields, R050 entity) {
  1078. fields.receiverBankBic.value = null
  1079. fields.receiverBankName.value = null
  1080. fields.receiverBankCorrAccount.value = null
  1081. entity.receiverBankName = null
  1082. entity.receiverBankCity = null
  1083. entity.receiverBankSettlementType = null
  1084. }
  1085.  
  1086.  
  1087. protected def receiverDataOnDrawerStatusChange(def ctx, BankUtils bankUtils) {
  1088. if (!(ctx.fields.drawerStatus.value in getInnIgnoreDrawerStatus())) {
  1089. Org org = ctx.hibernateTemplate.get(Org, ctx.entity.orgId)
  1090. Account account = bankUtils.findAccount(ctx.fields.payerAccount.value, ctx.fields.payerBankBic.value)
  1091.  
  1092. if (!account?.trustManagement) {
  1093. ctx.fields.receiverName.value = org.name
  1094. }
  1095. if (!isBudgetInn(ctx) && !org.federalTreasuryBody) {
  1096. ctx.fields.receiverINN.value = org.inn
  1097. }
  1098. ctx.fields.receiverKPP.value = org.defaultKpp?.kpp
  1099. fillReceiverKppList(ctx.fields, org)
  1100. }
  1101. }
  1102.  
  1103. protected def fillReceiverKppList(Map<String, FormFieldState> fields, Org org) {
  1104. Object curPayKpp = fields.receiverKPP.value;
  1105. boolean containCurKpp = false;
  1106.  
  1107. def kppList = new ArrayList<GridRowData>()
  1108. org.orgKpp.each { OrgKpp kpp ->
  1109. if (!containCurKpp && curPayKpp != null && curPayKpp.equals(kpp.kpp)) {
  1110. containCurKpp = true
  1111. };
  1112. kppList << new GridRowData(kpp.kpp, [kpp.kpp])
  1113. }
  1114. if (!containCurKpp && curPayKpp != null) {
  1115. kppList << new GridRowData(curPayKpp, [curPayKpp])
  1116. }
  1117. fields.receiverKPP.items = kppList.sort()
  1118. }
  1119.  
  1120. protected
  1121. def onCorrespondentSelect(Serializable id, Map<String, FormFieldState> fields, HibernateTemplate hibernateTemplate, BankUtils bankUtils) {
  1122. if (id) {
  1123. Correspondent correspondent = hibernateTemplate.get(Correspondent, id)
  1124. if (correspondent) {
  1125. fields.payerINN.value = correspondent.inn
  1126. fields.payerKPP.value = correspondent.kpp
  1127. fields.payerAccount.value = correspondent.account
  1128. fields.payerName.value = correspondent.name
  1129. fields.payerBankBic.value = correspondent.bic
  1130. }
  1131. }
  1132. }
  1133.  
  1134. protected def createVatInfo(Map<String, FormFieldState> fields) {
  1135. SumFormatter sf = new SumFormatter();
  1136. BigDecimal vatRate = fields.vatRate.value
  1137. BigDecimal vatSum = fields.vatSum.value
  1138. BigDecimal documentSum = fields.documentSum.value
  1139. def rule = R030VatCalculationRule.valueOf(fields.vatCalculationRule.value)
  1140. return rule.getPurpose(documentSum, vatRate, vatSum, sf)
  1141. }
  1142.  
  1143.  
  1144. protected def fillPayerReq(Map<String, FormFieldState> fields, Object entity, BankUtils bankUtils) {
  1145. String payerBankBic = fields.payerBankBic.value
  1146. if (payerBankBic) {
  1147. def payerBankInfo = bankUtils.getBankInfo(payerBankBic)
  1148. if (payerBankInfo) {
  1149. fields.payerBankName.value = payerBankInfo.get(BankUtils.BANK_FULLNAME)
  1150. fields.payerBankCorrAccount.value = payerBankInfo.get(BankUtils.BANK_CORRACCOUNT)
  1151. entity.payerBankName = payerBankInfo.get(BankUtils.BANK_NAME)
  1152. entity.payerBankCity = payerBankInfo.get(BankUtils.BANK_CITYORIG)
  1153. entity.payerBankSettlementType = payerBankInfo.get(BankUtils.BANK_TNP)
  1154. } else {
  1155. clearPayerReq(fields, entity)
  1156. }
  1157. } else {
  1158. clearPayerReq(fields, entity)
  1159. }
  1160. checkSameBank(fields)
  1161. }
  1162.  
  1163. protected def clearPayerReq(Map<String, FormFieldState> fields, entity) {
  1164. fields.payerBankName.value = null
  1165. fields.payerBankCorrAccount.value = null
  1166. entity.payerBankName = null
  1167. entity.payerBankCity = null
  1168. entity.payerBankSettlementType = null
  1169. }
  1170.  
  1171. protected def checkSameBank(Map<String, FormFieldState> fields) {
  1172. String payerBic = fields.payerBankBic.value
  1173. String recBic = fields.receiverBankBic.value
  1174. if (payerBic && recBic && payerBic.equals(recBic)) {
  1175. fields.paymentKind.value = null
  1176. fields.paymentCode.value = "0"
  1177. }
  1178. }
  1179.  
  1180. protected def onRequirePayerNameEnable(FormContext ctx, BankUtils bankUtils) {
  1181. if (ctx.operation == WidgetCreator.FormOperation.SHOW) {
  1182. return
  1183. }
  1184. if (checkPayerNameConditionEnabling(ctx)) {
  1185. ctx.fields.receiverName.disabled = false
  1186. } else {
  1187. ctx.fields.receiverName.disabled = true
  1188. if (ctx.entity.orgId) {
  1189. Org org = ctx.hibernateTemplate.get(Org, ctx.entity.orgId)
  1190. ctx.fields.receiverName.value = org?.name
  1191. }
  1192. onRequirePayerNameChange(ctx, bankUtils)
  1193. }
  1194. }
  1195.  
  1196. protected boolean checkPayerNameConditionEnabling(FormContext ctx) {
  1197. return true
  1198. }
  1199.  
  1200. protected static String makeNotNullElement(String text) {
  1201. return text ?: "";
  1202. }
  1203.  
  1204. protected def buildPayerFullAddress(def address) {
  1205. if (!address) {
  1206. return null
  1207. }
  1208. if (address.getFullAddress()) {
  1209. return address.getFullAddress();
  1210. } else {
  1211. StringBuilder sb = new StringBuilder();
  1212. sb.append(makeNotNullElement(address.getZipcode())).append(", ");
  1213. sb.append(makeNotNullElement(address.getCity())).append(", ");
  1214. sb.append(makeNotNullElement(address.getStreet())).append(", ");
  1215. sb.append(makeNotNullElement(address.getHouse())).append(", ");
  1216. sb.append(makeNotNullElement(address.getBuilding())).append(", ");
  1217. sb.append(makeNotNullElement(address.getFlat()));
  1218. return sb.toString();
  1219. }
  1220. }
  1221.  
  1222. protected def onRequirePayerNameChange(def ctx, BankUtils bankUtils) {
  1223. String receiverAccount = ctx.fields.receiverAccount.value
  1224. Org org = ctx.hibernateTemplate.get(Org, ctx.entity.orgId)
  1225.  
  1226. def orgName = org.name
  1227. List<String> nonResidentAccounts = ctx.hibernateTemplate.find("select balanceAccount from NonResidentBankAccount")
  1228.  
  1229. StringBuilder name = new StringBuilder().append(orgName)
  1230.  
  1231. def summa = ctx.fields.documentSum.value ?: 0
  1232.  
  1233. Account account = bankUtils.findAccount(ctx.fields.payerAccount.value, ctx.fields.payerBankBic.value)
  1234.  
  1235. if (account?.trustManagement) {
  1236. ctx.fields.payerName.value = account.accountName
  1237. } else if (nonResidentAccounts.find {
  1238. receiverAccount?.substring(0, it.length()) == it
  1239. } && summa > MIN_SUM_WITH_ADDRESS) {
  1240. def payerAddress
  1241. StringBuilder nameAddress = new StringBuilder().append(orgName)
  1242. def payerActualAddress = org.addressCollection.addresses.find {
  1243. it.addressType.systemName == AddressType.JURIDICAL
  1244. }
  1245. if (!payerActualAddress) {
  1246. payerActualAddress = org.addressCollection.addresses.find {
  1247. it.addressType.systemName == AddressType.ACTUAL
  1248. }
  1249. }
  1250. if (payerActualAddress) {
  1251. def fullActualAddress = payerActualAddress.fullAddress
  1252. payerAddress = fullActualAddress ? fullActualAddress : buildPayerFullAddress(payerActualAddress)
  1253. nameAddress.append("//").append(payerAddress).append("//")
  1254. } else {
  1255. ctx.widgetCreator.showInformMessage(i18n("Фактический адрес организации-плательщика не найден в справочнике"),
  1256. i18n("«Плательщик»"))
  1257. }
  1258.  
  1259. if (nameAddress.length() > 160) {
  1260. ctx.widgetCreator.showInformMessage(i18n("Автоматическая подстановка адреса места нахождения невозможна из-за превышения максимально допустимой длины поля «Плательщик» (160 символов). ")
  1261. + i18n("Вам необходимо указать адрес вручную, выделив его знаками #1# начинающими и заканчивающими указание адреса ", " // ")
  1262. + i18n("(при указании адреса допускается использовать сокращения, позволяющие определенно установить информацию о плательщике)")
  1263. , i18n("«Плательщик»"))
  1264. } else {
  1265. ctx.fields.payerName.value = nameAddress.toString()
  1266. }
  1267. } else {
  1268. if (name.length() > 160) {
  1269. ctx.fields.payerName.value = name.toString().substring(0, 160)
  1270. } else {
  1271. ctx.fields.payerName.value = name.toString()
  1272. }
  1273.  
  1274. }
  1275. }
  1276.  
  1277. protected def onRequireVatEnable(FormContext ctx) {
  1278. def rule = R030VatCalculationRule.valueOf(ctx.fields.vatCalculationRule.value)
  1279. ctx.fields.vatRate.disabled = !rule.canEditVatRate
  1280. ctx.fields.vatSum.disabled = !rule.canEditVatSum
  1281. }
  1282.  
  1283. protected
  1284. def onRequireVatRecount(FormContext ctx, BigDecimal defaultVatRate = null, boolean showConfirmMessage = true) {
  1285. Map<String, FormFieldState> fields = ctx.fields
  1286. WidgetCreator widgetCreator = ctx.widgetCreator
  1287. def rule = R030VatCalculationRule.valueOf(fields.vatCalculationRule.value)
  1288. onRequireVatEnable(ctx)
  1289. if (fields.vatRate.disabled) {
  1290. fields.vatRate.value = defaultVatRate ?: lawChangeConfigService.isVAT2019(R030Utils.getTimeZoneByOrg(ctx.entity.orgId,
  1291. ctx.hibernateTemplate)) ? VAT20 : DEFAULT_VAT
  1292. }
  1293. def vatRate = rule.getVatRate(fields.documentSum.value, fields.vatRate.value, fields.vatSum.value)
  1294. def vatSum = rule.getVatSum(fields.documentSum.value, fields.vatRate.value, fields.vatSum.value)
  1295. def docSum = rule.getDocSum(fields.documentSum.value, fields.vatRate.value, fields.vatSum.value)
  1296.  
  1297. if (docSum && docSum != fields.documentSum.value) {
  1298. if (showConfirmMessage) {
  1299. SumFormatter sf = new SumFormatter();
  1300. if (widgetCreator.showConfirmMessage(i18n("Сумма платежа: ") + sf.format(docSum) + i18n(" руб.\n") +
  1301. i18n("Величина НДС: ") + sf.format(vatSum) + i18n(" руб.\nИзменить?"), i18n("Изменение суммы платежа"), "changeDocSum")) {
  1302. fields.documentSum.value = docSum
  1303. } else {
  1304. fields.vatCalculationRule.value = R030VatCalculationRule.VatAddNoChange.name()
  1305. rule = R030VatCalculationRule.valueOf(fields.vatCalculationRule.value)
  1306. vatSum = rule.getVatSum(fields.documentSum.value, fields.vatRate.value, fields.vatSum.value)
  1307. }
  1308. } else {
  1309. fields.documentSum.value = docSum
  1310. }
  1311. }
  1312. fields.vatRate.value = vatRate
  1313. fields.vatSum.value = vatSum;
  1314.  
  1315. onRequireChangeVatInfo(fields)
  1316. revertVatAddIfNeeded(fields)
  1317. }
  1318.  
  1319. // Возвращаем значение которое должно отображаться в дропдауне вместо синтетического, использованного для рассчетов
  1320. protected def revertVatAddIfNeeded(Map<String, FormFieldState> fields) {
  1321. if (fields.vatCalculationRule.value.equals(R030VatCalculationRule.VatAddNoChange.name())) {
  1322. fields.vatCalculationRule.value = R030VatCalculationRule.VatAdd.name()
  1323. }
  1324. }
  1325.  
  1326. protected def onRequireChangeVatInfo(Map<String, FormFieldState> fields) {
  1327. String vatInfo = createVatInfo(fields)
  1328. if (vatInfo) {
  1329. String paymentPurpose = (fields.paymentPurpose.value as String ?: "").trim()
  1330. if (paymentPurpose) {
  1331. def replaced = false;
  1332. for (String regExp : R030VatCalculationRule.vatMentions) {
  1333. if (paymentPurpose =~ "${regExp}") {
  1334. paymentPurpose = paymentPurpose.replaceAll(regExp, vatInfo)
  1335. replaced = true
  1336. break
  1337. }
  1338. }
  1339. if (!replaced) {
  1340. def matcher = ppCurrencyTypeMatcher paymentPurpose
  1341. paymentPurpose = (matcher.matches() ?
  1342. matcher[0][1] + matcher[0][2] + " " + vatInfo + "." + matcher[0][3] :
  1343. paymentPurpose + "\r\n" + vatInfo + ".")
  1344. }
  1345. } else {
  1346. paymentPurpose = vatInfo
  1347. }
  1348. fields.paymentPurpose.value = paymentPurpose
  1349. }
  1350. }
  1351.  
  1352. public static def ppCurrencyTypeMatcher(String paymentPurpose) {
  1353. return Pattern.compile(/^(.*?)(\{VO[^\}]*?\})(.*?)$/, Pattern.DOTALL).matcher(paymentPurpose)
  1354. }
  1355.  
  1356. protected void updatePaymentCode(FormContext ctx) {
  1357. String paymentKind = ctx.fields.paymentKind.value;
  1358. DetachedCriteria c = DetachedCriteria.forClass(PaymentKind);
  1359. c.add(paymentKind ? Restrictions.eq("kind", paymentKind) : Restrictions.isNull("kind"));
  1360. List<PaymentKind> paymentKinds = ctx.hibernateTemplate.findByCriteria(c);
  1361.  
  1362. if (paymentKinds.size() > 0) {
  1363. ctx.fields.paymentCode.value = paymentKinds.get(0).code
  1364. } else {
  1365. ctx.fields.paymentCode.value = ""
  1366. }
  1367. }
  1368.  
  1369. protected def isTaxPeriod(def ctx) {
  1370. return ctx.fields.taxOrCustoms.value != "Код тамож. органа"
  1371. }
  1372.  
  1373. def addNewOfficials = { FormFieldSubmitContext<R050> ctx ->
  1374. if (ctx.isFormChanged()) {
  1375. Correspondent correspondent = ctx.entityFactory.newEntity(Correspondent)
  1376. Org org = ctx.hibernateTemplate.get(Org, ctx.entity.orgId)
  1377. correspondent.name = ctx.fields.payerName.value
  1378. correspondent.inn = ctx.entity.payerINN
  1379. correspondent.org = org
  1380. correspondent.kpp = ctx.entity.payerKPP
  1381. correspondent.account = ctx.entity.payerAccount
  1382. correspondent.bic = ctx.entity.payerBankBic
  1383. List<ValidationResult> errors = []
  1384. if (!correspondent.name) {
  1385. errors << new ValidationError(i18n("Поле 'Наименование' не заполнено"))
  1386. }
  1387. if (!correspondent.kpp) {
  1388. errors << new ValidationError(i18n("Поле 'КПП' не заполнено"))
  1389. }
  1390. if (!correspondent.account) {
  1391. errors << new ValidationError(i18n("Поле 'Счет' не заполнено"))
  1392. }
  1393. if (!correspondent.bic) {
  1394. errors << new ValidationError(i18n("Поле 'БИК' не заполнено"))
  1395. }
  1396. if (!correspondent.inn) {
  1397. errors << new ValidationError(i18n("Поле 'ИНН' не заполнено"))
  1398. }
  1399.  
  1400. if (errors.size() > 0) {
  1401. ctx.widgetCreator.showErrorsForm(errors)
  1402. return
  1403. } else {
  1404. DetachedCriteria criteria = DetachedCriteria.forClass(Correspondent)
  1405. criteria.add(Restrictions.eq("name", correspondent.name))
  1406. criteria.add(Restrictions.eq("org.id", correspondent.org.id))
  1407. criteria.add(Restrictions.eq("kpp", correspondent.kpp))
  1408. criteria.add(Restrictions.eq("inn", correspondent.bic))
  1409.  
  1410. List<Officials> officialsList = ctx.hibernateTemplate.findByCriteria(criteria)
  1411. if (officialsList.size() > 0) {
  1412. errors << new ValidationError(i18n("Ответственное лицо '") + correspondent.name + i18n("' уже есть в справочнике"))
  1413. ctx.widgetCreator.showErrorsForm(errors)
  1414. return
  1415. }
  1416. ctx.hibernateTemplate.save(correspondent)
  1417. ctx.widgetCreator.showInformMessage(i18n("Ответственное лицо добавлено в справочник корреспондентов"), i18n("Информация"))
  1418. }
  1419. }
  1420. }
  1421.  
  1422. protected void appendStateToTitle(FormInitContext<R050> ctx) {
  1423. ctx.execute DocUtils.appendStateToTitle.curry(null, ctx.entity.state, StateType.CLIENT)
  1424. }
  1425.  
  1426. protected List<OrgCopyService.MappingEntry> getMapping() {
  1427. return [
  1428. new OrgCopyService.MappingEntry(ORG_ID, "orgId"),
  1429. new OrgCopyService.MappingEntry(ORG_NAME, "receiverName"),
  1430. new OrgCopyService.MappingEntry(ORG_INN, "receiverINN"),
  1431. new OrgCopyService.MappingEntry(ORG_KPP, "receiverKPP")
  1432. ]
  1433. }
  1434.  
  1435. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement