PageRenderTime 101ms CodeModel.GetById 57ms app.highlight 37ms RepoModel.GetById 1ms app.codeStats 1ms

/src/mpv5/db/objects/SubItem.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 962 lines | 666 code | 98 blank | 198 comment | 108 complexity | 5cc44dcfceb0c86ec3fce7ddc66b203a MD5 | raw file
  1/*
  2 *  This file is part of YaBS.
  3 *
  4 *      YaBS is free software: you can redistribute it and/or modify
  5 *      it under the terms of the GNU General Public License as published by
  6 *      the Free Software Foundation, either version 3 of the License, or
  7 *      (at your option) any later version.
  8 *
  9 *      YaBS is distributed in the hope that it will be useful,
 10 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 11 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 12 *      GNU General Public License for more details.
 13 *
 14 *      You should have received a copy of the GNU General Public License
 15 *      along with YaBS.  If not, see <http://www.gnu.org/licenses/>.
 16 */
 17package mpv5.db.objects;
 18
 19import java.util.Arrays;
 20import mpv5.db.common.Triggerable;
 21import java.math.BigDecimal;
 22import java.util.ArrayList;
 23import java.util.Collections;
 24import java.util.Comparator;
 25import java.util.Date;
 26import java.util.HashMap;
 27import java.util.LinkedList;
 28import java.util.List;
 29import javax.swing.JButton;
 30import javax.swing.JComponent;
 31import mpv5.db.common.Context;
 32import mpv5.db.common.DatabaseObject;
 33import mpv5.db.common.NodataFoundException;
 34import mpv5.db.common.QueryCriteria;
 35import mpv5.db.common.QueryHandler;
 36import mpv5.globals.Constants;
 37import mpv5.globals.GlobalSettings;
 38import mpv5.globals.Headers;
 39import mpv5.handler.VariablesHandler;
 40import mpv5.logging.Log;
 41import mpv5.ui.panels.ItemPanel;
 42import mpv5.utils.models.MPComboBoxModelItem;
 43import mpv5.utils.models.MPTableModel;
 44import mpv5.utils.numberformat.FormatNumber;
 45
 46/**
 47 *
 48 *  
 49 */
 50public final class SubItem extends DatabaseObject implements Triggerable {
 51
 52    public static final int TYPE_TEXT = 1;
 53    public static final int TYPE_PRODUCT = 2;
 54    public static final int TYPE_NORMAL = 0;
 55    private static final long serialVersionUID = 1L;
 56
 57    public static LinkedList<SubItem> saveModel(Item dataOwner, MPTableModel model, boolean deleteRemovedSubitems, boolean cloneSubitems) {
 58        List<Object[]> rowsl = model.getValidRows(new int[]{4});
 59        LinkedList<SubItem> items = new LinkedList<SubItem>();
 60        Log.Debug(SubItem.class, "Rows found: " + rowsl.size());
 61        for (int i = 0; i < rowsl.size(); i++) {
 62            Object[] row = rowsl.get(i);
 63            for (int j = 0; j < row.length; j++) {
 64                if (row[j] == null) {
 65                    row[j] = "";
 66                }
 67            }
 68            SubItem it = new SubItem();
 69            it.setOrdernr(i);
 70            Log.Print(Arrays.asList(row));
 71            try {
 72                if (!cloneSubitems && row[0] != null && Integer.valueOf(row[0].toString()).intValue() > 0) {
 73                    it.setIDS(Integer.valueOf(row[0].toString()).intValue());
 74                } else {
 75                    it.setIDS(-1);
 76                }
 77            } catch (Exception e) {
 78                Log.Debug(SubItem.class, e.getMessage());
 79            }
 80            it.setCname(row[14].toString());
 81            it.setItemsids(dataOwner.__getIDS());
 82            it.setCountvalue(new BigDecimal(row[1].toString()));
 83            it.setDatedelivery(dataOwner.__getDatetodo());
 84            it.setDescription(row[4].toString());
 85            it.setExternalvalue(new BigDecimal(row[5].toString()));
 86            it.setInternalvalue(new BigDecimal(row[5].toString()));//not supported yet
 87            it.setMeasure(row[3].toString());
 88
 89            if (row[10] instanceof Product) {
 90                try {
 91                    it.setOriginalproductsids(((Product) row[10]).__getIDS());
 92                } catch (Exception e) {
 93                    Log.Debug(e);
 94                }
 95            } else {
 96            }
 97            it.setLinkurl((row[12 + 1].toString()));
 98            it.setQuantityvalue(new BigDecimal(row[2].toString()));
 99            it.setTaxpercentvalue(new BigDecimal(row[6].toString()));
100            it.setDiscount(new BigDecimal(row[15].toString()));
101            calculate(it);
102
103            if (!it.isExisting()) {
104                it.setDateadded(new Date());
105                it.setGroupsids(dataOwner.__getGroupsids());
106            }
107            it.save(true);
108            items.add(it.getOrdernr(), it);
109        }
110
111        if (deleteRemovedSubitems) {
112            for (int i = 0; i < deletionQueue.size(); i++) {
113                try {
114                    QueryHandler.delete(SubItem.getObject(Context.getSubItem(), deletionQueue.get(i)));
115                } catch (NodataFoundException ex) {
116                    Log.Debug(ex);
117                }
118            }
119        }
120        deletionQueue.clear();
121        return items;
122
123    }
124
125    /**
126     * Save the model of SubItems
127     * @param dataOwner
128     * @param model
129     * @param deleteRemovedSubitems
130     * @return
131     */
132    public static List<SubItem> saveModel(Item dataOwner, MPTableModel model, boolean deleteRemovedSubitems) {
133        return saveModel(dataOwner, model, deleteRemovedSubitems, false);
134    }
135
136    /**
137     * Convert the model to a list of String arrays
138     * @param dataOwner
139     * @param model
140     * @param t
141     * @return
142     */
143    public static LinkedList<String[]> convertModel(Item dataOwner, MPTableModel model, Template t) {
144        List<Object[]> rowsl = model.getValidRows(new int[]{4});
145        LinkedList<String[]> rowsk = new LinkedList<String[]>();
146        Log.Debug(SubItem.class, "Rows found: " + rowsl.size());
147        for (int i = 0; i < rowsl.size(); i++) {
148            Object[] row = rowsl.get(i);
149
150            for (int j = 0; j < row.length; j++) {
151                if (row[j] == null) {
152                    row[j] = "";
153                }
154            }
155
156            final SubItem it = new SubItem();
157            it.setOrdernr(i);
158            try {
159                if (row[0] != null && Integer.valueOf(row[0].toString()).intValue() > 0) {
160                    it.setIDS(Integer.valueOf(row[0].toString()).intValue());
161                } else {
162                    it.setIDS(-1);
163                }
164            } catch (Exception e) {
165                Log.Debug(SubItem.class, e.getMessage());
166            }
167            it.setCname(row[14].toString());
168            it.setItemsids(dataOwner.__getIDS());
169            it.setCountvalue(new BigDecimal(row[1].toString()));
170            it.setDatedelivery(dataOwner.__getDatetodo());
171            it.setDescription(row[4].toString());
172            it.setExternalvalue(new BigDecimal(row[5].toString()));
173            it.setInternalvalue(new BigDecimal(row[5].toString()));//not supported yet
174            it.setMeasure(row[3].toString());
175            it.setOriginalproductsids(Integer.valueOf(row[10].toString()));
176            if (row[10] instanceof Product) {
177                try {
178                    it.setOriginalproductsids(((Product) row[10]).__getIDS());
179                } catch (Exception e) {
180                    Log.Debug(e);
181                }
182            }
183            it.setQuantityvalue(new BigDecimal(row[2].toString()));
184            it.setTaxpercentvalue(new BigDecimal(row[6].toString()));
185            it.setLinkurl((row[12 + 1].toString()));
186            it.setDiscount(new BigDecimal(row[15].toString()));
187
188            calculate(it);
189
190            if (!it.isExisting()) {
191                it.setDateadded(new Date());
192                it.setGroupsids(dataOwner.__getGroupsids());
193            }
194
195//            it.save();
196            rowsk.add(it.getOrdernr(), it.toStringArray());
197        }
198
199        return rowsk;
200    }
201    private static List<Integer> deletionQueue = new ArrayList<Integer>();
202
203    /**
204     * Mark a subitem for deletion
205     * @param valueAt INT or Entity
206     */
207    public static void addToDeletionQueue(Object valueAt) {
208        Log.Debug(SubItem.class, "Adding to deletionqueue: " + valueAt);
209        if (valueAt != null) {
210            try {
211                Integer isd = Integer.valueOf(valueAt.toString());
212                deletionQueue.add(isd);
213            } catch (NumberFormatException numberFormatException) {
214                Integer isd = ((Entity) valueAt).getValue();
215                deletionQueue.add(isd);
216            }
217        }
218    }
219
220    /**
221     * UN-Mark a subitem for deletion
222     * @param valueAt INT or Entity
223     */
224    public static void removeFromDeletionQueue(Object valueAt) {
225        Log.Debug(SubItem.class, "Removing from deletionqueue: " + valueAt);
226        if (valueAt != null) {
227            try {
228                Integer isd = Integer.valueOf(valueAt.toString());
229                deletionQueue.remove(isd);
230            } catch (NumberFormatException numberFormatException) {
231                Integer isd = ((Entity) valueAt).getValue();
232                deletionQueue.add(isd);
233            }
234        }
235    }
236    private int itemsids;
237    private int ordernr;
238    private int inttype;
239    private int originalproductsids;
240    private BigDecimal countvalue = BigDecimal.ZERO;
241    private BigDecimal quantityvalue = BigDecimal.ZERO;
242    private String measure = "";
243    private String description = "";
244    private String linkurl = "";
245    private BigDecimal internalvalue = BigDecimal.ZERO;
246    private BigDecimal externalvalue = BigDecimal.ZERO;
247    private BigDecimal taxpercentvalue = BigDecimal.ZERO;
248    private BigDecimal totalnetvalue = BigDecimal.ZERO;
249    private BigDecimal totalbrutvalue = BigDecimal.ZERO;
250    private Date datedelivery;
251    private BigDecimal totaltaxvalue = BigDecimal.ZERO;
252    private BigDecimal discount = BigDecimal.ZERO;
253    private BigDecimal discvalue = BigDecimal.ZERO;
254
255    public SubItem() {
256        setContext(Context.getSubItem());
257    }
258
259    /**
260     *
261     * @return
262     */
263    public static SubItem getDefaultItem() {
264        SubItem i = new SubItem();
265
266        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("defunit")) {
267            String defunit = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("defunit");
268            i.setMeasure(defunit);
269        }
270        BigDecimal deftax = BigDecimal.ZERO;
271        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("deftax")) {
272            int taxid = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("deftax", new Integer(0));
273            deftax = Tax.getTaxValue(taxid);
274        }
275        i.setTaxpercentvalue(deftax);
276
277        BigDecimal defdiscount = BigDecimal.ZERO;
278        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("defdiscount")) {
279            defdiscount = new BigDecimal(mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("defdiscount"));
280        }
281        i.setDiscount(defdiscount);
282
283        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("defcount")) {
284            Double defcount = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("defcount", 0d);
285            i.setQuantityvalue(new BigDecimal(defcount.toString()));
286        } else {
287            i.setQuantityvalue(BigDecimal.ONE);
288        }
289
290        return i;
291    }
292
293    /**
294     *
295     * @param product 
296     */
297    public SubItem(Product product) {
298        this();
299        setCname(product.__getCname());
300        setDateadded(new Date());
301        setDatedelivery(new Date());
302
303////////////////format///////////////////////////////////////////////////////////
304        Context contextl = product.getContext();
305        String params = "cname";
306        String vars = null;
307        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty(contextl + mpv5.ui.beans.LightMPComboBox.VALUE_SEARCHFIELDS)
308                && mpv5.db.objects.User.getCurrentUser().getProperties().getProperty(contextl + mpv5.ui.beans.LightMPComboBox.VALUE_SEARCHFIELDS).contains("_$")) {
309            try {
310                params = "ids";
311                vars = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty(contextl + mpv5.ui.beans.LightMPComboBox.VALUE_SEARCHFIELDS);
312                String[] vaars = vars.split("_\\$");
313
314                for (int i = 0; i < vaars.length; i++) {
315                    try {
316                        if (vaars[i] != null && vaars[i].contains("$_")) {
317                            params += "," + vaars[i].split("\\$_")[0].replace(",", "").replace("'", "`");
318                        }
319                    } catch (Exception e) {
320                        Log.Debug(e);
321                    }
322                }
323
324                QueryCriteria qc = new QueryCriteria("ids", product.__getIDS());
325                Object[][] result = QueryHandler.instanceOf().clone(Context.getProduct()).select(params, qc);
326
327                String formatString = vars;
328                if (formatString != null) {
329                    vaars = formatString.split("_\\$");
330                    Log.Debug(MPComboBoxModelItem.class, "Length of var string: " + vaars.length);
331                }
332                String x = "";
333                String format = formatString;
334                for (int j = 1; j < result[0].length; j++) {
335                    String k = String.valueOf(result[0][j]);
336                    if (format == null) {
337                        x += k;
338                    } else {
339                        try {
340                            format = format.replaceFirst("_\\$(.*?)\\$_", k);
341                        } catch (Exception e) {
342                            Log.Debug(e);
343                        }
344                        x = format;
345                    }
346                }
347
348                setDescription(VariablesHandler.parse(x, product));
349            } catch (NodataFoundException nodataFoundException) {
350                setDescription(VariablesHandler.parse(product.__getCname(), product));
351            }
352        } else {
353            Log.Debug(SubItem.class, "No format defined..");
354            setDescription(VariablesHandler.parse(product.__getCname(), product));
355        }
356///////////////end format////////////////////////////////////////////////////////
357        setExternalvalue(product.findPriceFor(1d));
358        setGroupsids(mpv5.db.objects.User.getCurrentUser().__getGroupsids());
359        setIntaddedby(mpv5.db.objects.User.getCurrentUser().__getIDS());
360        setInternalvalue(product.__getInternalnetvalue());
361        setMeasure(product.__getMeasure());
362        setOriginalproductsids(product.__getIDS());
363        setQuantityvalue(BigDecimal.ONE);
364        setTaxpercentvalue(Tax.getTaxValue(product.__getTaxids()));
365        setLinkurl(product.__getUrl());
366        calculate(this);
367    }
368
369    /**
370     * Generates a SubItem with useless sample data
371     * @return
372     */
373    public static SubItem getRandomItem() {
374        SubItem i = new SubItem();
375        i.fillSampleData();
376        i.setGroupsids(1);
377        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("defunit")) {
378            String defunit = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("defunit");
379            i.setMeasure(defunit);
380        }
381        BigDecimal deftax = BigDecimal.ZERO;
382        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("deftax")) {
383            int taxid = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("deftax", 0);
384            deftax = Tax.getTaxValue(taxid);
385            i.setTaxpercentvalue(deftax);
386        }
387        Double defcount = 1d;
388        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("defcount")) {
389            defcount = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("defcount", 0d);
390            i.setQuantityvalue(new BigDecimal(defcount.toString()));
391        }
392        return i;
393    }
394
395    /**
396     * Generates a String array out of this SubItem
397     * @return
398     */
399    public synchronized String[] toStringArray() {
400        calculate(this);
401
402        List<String> all = new LinkedList<String>();
403
404        String[] possibleCols = new String[]{
405            ////////////////// The exported columns///////////////////////////////////////
406            getInttype() != TYPE_TEXT ? String.valueOf(FormatNumber.formatInteger(this.__getCountvalue())) : "",
407            getInttype() != TYPE_TEXT ? String.valueOf(FormatNumber.formatDezimal(this.__getQuantityvalue())) : "",
408            getInttype() != TYPE_TEXT ? __getMeasure() : "",
409            __getDescription(),
410            getInttype() != TYPE_TEXT ? String.valueOf(FormatNumber.formatLokalCurrency(this.__getExternalvalue())) : "",
411            getInttype() != TYPE_TEXT ? String.valueOf(FormatNumber.formatLokalCurrency(this.__getTotalnetvalue())) : "",
412            getInttype() != TYPE_TEXT ? String.valueOf(FormatNumber.formatPercent(this.__getTaxpercentvalue())) : "",
413            getInttype() != TYPE_TEXT ? String.valueOf(FormatNumber.formatLokalCurrency(this.getTotalTaxValue())) : "",
414            getInttype() != TYPE_TEXT ? String.valueOf(FormatNumber.formatLokalCurrency(this.__getTotalbrutvalue())) : "",
415            __getLinkurl(),
416            __getCname()
417        ///////////////////////////////////////////////////////////////////////////////
418        };
419        List<String> l = Arrays.asList(possibleCols);
420        all.addAll(l);
421
422        if (GlobalSettings.getBooleanProperty("org.openyabs.exportproperty.productsresolved", false) && __getOriginalproductsids() > 0) {
423            try {
424                Product p = (Product) DatabaseObject.getObject(Context.getProduct(), __getOriginalproductsids());
425                List<String[]> vals = p.getValues3();
426                Collections.sort(vals, new Comparator<String[]>() {
427
428                    public int compare(String[] o1, String[] o2) {
429                        return o1[0].compareTo(o2[0]);
430                    }
431                });
432                for (int i = 0; i < vals.size(); i++) {
433                    String[] v = vals.get(i);
434                    all.add(v[1]);
435                    if (Log.getLoglevel() == Log.LOGLEVEL_DEBUG) {
436                        Log.Debug(this, (12 + i) + ": " + v[0] + " ");
437                    }
438                }
439            } catch (Exception ex) {
440                Log.Debug(ex);
441            }
442        }
443
444        return all.toArray(new String[0]);
445    }
446
447
448    /**
449     * @return the itemsids
450     */
451    public int __getItemsids() {
452        return itemsids;
453    }
454
455    /**
456     * @param itemsids the itemsids to set
457     */
458    public void setItemsids(int itemsids) {
459        this.itemsids = itemsids;
460    }
461
462    /**
463     * @return the originalproductsids
464     */
465    public int __getOriginalproductsids() {
466        return originalproductsids;
467    }
468
469    /**
470     * @param originalproductsids the originalproductsids to set
471     */
472    public void setOriginalproductsids(int originalproductsids) {
473        this.originalproductsids = originalproductsids;
474        if (originalproductsids > 0) {
475            setInttype(TYPE_PRODUCT);
476        } else {
477            setInttype(TYPE_NORMAL);
478        }
479    }
480
481    /**
482     * @return the count
483     */
484    public BigDecimal __getCountvalue() {
485        return countvalue;
486    }
487
488    /**
489     * @param count the count to set
490     */
491    public void setCountvalue(BigDecimal count) {
492        this.countvalue = count;
493    }
494
495    /**
496     * @return the quantity
497     */
498    public BigDecimal __getQuantityvalue() {
499        return quantityvalue;
500    }
501
502    /**
503     * @param quantity the quantity to set
504     */
505    public void setQuantityvalue(BigDecimal quantity) {
506        this.quantityvalue = quantity;
507        if (quantity.compareTo(BigDecimal.ZERO) == 0) {
508            setInttype(TYPE_TEXT);
509        }
510    }
511
512    /**
513     * @return the measure
514     */
515    public String __getMeasure() {
516        return measure;
517    }
518
519    /**
520     * @param measure the measure to set
521     */
522    public void setMeasure(String measure) {
523        this.measure = measure;
524    }
525
526    /**
527     * @return the description
528     */
529    public String __getDescription() {
530        return description;
531    }
532
533    /**
534     * @param description the description to set
535     */
536    public void setDescription(String description) {
537        this.description = description;
538    }
539
540    /**
541     * @return the taxpercent
542     */
543    public BigDecimal __getTaxpercentvalue() {
544        return taxpercentvalue;
545    }
546
547    /**
548     * @param taxpercent the taxpercent to set
549     */
550    public void setTaxpercentvalue(BigDecimal taxpercent) {
551        this.taxpercentvalue = taxpercent;
552    }
553
554    /**
555     * @return the datedelivery
556     */
557    public Date __getDatedelivery() {
558        return datedelivery;
559    }
560
561    /**
562     * @param datedelivery the datedelivery to set
563     */
564    public void setDatedelivery(Date datedelivery) {
565        this.datedelivery = datedelivery;
566    }
567
568    /**
569     * 
570     * @return 
571     */
572    public BigDecimal __getDiscount() {
573        return discount;
574    }
575
576    /**
577     * 
578     * @param discount 
579     */
580    public void setDiscount(BigDecimal discount) {
581        this.discount = discount;
582    }
583
584    public BigDecimal getDiscvalue() {
585        return discvalue;
586    }
587
588    public void defDiscvalue(BigDecimal discvalue) {
589        this.discvalue = discvalue;
590    }
591
592    @Override
593    public JComponent getView() {
594        try {
595            Item dos = (Item) DatabaseObject.getObject(Context.getItem(), __getItemsids());
596            ItemPanel ip = new ItemPanel(Context.getItem(), dos.__getInttype());
597            return ip;
598        } catch (NodataFoundException ex) {
599            throw new RuntimeException(ex);
600        }
601    }
602
603    @Override
604    public mpv5.utils.images.MPIcon getIcon() {
605        return null;
606    }
607
608    /**
609     * Generates a table model out of the given SubItems
610     * @param items
611     * @return
612     */
613    public static MPTableModel toModel(SubItem[] items) {
614        return toModel(items, false);
615    }
616    /**
617     * The ADD button index
618     */
619    public static int COLUMNINDEX_ADD = 11;
620    /**
621     * The CLEAR button index
622     */
623    public static int COLUMNINDEX_REMOVE = 12;
624    /**
625     * Compares by ordernr
626     */
627    public static Comparator<SubItem> ORDER_COMPARATOR = new Comparator<SubItem>() {
628
629        @Override
630        public int compare(SubItem o1, SubItem o2) {
631            return (o1.getOrdernr() > o2.getOrdernr()) ? 1 : -1;
632        }
633    };
634
635    /**
636     * Generates a table model out of the given SubItems
637     * @param items
638     * @param removeSubitemIds
639     * @return
640     */
641    public static MPTableModel toModel(SubItem[] items, boolean removeSubitemIds) {
642        //"Internal ID", "ID", "Count", "Measure", "Description", "Netto Price", "Tax Value", "Total Price"
643        Object[][] data = new Object[items.length][];
644        List<SubItem> tlist = new LinkedList<SubItem>();
645        tlist.addAll(Arrays.asList(items));
646        Collections.sort(tlist, SubItem.ORDER_COMPARATOR);
647
648        for (int i = 0; i < tlist.size(); i++) {
649            SubItem subItem = tlist.get(i);
650            if (subItem != null) {
651                data[i] = subItem.getRowData(i + 1);
652            } else {
653                data[i] = getDefaultItem().getRowData(i + 1);
654            }
655            if (removeSubitemIds) {
656                data[i][0] = -1;
657            }
658        }
659
660
661        MPTableModel model = new MPTableModel(
662                new Class[]{
663                    Integer.class, Integer.class, BigDecimal.class, String.class, Object.class, BigDecimal.class, BigDecimal.class, BigDecimal.class,
664                    BigDecimal.class, BigDecimal.class, Product.class, JButton.class, JButton.class, String.class, String.class, BigDecimal.class, BigDecimal.class},
665                new boolean[]{false, false, true, true, true, true, true, false, false, false, false, true, true, true, true, true, true, true},
666                data,
667                Headers.SUBITEMS.getValue());
668
669        model.setContext(Context.getSubItem());
670        String defunit = null;
671        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("defunit")) {
672            defunit = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("defunit");
673        }
674        BigDecimal deftax = BigDecimal.ZERO;
675        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("deftax")) {
676            int taxid = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("deftax", 0);
677            deftax = Tax.getTaxValue(taxid);
678        }
679        Double defcount = 1d;
680        if (mpv5.db.objects.User.getCurrentUser().getProperties().hasProperty("defcount")) {
681            defcount = mpv5.db.objects.User.getCurrentUser().getProperties().getProperty("defcount", 0d);
682        }
683        model.defineRow(new Object[]{0, 0, defcount, defunit, null, 0.0, deftax, 0.0, 0.0, 0.0, null, "A", "C", "", "", 0.0, 0.0});
684        model.setAutoCountColumn(1);
685
686        return model;
687    }
688
689    /**
690     * Turn this SubItem into table row data
691     * @param row
692     * @return
693     */
694    public synchronized Object[] getRowData(int row) {
695        Object[] data = new Object[17];
696        for (int i = 0; i < data.length; i++) {
697            data[0] = __getIDS();
698            data[1] = Integer.valueOf(row);
699            data[2] = __getQuantityvalue();
700            data[3] = __getMeasure();
701            data[4] = __getDescription();
702            data[5] = __getExternalvalue();
703            data[6] = __getTaxpercentvalue();
704            data[7] = __getQuantityvalue().multiply(__getExternalvalue().multiply(((__getTaxpercentvalue().divide(Constants.BD100, 9, BigDecimal.ROUND_HALF_UP).add(BigDecimal.ONE)))));
705            data[8] = 0.0;
706            data[9] = 0.0;
707            if (__getOriginalproductsids() > 0) {
708                try {
709                    data[10] = Product.getObject(Context.getProduct(), __getOriginalproductsids());
710                } catch (NodataFoundException ex) {
711                    Log.Debug(ex);
712                }
713            }
714            data[11] = "A";
715            data[12] = "C";
716            data[12 + 1] = __getLinkurl();
717            data[14] = __getCname();
718            data[15] = __getDiscount();
719            data[16] = 0.0;
720        }
721        return data;
722    }
723
724    /**
725     * Turn this SubItem into table row data
726     * @param row
727     * @return
728     */
729    public static synchronized SubItem getFromModel(MPTableModel m, int row) {
730        SubItem t = new SubItem();
731
732        if (m.getValueAt(row, 0) != null) {
733            t.setIDS(Integer.valueOf(m.getValueAt(row, 0).toString()));
734        }
735        if (m.getValueAt(row, 1) != null) {
736            t.setCountvalue(new BigDecimal(m.getValueAt(row, 1).toString()));
737        }
738        if (m.getValueAt(row, 2) != null) {
739            t.setQuantityvalue(new BigDecimal(m.getValueAt(row, 2).toString()));
740        }
741        if (m.getValueAt(row, 3) != null) {
742            t.setMeasure(m.getValueAt(row, 3).toString());
743        }
744        if (m.getValueAt(row, 4) != null) {
745            t.setDescription(m.getValueAt(row, 4).toString());
746        }
747        if (m.getValueAt(row, 5) != null) {
748            t.setExternalvalue(new BigDecimal(m.getValueAt(row, 5).toString()));
749        }
750        if (m.getValueAt(row, 6) != null) {
751            t.setTaxpercentvalue(new BigDecimal(m.getValueAt(row, 6).toString()));
752        }
753        if (m.getValueAt(row, 10) != null) {
754            try {
755                t.setOriginalproductsids(((Product) m.getValueAt(row, 10)).__getIDS());
756            } catch (Exception e) {
757                Log.Debug(e);
758            }
759        }
760        if (m.getValueAt(row, 13) != null) {
761            t.setLinkurl(m.getValueAt(row, 13).toString());
762        }
763        if (m.getValueAt(row, 14) != null) {
764            t.setCname(m.getValueAt(row, 14).toString());
765        }
766        if (m.getValueAt(row, 15) != null) {
767            t.setDiscount(new BigDecimal(m.getValueAt(row, 15).toString()));
768        }
769
770        return t;
771    }
772
773    /**
774     * @return the internalvalue
775     */
776    public BigDecimal __getInternalvalue() {
777        return internalvalue;
778    }
779
780    /**
781     * @param internalvalue the internalvalue to set
782     */
783    public void setInternalvalue(BigDecimal internalvalue) {
784        this.internalvalue = internalvalue;
785    }
786
787    /**
788     * @return the externalvalue
789     */
790    public BigDecimal __getExternalvalue() {
791        return externalvalue;
792    }
793
794    /**
795     * @param externalvalue the externalvalue to set
796     */
797    public void setExternalvalue(BigDecimal externalvalue) {
798        this.externalvalue = externalvalue;
799    }
800
801    @Override
802    public HashMap<String, Object> resolveReferences(HashMap<String, Object> map) {
803
804        if (map.containsKey("originalproductsids")) {
805            try {
806                try {
807                    map.put("originalproduct", DatabaseObject.getObject(Context.getProduct(), Integer.valueOf(map.get("originalproductsids").toString())));
808                    map.remove("originalproductsids");
809                } catch (NodataFoundException ex) {
810                    map.put("originalproduct", null);
811                }
812            } catch (NumberFormatException numberFormatException) {
813                //already resolved?
814            }
815        }
816
817        return super.resolveReferences(map);
818    }
819
820    /**
821     * @return the totalnetvalue
822     */
823    public BigDecimal __getTotalnetvalue() {
824        return totalnetvalue;
825    }
826
827    /**
828     * @param totalnetvalue the totalnetvalue to set
829     */
830    public void setTotalnetvalue(BigDecimal totalnetvalue) {
831        this.totalnetvalue = totalnetvalue;
832    }
833
834    /**
835     * @return the totalbrutvalue
836     */
837    public BigDecimal __getTotalbrutvalue() {
838        return totalbrutvalue;
839    }
840
841    /**
842     * @param totalbrutvalue the totalbrutvalue to set
843     */
844    public void setTotalbrutvalue(BigDecimal totalbrutvalue) {
845        this.totalbrutvalue = totalbrutvalue;
846    }
847
848    static void calculate(SubItem s) {
849        BigDecimal disc = s.__getDiscount().divide(BD100, 9, BigDecimal.ROUND_HALF_UP);
850        s.setTotalbrutvalue(s.quantityvalue.multiply(s.externalvalue.multiply(((s.taxpercentvalue.divide(Constants.BD100, 9, BigDecimal.ROUND_HALF_UP)).add(BigDecimal.ONE)))));
851        s.setTotalbrutvalue(s.totalbrutvalue.subtract(s.totalbrutvalue.multiply(disc)));
852        s.defTotaltaxvalue(s.quantityvalue.multiply(s.externalvalue.multiply((s.taxpercentvalue.divide(Constants.BD100, 9, BigDecimal.ROUND_HALF_UP)))));
853        s.defTotaltaxvalue(s.totaltaxvalue.subtract(s.totaltaxvalue.multiply(disc)));
854        s.setTotalnetvalue(s.quantityvalue.multiply(s.externalvalue));
855        s.defDiscvalue(s.totalnetvalue.multiply(disc));
856    }
857
858    @Override
859    public boolean save() {
860        calculate(this);
861        return super.save();
862    }
863
864    private void defTotaltaxvalue(BigDecimal value) {
865        totaltaxvalue = value;
866    }
867
868    /**
869     * 
870     * @return
871     */
872    public BigDecimal getTotalTaxValue() {
873        return totaltaxvalue;
874    }
875
876    /**
877     * @return the linkurl
878     */
879    public String __getLinkurl() {
880        return linkurl;
881    }
882
883    /**
884     * @param linkurl the linkurl to set
885     */
886    public void setLinkurl(String linkurl) {
887        this.linkurl = linkurl;
888    }
889
890    @Override
891    public boolean save(boolean b) {
892        if (getCname().length() == 0) {
893            setCname("   ");
894        }
895        return super.save(b);
896    }
897
898    @Override
899    public void triggerOnCreate() {
900        if (__getOriginalproductsids() > 0) {
901            try {
902                Product p = (Product) DatabaseObject.getObject(Context.getProduct(), originalproductsids);
903                if (p.__getIntinventorytype() == 1) {
904                    p.setStockvalue(p.__getStockvalue().subtract(__getQuantityvalue()));
905                    p.save(true);
906                }
907            } catch (NodataFoundException ex) {
908                Log.Debug(this, ex.getMessage());//jemand hats gel??scht:-/
909                originalproductsids = -1;
910                save(true);
911            }
912        }
913    }
914
915    @Override
916    public void triggerOnUpdate() {
917    }
918
919    @Override
920    public void triggerOnDelete() {
921        // Log.Debug(this, "Deleting... " + IDENTITY);
922    }
923
924    @Override
925    public String toString() {
926        if (description != null && description.length() > 15) {
927            return description.substring(0, 14);
928        } else {
929            return description;
930        }
931    }
932
933    /**
934     * @return the order
935     */
936    @Persistable(true)
937    public int getOrdernr() {
938        return ordernr;
939    }
940
941    /**
942     * @param ordernr the order to set
943     */
944    public void setOrdernr(int ordernr) {
945        this.ordernr = ordernr;
946    }
947
948    /**
949     * @return the inttype
950     */
951    @Persistable(true)
952    public int getInttype() {
953        return inttype;
954    }
955
956    /**
957     * @param inttype the inttype to set
958     */
959    public void setInttype(int inttype) {
960        this.inttype = inttype;
961    }
962}