Documentation/Index/DenyMPKSelectWithNoOrgAccess: VatNoteCostForm.inc

Plik VatNoteCostForm.inc, 61.0 KB (dodany przez lglomb, 9 years temu)
xx

Klasa

Line 
1<?php
2require_once(LIB_PATH.'widgets/DialogForm.inc');
3require_once(LIB_PATH.'forms/Label.inc');
4require_once(LIB_PATH.'forms/TextInput.inc');
5require_once(LIB_PATH.'forms/TextArea.inc');
6require_once(LIB_PATH.'forms/ModernSelect.inc');
7require_once(LIB_PATH.'forms/DBSelect.inc');
8require_once(LIB_PATH.'forms/IButton.inc');
9require_once(LIB_PATH.'forms/RadioGroup2.inc');
10require_once(LIB_PATH.'forms/CalendarInput.inc');
11require_once(MOD_PATH.'ADocuments/beans/VatNoteCost.inc');
12require_once(MOD_PATH.'Dictionaries/VatRates/services/VatRatesService.inc');
13require_once(MOD_PATH.'Dictionaries/CurrencyDict/CurrencyService.inc');
14require_once('./classes/LookupWidget/LookupWidget2.inc');
15require_once('./classes/LookupWidget/Projects/ProjectsSearchEngine.inc');
16require_once('./classes/LookupWidget/Projects/ProjectsLookupManager.inc');
17require_once('./classes/FieldTools/RightCheckers/UniFieldsRightsChecker.inc');
18require_once('./classes/Access/forms/FieldsAccessManageDialog.inc');
19require_once(LIB_PATH.'system/SystemRegistry.inc');
20
21/**
22 *  @author Marcin Król
23 *  @version 0.1
24 */
25class VatNoteCostForm extends DialogForm {
26
27    private static $cMethods = array(
28        1 => 'getNextPos',
29        2 => 'setAmountAll',
30        3 => 'loadListsByYear',
31        4 => 'applyProjectFilter',
32        'loadMPK',
33        'loadRK',
34        7 => 'calculateVat',
35        8 => 'doSave',
36        'loadAA'
37    );
38
39        public $doStaticClear = TRUE;
40
41
42        /**
43         *
44         */
45    public function __construct($name, $caption=NULL, $dstyle = BS_DIALOG) {
46
47                parent::__construct($name, $caption, $dstyle);
48
49                $this->path = MOD_PATH.'ADocuments/plugins/vatnote/VatNoteCostForm.inc';
50                $this->icon = '';
51
52        $this->db = PgManager::getInstance();
53
54        $this->HWND = Application::registerClass($this->path, 'VatNoteCostForm');
55
56        $this->onbOkClick = 'STDLib.asyncSubmit($(\''.$this->name.'dbox_cnt\'), \'\');$A1(\''.$this->HWND.'\',\''.$this->name.'\','.(int)array_search('doSave', self::$cMethods).',0,0,0,true); return false;';
57            $this->onbSaveClick = 'STDLib.asyncSubmit($(\''.$this->name.'dbox_cnt\'), \'\');$A1(\''.$this->HWND.'\',\''.$this->name.'\','.(int)array_search('doSave', self::$cMethods).',1,0,0,true); return false;';
58
59        if ($this->isOpened() AND !$this->noNeedForCreate() AND !Request::hasMethodCall($this->HWND, array(1,2,3,4,5,6,7))) {
60                $this->create();
61        }
62    }
63
64    public function applyProjectFilter($projid) {
65
66        $this->create();
67        $this->projid->selectItem($projid);
68
69        if (method_exists($this->povcid, 'update')) {
70            $this->povcid->update();
71        } else {
72            $this->povcid->autoClear = TRUE;
73            if ($projid) {
74                $this->povcid->setFilterString('projid='.$projid.'');
75                $this->povcid->search($projid);
76            }
77        }
78
79        if (method_exists($this->tovcid, 'update')) {
80            $this->tovcid->update();
81        }
82        if (method_exists($this->adanid, 'update')) {
83            $this->adanid->update();
84        }
85
86        return $this->toHtml('toHtml');
87
88    }
89
90
91
92    /**
93     * Load selection lists by year
94     */
95    public function loadListsByYear($year) {
96        require_once(MOD_PATH.'Dictionaries/VatNote/services/CostTypeService.inc');
97        require_once(MOD_PATH.'Dictionaries/VatNote/services/VCostPlaceService.inc');
98
99        $costTypeService = new CostTypeService();
100        $vcostPlaceService = new VCostPlaceService();
101
102        if (!is_int((int)$year)) {
103            throw new WidgetException($this->name.'year__', Translator::translate('Wybierz rok z listy'));
104        }
105
106        $data = $this->getSData();
107        $this->setSData(
108            array(
109                'year' => $year
110            )
111        );
112
113        $_SESSION['current_account_year'] = $year;
114
115        $this->create();
116        $this->year__->selectItem($year);
117
118        $filterSQL = 'ent_id = '.SysContext::$ent_id.' AND year__ = '.$year;
119        if(isset($data['acorid']) && $data['acorid'] && $vcostPlaceService->definedForAcorid($data['acorid'], $year)) {
120            $filterSQL .= ' AND acorid = '.$data['acorid'];
121        } else {
122            $filterSQL .= ' AND acorid IS NULL';
123        }
124
125        if (method_exists($this->povcid, 'update')) {
126            $this->povcid->update();
127        } else {
128            $this->povcid->autoClear = TRUE;
129            $this->povcid->setFilterString($filterSQL);
130            $this->povcid->search(NULL);
131            //$this->povcid->toHtml();
132        }
133
134        $filterSQL = 'ent_id = '.SysContext::$ent_id.' AND year__ = '.$year;
135        if(isset($data['acorid']) && $data['acorid'] && $costTypeService->definedForAcorid($data['acorid'], $year)) {
136            $filterSQL .= ' AND acorid = '.$data['acorid'];
137        } else {
138            $filterSQL .= ' AND acorid IS NULL';
139        }
140
141        if (method_exists($this->tovcid, 'update')) {
142            $this->tovcid->update();
143        } else {
144            $this->tovcid->autoClear = TRUE;
145            $this->tovcid->setFilterString($filterSQL);
146            $this->tovcid->search(NULL);
147        }
148
149        if (method_exists($this->adanid, 'update')) {
150            $this->adanid->update();
151        } else {
152            $this->adanid->autoClear = TRUE;
153            $this->adanid->setFilterString('year__ = \''.$year.'\'');
154            $this->adanid->search(NULL);
155        }
156
157        //JScript::add('ceval(\'App.'.$this->name.'.center();\');');
158
159        return $this->toHtml('toHtml');
160
161    }
162
163    public function loadMPK($povcid) {
164
165        if (!is_numeric($povcid)) {
166            JScript::alert(Translator::translate('Brak identyfikatora MPK'));
167            return FALSE;
168        }
169
170        require_once('./classes/LookupWidget/LookupWidget2.inc');
171        require_once('./classes/LookupWidget/PlacesOfVCosts/PlacesOfVCostsSearchEngine.inc');
172
173        $mpk = new LookupWidget2($this->name.'povcid', new PlacesOfVCostsSearchEngine(), FALSE, 1);
174        $mpk->autoClear = TRUE;
175        $mpk->setInitialValueByKey($povcid, TRUE);
176
177        return $mpk->toHtml('fast');
178
179    }
180
181    public function loadRK($tovcid) {
182
183        if (!is_numeric($tovcid)) {
184            JScript::alert(Translator::translate('Brak identyfikatora RK'));
185            return FALSE;
186        }
187
188        $out = $this->db->select('types_of_vcosts', 'tovcid', 'prn_id = '.$tovcid.' AND ent_id = '.SysContext::$ent_id.'', FALSE, PGSQL_ASSOC);
189        if (isset($out[0]['tovcid'])) {
190            JScript::alert(Translator::translate('Wybrany Rodzaj kosztów nie może zostać dodany ze względu na ograniczenie wyboru tylko do końcowych kont'));
191            return FALSE;
192        }
193
194        require_once('./classes/LookupWidget/LookupWidget2.inc');
195        require_once('./classes/LookupWidget/TypesOfVCosts/TypesOfVCostsSearchEngine.inc');
196
197        $rk = new LookupWidget2($this->name.'tovcid', new TypesOfVCostsSearchEngine(), FALSE, 1);
198        $rk->autoClear = TRUE;
199        $rk->setInitialValueByKey($tovcid, TRUE);
200
201        return $rk->toHtml('fast');
202
203    }
204
205    public function loadAA($adanid) {
206
207        if (!is_numeric($adanid)) {
208            JScript::alert(Translator::translate('Brak identyfikatora'));
209            return FALSE;
210        }
211
212        require_once('./classes/LookupWidget/LookupWidget2.inc');
213        require_once('./classes/LookupWidget/AdditionalAnalytics/AdditionalAnalyticsSearchEngine.inc');
214
215        $aa = new LookupWidget2($this->name.'adanid', new AdditionalAnalyticsSearchEngine(), FALSE, 1);
216        $aa->autoClear = TRUE;
217        $aa->setInitialValueByKey($adanid, TRUE);
218
219        return $aa->toHtml('fast');
220
221    }
222
223    public function calculateVat($data = array()) {
224        if (is_array($data) AND !empty($data)) {
225            if (!isset($data['vat_id'])) return '';
226
227            $vat_id = $data['vat_id'];
228            $amount = $data['amount'];
229            $isneto = $data['isneto'];
230            $vc_count = isset($data['vc_count']) ? $data['vc_count'] : NULL;
231
232        } else {
233            if (!isset($_POST[$this->name.'vat_id'])) return '';
234
235            $vat_id = $_POST[$this->name.'vat_id'];
236            $amount = $_POST[$this->name.'amount'];
237            $isneto = $_POST[$this->name.'isneto'];
238            $vc_count = NULL;
239        }
240
241        if (!$amount) {
242            return 0;
243        }
244        $amount = str_replace(array(',', ' '), array('.', ''), $amount);
245
246        require_once(MOD_PATH.'Dictionaries/VatRates/beans/VatRateBean.inc');
247        $vat = new VatRateBean($vat_id);
248        $vat = bcdiv((string)$vat->data['vatval'], '100', 2);
249        if ($isneto == 't') {
250            $amtvat = round(bcmul($amount,  $vat, 4), 2);
251
252        } else {
253            $amtvat = round(bcsub($amount, bcdiv($amount,  (string)(1 + $vat), 4), 4), 2);
254        }
255
256        $this->setSData(array('amtvat' => (string)$amtvat));
257
258        return $amtvat;
259    }
260
261    private function loadFromSelProducts($data, $bean) {
262
263        require_once(MOD_PATH.'Evidence/services/FKElementsService.inc');
264        require_once(MOD_PATH.'ADocuments/beans/Document.inc');
265
266        $fkElements = $data['fkelid'];
267        $isneto = $bean->data['isneto'];
268        $amount = 0;
269
270        $document = Document::getInstance($data['doc_id']);
271
272        foreach ($fkElements as $fkelid) {
273            $fkElement = FKElementsService::getInstance($fkelid);
274            $quantm = $bean->calculateQuantumToFkElement($fkElement);
275            if (!$quantm) {
276                continue;
277            }
278
279            if ($isneto == 't') {
280                $amount += ($fkElement->data['netto_'] * $quantm);
281            } else {
282                $amount += ($fkElement->data['brutto'] * $quantm);
283            }
284        }
285
286        $bean->set('amount', round($amount, 22));
287
288        if ($isneto == 't') {
289            if ($document->get('netto_')) {
290                $bean->set('prtcip', ($amount/$document->get('netto_'))*100);
291            }
292        } else {
293            if ($document->get('amount')) {
294                $bean->set('prtcip', ($amount/$document->get('amount'))*100);
295            }
296        }
297
298        $bean->set('prtcip', round($bean->get('prtcip'), 2));
299
300    }
301
302        /**
303         *
304         */
305        public function getCallableMethods() {
306                return self::$cMethods;
307        }
308
309        /**
310         *
311         */
312        public function open($params = NULL) {
313        $data = array();
314
315        if ($this->isOpened()) $this->clear();
316
317        $defaultCurrency = CurrencyService::getDefaultCurrency();
318        if (!$defaultCurrency) {
319            JScript::alert(Translator::translate('Brak zdefiniowanej domyślnej waluty'));
320            return FALSE;
321        }
322
323        parent::open($params, $data);
324                $bean = new VatNoteCost();
325        $pkname = $bean->getPkeyName();
326
327                if (!isset($data['doc_id']) AND !isset($data[$pkname])) {
328                        $this->close();
329                        return FALSE;
330        }
331        $orunid = FALSE;
332
333        $currentYear = date('Y');
334        $initdt = (isset($data['initdt'])) ? $data['initdt'] : $currentYear;
335
336        $data['year'] = SystemRegistry::get('UserSettings.AccountYear', NULL);
337        if (!$data['year']) {
338            $data['year'] = (isset($_SESSION['current_account_year'])) ? $_SESSION['current_account_year'] : $currentYear;
339        } else {
340            $initdt = $data['year'];
341        }
342        $selectedYear = NULL;
343
344        $years = array();
345        $minYear = min($currentYear - 1, $initdt, $currentYear + 1);
346        $maxYear = max($currentYear - 1, $initdt, $currentYear + 1);
347
348        $yearsRange = range($minYear, $maxYear);
349        foreach ($yearsRange as $year) {
350            $years[] = array(
351                'id' => $year,
352                'val' => $year
353            );
354        }
355
356        if ($initdt AND in_array($initdt, $yearsRange)) {
357            $selectedYear = $initdt;
358        } else {
359            $selectedYear = $data['year'];
360        }
361        $data['year'] = $selectedYear;
362
363                $this->setSData($data);
364
365                $this->caption = Translator::translate('Koszt');
366                $readOnly = FALSE;
367
368                if (isset($data[$pkname])) {
369
370                        $bean = new VatNoteCost($data[$pkname]);
371            $data['doc_id'] = $bean->get('doc_id');
372
373                        $res = $this->db->query('SELECT doc_id, netto_, amount AS brutto, cretid, acorid FROM vatnote WHERE doc_id='.$bean->get('doc_id'), FALSE, PGSQL_ASSOC);
374
375            if (isset($res[0]['doc_id'])) {
376                $this->setSData(array('acorid' => $res[0]['acorid']));
377                $cretid = $res[0]['cretid'];
378                $cr_avg = 1;
379                if ($cretid) {
380                    require_once(MOD_PATH.'Dictionaries/CurrencyDict/beans/CurrencyExchangeTableBean.inc');
381                    $currExBean = new CurrencyExchangeTableBean($cretid);
382                    $cr_avg = $currExBean->get('cr_avg');
383                    if ($cr_avg <= 0) {
384                        $cr_avg = 1;
385                    }
386                }
387                $bean->data = array_merge($bean->data, $res[0]);
388                if ($bean->getb('isneto')) {
389                    if ($res[0]['netto_']) {
390                        $bean->data['value_'] = $res[0]['netto_'] * $cr_avg;
391                    }
392                } else {
393                    if ($res[0]['brutto']) {
394                        $bean->data['value_'] = $res[0]['brutto'] * $cr_avg;
395                    }
396                }
397                        } else {
398                                $bean->set('netto_', 0);
399                                $bean->set('cursmb', $defaultCurrency);
400            }
401
402            //$selectedYear = NULL;
403            $hasYear = FALSE;
404            if ($bean->data['adanid']) {
405                $q = $this->db->select('additional_analytics', 'year__', 'adanid = '.$bean->data['adanid'].'', FALSE, PGSQL_ASSOC);
406                if (isset($q[0]['year__'])) {
407                    $selectedYear = $q[0]['year__'];
408                    $hasYear = TRUE;
409                }
410            }
411            if ((!$hasYear) AND ($bean->data['tovcid'])) {
412                $q = $this->db->select('types_of_vcosts', 'year__', 'tovcid = '.$bean->data['tovcid'].'', FALSE, PGSQL_ASSOC);
413                if (isset($q[0]['year__'])) {
414                    $selectedYear = $q[0]['year__'];
415                    $hasYear = TRUE;
416                }
417            }
418            if ((!$hasYear) AND ($bean->data['povcid'])) {
419                $q = $this->db->select('places_of_vcosts', 'year__', 'povcid = '.$bean->data['povcid'].'', FALSE, PGSQL_ASSOC);
420                if (isset($q[0]['year__'])) {
421                    $selectedYear = $q[0]['year__'];
422                    $hasYear = TRUE;
423                }
424            }
425            $this->setSData(array('year' => $selectedYear));
426            $data['year'] = $selectedYear;
427
428                        $readOnly = !UserRights::checkSysAcc('bswfms.extras.privilages.vatnote_edit');
429
430            if (isset($data[$pkname]) && isset($data['mode']) && ($data['mode'] === 'new')) {
431                unset($data[$pkname]);
432                $bean->uset($pkname);
433                $this->setSData(array($pkname => NULL));
434            }
435
436        } else {
437            $bean->set('doc_id', $data['doc_id']);
438            $bean->set('isneto', 't');
439            $bean->set('netto_', NULL);
440            $bean->set('brutto', NULL);
441            $bean->set('value_', NULL);
442            $bean->set('amount', NULL);
443            $bean->set('prtcip', NULL);
444
445            $res = $this->db->query('SELECT v.netto_, v.amount as brutto, vc.cursmb, vc.isneto, vc.amount, vc.amtvat FROM vatnote v LEFT JOIN vatnote_costs vc USING(doc_id) WHERE v.doc_id='.$data['doc_id'], FALSE, PGSQL_ASSOC);
446
447            if (is_array($res) AND isset($res[0]['brutto'])) {
448                //$bean->data = array_merge($bean->data, $res[0]);
449                $vnetto = $res[0]['netto_'];
450                $vbrutto = $res[0]['brutto'];
451                $netto_sum = '0';
452                $brutto_sum = '0';
453                $is_brutto = FALSE;
454                $vc_count = count($res) - (int)(!isset($res[0]['isneto']));
455                foreach($res as $vcost) {
456                    $netto_sum = bcadd(($vcost['isneto'] == 't') ? $vcost['amount'] : bcsub($vcost['amount'], $vcost['amtvat'], 3), $netto_sum, 3);
457                    $brutto_sum = bcadd(($vcost['isneto'] == 'f') ? $vcost['amount'] : bcadd($vcost['amount'], $vcost['amtvat'], 3), $brutto_sum, 3);
458                    $is_brutto = $is_brutto || ($vcost['isneto'] == 'f');
459                }
460                if ($vnetto) {
461                    $amount = $vnetto;
462
463                } else {
464                    $amount = $vbrutto;
465                    $bean->set('isneto', 'f');
466                }
467
468                $value = $amount;
469                if (empty($vnetto)) {
470                    $amount = bcsub($vbrutto, $brutto_sum, 3);
471                } elseif ($is_brutto) {
472                    $amount = bcsub($vbrutto, $brutto_sum, 3);
473                    $amount = bcdiv($amount, (string)(1 + (SystemRegistry::get('VatRates.DefaultVatRateValue', '23.0')/100)), 3);
474                } else {
475                    $amount = bcsub($vnetto, $netto_sum, 3);
476                }
477                $bean->set('netto_', round($vnetto, 2));
478                $bean->set('brutto', round($vbrutto, 2));
479                $bean->set('value_', round($value, 2));
480                $bean->set('amount', round($amount, 2));
481                $prtcip = round($amount * (100/$value), 2);
482                //$prtcip = (($vc_count % 2) ? floor($prtcip) : ceil($prtcip));
483                $bean->set('prtcip', ($prtcip > 100 OR $prtcip < 0) ? NULL : $prtcip);
484            }
485
486                        $res = $this->db->select('vatnote_costs', 'tovcid, count(*) as cc', 'tovcid IS NOT NULL AND doc_id='.$data['doc_id'].' GROUP BY tovcid ORDER BY cc DESC', FALSE, PGSQL_ASSOC, 0);
487
488                        if (is_array($res) AND $res[0]) {
489                                $bean->set('tovcid', $res[0]);
490                        }
491                        $bean->data['posnum'] = $bean->getNextPosNum();
492
493            if (!$orunid) {
494                require_once(MOD_PATH.'Employers/OrganizationUnits/OrganizationUnitBean.inc');
495                $orunid = OrganizationUnitBean::getDefaultAcorid(SysContext::$usr_info['orunid'][0]);
496
497                if (!is_numeric($orunid)) {
498                    $qq = $this->db->query('SELECT get_post('.SysContext::$usr_info['orunid'][0].') AS orunid', FALSE, PGSQL_ASSOC);
499                    if (isset($qq[0]['orunid'])) {
500                        $orunid = $qq[0]['orunid'];
501                    }
502                }
503            }
504
505            $yearSQLFilter = '';
506            if ((isset($data['year'])) AND (!empty($data['year']))) {
507                $yearSQLFilter = ' AND year__ = '.$data['year'];
508                $bean->data['year'] = $data['year'];
509            } else {
510                $yearSQLFilter = ' AND year__ = '.$currentYear;
511                $bean->data['year'] = $currentYear;
512            }
513
514                        // if VATNOTE_MPK_INIT then initialize MPK with proper orunid
515                        // TODO: should be done by dialog/widget custom scripts feature
516                        if (defined('VATNOTE_MPK_INIT')) {
517                                if (VATNOTE_MPK_INIT === 'adduid') {
518                                        $res = $this->db->select('users_link_org_units', 'orunid', 'usr_id = (SELECT adduid FROM documents WHERE doc_id = '.$data['doc_id'].') LIMIT 1', FALSE, PGSQL_NUM);
519                                        if (is_array($res)) {
520                                                $orunid = $res[0][0];
521                                        }
522                                }
523                        }
524
525            $orunidSQLFilter = $orunid ? 'orunid = '.$orunid.' AND ' : '';
526                        $res = $this->db->select('places_of_vcosts', 'povcid', ''.$orunidSQLFilter.'is_del IS NOT TRUE AND ent_id = '.SysContext::$ent_id.' '.$yearSQLFilter.' ORDER BY prior_ ASC LIMIT 1', FALSE, PGSQL_NUM, 0);
527                        if (is_array($res)) {
528                                $bean->data['povcid'] = $res[0];
529                        } elseif ($orunid) {
530                                // if MPK not found then try to set MPK of the parent ORGCELL
531                                $res = $this->db->query('SELECT get_post('.$orunid.')', FALSE, PGSQL_NUM);
532                                if (is_array($res) AND isset($res[0][0]) AND is_numeric($res[0][0]) AND $res[0][0] > 0) {
533                                        $res = $this->db->select('places_of_vcosts', 'povcid', 'orunid=(SELECT get_post('.$orunid.')::int4) AND is_del IS NOT TRUE AND ent_id = '.SysContext::$ent_id.' '.$yearSQLFilter.' ORDER BY prior_ ASC LIMIT 1', FALSE, PGSQL_NUM, 0);
534                                        if (is_array($res)) {
535                                                $bean->data['povcid'] = $res[0];
536                                        }
537                                }
538                        }
539
540            if (defined('VATNOTE_MPK_INIT') AND (VATNOTE_MPK_INIT === FALSE)) {
541                $bean->data['povcid'] = FALSE;
542            }
543
544            if ($bean->getb('isneto') AND defined('VATNOTE_COST_ADDITIONAL_FIELDS') AND (VATNOTE_COST_ADDITIONAL_FIELDS === TRUE)) {
545                $bean->data['vat_id'] = SystemRegistry::get('VatRates.DefaultVatRateID');
546
547                $amtvat = $this->calculateVat($bean->data);
548                $bean->set('amtvat', $amtvat);
549            }
550
551            if (isset($data['accdid']) AND is_numeric($data['accdid'])) {
552                $res = $this->db->select('types_of_accountants_doc', 'vtrgid, isneto', 'accdid = '.$data['accdid'].' AND ent_id = '.SysContext::$ent_id.' AND is_del IS NOT TRUE', FALSE, PGSQL_ASSOC);
553                if (isset($res[0]['vtrgid'])) {
554                    $bean->set('vtrgid', $res[0]['vtrgid']);
555                    $bean->set('isneto', $res[0]['isneto']);
556                }
557            }
558        }
559
560        if ((isset($data['fkelid'])) AND (is_array($data['fkelid'])) AND (!empty($data['fkelid'])) AND (!isset($data[$pkname]))) {
561            $this->loadFromSelProducts($data, $bean);
562        }
563
564                $this->setSData($bean->data);
565        $this->create();
566
567        $this->year__->addAssocArray($years, 'id', 'val');
568
569        $this->year__->selectItem($selectedYear);
570
571                $this->setData($bean->data);
572
573        $rst = $this->db->select('documents d', '(SELECT s.status FROM types_of_processes_states s WHERE s.tpstid = d.tpstid)', 'd.doc_id='.$bean->get('doc_id'), FALSE, 0,0);
574        if (is_array($rst) AND ($rst[0] == 'FINAL')) {
575            $readOnly = TRUE;
576        }
577
578        if (isset($this->featuresForm)) {
579            $fdata = array('clsnam' => MapService::VNCOST);
580                if (isset($data[$pkname])) {
581                $fdata['keyval'] = $data[$pkname];
582            }
583            $this->featuresForm->open($fdata);
584        }
585
586        $this->setReadOnly($readOnly);
587        }
588
589    public function close($destroy = TRUE) {
590
591        FieldsAccessManageDialog::unregister($this->name);
592
593        return parent::close($destroy);
594
595    }
596
597    /**
598     *
599     */
600    public function isDataValid($data) {
601
602
603                return TRUE;
604        }
605
606    /**
607     *
608     */
609    public function getNextPos() {
610        $data = $this->getSData();
611                if (!isset($data['doc_id'])) return FALSE;
612
613                $res = $this->db->select('vatnote_costs', 'max(posnum)::int + 1', 'doc_id='.$data['doc_id'], FALSE, PGSQL_NUM, 0);
614                if (is_array($res)) {
615
616                        $data = array(
617                                'posnum' => is_numeric($res[0]) ? $res[0] : 1,
618                        );
619
620                        return json_encode($data);
621                }
622                return FALSE;
623        }
624
625    /**
626     *
627     */
628    public function setAmountAll() {
629        $data = $this->getSData();
630                if (!isset($data['doc_id'])) return FALSE;
631
632                $res = $this->db->select('vatnote', 'netto_', 'doc_id='.$data['doc_id'], FALSE, PGSQL_NUM, 0);
633                if (is_array($res)) {
634
635                        $data = array(
636                                'prtcip' => 100,
637                                'amount' => is_numeric($res[0]) ? $res[0] : 0,
638                        );
639
640                        return json_encode($data);
641                }
642                return FALSE;
643        }
644
645
646
647    public function doSave($param = 0) {
648
649                $data = $this->getSData();
650
651        $doNotClose = (bool)$param;
652
653                $res = $this->save();
654
655                if (!$doNotClose) {
656                        $this->close();
657                        JScript::registerOnLoad('s_eval('.$this->appName.'.afterSubmit);Dialog.closeCallback(0,\''.$this->name.'\');');
658                } else {
659            JScript::registerOnLoad('s_eval('.$this->appName.'.afterSubmit)');
660
661                    if ($res AND $param AND $doNotClose) {
662
663                if (isset($this->featuresForm)) {
664                    $this->featuresForm->close();
665                }
666                        $data = $this->getSData();
667                    $this->open($data);
668
669                Jscript::addBefore('this.sender=\''.$this->name.'\';callback=Dialog.showCallback;');
670
671                return $this->toHtml(1);
672                    }
673                }
674        }
675
676
677
678    /**
679     *
680     */
681    public function save() {
682                $data = $this->getData();
683
684        $fkElements = isset($data['fkelid']) ? $data['fkelid'] : FALSE;
685
686                $bean = new VatNoteCost();
687                if ($this->readOnly OR !isset($data['doc_id']) OR (isset($data[$bean->getPkeyName()]) AND !UserRights::checkSysAcc('bswfms.extras.privilages.vatnote_edit'))) {
688                        $this->close();
689
690                        return FALSE;
691                }
692
693                $result = TRUE;
694                $ss = '';
695                if (isset($data[$bean->getPkeyName()])) {
696                        $bean = new VatNoteCost($data[$bean->getPkeyName()]);
697
698                        $ss = ' AND '.$bean->getPkeyName().'!='.$bean->getpKeyValue();
699                }
700        $res = $this->db->select('vatnote', 'amount, netto_, vat___, (SELECT 1 FROM vatnote_costs WHERE isneto IS FALSE AND doc_id='.$data['doc_id'].' LIMIT 1) as has_brutto', 'doc_id='.$data['doc_id'], FALSE, PGSQL_ASSOC);
701
702                if (is_array($res) AND is_numeric($res[0]['amount'])) {
703            $vatnote_brutto = $res[0]['amount'];
704            $vatnote_netto = $res[0]['netto_'];
705            $vatnote_amtvat = $res[0]['vat___'];
706            $amount = $data['amount'];
707            if ($data['isneto'] == 't') {
708                $vatnote_amount = $vatnote_netto;
709                $amount = round(bcadd($amount, (isset($data['amtvat']) ? $data['amtvat'] : 0), 3), 2);
710            } else {
711                $vatnote_amount = $vatnote_brutto;
712            }
713
714            $sum_str = $res[0]['has_brutto'] ? 'sum(CASE WHEN isneto THEN amount + amtvat ELSE amount END)' : 'sum(amount)';
715
716                        if (isset($data['povcid']) AND $data['povcid'] > 0) {
717                                $res2 = $this->db->select('vatnote_costs', $sum_str, 'doc_id='.$data['doc_id'].' AND povcid IS NOT NULL'.$ss, FALSE, PGSQL_NUM, 0);
718
719                                if (is_array($res2) AND round(abs((float)$res2[0] + (float)$amount), 2) > abs((float)$vatnote_brutto)) {
720                                        jscript::add('BalloonHint.showOn($(\''.$this->name.'lremark\'),\'\', \''.sprintf(Translator::translateJS('Nie można dodać kosztu o wartości %.2f, ponieważ suma wszystkich kosztów dla %s, przekroczy wartość %s (%.2f) faktury.'), $data['amount'], Translator::translateJS('MPK'), (($data['isneto'] == 't') ? 'netto' : 'brutto'), $vatnote_amount).'\', 300, null, BHS_MUSTBECLOSED|BHS_NOARROW, BHP_BOTTOM, 0,0,BHM_WARNING)');
721                                        return FALSE;
722                                }
723                        }
724                        if (isset($data['tovcid']) AND $data['tovcid'] > 0) {
725                                $res2 = $this->db->select('vatnote_costs', $sum_str, 'doc_id='.$data['doc_id'].' AND tovcid IS NOT NULL'.$ss, FALSE, PGSQL_NUM, 0);
726
727                                if (is_array($res2) AND round(abs((float)$res2[0] + (float)$amount), 2) > abs((float)$vatnote_brutto)) {
728                                        jscript::add('BalloonHint.showOn($(\''.$this->name.'lremark\'),\'\', \''.sprintf(Translator::translateJS('Nie można dodać kosztu o wartości %.2f, ponieważ suma wszystkich kosztów dla %s, przekroczy wartość %s (%.2f) faktury.'), $data['amount'], Translator::translateJS('RK'), (($data['isneto'] == 't') ? 'netto' : 'brutto'), $vatnote_amount).'\', 300, null, BHS_MUSTBECLOSED|BHS_NOARROW, BHP_BOTTOM, 0,0,BHM_WARNING)');
729                                        return FALSE;
730                                }
731                        }
732                }
733                if (!$result) {
734                        return FALSE;
735                }
736        $bean->data = array_merge($bean->data, $data);
737
738        if ($bean->save()) {
739            if ($fkElements) {
740                foreach ($fkElements as $fkelid) {
741                    $bean->attachFkElement($fkelid);
742                }
743            }
744
745            if (isset($this->featuresForm)) {
746                $this->featuresForm->setKeyval($bean->get('vtcoid'));
747                $this->featuresForm->save();
748            }
749
750            //trzeba zbilansowac i jezeli suma bedzie sie roznic tylko 1gr to dodac jeden grosz do vatu dla tej pozycji jezeli netto lub ostatniej pozycji netto
751            $vcosts = $this->db->query('SELECT vc.vtcoid, vc.isneto, vc.amount, vc.amtvat FROM vatnote_costs vc WHERE vc.doc_id='.$data['doc_id'].' ORDER BY vtcoid ASC', FALSE, PGSQL_ASSOC);
752
753            if (is_array($vcosts) AND isset($vcosts[0]['amount'])) {
754                $netto_sum = '0';
755                $brutto_sum = '0';
756                $vat_sum = '0';
757                $has_brutto = FALSE;
758                $last_netto = NULL;
759                $vc_count = count($vcosts) - (int)(!isset($vcosts[0]['isneto']));
760                foreach($vcosts as $vcost) {
761                    $netto_sum = bcadd(($vcost['isneto'] == 't') ? $vcost['amount'] : bcsub($vcost['amount'], $vcost['amtvat'], 3), $netto_sum, 3);
762                    $brutto_sum = bcadd(($vcost['isneto'] == 'f') ? $vcost['amount'] : bcadd($vcost['amount'], $vcost['amtvat'], 3), $brutto_sum, 3);
763                    $vat_sum = bcadd($vcost['amtvat'], $vat_sum, 3);
764                    $has_brutto = $has_brutto || ($vcost['isneto'] == 'f');
765                    if ($vcost['isneto'] == 't') $last_netto = $vcost;
766                }
767                if (isset($vatnote_amtvat) AND (($vatdiff = abs(round((float)bcsub($vatnote_amtvat, $vat_sum, 3), 2))) == 0.01)) {
768                    $vcost['amtvat'] = round(bcadd($vcost['amtvat'], (string)$vatdiff, 3), 2);
769                    $this->db->update('vatnote_costs', $vcost, 'vtcoid = '.$vcost['vtcoid']);
770                }
771            }
772            $this->setSData(array_merge($this->getSData(), array('vtcoid' => $bean->get('vtcoid'))));
773            return $bean->get('vtcoid');
774                }
775
776                return FALSE;
777    }
778
779    /**
780         *
781         */
782    protected function create() {
783        if (!$this->isOpened()) {
784            return FALSE;
785        }
786
787        require_once('./classes/FeatureBox/FeaturesHelper.inc');
788
789        $data = $this->getSData();
790
791        if (FeaturesHelper::hasFeatures(MapService::VNCOST)) {
792            require_once(LIB_PATH.'widgets/NewPostPanel.inc');
793            require_once('./classes/FeatureBox/UniFeaturesForm.inc');
794
795            $this->tabPanel = new NewPostPanel($this->name.'tabPanel', NewPostPanel::STYLE2);
796            $this->tabPanel->top = '0px';
797            $this->tabPanel->left = '0px';
798            $this->add($this->tabPanel);
799
800            $this->tabOveral = &$this->tabPanel->addTab($this->name.'p1', Translator::translate('Ogólne'));
801            //$this->tabOveral->setRightsChecker(new EventFieldsRightsChecker(), FALSE);
802            $this->tabFeatures = &$this->tabPanel->addTab($this->name.'p2', Translator::translate('Cechy'));
803
804            $this->featuresForm = new UniFeaturesForm($this->name.'FF', Translator::translate('Cechy'), BS_NONE);
805            $this->featuresForm->top = '4px';
806            $this->featuresForm->left = '0px';
807
808            $this->tabFeatures->add($this->featuresForm);
809            $fieldsAccessObjName = $this->tabOveral->name.'_tab';
810            //$tab->onSelect = "if (typeof $flag == 'undefined') { App.{$this->featuresForm->name}.open_show(({contid:$contid,mode:'$mode'}).toJSONString()); } $flag = 1;";
811        } else {
812            $this->tabOveral = &$this;
813            $this->height = ((int)$this->height - 40).'px';
814            $fieldsAccessObjName = $this->name;
815        }
816
817        $this->tabOveral->setRightsChecker(new UniFieldsRightsChecker('VATNOTE_COST'), FALSE);
818
819        $bean = null;
820        if(isset($data['vtcoid'])) {
821            $bean = new VatNoteCost($data['vtcoid']);
822        }
823
824                $top = 8;
825                $int = 28;
826
827                $this->lisneto = new Label($this->name.'lisneto');
828                $this->lisneto->top = $top.'px';
829                $this->lisneto->left = '10px';
830                $this->lisneto->width = '90px';
831                $this->lisneto->height = '20px';
832                $this->lisneto->text = Translator::translate('Koszt liczony z').':';
833
834                $this->isneto = new RadioGroup2($this->name.'isneto', ' '.Translator::translate('Księguj jako').' ', FALSE);
835                $this->isneto->position = 'absolute';
836                $this->isneto->top = $top.'px';
837                $this->isneto->left = '100px';
838                $this->isneto->width = '220px';
839                $this->isneto->height = '20px';
840                $this->isneto->radioMode();
841
842        $radioButton1 = $this->isneto->addRadioButton('t', Translator::translate('netto'), TRUE, FALSE);
843        $radioButton2 = $this->isneto->addRadioButton('f', Translator::translate('brutto'), FALSE, FALSE);
844
845        if ((isset($data['netto_'])) AND (isset($data['brutto']))) {
846            $radioButton1->onClick = '$(\''.$this->name.'value_\').value = \''.$data['netto_'].'\'; App.'.$this->name.'onIsNettoChange(true);';
847            $radioButton2->onClick = '$(\''.$this->name.'value_\').value = \''.$data['brutto'].'\'; App.'.$this->name.'onIsNettoChange(false);';
848        }
849
850                $this->isneto->setCaptionStyle('text-align:left; padding:0 0 1px 3px;');
851        $this->isneto->setCaptionSide('right');
852                $this->isneto->update();
853
854        $top += $int;
855
856                $this->lalert = new Label($this->name.'lalert');
857                $this->lalert->top = $top.'px';
858                $this->lalert->left = '10px';
859                $this->lalert->width = ((int)$this->width-34).'px';
860                $this->lalert->height = '36px';
861                if (isset($data['vtcoid']) AND !UserRights::checkSysAcc('bswfms.extras.privilages.vatnote_edit')) {
862                        $top += 54 + $int;
863
864                        $this->lalert->text = '<table cellpadding=0 cellspacing=0><tr><td style="vertical-align:middle;"><img src="'.IMG_PATH.'MessageBox/info_n.png" class="I32" /></td><td style="vertical-align:middle; padding-left:14px;">'.Translator::translate('<b>Brak uprawnień do edycji kosztów.</b> Formularz będzie dostępny tylko do odczytu.').'</td></tr></table>';
865                } else {
866                        $top = 14 + $int;
867                }
868
869                $this->lposnum = new Label($this->name.'lposnum');
870                $this->lposnum->top = $top.'px';
871                $this->lposnum->left = '10px';
872                $this->lposnum->width = '80px';
873                $this->lposnum->height = '20px';
874                $this->lposnum->text = Translator::translate('Pozycja faktury').':';
875
876                $this->posnum = new TextInput($this->name.'posnum');
877                $this->posnum->setCssFormatting('', 'width:76px; top:'.$top.'px; left:100px; text-align:right; position:absolute; padding-right:20px;');
878                $this->posnum->setHTMLFormatting('autocomplete', 'off');
879                $this->posnum->setHTMLFormatting('onchange', '$(\''.$this->name.'prtcip\').value=\'\';');
880        $this->posnum->mode = 'positive_int';
881
882                $this->bPosnum = new IButton($this->name.'bPosnum');
883                $this->bPosnum->icon = 'toolbarIcons/add2.gif';
884                $this->bPosnum->top = $top.'px';
885                $this->bPosnum->left = '160px';
886                $this->bPosnum->width = '20px';
887                $this->bPosnum->height = '20px';
888                $this->bPosnum->style = 'line-height:18px;';
889                $this->bPosnum->addHTMLAttr('title', Translator::translate('Wstaw kolejny numer'));
890                $this->bPosnum->onClick = '$A1(\''.$this->name.'\',\''.$this->name.'\', 1, 0,\'loadDataFromJSON(text,\\\''.$this->name.'\\\');\');';
891
892                $this->lposnum2 = new Label($this->name.'lposnum2');
893                $this->lposnum2->top = ($top-6).'px';
894                $this->lposnum2->left = '190px';
895                $this->lposnum2->width = '';
896                $this->lposnum2->height = '36px';
897                $this->lposnum2->text = Translator::translate('Pozostaw pusty numer pozycji, jeżeli koszt dotyczy całości faktury.');
898
899        $top += $int+5;
900
901        $this->lyear_ = new Label($this->name.'lyear_');
902        $this->lyear_->top = $top.'px';
903        $this->lyear_->left = '10px';
904        $this->lyear_->width = '80px';
905        $this->lyear_->height = '20px';
906        $this->lyear_->text = Translator::translate('Rok obrach.').':';
907        $this->lyear_->helpText = Translator::translate('Rok obrachunkowy');
908
909        $this->year__ = new ModernSelect($this->name.'year__', NULL, FALSE, TRUE);
910        $this->year__->setCssFormatting('', 'width:60px; top: '.$top.'px; left:100px; text-align:right; position:absolute;');
911        $this->year__->setHTMLFormatting('onchange', 'STDLib.asyncSubmit($(\''.$this->name.'\'), \'A ku ku\');$A1(\''.$this->HWND.'\',\''.$this->name.'\',3,this.value,\'Dialog.showCallback(text, \\\''.$this->name.'\\\');\', 0, true);');
912        $this->year__->selectItemOnEvent();
913
914        $this->lprojid = new Label($this->name.'lprojid');
915        $this->lprojid->top = $top.'px';
916        $this->lprojid->left = '170px';
917        $this->lprojid->width = '80px';
918        $this->lprojid->height = '20px';
919        $this->lprojid->text = Translator::translate('Projekt').':';
920
921        $this->projid = new LookupWidget2($this->name.'projid', new ProjectsSearchEngine(), FALSE, TRUE);
922        $this->projid->width = '200px';
923        $this->projid->left = '220px';
924        $this->projid->top = $top.'px';
925        if (!defined('PROJECT_AND_MPK_AUTO_FILTER') OR (PROJECT_AND_MPK_AUTO_FILTER === TRUE)) {
926            $this->projid->setOnChange('STDLib.asyncSubmit($(\''.$this->name.'\'), \'A ku ku\');$A1(\''.$this->HWND.'\',\''.$this->name.'\',4,this.value,\'Dialog.showCallback(text, \\\''.$this->name.'\\\');\', 0, true);');
927        }
928        ProjectsLookupManager::manage($this->projid);
929
930        $top += $int+5;
931
932                $this->lpovcid = new Label($this->name.'lpovcid');
933                $this->lpovcid->top = $top.'px';
934                $this->lpovcid->left = '10px';
935                $this->lpovcid->width = '80px';
936                $this->lpovcid->height = '20px';
937                $this->lpovcid->text = Translator::translate('MPK').':';
938
939        // Build filterstring for places of vcosts selector
940        require_once(MOD_PATH.'Dictionaries/VatNote/services/VCostPlaceService.inc');
941        $vcostPlaceService = new VCostPlaceService();
942        $filterSQL = 'ent_id = '.SysContext::$ent_id.' AND year__ = '.$data['year'];
943        if(isset($data['acorid']) && $data['acorid'] && $vcostPlaceService->definedForAcorid($data['acorid'], $data['year'])) {
944            $filterSQL .= ' AND acorid = '.$data['acorid'];
945        } else {
946            $filterSQL .= ' AND acorid IS NULL';
947        }
948        if ($bean AND $bean->get('povcid')) {
949            $filterSQL = '(('.$filterSQL.') OR povcid = '.$bean->get('povcid').')';
950        }
951
952        if (UserRights::checkSysAcc('bswfms.extras.limitations.deny_select_mpk_no_acc')) {
953            $filterSQL .= ' AND (orunid IS NULL OR chkUsrOrgAcc('.SysContext::$usr_info['usr_id'].', orunid))';
954        }
955
956        if ((defined('MPK_STYLE')) AND (MPK_STYLE == 'ADVANCED')) {
957            require_once('./classes/LookupWidget/LookupWidget2.inc');
958            require_once('./classes/LookupWidget/PlacesOfVCosts/PlacesOfVCostsSearchEngine.inc');
959
960            $this->povcid = new LookupWidget2($this->name.'povcid', new PlacesOfVCostsSearchEngine(), FALSE, 1);
961            $this->povcid->top = $top.'px';
962            $this->povcid->left = '100px';
963            $this->povcid->width = '300px';
964            $this->povcid->height = '21px';
965            $this->povcid->setFilterString($filterSQL);
966
967            $ddHWND = Application::registerDialog(Application::getShortName('PlacesOfVCostsForm', 10), 'PlacesOfVCostsForm', MOD_PATH.'Dictionaries/VatNote/PlacesOfVCostsForm.inc');
968
969            $exSearch = new ImgFormButton(array(
970                'name' => $this->name . 'exSearch',
971                'image' => IMG_PATH.'toolbarIcons/list.gif',
972                'style' => 'position:absolute; top:'.$top.'px; left:400px;',
973                'title' => Translator::translate('Wyszukiwanie zaawansowane'),
974                'submit' => FALSE,
975                'script' => 'App.openDialogEx(\''.$ddHWND.'\', null, ({projid:$(\''.$this->projid->name.'\').value, year__:$(\''.$this->year__->name.'\').value, acorid:\''.(isset($data['acorid']) ? $data['acorid'] : NULL).'\',onAdd:\'App.'.$this->name.'onAdd\'}).toJSONString()); return false;'
976            ));
977
978            $this->tabOveral->add($exSearch);
979        } else {
980            $this->povcid = new DBSelect($this->name.'povcid');
981            $this->povcid->top = $top.'px';
982            $this->povcid->left = '100px';
983            $this->povcid->width = '320px';
984            $this->povcid->query = 'SELECT povcid,place_ || replace(COALESCE(\' - \' || dscrpt,\'\'),\'\\n\',\'<br>\') as txt FROM places_of_vcosts WHERE is_del IS NOT TRUE AND '.$filterSQL.' ORDER BY txt ASC';
985            if (UserRights::checkSysAcc('bswfms.settings.level1')) {
986                $this->povcid->dialogParams = 'year__:$(\''.$this->name.'year__\').value';
987                $this->povcid->dialogHWND = Application::registerDialog('CostPlaceForm', 'CostPlaceForm', MOD_PATH.'Dictionaries/VatNote/CostPlaceForm.inc', NULL, BS_DIALOG, '');
988            }
989
990        }
991        $top += $int;
992
993        $this->ltovcid = new Label($this->name.'ltovcid');
994        $this->ltovcid->top = $top.'px';
995                $this->ltovcid->left = '10px';
996                $this->ltovcid->width = '80px';
997                $this->ltovcid->height = '20px';
998                $this->ltovcid->text = Translator::translate('RK').':';
999
1000        // Build filterstring for types of vcosts selector
1001        require_once(MOD_PATH.'Dictionaries/VatNote/services/CostTypeService.inc');
1002        $costTypeService = new CostTypeService();
1003        $filterSQL = 'ent_id = '.SysContext::$ent_id.' AND year__ = '.$data['year'];
1004        if(isset($data['acorid']) && $data['acorid'] && $costTypeService->definedForAcorid($data['acorid'], $data['year'])) {
1005            $filterSQL .= ' AND acorid = '.$data['acorid'];
1006        } else {
1007            $filterSQL .= ' AND acorid IS NULL';
1008        }
1009        if ($bean AND $bean->get('tovcid')) {
1010            $filterSQL = '(('.$filterSQL.') OR tovcid = '.$bean->get('tovcid').')';
1011        }
1012
1013        if ((defined('RK_STYLE')) AND (RK_STYLE == 'ADVANCED')) {
1014            require_once('./classes/LookupWidget/LookupWidget2.inc');
1015            require_once('./classes/LookupWidget/TypesOfVCosts/TypesOfVCostsSearchEngine.inc');
1016
1017            $this->tovcid = new LookupWidget2($this->name.'tovcid', new TypesOfVCostsSearchEngine(), FALSE, 1);
1018            $this->tovcid->top = $top.'px';
1019            $this->tovcid->left = '100px';
1020            $this->tovcid->width = '300px';
1021            $this->tovcid->height = '21px';
1022            $this->tovcid->setFilterString($filterSQL);
1023
1024            $tovcHWND = Application::registerDialog(Application::getShortName('TypesOfVCostsForm', 10), 'TypesOfVCostsForm', MOD_PATH.'Dictionaries/VatNote/TypesOfVCostsForm.inc');
1025
1026            $tovcExSearch = new ImgFormButton(array(
1027                'name' => $this->name . 'tovcExSearch',
1028                'image' => IMG_PATH.'toolbarIcons/list.gif',
1029                'style' => 'position:absolute; top:'.$top.'px; left:400px;',
1030                'title' => Translator::translate('Wyszukiwanie zaawansowane'),
1031                'submit' => FALSE,
1032                'script' => 'App.openDialogEx(\''.$tovcHWND.'\', null, ({year__:$(\''.$this->year__->name.'\').value, acorid:\''.(isset($data['acorid']) ? $data['acorid'] : NULL).'\',onAdd:\'App.'.$this->name.'onTovcAdd\'}).toJSONString()); return false;'
1033            ));
1034
1035            $this->tabOveral->add($tovcExSearch);
1036        } else {
1037                $this->tovcid = new DBSelect($this->name.'tovcid');
1038                $this->tovcid->top = $top.'px';
1039                $this->tovcid->left = '100px';
1040                $this->tovcid->width = '320px';
1041            $this->tovcid->query = 'SELECT tovcid,COALESCE(type__, \'\') || replace(COALESCE(\' - \' || dscrpt,\'\'),\'\\n\',\' \') FROM types_of_vcosts WHERE tovcid NOT IN (SELECT prn_id FROM types_of_vcosts WHERE ent_id='.SysContext::$ent_id.' AND prn_id IS NOT NULL) AND is_del IS NOT TRUE AND '.$filterSQL.' ORDER BY type__ ASC, prior_ ASC';
1042            if (UserRights::checkSysAcc('bswfms.settings.level1')) {
1043                $this->tovcid->dialogParams = 'year__:$(\''.$this->name.'year__\').value';
1044                        $this->tovcid->dialogHWND = Application::registerDialog('CostTypeForm', 'CostTypeForm', MOD_PATH.'Dictionaries/VatNote/CostTypeForm.inc', NULL, BS_DIALOG, '');
1045            }
1046        }
1047
1048                $top += $int;
1049
1050                $this->ladanid = new Label($this->name.'ladanid');
1051                $this->ladanid->top = $top.'px';
1052                $this->ladanid->left = '10px';
1053                $this->ladanid->width = '80px';
1054                $this->ladanid->height = '20px';
1055        $this->ladanid->style = 'line-height: 18px;';
1056        $this->ladanid->text = ADDITIONAL_ANALYTICS_TEXT.':';
1057        $this->ladanid->helpText = ADDITIONAL_ANALYTICS_TEXT;
1058
1059        if ((defined('ADDITIONAL_ANALYTICS_STYLE')) AND (ADDITIONAL_ANALYTICS_STYLE == 'ADVANCED')) {
1060            require_once('./classes/LookupWidget/LookupWidget2.inc');
1061            require_once('./classes/LookupWidget/AdditionalAnalytics/AdditionalAnalyticsSearchEngine.inc');
1062
1063            $this->adanid = new LookupWidget2($this->name.'adanid', new AdditionalAnalyticsSearchEngine(), FALSE, 1);
1064            $this->adanid->top = $top.'px';
1065            $this->adanid->left = '100px';
1066            $this->adanid->width = '300px';
1067            $this->adanid->height = '21px';
1068            $this->adanid->setFilterString('year__ = '.$data['year'].'');
1069
1070            $aavcHWND = Application::registerDialog(Application::getShortName('TypesOfAdditionalAnalyticsForm'), 'TypesOfAdditionalAnalyticsForm', MOD_PATH.'Dictionaries/VatNote/TypesOfAdditionalAnalyticsForm.inc');
1071
1072            $aavcExSearch = new ImgFormButton(array(
1073                'name' => $this->name . 'aavcExSearch',
1074                'image' => IMG_PATH.'toolbarIcons/list.gif',
1075                'style' => 'position:absolute; top:'.$top.'px; left:400px;',
1076                'title' => Translator::translate('Wyszukiwanie zaawansowane'),
1077                'submit' => FALSE,
1078                'script' => 'App.openDialogEx(\''.$aavcHWND.'\', null, ({year__:$(\''.$this->year__->name.'\').value, onAdd:\'App.'.$this->name.'onAaAdd\'}).toJSONString()); return false;'
1079            ));
1080
1081            $this->tabOveral->add($aavcExSearch);
1082        } else {
1083            $this->adanid = new DBSelect($this->name.'adanid');
1084            $this->adanid->top = $top.'px';
1085            $this->adanid->left = '100px';
1086            $this->adanid->width = '320px';
1087            $this->adanid->query = 'SELECT adanid,actnbr || replace(COALESCE(\' - \' || dscrpt,\'\'),\'\\n\',\' \') AS dscrpt FROM additional_analytics WHERE is_del IS NOT TRUE AND ent_id='.SysContext::$ent_id.' AND year__ = '.$data['year'].' ORDER BY prior_ ASC';
1088            if (UserRights::checkSysAcc('bswfms.settings.level1')) {
1089                $this->adanid->dialogParams = 'year__:$(\''.$this->name.'year__\').value';
1090                $this->adanid->dialogHWND = Application::registerDialog('AdAnalFrm', 'AdditionalAnalyticsForm', MOD_PATH.'Dictionaries/VatNote/AdditionalAnalyticsForm.inc', NULL, BS_DIALOG, '');
1091            }
1092        }
1093
1094                $top += $int;
1095
1096                $this->lprtcip = new Label($this->name.'lprtcip');
1097                $this->lprtcip->top = $top.'px';
1098                $this->lprtcip->left = '10px';
1099                $this->lprtcip->width = '80px';
1100                $this->lprtcip->height = '20px';
1101                $this->lprtcip->text = Translator::translate('Udział').' (%):';
1102
1103                $this->prtcip = new TextInput($this->name.'prtcip');
1104                $this->prtcip->setCssFormatting('', 'width:85px; top:'.$top.'px; left:100px; text-align:right; position:absolute;');
1105                $this->prtcip->setHTMLFormatting('autocomplete', 'off');
1106                $this->prtcip->mode = 'positive_numeric';
1107
1108                $this->lprtcip2 = new Label($this->name.'lprtcip2');
1109                $this->lprtcip2->top = ($top-2).'px';
1110                $this->lprtcip2->left = '190px';
1111                $this->lprtcip2->width = '';
1112                $this->lprtcip2->height = '36px';
1113
1114                $value_ = new TextInput($this->name.'value_');
1115                $value_->setCssFormatting('', 'width:70px; text-align:right; position:relative;');
1116                $value_->setHTMLFormatting('autocomplete', 'off');
1117                $value_->mode = 'money';
1118                if (isset($data['value_']) AND $value_->getValue() === '') {
1119                        $value_->setValue($data['value_']);
1120                }
1121
1122                $top += $int;
1123
1124                $this->lamount = new Label($this->name.'lamount');
1125                $this->lamount->top = $top.'px';
1126                $this->lamount->left = '10px';
1127                $this->lamount->width = '80px';
1128                $this->lamount->height = '20px';
1129                $this->lamount->text = Translator::translate('Wartość').':';
1130
1131                $this->amount = new TextInput($this->name.'amount');
1132                $this->amount->setCssFormatting('', 'width:85px; top:'.$top.'px; left:100px; text-align:right; position:absolute;');
1133                $this->amount->setHTMLFormatting('autocomplete', 'off');
1134                $this->amount->mode = 'money';
1135        $calculateVatJSFun = '';
1136        if (defined('VATNOTE_COST_ADDITIONAL_FIELDS') AND (VATNOTE_COST_ADDITIONAL_FIELDS === TRUE)) {
1137            $calculateVatJSFun = 'App.'.$this->name.'calculateVat();';
1138        }
1139        $this->prtcip->setHTMLFormatting('onkeyup', 'this.onchange();');
1140                $this->prtcip->setHTMLFormatting('onchange', 'if(parseFloat2(this.value) > 100)this.value=100; $(\''.$this->amount->name.'\').value=bcround(bcmul(this.value,bcdiv($(\''.$value_->name.'\').value,100)),2);'.$calculateVatJSFun.'');
1141
1142                $this->amount->setHTMLFormatting('onkeyup', 'this.onchange();');
1143                $this->amount->setHTMLFormatting('onchange', '$(\''.$this->prtcip->name.'\').value=Math.min(100,bcround(bcmul(this.value, bcdiv(100,$(\''.$value_->name.'\').value)),2));'.$calculateVatJSFun.'');
1144
1145        $vatNoteDecHWND = Application::registerDialog(Application::getShortName('VNCDLG'.$this->name), 'VatNoteCostsDecompositionListDialog', MOD_PATH.'ADocuments/forms/VatNoteCostsDecompositionListDialog.inc');
1146        $vatNoteDecList = new IButton($this->name.'vatsum');
1147        $vatNoteDecList->icon = 'toolbarIcons/sumlist.gif';
1148        $vatNoteDecList->top = $top.'px';
1149        $vatNoteDecList->left = '184px';
1150        $vatNoteDecList->width = '20px';
1151        $vatNoteDecList->height = '20px';
1152        $vatNoteDecList->style = 'line-height:18px; border-radius:0 3px 3px 0;';
1153        $vatNoteDecList->addHTMLAttr('title', Translator::translate('Rozpis na pozycje'));
1154        if (isset($data['vtcoid'])) {
1155            $vatNoteDecList->onClick = 'App.openDialogEx(\''.$vatNoteDecHWND.'\', null, ({doc_id:'.$data['doc_id'].', vtcoid:'.$data['vtcoid'].', isneto:($(\''.$this->name.'isneto_t\').checked ? 1 : 0), parentHWND:\''.$this->name.'\'}).toJSONString());';
1156        } else {
1157            $msg = Translator::translate('Koszt musi zostać zapisany przed wprowadzeniem rozpisu.<br><br>Czy chcesz zapisać teraz?');
1158                $js = 'alertMessage(\''.$msg.'\',\'\',MB_YESNO,\'question.gif\',\'if (id==MB_YES){fireEvent2($(\\\''.$this->name.'[bSave]\\\'), \\\'click\\\');}\');';
1159            $vatNoteDecList->onClick = $js;
1160        }
1161
1162        $this->tabOveral->add($vatNoteDecList);
1163
1164                $value_->setHTMLFormatting('onkeyup', 'this.onchange();');
1165                $value_->setHTMLFormatting('onchange', '$(\''.$this->amount->name.'\').value=bcround(bcmul($(\''.$this->prtcip->name.'\').value,bcdiv(this.value,100)),2);'.$calculateVatJSFun.'');
1166
1167                $this->lprtcip2->text = '%&nbsp;&nbsp;'.sprintf(Translator::translate('z %s %s wartości faktury.'), $value_->toHtml(), (isset($data['cursmb']) ? $data['cursmb'] : ''));
1168
1169        if ((defined('VATNOTE_COST_ADDITIONAL_FIELDS')) AND (VATNOTE_COST_ADDITIONAL_FIELDS === TRUE)) {
1170            $top += $int;
1171
1172            $this->lvat_id = new Label($this->name.'lvat_id');
1173            $this->lvat_id->width = '70px';
1174            $this->lvat_id->height = '20px';
1175            $this->lvat_id->top = $top.'px';
1176            $this->lvat_id->left = '10px';
1177            $this->lvat_id->text = Translator::translate('VAT').':';
1178
1179            $this->vat_id = new ModernSelect($this->name.'vat_id');
1180            $this->vat_id->setCSSFormatting(NULL, 'text-align:right;width:85px; height:20px; left: 100px; top:'.$top.'px; position:absolute;');
1181            $this->vat_id->addItem(NULL, '--'.Translator::translate('wybierz').'--');
1182            $this->vat_id->addArray(VatRatesService::getDefinedVATRates());
1183            $this->vat_id->selectItemOnEvent();
1184            $this->vat_id->setHTMLFormatting('onchange', 'App.'.$this->name.'calculateVat();');
1185
1186            $this->lamtvat = new Label($this->name.'lamtvat');
1187            $this->lamtvat->top = $top.'px';
1188            $this->lamtvat->left = '190px';
1189            $this->lamtvat->height = '20px';
1190            $this->lamtvat->width = '85px';
1191            $this->lamtvat->text = Translator::translate('Wartość VAT').':';
1192
1193            $this->amtvat = new TextInput($this->name.'amtvat', 0);
1194            $this->amtvat->setCSSFormatting(NULL, 'text-align:right; width:85px; height:20px; left: 270px; top:'.$top.'px; position:absolute;');
1195            $this->amtvat->mode = 'money';
1196            $this->amtvat->setReadOnly(FALSE);
1197
1198            $top += $int;
1199
1200            $this->ltaxdat = new Label($this->name.'ltaxdat');
1201            $this->ltaxdat->top = $top.'px';
1202            $this->ltaxdat->left = '10px';
1203            $this->ltaxdat->width = '80px';
1204            $this->ltaxdat->height = '16px';
1205            $this->ltaxdat->text = Translator::translate('Data obowiązku').':';
1206            $this->ltaxdat->helpText = Translator::translate('Data obowiązku podatkowego');
1207
1208            //
1209            $this->taxdat = new CalendarInput($this->name.'taxdat');
1210            $this->taxdat->top = $top.'px';
1211            $this->taxdat->left = '100px';
1212            $this->taxdat->width = '100px';
1213            $this->taxdat->setFormat('y-m-d');
1214            $this->taxdat->withClearButton = TRUE;
1215            $this->taxdat->setHtmlFormatting('onkeydown', 'return submitOnKey(event, 13);');
1216            $this->taxdat->submitOnClose = FALSE;
1217        }
1218
1219        $top += $int;
1220
1221        if (UserRights::checkSysAcc('bswfms.processes.read')) {
1222                        include_once('./classes/LookupWidget/LookupWidget2.inc');
1223                include_once('./classes/LookupWidget/Processes/EditableProcessesSearchEngine.inc');
1224
1225                        $this->lprc_id = new Label($this->name.'lprc_id');
1226                        $this->lprc_id->top = $top.'px';
1227                        $this->lprc_id->left = '10px';
1228                        $this->lprc_id->width = '80px';
1229                        $this->lprc_id->height = '20px';
1230                        $this->lprc_id->text = Translator::translate('Sprawa').':';
1231
1232                $this->prc_id = new LookupWidget2($this->name.'prc_id', new EditableProcessesSearchEngine());
1233                $this->prc_id->top = $top.'px';
1234                $this->prc_id->left = '100px';
1235                $this->prc_id->width = '320px';
1236
1237            $top += $int;
1238        }
1239
1240        $this->lvtrgid = new Label($this->name.'lvtrgid');
1241        $this->lvtrgid->top = $top.'px';
1242        $this->lvtrgid->left = '10px';
1243        $this->lvtrgid->width = '80px';
1244        $this->lvtrgid->height = '20px';
1245        $this->lvtrgid->text = Translator::translate('Rejestr VAT').':';
1246
1247        require_once('./classes/LookupWidget/LookupWidget2.inc');
1248        require_once('./classes/LookupWidget/VatRegisters/VatRegistersSearchEngine.inc');
1249        require_once('./classes/LookupWidget/VatRegisters/VatRegistersLookupManager.inc');
1250        $this->vtrgid = new LookupWidget2($this->name.'vtrgid', new VatRegistersSearchEngine());
1251        $this->vtrgid->top = $top.'px';
1252        $this->vtrgid->left = '100px';
1253        $this->vtrgid->width = '320px';
1254        VatRegistersLookupManager::manage($this->vtrgid);
1255        /* #8144
1256        $top += $int;
1257        $this->lnkup__ = new Label($this->name.'lnkup__');
1258        $this->lnkup__->width = '90px';
1259        $this->lnkup__->height = '20px';
1260        $this->lnkup__->top = $top.'px';
1261        $this->lnkup__->left = '10px';
1262        $this->lnkup__->text = Translator::translate('Podlega odl.').':';
1263        $this->lnkup__->helpText = Translator::translate('Podlega odliczeniu');
1264
1265                $this->nkup__ = new RadioGroup2($this->name.'nkup__', ' '.Translator::translate('Księguj jako').' ', FALSE);
1266                $this->nkup__->position = 'absolute';
1267                $this->nkup__->top = $top.'px';
1268                $this->nkup__->left = '100px';
1269                $this->nkup__->width = '220px';
1270                $this->nkup__->height = '20px';
1271                $this->nkup__->radioMode();
1272
1273        $radioButton1 = $this->nkup__->addRadioButton('t', Translator::translate('Tak'), TRUE, FALSE);
1274        $radioButton2 = $this->nkup__->addRadioButton('f', Translator::translate('Nie'), FALSE, FALSE);
1275
1276                $this->nkup__->setCaptionStyle('text-align:left; padding:0 0 1px 3px;');
1277        $this->nkup__->setCaptionSide('right');
1278                $this->nkup__->update();
1279        */
1280
1281        $top += $int;
1282                $this->laccnum = new Label($this->name.'laccnum');
1283                $this->laccnum->top = $top.'px';
1284                $this->laccnum->left = '10px';
1285                $this->laccnum->width = '80px';
1286                $this->laccnum->height = '20px';
1287                $this->laccnum->text = Translator::translate('Inne konto').':';
1288
1289                $this->accnum = new TextInput($this->name.'accnum');
1290                $this->accnum->setCssFormatting('', 'width:320px; top:'.$top.'px; left:100px; text-align:right; position:absolute;');
1291                $this->accnum->setHTMLFormatting('autocomplete', 'on');
1292
1293        $top += $int;
1294                $this->lremark = new Label($this->name.'lremark');
1295                $this->lremark->top = $top.'px';
1296                $this->lremark->left = '10px';
1297                $this->lremark->width = '80px';
1298                $this->lremark->height = '20px';
1299                $this->lremark->text = Translator::translate('Opis').':';
1300
1301                $this->remark = new Textarea($this->name.'remark');
1302                $this->remark->setCssFormatting('', 'width:320px; height:60px; top:'.$top.'px; left:100px; position:absolute;');
1303
1304                $top += $int+40;
1305
1306        if (method_exists($this->povcid, 'update')) {
1307            $this->povcid->update();
1308        }
1309        if (method_exists($this->tovcid, 'update')) {
1310            $this->tovcid->update();
1311        }
1312
1313        if (method_exists($this->adanid, 'update')) {
1314            $this->adanid->update();
1315        }
1316
1317        $this->width = '435px';
1318        if (isset($this->tabPanel)) {
1319            $this->height = ($top + 110).'px';
1320            $this->tabPanel->width = ((int)$this->width - 4).'px';
1321            $this->tabPanel->height = ((int)$this->height - 70).'px';
1322            $this->featuresForm->width = ((int)$this->tabPanel->width).'px';
1323            $this->featuresForm->height = ((int)$this->tabPanel->height-35).'px';
1324        } else {
1325            $this->height = ($top + 70).'px';
1326        }
1327
1328        $this->tabOveral->add($this->lalert);
1329
1330        $this->tabOveral->add($this->lisneto);
1331        $this->tabOveral->add($this->isneto, 'isneto');
1332        $this->lisneto->setLabelFor($this->isneto);
1333
1334        $this->tabOveral->add($this->lposnum);
1335        $this->tabOveral->add($this->posnum, 'posnum');
1336        $this->lposnum->setLabelFor($this->posnum);
1337
1338        $this->tabOveral->add($this->bPosnum);
1339        if (!$this->readOnly) {
1340            $this->tabOveral->add($this->lposnum2);
1341        }
1342
1343        $this->tabOveral->add($this->lyear_);
1344        $this->tabOveral->add($this->year__);
1345        $this->lyear_->setLabelFor($this->year__);
1346
1347        $this->tabOveral->add($this->lprojid);
1348        $this->tabOveral->add($this->projid, 'projid');
1349        $this->lprojid->setLabelFor($this->projid);
1350
1351        $this->tabOveral->add($this->lpovcid);
1352        $this->tabOveral->add($this->povcid, 'povcid');
1353        $this->lpovcid->setLabelFor($this->povcid);
1354
1355        $this->tabOveral->add($this->ltovcid);
1356        $this->tabOveral->add($this->tovcid, 'tovcid');
1357        $this->ltovcid->setLabelFor($this->tovcid);
1358
1359        $this->tabOveral->add($this->ladanid);
1360        $this->tabOveral->add($this->adanid, 'adanid');
1361        $this->ladanid->setLabelFor($this->adanid);
1362
1363        $this->tabOveral->add($this->lprtcip);
1364        $this->tabOveral->add($this->prtcip, 'prtcip');
1365        $this->tabOveral->add($this->lprtcip2);
1366        $this->lprtcip->setLabelFor($this->prtcip);
1367
1368        //$this->tabOveral->add($this->bAll);
1369        $this->tabOveral->add($this->lamount);
1370        $this->tabOveral->add($this->amount, 'amount');
1371        $this->lamount->setLabelFor($this->amount);
1372
1373        if (defined('VATNOTE_COST_ADDITIONAL_FIELDS') AND (VATNOTE_COST_ADDITIONAL_FIELDS === TRUE)) {
1374            $this->tabOveral->add($this->lvat_id);
1375            $this->tabOveral->add($this->vat_id, 'vat_id');
1376            $this->lvat_id->setLabelFor($this->vat_id);
1377
1378            $this->tabOveral->add($this->lamtvat);
1379            $this->tabOveral->add($this->amtvat, 'amtvat');
1380            $this->lamtvat->setLabelFor($this->amtvat);
1381
1382            $this->tabOveral->add($this->ltaxdat);
1383            $this->tabOveral->add($this->taxdat, 'taxdat');
1384            $this->ltaxdat->setLabelFor($this->taxdat);
1385        }
1386                if (isset($this->prc_id)) {
1387                $this->tabOveral->add($this->lprc_id);
1388                $this->tabOveral->add($this->prc_id, 'prc_id');
1389            $this->lprc_id->setLabelFor($this->prc_id);
1390                }
1391
1392        $this->tabOveral->add($this->lvtrgid);
1393        $this->tabOveral->add($this->vtrgid, 'vtrgid');
1394        $this->lvtrgid->setLabelFor($this->vtrgid);
1395
1396        /*
1397        $this->add($this->lnkup__);
1398        $this->add($this->nkup__, 'nkup__');
1399        */
1400
1401        $this->tabOveral->add($this->laccnum);
1402        $this->tabOveral->add($this->accnum, 'accnum');
1403        $this->laccnum->setLabelFor($this->accnum);
1404
1405        $this->tabOveral->add($this->lremark);
1406        $this->tabOveral->add($this->remark, 'remark');
1407        $this->lremark->setLabelFor($this->remark);
1408
1409        if (isset($ddHWND)) {
1410            JScript::add('App.'.$this->name.'onAdd = function(povcid) {
1411                $A1(\''.$this->HWND.'\',\''.$this->name.'\', '.(int)array_search('loadMPK', self::$cMethods).', povcid,\'if(text)$(\\\''.$this->povcid->name.'\\\').innerHTML=text;\');
1412            }');
1413        }
1414
1415        if (isset($tovcHWND)) {
1416            JScript::add('App.'.$this->name.'onTovcAdd = function(tovcid) {
1417                $A1(\''.$this->HWND.'\',\''.$this->name.'\', '.(int)array_search('loadRK', self::$cMethods).', tovcid,\'if(text)$(\\\''.$this->tovcid->name.'\\\').innerHTML=text;\',0,true);
1418            }');
1419        }
1420
1421        if (isset($aavcHWND)) {
1422            JScript::add('App.'.$this->name.'onAaAdd = function(adanid) {
1423                $A1(\''.$this->HWND.'\',\''.$this->name.'\', '.(int)array_search('loadAA', self::$cMethods).', adanid,\'if(text)$(\\\''.$this->adanid->name.'\\\').innerHTML=text;\',0,true);
1424            }');
1425        }
1426
1427        JScript::add('App.'.$this->name.'onIsNettoChange = function(isneto) {
1428            var af = '.((defined('VATNOTE_COST_ADDITIONAL_FIELDS') AND (VATNOTE_COST_ADDITIONAL_FIELDS === TRUE)) ? 'true' : 'false').';
1429            if (af) {
1430                if (!isneto) {
1431                    $(\''.$this->name.'amount\').value = bcadd($(\''.$this->name.'amount\').value, $(\''.$this->name.'amtvat\').value, 2);
1432                } else {
1433                    $(\''.$this->name.'amount\').value = bcsub($(\''.$this->name.'amount\').value, $(\''.$this->name.'amtvat\').value, 2);
1434                }
1435            } else {
1436                fireEvent2($(\''.$this->name.'value_\'), \'change\');
1437            }
1438        }');
1439
1440        if (defined('VATNOTE_COST_ADDITIONAL_FIELDS') AND (VATNOTE_COST_ADDITIONAL_FIELDS === TRUE)) {
1441            JScript::add('App.'.$this->name.'calculateVat = function() {
1442                var vat_id = $(\''.$this->name.'vat_id\') ? $(\''.$this->name.'vat_id\').value : false;
1443                if (vat_id) {
1444                    STDLib.asyncSubmit(\''.$this->name.'\'); $A1(\''.$this->HWND.'\', \''.$this->name.'\', '.(int)array_search('calculateVat', self::$cMethods).',0,\'$(\\\''.$this->amtvat->name.'\\\').value=text;\', 0, false)
1445                }
1446                return false;
1447            };');
1448        }
1449
1450        FieldsAccessManageDialog::registerFor($this->tabOveral, $fieldsAccessObjName);
1451
1452        $this->addButtonsPanel(array('bOk', 'bSave','bCancel'));
1453        $this->bSave->style = 'left: 0px; margin-right: 135px; width: 85px;';
1454    }
1455
1456}
1457?>