KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencrx > kernel > layer > application > Depots


1 /*
2  * ====================================================================
3  * Project: opencrx, http://www.opencrx.org/
4  * Name: $Id: Depots.java,v 1.28 2006/03/18 00:32:17 wfro Exp $
5  * Description: openCRX application plugin
6  * Revision: $Revision: 1.28 $
7  * Owner: CRIXP AG, Switzerland, http://www.crixp.com
8  * Date: $Date: 2006/03/18 00:32:17 $
9  * ====================================================================
10  *
11  * This software is published under the BSD license
12  * as listed below.
13  *
14  * Copyright (c) 2004-2005, CRIXP Corp., Switzerland
15  * All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  *
21  * * Redistributions of source code must retain the above copyright
22  * notice, this list of conditions and the following disclaimer.
23  *
24  * * Redistributions in binary form must reproduce the above copyright
25  * notice, this list of conditions and the following disclaimer in
26  * the documentation and/or other materials provided with the
27  * distribution.
28  *
29  * * Neither the name of CRIXP Corp. nor the names of the contributors
30  * to openCRX may be used to endorse or promote products derived
31  * from this software without specific prior written permission
32  *
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
35  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
36  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
37  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
39  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
40  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
41  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
43  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
45  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
46  * POSSIBILITY OF SUCH DAMAGE.
47  *
48  * ------------------
49  *
50  * This product includes software developed by the Apache Software
51  * Foundation (http://www.apache.org/).
52  *
53  * This product includes software developed by contributors to
54  * openMDX (http://www.openmdx.org/)
55  */

56 package org.opencrx.kernel.layer.application;
57
58 import java.math.BigDecimal JavaDoc;
59 import java.util.ArrayList JavaDoc;
60 import java.util.Date JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.List JavaDoc;
63
64 import org.opencrx.kernel.generic.OpenCrxException;
65 import org.openmdx.base.accessor.jmi.cci.RefPackage_1_0;
66 import org.openmdx.base.exception.ServiceException;
67 import org.openmdx.base.text.format.DateFormat;
68 import org.openmdx.compatibility.base.dataprovider.cci.AttributeSelectors;
69 import org.openmdx.compatibility.base.dataprovider.cci.AttributeSpecifier;
70 import org.openmdx.compatibility.base.dataprovider.cci.DataproviderObject;
71 import org.openmdx.compatibility.base.dataprovider.cci.DataproviderObject_1_0;
72 import org.openmdx.compatibility.base.dataprovider.cci.Directions;
73 import org.openmdx.compatibility.base.dataprovider.cci.Orders;
74 import org.openmdx.compatibility.base.dataprovider.cci.RequestCollection;
75 import org.openmdx.compatibility.base.dataprovider.cci.ServiceHeader;
76 import org.openmdx.compatibility.base.dataprovider.cci.SystemAttributes;
77 import org.openmdx.compatibility.base.naming.Path;
78 import org.openmdx.compatibility.base.query.FilterOperators;
79 import org.openmdx.compatibility.base.query.FilterProperty;
80 import org.openmdx.compatibility.base.query.Quantors;
81 import org.openmdx.kernel.exception.BasicException;
82 import org.openmdx.model1.accessor.basic.cci.Model_1_0;
83
84 public class Depots {
85
86     //-----------------------------------------------------------------------
87
public Depots(
88         Model_1_0 model,
89         OpenCrxKernel_1 plugin,
90         RequestCollection delegation,
91         RefPackage_1_0 rootPkg
92     ) {
93         this.model = model;
94         this.plugin = plugin;
95         this.delegation = delegation;
96         this.rootPkg = rootPkg;
97     }
98
99     //-----------------------------------------------------------------------
100
private String JavaDoc stripWhitespaces(
101         String JavaDoc s
102     ) {
103         String JavaDoc stripped = "";
104         for(int i = 0; i < s.length(); i++) {
105             if(!Character.isWhitespace(s.charAt(i))) {
106                 stripped += s.charAt(i);
107             }
108         }
109         return stripped;
110     }
111     
112     //-----------------------------------------------------------------------
113
private void testForOpenPosition(
114         ServiceHeader header,
115         String JavaDoc valueDate,
116         short bookingType,
117         Path positionIdentity
118     ) throws ServiceException {
119         
120         List JavaDoc bookingPeriods = this.delegation.addFindRequest(
121             positionIdentity.getPrefix(7).getChild("bookingPeriod"),
122             null,
123             AttributeSelectors.ALL_ATTRIBUTES,
124             0,
125             Integer.MAX_VALUE,
126             Directions.ASCENDING
127         );
128         DataproviderObject_1_0 depot = this.plugin.retrieveObjectFromLocal(header, positionIdentity.getParent().getParent());
129         String JavaDoc depotNumber = (String JavaDoc)depot.values("depotNumber").get(0);
130         DataproviderObject_1_0 depotPosition = this.plugin.retrieveObjectFromLocal(header, positionIdentity);
131         String JavaDoc positionName = (String JavaDoc)depotPosition.values("name").get(0);
132         
133         // Check for depot position isLocked
134
if(
135             (depotPosition.values("isLocked").size() > 0) &&
136             ((Boolean JavaDoc)depotPosition.values("isLocked").get(0)).booleanValue()
137         ) {
138             throw new ServiceException(
139                 OpenCrxException.DOMAIN,
140                 OpenCrxException.DEPOT_POSITION_IS_LOCKED,
141                 new BasicException.Parameter[]{
142                     new BasicException.Parameter("param0", depotNumber),
143                     new BasicException.Parameter("param1", positionName)
144                 },
145                 "Depot position is locked"
146             );
147         }
148         // Check for closing date of depot position
149
if(
150             (depotPosition.values("closingDate").size() > 0) &&
151             (valueDate.compareToIgnoreCase((String JavaDoc)depotPosition.values("closingDate").get(0)) >= 0)
152         ) {
153             throw new ServiceException(
154                 OpenCrxException.DOMAIN,
155                 OpenCrxException.DEPOT_POSITION_IS_CLOSED,
156                 new BasicException.Parameter[]{
157                     new BasicException.Parameter("param0", depotNumber),
158                     new BasicException.Parameter("param1", positionName),
159                     new BasicException.Parameter("param2", depotPosition.values("closingDate").get(0))
160                 },
161                 "Depot position is closed"
162             );
163         }
164         // Check for opening date of depot position
165
if(
166             (depotPosition.values("openingDate").size() > 0) &&
167             (valueDate.compareToIgnoreCase((String JavaDoc)depotPosition.values("openingDate").get(0)) < 0)
168         ) {
169             throw new ServiceException(
170                 OpenCrxException.DOMAIN,
171                 OpenCrxException.DEPOT_POSITION_IS_NOT_OPEN,
172                 new BasicException.Parameter[]{
173                     new BasicException.Parameter("param0", depotNumber),
174                     new BasicException.Parameter("param1", positionName),
175                     new BasicException.Parameter("param2", depotPosition.values("openingDate").get(0))
176                 },
177                 "Depot position is not open"
178             );
179         }
180         
181         // Check for depot isLocked
182
if(
183             (depot.values("isLocked").size() > 0) &&
184             ((Boolean JavaDoc)depot.values("isLocked").get(0)).booleanValue()
185         ) {
186             throw new ServiceException(
187                 OpenCrxException.DOMAIN,
188                 OpenCrxException.DEPOT_DEPOT_IS_LOCKED,
189                 new BasicException.Parameter[]{
190                     new BasicException.Parameter("param0", depotNumber)
191                 },
192                 "Depot is locked"
193             );
194         }
195         // Check for closing date of depot
196
if(
197             (depot.values("closingDate").size() > 0) &&
198             (valueDate.compareToIgnoreCase((String JavaDoc)depot.values("closingDate").get(0)) >= 0)
199         ) {
200             throw new ServiceException(
201                 OpenCrxException.DOMAIN,
202                 OpenCrxException.DEPOT_DEPOT_IS_CLOSED_CAN_NOT_BOOK,
203                 new BasicException.Parameter[]{
204                     new BasicException.Parameter("param0", depotNumber),
205                     new BasicException.Parameter("param1", depot.values("closingDate").get(0))
206                 },
207                 "Depot is closed"
208             );
209         }
210         // Check for opening date of depot
211
if(
212             (depot.values("openingDate").size() > 0) &&
213             (valueDate.compareToIgnoreCase((String JavaDoc)depot.values("openingDate").get(0)) < 0)
214         ) {
215             throw new ServiceException(
216                 OpenCrxException.DOMAIN,
217                 OpenCrxException.DEPOT_DEPOT_IS_NOT_OPEN,
218                 new BasicException.Parameter[]{
219                     new BasicException.Parameter("param0", depotNumber),
220                     new BasicException.Parameter("param1", depot.values("openingDate").get(0))
221                 },
222                 "Depot is not open"
223             );
224         }
225         // Find booking period matching value date
226
DataproviderObject_1_0 bookingPeriod = null;
227         for(
228             Iterator JavaDoc i = bookingPeriods.iterator();
229             i.hasNext();
230         ) {
231             DataproviderObject_1_0 period = (DataproviderObject_1_0)i.next();
232             String JavaDoc periodStartsAt = (String JavaDoc)period.values("periodStartsAt").get(0);
233             String JavaDoc periodEndsAtExclusive = (String JavaDoc)period.values("periodEndsAtExclusive").get(0);
234             if(
235                 ((periodStartsAt == null) || (valueDate.compareToIgnoreCase(periodStartsAt) >= 0)) &&
236                 ((periodEndsAtExclusive == null) || (valueDate.compareToIgnoreCase(periodEndsAtExclusive) < 0))
237             ) {
238                 bookingPeriod = period;
239                 break;
240             }
241         }
242         if(bookingPeriod == null) {
243             throw new ServiceException(
244                 OpenCrxException.DOMAIN,
245                 OpenCrxException.DEPOT_BOOKING_PERIOD_NOT_FOUND,
246                 new BasicException.Parameter[]{
247                     new BasicException.Parameter("param0", valueDate),
248                 },
249                 "No booking period found for value date"
250             );
251         }
252         String JavaDoc bookingPeriodName = (String JavaDoc)bookingPeriod.values("name").get(0);
253         // Check for non-final booking period
254
if(
255             (bookingPeriod.values("isFinal").size() > 0) &&
256             ((Boolean JavaDoc)bookingPeriod.values("isFinal").get(0)).booleanValue()
257         ) {
258             throw new ServiceException(
259                 OpenCrxException.DOMAIN,
260                 OpenCrxException.DEPOT_BOOKING_PERIOD_IS_FINAL,
261                 new BasicException.Parameter[]{
262                     new BasicException.Parameter("param0", bookingPeriodName)
263                 },
264                 "Booking period is final"
265             );
266         }
267         // Check for non-closed booking period
268
if(
269             (bookingPeriod.values("isClosed").size() > 0) &&
270             ((Boolean JavaDoc)bookingPeriod.values("isClosed").get(0)).booleanValue() &&
271             (bookingPeriod.values("closingBookingTypeThreshold").size() > 0) &&
272             bookingType <= ((Number JavaDoc)bookingPeriod.values("closingBookingTypeThreshold").get(0)).intValue()
273         ) {
274             throw new ServiceException(
275                 OpenCrxException.DOMAIN,
276                 OpenCrxException.DEPOT_BOOKING_PERIOD_IS_CLOSED,
277                 new BasicException.Parameter[]{
278                     new BasicException.Parameter("param0", bookingPeriodName),
279                     new BasicException.Parameter("param1", bookingPeriod.values("closingBookingTypeThreshold").get(0))
280                 },
281                 "Booking period is closed"
282             );
283         }
284     }
285     
286     //-----------------------------------------------------------------------
287
private void testForBalance(
288         Path compoundBookingIdentity,
289         Number JavaDoc balance
290     ) throws ServiceException {
291         List JavaDoc creditBookings = this.delegation.addFindRequest(
292             compoundBookingIdentity.getPrefix(compoundBookingIdentity.size()-2).getChild("booking"),
293             new FilterProperty[]{
294                 new FilterProperty(
295                     Quantors.THERE_EXISTS,
296                     SystemAttributes.OBJECT_CLASS,
297                     FilterOperators.IS_IN,
298                     new String JavaDoc[]{"org:opencrx:kernel:depot1:CreditBooking"}
299                 ),
300                 new FilterProperty(
301                     Quantors.THERE_EXISTS,
302                     "cb",
303                     FilterOperators.IS_IN,
304                     new Path[]{compoundBookingIdentity}
305                 )
306             },
307             AttributeSelectors.ALL_ATTRIBUTES,
308             0,
309             Integer.MAX_VALUE,
310             Directions.ASCENDING
311         );
312         BigDecimal JavaDoc compoundBalance = new BigDecimal JavaDoc(0);
313         for(
314             Iterator JavaDoc i = creditBookings.iterator();
315             i.hasNext();
316         ) {
317             DataproviderObject_1_0 booking = (DataproviderObject_1_0)i.next();
318             compoundBalance = compoundBalance.add(
319                 (BigDecimal JavaDoc)booking.values("quantityCredit").get(0)
320             );
321         }
322         if(compoundBalance.compareTo(balance) != 0) {
323             throw new ServiceException(
324                 OpenCrxException.DOMAIN,
325                 OpenCrxException.DEPOT_REVERSAL_BALANCE_MISMATCH,
326                 new BasicException.Parameter[]{
327                     new BasicException.Parameter("param0", compoundBalance),
328                     new BasicException.Parameter("param1", balance)
329                 },
330                 "Balance mismatch"
331             );
332         }
333     }
334     
335     //-----------------------------------------------------------------------
336
public DataproviderObject_1_0 createCreditDebitBooking(
337         ServiceHeader header,
338         Path depotEntityIdentity,
339         String JavaDoc valueDate,
340         short bookingType,
341         BigDecimal JavaDoc quantity,
342         String JavaDoc bookingTextName,
343         Path bookingTextIdentity,
344         Path positionCreditIdentity,
345         Path positionDebitIdentity,
346         Path productConfigurationSetIdentity,
347         Path originIdentity,
348         Path reversalOf
349     ) throws ServiceException {
350         return this.createCompoundBooking(
351             header,
352             depotEntityIdentity,
353             valueDate,
354             bookingType,
355             new BigDecimal JavaDoc[]{quantity},
356             new String JavaDoc[]{bookingTextName},
357             new Path[]{bookingTextIdentity},
358             new Path[]{positionCreditIdentity},
359             new Path[]{positionDebitIdentity},
360             new Path[]{productConfigurationSetIdentity},
361             new Path[]{originIdentity},
362             reversalOf
363         );
364     }
365     
366     //-----------------------------------------------------------------------
367
public DataproviderObject_1_0 createCompoundBooking(
368         ServiceHeader header,
369         Path depotEntityIdentity,
370         String JavaDoc valueDate,
371         short bookingType,
372         BigDecimal JavaDoc[] quantities,
373         String JavaDoc[] bookingTextNames,
374         Path[] bookingTextIdentities,
375         Path[] creditPositionIdentities,
376         Path[] debitPositionIdentities,
377         Path[] productConfigurationSetIdentities,
378         Path[] originIdentities,
379         Path reversalOf
380     ) throws ServiceException {
381
382         // Set default valueDate to current date
383
if(valueDate == null) {
384             valueDate = DateFormat.getInstance().format(new Date JavaDoc());
385         }
386         
387         // Assert open positions
388
for(int i = 0; i < creditPositionIdentities.length; i++) {
389             this.testForOpenPosition(
390                 header,
391                 valueDate,
392                 bookingType,
393                 creditPositionIdentities[i]
394             );
395             this.testForOpenPosition(
396                 header,
397                 valueDate,
398                 bookingType,
399                 debitPositionIdentities[i]
400             );
401         }
402         
403         // Test for matching balance
404
BigDecimal JavaDoc balance = new BigDecimal JavaDoc(0);
405         for(int i = 0; i < quantities.length; i++) {
406             if(quantities[i] == null) {
407                 throw new ServiceException(
408                     OpenCrxException.DOMAIN,
409                     OpenCrxException.DEPOT_MISSING_QUANTITY,
410                     null,
411                     "Missing quantity"
412                 );
413             }
414             balance = balance.add(quantities[i]);
415         }
416         if(reversalOf != null) {
417             this.testForBalance(
418                 reversalOf,
419                 balance
420             );
421         }
422         
423         // bookingText
424
DataproviderObject_1_0[] bookingTexts = new DataproviderObject_1_0[bookingTextNames.length];
425         for(int i = 0; i < bookingTextNames.length; i++) {
426             if((bookingTextIdentities != null) && (bookingTextIdentities[i] != null)) {
427                 bookingTexts[i] = this.plugin.retrieveObjectFromLocal(header, bookingTextIdentities[i]);
428             }
429             else {
430                 if(bookingTextNames[i] != null) {
431                     List JavaDoc texts = this.delegation.addFindRequest(
432                         depotEntityIdentity.getChild("bookingText"),
433                         new FilterProperty[]{
434                             new FilterProperty(
435                                 Quantors.THERE_EXISTS,
436                                 "name",
437                                 FilterOperators.IS_IN,
438                                 new Object JavaDoc[]{bookingTextNames[i]}
439                             )
440                         },
441                         AttributeSelectors.ALL_ATTRIBUTES,
442                         0,
443                         Integer.MAX_VALUE,
444                         Directions.ASCENDING
445                     );
446                     if(texts.size() > 0) {
447                         bookingTexts[i] = (DataproviderObject_1_0)texts.get(0);
448                     }
449                 }
450             }
451             if(bookingTexts[i] == null) {
452                throw new ServiceException(
453                    OpenCrxException.DOMAIN,
454                    OpenCrxException.DEPOT_MISSING_BOOKING_TEXT,
455                    null,
456                    "Missing booking text"
457                );
458             }
459         }
460         // creditPositions
461
DataproviderObject_1_0[] creditPositions = new DataproviderObject_1_0[creditPositionIdentities.length];
462         for(int i = 0; i < creditPositionIdentities.length; i++) {
463             if(creditPositionIdentities[i] != null) {
464                 creditPositions[i] = this.plugin.retrieveObjectFromLocal(
465                     header,
466                     creditPositionIdentities[i]
467                 );
468             }
469             if(creditPositions[i] == null) {
470                throw new ServiceException(
471                    OpenCrxException.DOMAIN,
472                    OpenCrxException.DEPOT_MISSING_POSITION_CREDIT,
473                    null,
474                    "Missing credit position"
475                );
476             }
477         }
478         // debitPositions
479
DataproviderObject_1_0[] debitPositions = new DataproviderObject_1_0[debitPositionIdentities.length];
480         for(int i = 0; i < debitPositionIdentities.length; i++) {
481             if(debitPositionIdentities[i] != null) {
482                 debitPositions[i] = this.plugin.retrieveObjectFromLocal(
483                     header,
484                     debitPositionIdentities[i]
485                 );
486             }
487             if(debitPositions[i] == null) {
488                throw new ServiceException(
489                    OpenCrxException.DOMAIN,
490                    OpenCrxException.DEPOT_MISSING_POSITION_DEBIT,
491                    null,
492                    "Missing debit position"
493                );
494             }
495         }
496         // Position name
497
for(int i = 0; i < creditPositions.length; i++) {
498             if(
499                 (creditPositions[i].values("name").get(0) == null) ||
500                 (debitPositions[i].values("name").get(0) == null) ||
501                 !creditPositions[i].values("name").get(0).equals(debitPositions[i].values("name").get(0))
502             ) {
503                throw new ServiceException(
504                    OpenCrxException.DOMAIN,
505                    OpenCrxException.DEPOT_POSITION_NAME_MISMATCH,
506                    new BasicException.Parameter[]{
507                        new BasicException.Parameter("param0", creditPositions[i].values("name").get(0)),
508                        new BasicException.Parameter("param1", debitPositions[i].values("name").get(0))
509                    },
510                    "position names debit/credit do not match"
511                );
512             }
513         }
514         // Value date
515
if(valueDate == null) {
516             valueDate = DateFormat.getInstance().format(new Date JavaDoc());
517         }
518         String JavaDoc bookingDate = DateFormat.getInstance().format(new Date JavaDoc());
519
520         // Create compound booking
521
DataproviderObject compoundBooking = new DataproviderObject(
522             depotEntityIdentity.getPrefix(
523                 depotEntityIdentity.size()-2
524             ).getDescendant(
525                 new String JavaDoc[]{"cb", this.plugin.getUidAsString()}
526             )
527         );
528         compoundBooking.values(SystemAttributes.OBJECT_CLASS).add(
529             "org:opencrx:kernel:depot1:CompoundBooking"
530         );
531         // name
532
String JavaDoc positionName0 = (String JavaDoc)creditPositions[0].values("name").get(0);
533         
534         // depotCredit
535
DataproviderObject_1_0 depotCredit0 = this.plugin.retrieveObjectFromLocal(
536             header,
537             creditPositions[0].path().getPrefix(creditPositions[0].path().size()-2)
538         );
539         String JavaDoc depotNumberCredit0 = (String JavaDoc)depotCredit0.values("depotNumber").get(0);
540
541         // depotDebit
542
DataproviderObject_1_0 depotDebit0 = this.plugin.retrieveObjectFromLocal(
543             header,
544             debitPositions[0].path().getPrefix(debitPositions[0].path().size()-2)
545         );
546         String JavaDoc depotNumberDebit0 = (String JavaDoc)depotDebit0.values("depotNumber").get(0);
547         if(
548             (bookingTexts[0].values("creditFirst").get(0) == null) ||
549             !((Boolean JavaDoc)bookingTexts[0].values("creditFirst").get(0)).booleanValue()
550         ) {
551             compoundBooking.values("name").add(
552                 depotNumberCredit0 + " " + bookingTexts[0].values("cbNameInfix1").get(0) + " " + positionName0 + " " + bookingTexts[0].values("cbNameInfix2").get(0) + " " + depotNumberDebit0
553             );
554         }
555         else {
556             compoundBooking.values("name").add(
557                 depotNumberDebit0 + " " + bookingTexts[0].values("cbNameInfix1").get(0) + " " + positionName0 + " " + bookingTexts[0].values("cbNameInfix2").get(0) + " " + depotNumberCredit0
558             );
559         }
560         compoundBooking.values("bookingType").add(new Short JavaDoc(bookingType));
561         compoundBooking.values("bookingStatus").add(new Short JavaDoc(BOOKING_STATUS_PENDING));
562         compoundBooking.values("bookingDate").add(bookingDate);
563         if(reversalOf != null) {
564             compoundBooking.values("reversalOf").add(reversalOf);
565         }
566         // Create compound booking
567
this.delegation.addCreateRequest(
568             compoundBooking
569         );
570             
571         // Create bookings
572
for(
573             int i = 0;
574             i < creditPositions.length;
575             i++
576         ) {
577             String JavaDoc positionName = (String JavaDoc)creditPositions[i].values("name").get(0);
578             
579             // depotCredit
580
DataproviderObject_1_0 depotCredit = this.plugin.retrieveObjectFromLocal(
581                 header,
582                 creditPositions[i].path().getPrefix(creditPositions[i].path().size()-2)
583             );
584             String JavaDoc depotNumberCredit = (String JavaDoc)depotCredit.values("depotNumber").get(0);
585     
586             // depotDebit
587
DataproviderObject_1_0 depotDebit = this.plugin.retrieveObjectFromLocal(
588                 header,
589                 debitPositions[i].path().getPrefix(debitPositions[i].path().size()-2)
590             );
591             String JavaDoc depotNumberDebit = (String JavaDoc)depotDebit.values("depotNumber").get(0);
592     
593             // Create credit booking
594
DataproviderObject bookingCredit = new DataproviderObject(
595                 depotEntityIdentity.getPrefix(
596                     depotEntityIdentity.size()-2
597                 ).getDescendant(
598                     new String JavaDoc[]{"booking", this.plugin.getUidAsString()}
599                 )
600             );
601             bookingCredit.values(SystemAttributes.OBJECT_CLASS).add(
602                 "org:opencrx:kernel:depot1:CreditBooking"
603             );
604             bookingCredit.values("name").add(
605                 depotNumberCredit + " " + bookingTexts[i].values("creditBookingNameInfix").get(0) + " " + positionName
606             );
607             bookingCredit.values("quantityCredit").add(quantities[i]);
608             bookingCredit.values("valueDate").add(valueDate);
609             bookingCredit.values("bookingType").add(new Short JavaDoc(bookingType));
610             bookingCredit.values("bookingStatus").add(new Short JavaDoc(BOOKING_STATUS_PENDING));
611             bookingCredit.values("bookingDate").add(bookingDate);
612             bookingCredit.values("cb").add(compoundBooking.path());
613             bookingCredit.values("position").add(creditPositions[i].path());
614             if(originIdentities[i] != null) {
615                 bookingCredit.values("origin").add(originIdentities[i]);
616             }
617             this.delegation.addCreateRequest(bookingCredit);
618             
619             // Clone product configurations
620
if(productConfigurationSetIdentities[i] != null) {
621                 this.plugin.products.cloneProductConfigurationSet(
622                     header,
623                     productConfigurationSetIdentities[i],
624                     bookingCredit.path(),
625                     false,
626                     false
627                 );
628             }
629             
630             // Create debit booking
631
DataproviderObject bookingDebit = new DataproviderObject(
632                 depotEntityIdentity.getPrefix(
633                     depotEntityIdentity.size()-2
634                 ).getDescendant(
635                     new String JavaDoc[]{"booking", this.plugin.getUidAsString()}
636                 )
637             );
638             bookingDebit.values(SystemAttributes.OBJECT_CLASS).add(
639                 "org:opencrx:kernel:depot1:DebitBooking"
640             );
641             bookingDebit.values("name").add(
642                 depotNumberDebit + " " + bookingTexts[i].values("debitBookingNameInfix").get(0) + " " + positionName
643             );
644             bookingDebit.values("quantityDebit").add(quantities[i]);
645             bookingDebit.values("valueDate").add(valueDate);
646             bookingDebit.values("bookingType").add(new Short JavaDoc(bookingType));
647             bookingDebit.values("bookingStatus").add(new Short JavaDoc(BOOKING_STATUS_PENDING));
648             bookingDebit.values("bookingDate").add(bookingDate);
649             bookingDebit.values("cb").add(compoundBooking.path());
650             bookingDebit.values("position").add(debitPositions[i].path());
651             if(originIdentities[i] != null) {
652                 bookingDebit.values("origin").add(originIdentities[i]);
653             }
654             this.delegation.addCreateRequest(bookingDebit);
655         }
656         
657         return compoundBooking;
658     }
659     
660     //-----------------------------------------------------------------------
661
public DataproviderObject_1_0 getAndCreateDepotPosition(
662         ServiceHeader header,
663         Path depotEntityIdentity,
664         String JavaDoc depotNumber,
665         Path depotIdentity,
666         String JavaDoc positionName,
667         Path productIdentity,
668         String JavaDoc openingDate
669     ) throws ServiceException {
670         DataproviderObject_1_0 depot = null;
671         if(depotIdentity != null) {
672             depot = this.plugin.retrieveObjectFromLocal(header, depotIdentity);
673         }
674         else {
675             if(depotNumber == null) {
676                throw new ServiceException(
677                    OpenCrxException.DOMAIN,
678                    OpenCrxException.DEPOT_MISSING_DEPOT_NUMBER,
679                    null,
680                    "Missing depot number"
681                );
682             }
683             List JavaDoc depots = this.delegation.addFindRequest(
684                 depotEntityIdentity.getPrefix(5).getChild("extent"),
685                 new FilterProperty[]{
686                     new FilterProperty(
687                         Quantors.THERE_EXISTS,
688                         SystemAttributes.OBJECT_IDENTITY,
689                         FilterOperators.IS_LIKE,
690                         new Object JavaDoc[]{depotEntityIdentity.getDescendant(new String JavaDoc[]{"depotHolder", ":*", "depot", ":*"})}
691                     ),
692                     new FilterProperty(
693                         Quantors.THERE_EXISTS,
694                         "depotNumber",
695                         FilterOperators.IS_IN,
696                         new Object JavaDoc[]{depotNumber}
697                     )
698                 },
699                 AttributeSelectors.ALL_ATTRIBUTES,
700                 0,
701                 Integer.MAX_VALUE,
702                 Directions.ASCENDING
703             );
704             if(depots.size() > 0) {
705                 depot = (DataproviderObject_1_0)depots.iterator().next();
706             }
707             else {
708                throw new ServiceException(
709                    OpenCrxException.DOMAIN,
710                    OpenCrxException.DEPOT_DEPOT_NOT_FOUND,
711                    new BasicException.Parameter[]{
712                        new BasicException.Parameter("param0", depotNumber)
713                    },
714                    "Depot not found"
715                );
716             }
717         }
718         List JavaDoc depotPositions = this.delegation.addFindRequest(
719             depot.path().getChild("position"),
720             new FilterProperty[]{
721                 new FilterProperty(
722                     Quantors.THERE_EXISTS,
723                     "name",
724                     FilterOperators.IS_IN,
725                     new Object JavaDoc[]{positionName}
726                 )
727             },
728             AttributeSelectors.ALL_ATTRIBUTES,
729             0,
730             Integer.MAX_VALUE,
731             Directions.ASCENDING
732         );
733         if(depotPositions.size() > 0) {
734             return (DataproviderObject_1_0)depotPositions.iterator().next();
735         }
736         // On-demand creation of position
737
else {
738             if(
739                 (depot.values("allowPositionAutoCreate").size() > 0) &&
740                 ((Boolean JavaDoc)depot.values("allowPositionAutoCreate").get(0)).booleanValue()
741             ) {
742                 DataproviderObject params = new DataproviderObject(new Path("xri:@openmdx:*"));
743                 params.values(SystemAttributes.OBJECT_CLASS).add(
744                     "org:opencrx:kernel:depot1:OpenDepotPositionParams"
745                 );
746                 params.values("name").add(positionName);
747                 if(productIdentity != null) {
748                     params.values("product").add(productIdentity);
749                 }
750                 if(openingDate != null) {
751                     params.values("openingDate").add(openingDate);
752                 }
753                 params.values("isLocked").add(Boolean.FALSE);
754                 return this.openDepotPosition(
755                     header,
756                     depot,
757                     params
758                 );
759             }
760             else {
761                 return null;
762             }
763         }
764     }
765     
766     //-----------------------------------------------------------------------
767
public DataproviderObject_1_0 createBookingByPosition(
768         ServiceHeader header,
769         Path depotEntityIdentity,
770         DataproviderObject params,
771         List JavaDoc errors
772     ) throws ServiceException {
773         return this.createCreditDebitBooking(
774             header,
775             depotEntityIdentity,
776             (String JavaDoc)params.values("valueDate").get(0),
777             params.values("bookingType").get(0) == null
778                 ? 0
779                 : ((Short JavaDoc)params.values("bookingType").get(0)).shortValue(),
780             (BigDecimal JavaDoc)params.values("quantity").get(0),
781             (String JavaDoc)params.values("bookingTextName").get(0),
782             (Path)params.values("bookingText").get(0),
783             (Path)params.values("positionCredit").get(0),
784             (Path)params.values("positionDebit").get(0),
785             null,
786             null,
787             (Path)params.values("reversalOf").get(0)
788         );
789     }
790     
791     //-----------------------------------------------------------------------
792
public DataproviderObject_1_0 createBookingByProduct(
793         ServiceHeader header,
794         Path depotEntityIdentity,
795         DataproviderObject params,
796         List JavaDoc errors
797     ) throws ServiceException {
798         if(params.values("product").get(0) == null) {
799            throw new ServiceException(
800                OpenCrxException.DOMAIN,
801                OpenCrxException.DEPOT_MISSING_PRODUCT,
802                null,
803                "Missing product"
804            );
805         }
806         DataproviderObject_1_0 product = this.plugin.retrieveObjectFromLocal(
807             header,
808             (Path)params.values("product").get(0)
809         );
810         String JavaDoc positionName = product.values("productNumber").size() > 0
811             ? (String JavaDoc)product.values("productNumber").get(0)
812             : (String JavaDoc)product.values("name").get(0);
813             
814         DataproviderObject_1_0 positionCredit = this.getAndCreateDepotPosition(
815             header,
816             depotEntityIdentity,
817             (String JavaDoc)params.values("depotNumberCredit").get(0),
818             (Path)params.values("depotCredit").get(0),
819             positionName,
820             product.path(),
821             (String JavaDoc)params.values("valueDate").get(0)
822         );
823         if(positionCredit == null) {
824            throw new ServiceException(
825                OpenCrxException.DOMAIN,
826                OpenCrxException.DEPOT_INVALID_POSITION_CREDIT,
827                null,
828                "Can not get/create credit depot position"
829            );
830         }
831         DataproviderObject_1_0 positionDebit = this.getAndCreateDepotPosition(
832             header,
833             depotEntityIdentity,
834             (String JavaDoc)params.values("depotNumberDebit").get(0),
835             (Path)params.values("depotDebit").get(0),
836             positionName,
837             product.path(),
838             (String JavaDoc)params.values("valueDate").get(0)
839         );
840         if(positionDebit == null) {
841            throw new ServiceException(
842                OpenCrxException.DOMAIN,
843                OpenCrxException.DEPOT_INVALID_POSITION_DEBIT,
844                null,
845                "Can not get/create debit depot position"
846            );
847         }
848         return this.createCreditDebitBooking(
849             header,
850             depotEntityIdentity,
851             (String JavaDoc)params.values("valueDate").get(0),
852             params.values("bookingType").get(0) == null
853                 ? 0
854                 : ((Short JavaDoc)params.values("bookingType").get(0)).shortValue(),
855             (BigDecimal JavaDoc)params.values("quantity").get(0),
856             (String JavaDoc)params.values("bookingTextName").get(0),
857             (Path)params.values("bookingText").get(0),
858             positionCredit.path(),
859             positionDebit.path(),
860             null,
861             null,
862             (Path)params.values("reversalOf").get(0)
863         );
864     }
865     
866     //-----------------------------------------------------------------------
867
public DataproviderObject_1_0 createBookingByPositionName(
868         ServiceHeader header,
869         Path depotEntityIdentity,
870         DataproviderObject params,
871         List JavaDoc errors
872     ) throws ServiceException {
873         DataproviderObject_1_0 positionCredit = this.getAndCreateDepotPosition(
874             header,
875             depotEntityIdentity,
876             (String JavaDoc)params.values("depotNumberCredit").get(0),
877             (Path)params.values("depotCredit").get(0),
878             (String JavaDoc)params.values("positionName").get(0),
879             null,
880             (String JavaDoc)params.values("valueDate").get(0)
881         );
882         if(positionCredit == null) {
883            throw new ServiceException(
884                OpenCrxException.DOMAIN,
885                OpenCrxException.DEPOT_INVALID_POSITION_CREDIT,
886                null,
887                "Can not get/create credit depot position"
888            );
889         }
890         DataproviderObject_1_0 positionDebit = this.getAndCreateDepotPosition(
891             header,
892             depotEntityIdentity,
893             (String JavaDoc)params.values("depotNumberDebit").get(0),
894             (Path)params.values("depotDebit").get(0),
895             (String JavaDoc)params.values("positionName").get(0),
896             null,
897             (String JavaDoc)params.values("valueDate").get(0)
898         );
899         if(positionDebit == null) {
900            throw new ServiceException(
901                OpenCrxException.DOMAIN,
902                OpenCrxException.DEPOT_INVALID_POSITION_DEBIT,
903                null,
904                "Can not get/create debit depot position"
905            );
906         }
907         return this.createCreditDebitBooking(
908             header,
909             depotEntityIdentity,
910             (String JavaDoc)params.values("valueDate").get(0),
911             params.values("bookingType").get(0) == null
912                 ? 0
913                 : ((Short JavaDoc)params.values("bookingType").get(0)).shortValue(),
914             (BigDecimal JavaDoc)params.values("quantity").get(0),
915             (String JavaDoc)params.values("bookingTextName").get(0),
916             (Path)params.values("bookingText").get(0),
917             positionCredit.path(),
918             positionDebit.path(),
919             null,
920             null,
921             (Path)params.values("reversalOf").get(0)
922         );
923     }
924     
925     //-----------------------------------------------------------------------
926
public void refreshReport(
927         ServiceHeader header,
928         Path depotIdentity,
929         DataproviderObject_1_0 report,
930         DataproviderObject_1_0 reportPreviousPeriod
931     ) throws ServiceException {
932         // Refresh only only draft reports
933
if(
934             (report.values("isDraft").size() > 0) &&
935             ((Boolean JavaDoc)report.values("isDraft").get(0)).booleanValue()
936         ) {
937             this.plugin.removeAll(
938                 report.path().getChild("itemPosition"),
939                 null,
940                 0,
941                 null
942             );
943             this.plugin.removeAll(
944                 report.path().getChild("itemBooking"),
945                 null,
946                 0,
947                 null
948             );
949             DataproviderObject_1_0 bookingPeriod = this.plugin.retrieveObjectFromLocal(
950                 header,
951                 (Path)report.values("bookingPeriod").get(0)
952             );
953             String JavaDoc periodStartsAt = (String JavaDoc)bookingPeriod.values("periodStartsAt").get(0);
954             String JavaDoc periodEndsAtExclusive = (String JavaDoc)bookingPeriod.values("periodEndsAtExclusive").get(0);
955             // positions
956
List JavaDoc positions = this.delegation.addFindRequest(
957                 depotIdentity.getChild("position"),
958                 null,
959                 AttributeSelectors.ALL_ATTRIBUTES,
960                 0,
961                 Integer.MAX_VALUE,
962                 Directions.ASCENDING
963             );
964             for(
965                 Iterator JavaDoc i = positions.iterator();
966                 i.hasNext();
967             ) {
968                 DataproviderObject_1_0 position = (DataproviderObject_1_0)i.next();
969                 
970                 // Set beginning of report balances to end of period balances of previous report
971
BigDecimal JavaDoc balanceBop = new BigDecimal JavaDoc(0);
972                 BigDecimal JavaDoc balanceDebitBop = new BigDecimal JavaDoc(0);
973                 BigDecimal JavaDoc balanceCreditBop = new BigDecimal JavaDoc(0);
974                 BigDecimal JavaDoc balance = new BigDecimal JavaDoc(0);
975                 BigDecimal JavaDoc balanceCredit = new BigDecimal JavaDoc(0);
976                 BigDecimal JavaDoc balanceDebit = new BigDecimal JavaDoc(0);
977                 if(reportPreviousPeriod != null) {
978                     List JavaDoc items = this.delegation.addFindRequest(
979                         reportPreviousPeriod.path().getChild("itemPosition"),
980                         new FilterProperty[]{
981                             new FilterProperty(
982                                 Quantors.THERE_EXISTS,
983                                 "position",
984                                 FilterOperators.IS_IN,
985                                 new Object JavaDoc[]{position.path()}
986                             )
987                         },
988                         AttributeSelectors.ALL_ATTRIBUTES,
989                         0,
990                         Integer.MAX_VALUE,
991                         Directions.ASCENDING
992                     );
993                     if(items.size() > 0) {
994                         DataproviderObject_1_0 itemPosition = (DataproviderObject_1_0)items.iterator().next();
995                         balanceBop = (BigDecimal JavaDoc)itemPosition.values("balance").get(0);
996                         balanceCreditBop = (BigDecimal JavaDoc)itemPosition.values("balanceCredit").get(0);
997                         balanceDebitBop = (BigDecimal JavaDoc)itemPosition.values("balanceDebit").get(0);
998                         balance = (BigDecimal JavaDoc)itemPosition.values("balance").get(0);
999                         balanceCredit = (BigDecimal JavaDoc)itemPosition.values("balanceCredit").get(0);
1000                        balanceDebit = (BigDecimal JavaDoc)itemPosition.values("balanceDebit").get(0);
1001                    }
1002                }
1003                // Bookings
1004
List JavaDoc bookings = null;
1005                if(periodEndsAtExclusive == null) {
1006                    bookings = this.delegation.addFindRequest(
1007                        depotIdentity.getPrefix(5).getChild("booking"),
1008                        new FilterProperty[]{
1009                            new FilterProperty(
1010                                Quantors.THERE_EXISTS,
1011                                "valueDate",
1012                                FilterOperators.IS_GREATER_OR_EQUAL,
1013                                new String JavaDoc[]{periodStartsAt}
1014                            ),
1015                            new FilterProperty(
1016                                Quantors.THERE_EXISTS,
1017                                "position",
1018                                FilterOperators.IS_IN,
1019                                new Object JavaDoc[]{position.path()}
1020                            ),
1021                            new FilterProperty(
1022                                Quantors.THERE_EXISTS,
1023                                "bookingStatus",
1024                                FilterOperators.IS_IN,
1025                                new Short JavaDoc[]{new Short JavaDoc(BOOKING_STATUS_PROCESSED)}
1026                            )
1027                        },
1028                        AttributeSelectors.ALL_ATTRIBUTES,
1029                        new AttributeSpecifier[]{
1030                            new AttributeSpecifier("valueDate", 0, Orders.ASCENDING)
1031                        },
1032                        0,
1033                        Integer.MAX_VALUE,
1034                        Directions.ASCENDING
1035                    );
1036                }
1037                else {
1038                    bookings = this.delegation.addFindRequest(
1039                        depotIdentity.getPrefix(5).getChild("booking"),
1040                        new FilterProperty[]{
1041                            new FilterProperty(
1042                                Quantors.THERE_EXISTS,
1043                                "valueDate",
1044                                FilterOperators.IS_GREATER_OR_EQUAL,
1045                                new String JavaDoc[]{periodStartsAt}
1046                            ),
1047                            new FilterProperty(
1048                                Quantors.THERE_EXISTS,
1049                                "valueDate",
1050                                FilterOperators.IS_LESS,
1051                                new String JavaDoc[]{periodEndsAtExclusive}
1052                            ),
1053                            new FilterProperty(
1054                                Quantors.THERE_EXISTS,
1055                                "position",
1056                                FilterOperators.IS_IN,
1057                                new Object JavaDoc[]{position.path()}
1058                            ),
1059                            new FilterProperty(
1060                                Quantors.THERE_EXISTS,
1061                                "bookingStatus",
1062                                FilterOperators.IS_IN,
1063                                new Short JavaDoc[]{new Short JavaDoc(BOOKING_STATUS_PROCESSED)}
1064                            )
1065                        },
1066                        AttributeSelectors.ALL_ATTRIBUTES,
1067                        new AttributeSpecifier[]{
1068                            new AttributeSpecifier("valueDate", 0, Orders.ASCENDING)
1069                        },
1070                        0,
1071                        Integer.MAX_VALUE,
1072                        Directions.ASCENDING
1073                    );
1074                }
1075                // Depot report item for each booking
1076
for(
1077                    Iterator JavaDoc j = bookings.iterator();
1078                    j.hasNext();
1079                ) {
1080                    DataproviderObject_1_0 booking = (DataproviderObject_1_0)j.next();
1081                    DataproviderObject itemBooking = new DataproviderObject(
1082                        report.path().getDescendant(new String JavaDoc[]{"itemBooking", this.plugin.getUidAsString()})
1083                    );
1084                    // Report item credit
1085
if("org:opencrx:kernel:depot1:CreditBooking".equals(booking.values(SystemAttributes.OBJECT_CLASS).get(0))) {
1086                        itemBooking.values(SystemAttributes.OBJECT_CLASS).add(
1087                            "org:opencrx:kernel:depot1:DepotReportItemCredit"
1088                        );
1089                        BigDecimal JavaDoc quantityCredit = (BigDecimal JavaDoc)booking.values("quantityCredit").get(0);
1090                        itemBooking.values("quantityCredit").add(quantityCredit);
1091                        balanceCredit = balanceCredit.add(quantityCredit);
1092                        balance = balance.add(quantityCredit);
1093                    }
1094                    // Report item debit
1095
else {
1096                        itemBooking.values(SystemAttributes.OBJECT_CLASS).add(
1097                            "org:opencrx:kernel:depot1:DepotReportItemDebit"
1098                        );
1099                        BigDecimal JavaDoc quantityDebit = (BigDecimal JavaDoc)booking.values("quantityDebit").get(0);
1100                        itemBooking.values("quantityDebit").add(quantityDebit);
1101                        balanceDebit = balanceDebit.add(quantityDebit);
1102                        balance = balance.subtract(quantityDebit);
1103                    }
1104                    itemBooking.values("positionName").addAll(
1105                        position.values("name")
1106                    );
1107                    itemBooking.values("valueDate").addAll(
1108                        booking.values("valueDate")
1109                    );
1110                    itemBooking.values("bookingDate").addAll(
1111                        booking.values("bookingDate")
1112                    );
1113                    itemBooking.values("balance").add(balance);
1114                    itemBooking.values("balanceCredit").add(balanceCredit);
1115                    itemBooking.values("balanceDebit").add(balanceDebit);
1116                    itemBooking.values("position").add(position.path());
1117                    itemBooking.values("booking").add(booking.path());
1118                    itemBooking.values("cb").addAll(
1119                        booking.values("cb")
1120                    );
1121                    // Create it
1122
this.delegation.addCreateRequest(itemBooking);
1123                }
1124                // Report item position
1125
DataproviderObject itemPosition = new DataproviderObject(
1126                    report.path().getDescendant(new String JavaDoc[]{"itemPosition", this.plugin.getUidAsString()})
1127                );
1128                itemPosition.values(SystemAttributes.OBJECT_CLASS).add(
1129                    "org:opencrx:kernel:depot1:DepotReportItemPosition"
1130                );
1131                itemPosition.values("positionName").addAll(
1132                    position.values("name")
1133                );
1134                itemPosition.values("valueDate").add(periodStartsAt);
1135                itemPosition.values("balanceBop").add(balanceBop);
1136                itemPosition.values("balanceCreditBop").add(balanceCreditBop);
1137                itemPosition.values("balanceDebitBop").add(balanceDebitBop);
1138                itemPosition.values("balance").add(balance);
1139                itemPosition.values("balanceCredit").add(balanceCredit);
1140                itemPosition.values("balanceDebit").add(balanceDebit);
1141                itemPosition.values("position").add(position.path());
1142                // Create it
1143
this.delegation.addCreateRequest(itemPosition);
1144            }
1145        }
1146    }
1147    
1148    //-----------------------------------------------------------------------
1149
public void assertReports(
1150        ServiceHeader header,
1151        Path depotIdentity
1152    ) throws ServiceException {
1153        
1154        DataproviderObject_1_0 depot = this.plugin.retrieveObjectFromLocal(header, depotIdentity);
1155        
1156        // Get booking periods
1157
List JavaDoc bookingPeriods = this.delegation.addFindRequest(
1158            depotIdentity.getPrefix(7).getChild("bookingPeriod"),
1159            null,
1160            AttributeSelectors.ALL_ATTRIBUTES,
1161            new AttributeSpecifier[]{
1162                new AttributeSpecifier("periodStartsAt", 0, Orders.ASCENDING)
1163            },
1164            0,
1165            Integer.MAX_VALUE,
1166            Directions.ASCENDING
1167        );
1168        DataproviderObject_1_0 reportPreviousPeriod = null;
1169        DataproviderObject_1_0 latestReport = null;
1170        
1171        // Assert report for each booking period
1172
for(
1173            Iterator JavaDoc i = bookingPeriods.iterator();
1174            i.hasNext();
1175        ) {
1176            DataproviderObject_1_0 bookingPeriod = (DataproviderObject_1_0)i.next();
1177            List JavaDoc reports = this.delegation.addFindRequest(
1178                depotIdentity.getChild("report"),
1179                new FilterProperty[]{
1180                    new FilterProperty(
1181                        Quantors.THERE_EXISTS,
1182                        "bookingPeriod",
1183                        FilterOperators.IS_IN,
1184                        new Object JavaDoc[]{bookingPeriod.path()}
1185                    )
1186                },
1187                AttributeSelectors.ALL_ATTRIBUTES,
1188                0,
1189                Integer.MAX_VALUE,
1190                Directions.ASCENDING
1191            );
1192            DataproviderObject_1_0 report = null;
1193            if(reports.size() > 0) {
1194                report = (DataproviderObject_1_0)reports.iterator().next();
1195            }
1196            else {
1197                DataproviderObject newReport = new DataproviderObject(
1198                    depotIdentity.getDescendant(new String JavaDoc[]{"report", this.plugin.getUidAsString()})
1199                );
1200                newReport.values(SystemAttributes.OBJECT_CLASS).add(
1201                    "org:opencrx:kernel:depot1:DepotReport"
1202                );
1203                newReport.values("name").addAll(
1204                    bookingPeriod.values("name")
1205                );
1206                newReport.values("description").addAll(
1207                    bookingPeriod.values("description")
1208                );
1209                newReport.values("isDraft").add(
1210                    Boolean.TRUE
1211                );
1212                newReport.values("bookingPeriod").add(
1213                    bookingPeriod.path()
1214                );
1215                this.delegation.addCreateRequest(
1216                    newReport
1217                );
1218                report = newReport;
1219            }
1220            // Latest report
1221
String JavaDoc currentDate = DateFormat.getInstance().format(new Date JavaDoc());
1222            if(
1223               (currentDate.compareTo(bookingPeriod.values("periodStartsAt").get(0)) >= 0) &&
1224               ((bookingPeriod.values("periodEndsAtExclusive").size() == 0) || (currentDate.compareTo(bookingPeriod.values("periodEndsAtExclusive").get(0)) < 0))
1225            ) {
1226                latestReport = report;
1227            }
1228            // Refresh
1229
this.refreshReport(
1230                header,
1231                depotIdentity,
1232                report,
1233                reportPreviousPeriod
1234            );
1235            reportPreviousPeriod = report;
1236        }
1237        if(latestReport != null) {
1238            DataproviderObject modifiableDepot = this.plugin.retrieveObjectForModification(depotIdentity);
1239            modifiableDepot.clearValues("latestReport").add(latestReport.path());
1240        }
1241    }
1242    
1243    //-----------------------------------------------------------------------
1244
public DataproviderObject_1_0 cancelCompoundBooking(
1245        ServiceHeader header,
1246        DataproviderObject_1_0 compoundBooking,
1247        DataproviderObject_1_0 params,
1248        List JavaDoc errors
1249    ) throws ServiceException {
1250        boolean isProcessed = compoundBooking.values("bookingStatus").size() > 0
1251            ? ((Number JavaDoc)compoundBooking.values("bookingStatus").get(0)).shortValue() == BOOKING_STATUS_PROCESSED
1252            : false;
1253        if(!isProcessed) {
1254            throw new ServiceException(
1255                OpenCrxException.DOMAIN,
1256                OpenCrxException.BOOKING_STATUS_MUST_BE_PROCESSED,
1257                null,
1258                "Booking status must be processed. Cancel is not allowed."
1259            );
1260        }
1261        short bookingType = compoundBooking.values("bookingType").size() > 0
1262            ? ((Number JavaDoc)compoundBooking.values("bookingType").get(0)).shortValue()
1263            : BOOKING_TYPE_STANDARD;
1264        // Can not cancel reversal bookings
1265
if(bookingType == BOOKING_TYPE_REVERSAL) {
1266            throw new ServiceException(
1267                OpenCrxException.DOMAIN,
1268                OpenCrxException.DEPOT_CAN_NOT_CANCEL_REVERSAL_BOOKING,
1269                null,
1270                "Can not cancel reversal booking"
1271            );
1272        }
1273        // Check whether compound booking already has a reversal booking
1274
List JavaDoc compoundBookings = this.delegation.addFindRequest(
1275            compoundBooking.path().getParent(),
1276            new FilterProperty[]{
1277                new FilterProperty(
1278                    Quantors.THERE_EXISTS,
1279                    "reversalOf",
1280                    FilterOperators.IS_IN,
1281                    new Path[]{compoundBooking.path()}
1282                )
1283            },
1284            AttributeSelectors.ALL_ATTRIBUTES,
1285            0,
1286            Integer.MAX_VALUE,
1287            Directions.ASCENDING
1288        );
1289        if(compoundBookings.size() > 0) {
1290            DataproviderObject_1_0 reversal = (DataproviderObject_1_0)compoundBookings.iterator().next();
1291            throw new ServiceException(
1292                OpenCrxException.DOMAIN,
1293                OpenCrxException.DEPOT_ALREADY_HAS_REVERSAL_BOOKING,
1294                new BasicException.Parameter[]{
1295                    new BasicException.Parameter("param0", reversal.values("name").get(0) + " / " + reversal.values("bookingDate").get(0))
1296                },
1297                "Compound booking already cancelled"
1298            );
1299        }
1300
1301        // Create cancel compound booking
1302
DataproviderObject cancelCompoundBooking = new DataproviderObject(
1303            compoundBooking.path().getParent().getChild(this.plugin.getUidAsString())
1304        );
1305        cancelCompoundBooking.values(SystemAttributes.OBJECT_CLASS).add(
1306            "org:opencrx:kernel:depot1:CompoundBooking"
1307        );
1308        cancelCompoundBooking.values("name").addAll(compoundBooking.values("name"));
1309        cancelCompoundBooking.values("description").addAll(compoundBooking.values("description"));
1310        cancelCompoundBooking.values("bookingDate").add(DateFormat.getInstance().format(new Date JavaDoc()));
1311        cancelCompoundBooking.values("bookingType").add(new Short JavaDoc(BOOKING_TYPE_REVERSAL));
1312        cancelCompoundBooking.values("bookingStatus").add(new Short JavaDoc(BOOKING_STATUS_PENDING));
1313        cancelCompoundBooking.values("reversalOf").add(compoundBooking.path());
1314        this.delegation.addCreateRequest(
1315            cancelCompoundBooking
1316        );
1317
1318        // Create cancel bookings
1319
List JavaDoc bookings = this.delegation.addFindRequest(
1320            compoundBooking.path().getPrefix(compoundBooking.path().size()-2).getChild("booking"),
1321            new FilterProperty[]{
1322                new FilterProperty(
1323                    Quantors.THERE_EXISTS,
1324                    "cb",
1325                    FilterOperators.IS_IN,
1326                    new Path[]{compoundBooking.path()}
1327                )
1328            },
1329            AttributeSelectors.ALL_ATTRIBUTES,
1330            0,
1331            Integer.MAX_VALUE,
1332            Directions.ASCENDING
1333        );
1334        for(
1335            Iterator JavaDoc i = bookings.iterator();
1336            i.hasNext();
1337        ) {
1338            DataproviderObject_1_0 booking = (DataproviderObject_1_0)i.next();
1339            DataproviderObject cancelBooking = new DataproviderObject(
1340                booking.path().getParent().getChild(this.plugin.getUidAsString())
1341            );
1342            if("org:opencrx:kernel:depot1:CreditBooking".equals(booking.values(SystemAttributes.OBJECT_CLASS).get(0))) {
1343                cancelBooking.values(SystemAttributes.OBJECT_CLASS).add(
1344                    "org:opencrx:kernel:depot1:DebitBooking"
1345                );
1346                cancelBooking.values("quantityDebit").addAll(booking.values("quantityCredit"));
1347            }
1348            else if("org:opencrx:kernel:depot1:DebitBooking".equals(booking.values(SystemAttributes.OBJECT_CLASS).get(0))) {
1349                cancelBooking.values(SystemAttributes.OBJECT_CLASS).add(
1350                    "org:opencrx:kernel:depot1:CreditBooking"
1351                );
1352                cancelBooking.values("quantityCredit").addAll(booking.values("quantityDebit"));
1353            }
1354            cancelBooking.values("name").addAll(booking.values("name"));
1355            cancelBooking.values("description").addAll(booking.values("description"));
1356            cancelBooking.values("valueDate").addAll(booking.values("valueDate"));
1357            cancelBooking.values("bookingDate").add(DateFormat.getInstance().format(new Date JavaDoc()));
1358            cancelBooking.values("position").addAll(booking.values("position"));
1359            this.testForOpenPosition(
1360                header,
1361                (String JavaDoc)cancelBooking.values("valueDate").get(0),
1362                BOOKING_TYPE_REVERSAL,
1363                (Path)cancelBooking.values("position").get(0)
1364            );
1365            cancelBooking.values("bookingType").add(new Short JavaDoc(BOOKING_TYPE_REVERSAL));
1366            cancelBooking.values("bookingStatus").add(new Short JavaDoc(BOOKING_STATUS_PENDING));
1367            cancelBooking.values("cb").add(cancelCompoundBooking.path());
1368            this.delegation.addCreateRequest(
1369                cancelBooking
1370            );
1371        }
1372        return cancelCompoundBooking;
1373    }
1374
1375    //-----------------------------------------------------------------------
1376
public void acceptCompoundBooking(
1377        ServiceHeader header,
1378        DataproviderObject_1_0 compoundBooking
1379    ) throws ServiceException {
1380        boolean isPending = compoundBooking.values("bookingStatus").size() > 0
1381            ? ((Number JavaDoc)compoundBooking.values("bookingStatus").get(0)).shortValue() == BOOKING_STATUS_PENDING
1382            : false;
1383        if(!isPending) {
1384            throw new ServiceException(
1385                OpenCrxException.DOMAIN,
1386                OpenCrxException.BOOKING_STATUS_MUST_BE_PENDING,
1387                null,
1388                "Booking status must be pending. Accept is not allowed."
1389            );
1390        }
1391        String JavaDoc acceptedBy = (String JavaDoc)header.getPrincipalChain().get(0) + " @ " + DateFormat.getInstance().format(new Date JavaDoc());
1392        DataproviderObject modifiedCompoundBooking = this.plugin.retrieveObjectForModification(compoundBooking.path());
1393        modifiedCompoundBooking.values("acceptedBy").add(acceptedBy);
1394    }
1395    
1396    //-----------------------------------------------------------------------
1397
public void finalizeCompoundBooking(
1398        ServiceHeader header,
1399        DataproviderObject_1_0 compoundBooking
1400    ) throws ServiceException {
1401        boolean isPending = compoundBooking.values("bookingStatus").size() > 0
1402            ? ((Number JavaDoc)compoundBooking.values("bookingStatus").get(0)).shortValue() == BOOKING_STATUS_PENDING
1403            : false;
1404        if(!isPending) {
1405            throw new ServiceException(
1406                OpenCrxException.DOMAIN,
1407                OpenCrxException.BOOKING_STATUS_MUST_BE_PENDING,
1408                null,
1409                "Booking status must be pending. Finalize is not allowed."
1410            );
1411        }
1412        // Process bookings
1413
List JavaDoc bookings = this.delegation.addFindRequest(
1414            compoundBooking.path().getPrefix(compoundBooking.path().size()-2).getChild("booking"),
1415            new FilterProperty[]{
1416                new FilterProperty(
1417                    Quantors.THERE_EXISTS,
1418                    "cb",
1419                    FilterOperators.IS_IN,
1420                    new Path[]{compoundBooking.path()}
1421                )
1422            },
1423            AttributeSelectors.ALL_ATTRIBUTES,
1424            0,
1425            Integer.MAX_VALUE,
1426            Directions.ASCENDING
1427        );
1428        for(
1429            Iterator JavaDoc i = bookings.iterator();
1430            i.hasNext();
1431        ) {
1432            DataproviderObject_1_0 booking = (DataproviderObject_1_0)i.next();
1433            this.testForOpenPosition(
1434                header,
1435                (String JavaDoc)booking.values("valueDate").get(0),
1436                ((Number JavaDoc)booking.values("bookingType").get(0)).shortValue(),
1437                (Path)booking.values("position").get(0)
1438            );
1439            DataproviderObject finalizedBooking = this.plugin.retrieveObjectForModification(booking.path());
1440            finalizedBooking.clearValues("bookingStatus").add(new Short JavaDoc(BOOKING_STATUS_PROCESSED));
1441        }
1442        // Process compound booking
1443
DataproviderObject finalizedCompoundBooking = this.plugin.retrieveObjectForModification(compoundBooking.path());
1444        finalizedCompoundBooking.clearValues("bookingStatus").add(new Short JavaDoc(BOOKING_STATUS_PROCESSED));
1445    }
1446
1447    //-----------------------------------------------------------------------
1448
public void removeCompoundBooking(
1449        ServiceHeader header,
1450        Path compoundBookingIdentity
1451    ) throws ServiceException {
1452        DataproviderObject_1_0 compoundBooking = this.plugin.retrieveObjectFromLocal(header, compoundBookingIdentity);
1453        // isPending
1454
boolean isPending = compoundBooking.values("bookingStatus").size() > 0
1455            ? ((Number JavaDoc)compoundBooking.values("bookingStatus").get(0)).shortValue() == BOOKING_STATUS_PENDING
1456            : false;
1457        if(!isPending) {
1458            throw new ServiceException(
1459                OpenCrxException.DOMAIN,
1460                OpenCrxException.BOOKING_STATUS_MUST_BE_PENDING,
1461                null,
1462                "Booking status is not pending. Delete is not allowed."
1463            );
1464        }
1465        // isLocked
1466
boolean isLocked = compoundBooking.values("isLocked").size() > 0
1467            ? ((Boolean JavaDoc)compoundBooking.values("isLocked").get(0)).booleanValue()
1468            : false;
1469        if(isLocked) {
1470            throw new ServiceException(
1471                OpenCrxException.DOMAIN,
1472                OpenCrxException.BOOKING_IS_LOCKED_CAN_NOT_DELETE,
1473                null,
1474                "Compound booking is locked. Delete is not allowed."
1475            );
1476        }
1477        // Delete bookings
1478
List JavaDoc bookings = this.delegation.addFindRequest(
1479            compoundBookingIdentity.getPrefix(compoundBookingIdentity.size()-2).getChild("booking"),
1480            new FilterProperty[]{
1481                new FilterProperty(
1482                    Quantors.THERE_EXISTS,
1483                    "cb",
1484                    FilterOperators.IS_IN,
1485                    new Path[]{compoundBookingIdentity}
1486                )
1487            },
1488            AttributeSelectors.ALL_ATTRIBUTES,
1489            0,
1490            Integer.MAX_VALUE,
1491            Directions.ASCENDING
1492        );
1493        List JavaDoc bookingIdentities = new ArrayList JavaDoc();
1494        for(
1495            Iterator JavaDoc i = bookings.iterator();
1496            i.hasNext();
1497        ) {
1498            DataproviderObject_1_0 booking = (DataproviderObject_1_0)i.next();
1499            bookingIdentities.add(booking.path());
1500        }
1501        for(
1502            Iterator JavaDoc i = bookingIdentities.iterator();
1503            i.hasNext();
1504        ) {
1505            Path bookingIdentity = (Path)i.next();
1506            this.plugin.removeObject(bookingIdentity);
1507        }
1508        
1509        // Delete compound booking
1510
this.plugin.removeObject(compoundBookingIdentity);
1511    }
1512
1513    //-----------------------------------------------------------------------
1514
public void removeBooking(
1515        Path bookingIdentity
1516    ) throws ServiceException {
1517        throw new ServiceException(
1518            OpenCrxException.DOMAIN,
1519            OpenCrxException.DEPOT_CAN_NOT_REMOVE_BOOKING,
1520            null,
1521            "Can not delete bookings"
1522        );
1523    }
1524
1525    //-----------------------------------------------------------------------
1526
private boolean hasBookings(
1527        Path bookingElementIdentity
1528    ) throws ServiceException {
1529        Path segmentIdentity = bookingElementIdentity.getPrefix(5);
1530        Path positionPattern = null;
1531        if(bookingElementIdentity.size() == 7) {
1532            positionPattern = bookingElementIdentity.getDescendant(
1533                new String JavaDoc[]{"contract", "%"}
1534            );
1535        }
1536        else if(bookingElementIdentity.size() == 9) {
1537            positionPattern = bookingElementIdentity.getDescendant(
1538                new String JavaDoc[]{"depot", "%"}
1539            );
1540        }
1541        else if(bookingElementIdentity.size() == 11) {
1542            positionPattern = bookingElementIdentity.getDescendant(
1543                new String JavaDoc[]{"position", "%"}
1544            );
1545        }
1546        else if(bookingElementIdentity.size() == 13) {
1547            positionPattern = bookingElementIdentity;
1548        }
1549        List JavaDoc bookings = this.delegation.addFindRequest(
1550            segmentIdentity.getPrefix(5).getChild("extent"),
1551            new FilterProperty[]{
1552                new FilterProperty(
1553                    Quantors.THERE_EXISTS,
1554                    "identity",
1555                    FilterOperators.IS_LIKE,
1556                    new Object JavaDoc[]{
1557                        segmentIdentity.getDescendant(
1558                            new String JavaDoc[]{"booking", ":*"}
1559                        )
1560                    }
1561                ),
1562                new FilterProperty(
1563                    Quantors.THERE_EXISTS,
1564                    "position",
1565                    FilterOperators.IS_LIKE,
1566                    new Object JavaDoc[]{positionPattern}
1567                )
1568            },
1569            AttributeSelectors.ALL_ATTRIBUTES,
1570            0,
1571            Integer.MAX_VALUE,
1572            Directions.ASCENDING
1573        );
1574        return bookings.size() > 0;
1575    }
1576    
1577    //-----------------------------------------------------------------------
1578
public void removeDepotEntity(
1579        Path depotEntityIdentity
1580    ) throws ServiceException {
1581        if(this.hasBookings(depotEntityIdentity)) {
1582            throw new ServiceException(
1583                OpenCrxException.DOMAIN,
1584                OpenCrxException.DEPOT_ENTITY_HAS_BOOKINGS,
1585                null,
1586                "Depot entity has bookings."
1587            );
1588        }
1589        this.delegation.addRemoveRequest(
1590            depotEntityIdentity
1591        );
1592    }
1593    
1594    //-----------------------------------------------------------------------
1595
public void removeDepotContract(
1596        Path depotContractIdentity
1597    ) throws ServiceException {
1598        if(this.hasBookings(depotContractIdentity)) {
1599            throw new ServiceException(
1600                OpenCrxException.DOMAIN,
1601                OpenCrxException.DEPOT_CONTRACT_HAS_BOOKINGS,
1602                null,
1603                "Depot entity has bookings."
1604            );
1605        }
1606        this.delegation.addRemoveRequest(
1607            depotContractIdentity
1608        );
1609    }
1610    
1611    //-----------------------------------------------------------------------
1612
public void removeDepot(
1613        Path depotIdentity
1614    ) throws ServiceException {
1615        if(this.hasBookings(depotIdentity)) {
1616            throw new ServiceException(
1617                OpenCrxException.DOMAIN,
1618                OpenCrxException.DEPOT_DEPOT_HAS_BOOKINGS,
1619                null,
1620                "Depot entity has bookings."
1621            );
1622        }
1623        this.delegation.addRemoveRequest(
1624            depotIdentity
1625        );
1626    }
1627    
1628    //-----------------------------------------------------------------------
1629
public void removeDepotPosition(
1630        Path depotPositionIdentity
1631    ) throws ServiceException {
1632        if(this.hasBookings(depotPositionIdentity)) {
1633            throw new ServiceException(
1634                OpenCrxException.DOMAIN,
1635                OpenCrxException.DEPOT_POSITION_HAS_BOOKINGS,
1636                null,
1637                "Depot entity has bookings."
1638            );
1639        }
1640        this.delegation.addRemoveRequest(
1641            depotPositionIdentity
1642        );
1643    }
1644    
1645    //-----------------------------------------------------------------------
1646
public DataproviderObject_1_0 openDepot(
1647        DataproviderObject_1_0 depotContract,
1648        DataproviderObject_1_0 params,
1649        List JavaDoc errors
1650    ) throws ServiceException {
1651        if(params.values("depotNumber").size() == 0) {
1652            throw new ServiceException(
1653                OpenCrxException.DOMAIN,
1654                OpenCrxException.BOOKING_DEPOT_NUMBER_REQUIRED,
1655                null,
1656                "Depot number is required."
1657            );
1658        }
1659        String JavaDoc depotNumber = (String JavaDoc)params.values("depotNumber").get(0);
1660        String JavaDoc depotNumberWithoutWhitespaces = this.stripWhitespaces(depotNumber);
1661        DataproviderObject depot = new DataproviderObject(
1662            depotContract.path().getDescendant(new String JavaDoc[]{"depot", depotNumberWithoutWhitespaces.replace('/', ':')})
1663        );
1664        depot.values(SystemAttributes.OBJECT_CLASS).add(
1665            "org:opencrx:kernel:depot1:Depot"
1666        );
1667        depot.values("name").addAll(params.values("name"));
1668        depot.values("description").addAll(params.values("description"));
1669        depot.values("depotNumber").add(depotNumber);
1670        depot.values("openingDate").add(
1671            params.values("openingDate").size() == 0
1672                ? DateFormat.getInstance().format(new Date JavaDoc())
1673                : (String JavaDoc)params.values("openingDate").get(0)
1674        );
1675        depot.values("depotType").addAll(params.values("depotType"));
1676        depot.values("depotGroup").addAll(params.values("depotGroup"));
1677        depot.values("isDefault").add(Boolean.FALSE);
1678        depot.values("isLocked").add(Boolean.FALSE);
1679        depot.values("allowPositionAutoCreate").add(Boolean.FALSE);
1680        this.plugin.createObject(
1681            depot
1682        );
1683        return depot;
1684    }
1685    
1686    //-----------------------------------------------------------------------
1687
public void closeDepot(
1688        DataproviderObject_1_0 depot,
1689        DataproviderObject_1_0 params,
1690        List JavaDoc errors
1691    ) throws ServiceException {
1692        if(depot.values("closingDate").size()> 0) {
1693            throw new ServiceException(
1694                OpenCrxException.DOMAIN,
1695                OpenCrxException.BOOKING_DEPOT_IS_CLOSED_CAN_NOT_CLOSE,
1696                null,
1697                "Depot is closed. Can not close."
1698            );
1699        }
1700        DataproviderObject closedDepot = this.plugin.retrieveObjectForModification(depot.path());
1701        closedDepot.clearValues("isLocked").add(Boolean.TRUE);
1702        closedDepot.clearValues("closingDate").add(
1703            params.values("closingDate").size() == 0
1704                ? DateFormat.getInstance().format(new Date JavaDoc())
1705                : (String JavaDoc)params.values("closingDate").get(0)
1706        );
1707    }
1708    
1709    //-----------------------------------------------------------------------
1710
public DataproviderObject_1_0 openDepotPosition(
1711        ServiceHeader header,
1712        DataproviderObject_1_0 depot,
1713        DataproviderObject_1_0 params
1714    ) throws ServiceException {
1715        String JavaDoc depotPositionQualifier = params.values("qualifier").size() > 0
1716            ? (String JavaDoc)params.values("qualifier").get(0)
1717            : null;
1718        Path productRoleIdentity = params.values("productRole").size() > 0
1719            ? (Path)params.values("productRole").get(0)
1720            : null;
1721        Path productIdentity = params.values("product").size() > 0
1722            ? (Path)params.values("product").get(0)
1723            : null;
1724        String JavaDoc positionName = params.values("name").size() > 0
1725            ? (String JavaDoc)params.values("name").get(0)
1726            : null;
1727        String JavaDoc positionDescription = params.values("description").size() > 0
1728            ? (String JavaDoc)params.values("description").get(0)
1729            : null;
1730        String JavaDoc openingDate = params.values("openingDate").size() == 0
1731            ? DateFormat.getInstance().format(new Date JavaDoc())
1732            : (String JavaDoc)params.values("openingDate").get(0);
1733        Boolean JavaDoc isLocked = params.values("isLocked").size() == 0
1734            ? Boolean.FALSE
1735            : (Boolean JavaDoc)params.values("isLocked").get(0);
1736        return this.openDepotPosition(
1737            header,
1738            depot,
1739            positionName,
1740            positionDescription,
1741            openingDate,
1742            depotPositionQualifier,
1743            productRoleIdentity,
1744            productIdentity,
1745            isLocked
1746        );
1747    }
1748    
1749    //-----------------------------------------------------------------------
1750
public DataproviderObject_1_0 openDepotPosition(
1751        ServiceHeader header,
1752        DataproviderObject_1_0 depot,
1753        String JavaDoc positionName,
1754        String JavaDoc positionDescription,
1755        String JavaDoc openingDate,
1756        String JavaDoc depotPositionQualifier,
1757        Path productRoleIdentity,
1758        Path productIdentity,
1759        Boolean JavaDoc isLocked
1760    ) throws ServiceException {
1761        DataproviderObject depotPosition = new DataproviderObject(
1762            depot.path().getDescendant(new String JavaDoc[]{"position", this.plugin.getUidAsString()})
1763        );
1764        DataproviderObject_1_0 productRole = null;
1765        DataproviderObject_1_0 product = null;
1766        if(productRoleIdentity != null) {
1767            // Check whether position with given productRole already
1768
// exists. If yes, do not create new position.
1769
List JavaDoc positions = null;
1770            if(depotPositionQualifier == null) {
1771                positions = this.delegation.addFindRequest(
1772                    depot.path().getChild("position"),
1773                    new FilterProperty[]{
1774                        new FilterProperty(
1775                            Quantors.THERE_EXISTS,
1776                            "basedOn",
1777                            FilterOperators.IS_IN,
1778                            new Object JavaDoc[]{productRoleIdentity}
1779                        )
1780                    },
1781                    AttributeSelectors.ALL_ATTRIBUTES,
1782                    0,
1783                    Integer.MAX_VALUE,
1784                    Directions.ASCENDING
1785                );
1786            }
1787            // qualifier and productRole must match
1788
else {
1789                positions = this.delegation.addFindRequest(
1790                    depot.path().getChild("position"),
1791                    new FilterProperty[]{
1792                        new FilterProperty(
1793                            Quantors.THERE_EXISTS,
1794                            "basedOn",
1795                            FilterOperators.IS_IN,
1796                            new Object JavaDoc[]{productRoleIdentity}
1797                        ),
1798                        new FilterProperty(
1799                            Quantors.THERE_EXISTS,
1800                            "qualifier",
1801                            FilterOperators.IS_IN,
1802                            new Object JavaDoc[]{depotPositionQualifier}
1803                        )
1804                    },
1805                    AttributeSelectors.ALL_ATTRIBUTES,
1806                    0,
1807                    Integer.MAX_VALUE,
1808                    Directions.ASCENDING
1809                );
1810            }
1811            if(positions.size() > 0) {
1812                return (DataproviderObject_1_0)positions.iterator().next();
1813            }
1814            productRole = this.plugin.retrieveObjectFromLocal(
1815                header,
1816                productRoleIdentity
1817            );
1818        }
1819        // Set class depending on supplied product and productRole
1820
if(productRole == null) {
1821            if(productIdentity != null) {
1822                // Check whether position with given product already
1823
// exists. If yes, do not create new position.
1824
List JavaDoc positions = null;
1825                if(depotPositionQualifier == null) {
1826                    positions = this.delegation.addFindRequest(
1827                        depot.path().getChild("position"),
1828                        new FilterProperty[]{
1829                            new FilterProperty(
1830                                Quantors.THERE_EXISTS,
1831                                "product",
1832                                FilterOperators.IS_IN,
1833                                new Object JavaDoc[]{productIdentity}
1834                            )
1835                        },
1836                        AttributeSelectors.ALL_ATTRIBUTES,
1837                        0,
1838                        Integer.MAX_VALUE,
1839                        Directions.ASCENDING
1840                    );
1841                }
1842                else {
1843                    positions = this.delegation.addFindRequest(
1844                        depot.path().getChild("position"),
1845                        new FilterProperty[]{
1846                            new FilterProperty(
1847                                Quantors.THERE_EXISTS,
1848                                "product",
1849                                FilterOperators.IS_IN,
1850                                new Object JavaDoc[]{productIdentity}
1851                            ),
1852                            new FilterProperty(
1853                                Quantors.THERE_EXISTS,
1854                                "qualifier",
1855                                FilterOperators.IS_IN,
1856                                new Object JavaDoc[]{depotPositionQualifier}
1857                            )
1858                        },
1859                        AttributeSelectors.ALL_ATTRIBUTES,
1860                        0,
1861                        Integer.MAX_VALUE,
1862                        Directions.ASCENDING
1863                    );
1864                }
1865                if(positions.size() > 0) {
1866                    return (DataproviderObject_1_0)positions.iterator().next();
1867                }
1868                product = this.plugin.retrieveObjectFromLocal(
1869                    header,
1870                    productIdentity
1871                );
1872                depotPosition.values(SystemAttributes.OBJECT_CLASS).add(
1873                    "org:opencrx:kernel:depot1:ProductDepotPosition"
1874                );
1875                depotPosition.values("product").add(product.path());
1876            }
1877            else {
1878                depotPosition.values(SystemAttributes.OBJECT_CLASS).add(
1879                    "org:opencrx:kernel:depot1:DepotPosition"
1880                );
1881            }
1882        }
1883        else if("org:opencrx:kernel:product1:ProductOffering".equals(productRole.values(SystemAttributes.OBJECT_CLASS).get(0))) {
1884            depotPosition.values(SystemAttributes.OBJECT_CLASS).add(
1885                "org:opencrx:kernel:depot1:ProductOfferingDepotPosition"
1886            );
1887        }
1888        else if("org:opencrx:kernel:product1:ProductBundle".equals(productRole.values(SystemAttributes.OBJECT_CLASS).get(0))) {
1889            depotPosition.values(SystemAttributes.OBJECT_CLASS).add(
1890                "org:opencrx:kernel:depot1:ProductBundleDepotPosition"
1891            );
1892        }
1893        else if("org:opencrx:kernel:product1:BundledProduct".equals(productRole.values(SystemAttributes.OBJECT_CLASS).get(0))) {
1894            depotPosition.values(SystemAttributes.OBJECT_CLASS).add(
1895                "org:opencrx:kernel:depot1:BundledProductDepotPosition"
1896            );
1897        }
1898        
1899        // In case a depot position qualifier is specified, set name to name + " #" + depotPositionQualifier.
1900
String JavaDoc name =
1901            positionName != null
1902                ? positionName
1903                : product != null
1904                    ? (String JavaDoc)product.values("name").get(0)
1905                    : productRole != null
1906                        ? (String JavaDoc)productRole.values("name").get(0)
1907                        : "";
1908        if(depotPositionQualifier != null) {
1909            depotPosition.values("qualifier").add(depotPositionQualifier);
1910            name += " #" + depotPositionQualifier;
1911        }
1912        depotPosition.values("name").add(name);
1913        // Set path qualifier to name (remove blanks and replace / by :
1914
String JavaDoc nameWithoutWhitspaces = this.stripWhitespaces(name);
1915        if(nameWithoutWhitspaces.length() > 0) {
1916            depotPosition.path().setTo(
1917                depotPosition.path().getParent().getChild(nameWithoutWhitspaces.replace('/', ':'))
1918            );
1919        }
1920        // description
1921
depotPosition.values("description").add(
1922            positionDescription != null
1923                ? positionDescription
1924                : product != null
1925                    ? product.values("description").get(0)
1926                    : productRole != null
1927                        ? productRole.values("description").get(0)
1928                        : ""
1929        );
1930        depotPosition.values("basedOn").add(productRoleIdentity);
1931        depotPosition.values("openingDate").add(openingDate);
1932        depotPosition.values("isLocked").add(isLocked);
1933        try {
1934            return this.plugin.retrieveObjectFromDelegation(depotPosition.path());
1935        }
1936        catch(ServiceException e) {
1937            this.plugin.createObject(
1938                depotPosition
1939            );
1940            return depotPosition;
1941        }
1942    }
1943    
1944    //-----------------------------------------------------------------------
1945
public void closeDepotPosition(
1946        DataproviderObject_1_0 depotPosition,
1947        DataproviderObject_1_0 params,
1948        List JavaDoc errors
1949    ) throws ServiceException {
1950        if(depotPosition.values("closingDate").size()> 0) {
1951            throw new ServiceException(
1952                OpenCrxException.DOMAIN,
1953                OpenCrxException.BOOKING_DEPOT_POSITION_IS_CLOSED_CAN_NOT_CLOSE,
1954                null,
1955                "Depot position is closed. Can not close."
1956            );
1957        }
1958        DataproviderObject closedDepotPosition = this.plugin.retrieveObjectForModification(depotPosition.path());
1959        closedDepotPosition.clearValues("isLocked").add(Boolean.TRUE);
1960        closedDepotPosition.clearValues("closingDate").add(
1961            params.values("closingDate").size() == 0
1962                ? DateFormat.getInstance().format(new Date JavaDoc())
1963                : (String JavaDoc)params.values("closingDate").get(0)
1964        );
1965    }
1966    
1967    //-----------------------------------------------------------------------
1968
public void lockCompoundBooking(
1969        ServiceHeader header,
1970        DataproviderObject_1_0 compoundBooking,
1971        DataproviderObject_1_0 params
1972    ) throws ServiceException {
1973        boolean isPending = compoundBooking.values("bookingStatus").size() > 0
1974            ? ((Number JavaDoc)compoundBooking.values("bookingStatus").get(0)).shortValue() == BOOKING_STATUS_PENDING
1975            : false;
1976        if(!isPending) {
1977            throw new ServiceException(
1978                OpenCrxException.DOMAIN,
1979                OpenCrxException.BOOKING_STATUS_MUST_BE_PENDING,
1980                null,
1981                "Booking status is not pending. Locking is not allowed."
1982            );
1983        }
1984        DataproviderObject modifiedCompoundBooking = this.plugin.retrieveObjectForModification(
1985            compoundBooking.path()
1986        );
1987        modifiedCompoundBooking.clearValues("isLocked").add(Boolean.TRUE);
1988        modifiedCompoundBooking.clearValues("lockingReason").addAll(
1989            params.values("lockingReason")
1990        );
1991        modifiedCompoundBooking.clearValues("lockModifiedAt").add(
1992            DateFormat.getInstance().format(new Date JavaDoc())
1993        );
1994    }
1995    
1996    //-----------------------------------------------------------------------
1997
public void unlockCompoundBooking(
1998        ServiceHeader header,
1999        DataproviderObject_1_0 compoundBooking,
2000        DataproviderObject_1_0 params
2001    ) throws ServiceException {
2002        boolean isPending = compoundBooking.values("bookingStatus").size() > 0
2003            ? ((Number JavaDoc)compoundBooking.values("bookingStatus").get(0)).shortValue() == BOOKING_STATUS_PENDING
2004            : false;
2005        if(!isPending) {
2006            throw new ServiceException(
2007                OpenCrxException.DOMAIN,
2008                OpenCrxException.BOOKING_STATUS_MUST_BE_PENDING,
2009                null,
2010                "Booking status is not pending. Unlocking is not allowed."
2011            );
2012        }
2013        DataproviderObject modifiedCompoundBooking = this.plugin.retrieveObjectForModification(
2014            compoundBooking.path()
2015        );
2016        modifiedCompoundBooking.clearValues("isLocked").add(Boolean.FALSE);
2017        modifiedCompoundBooking.clearValues("lockingReason").add(
2018            new Short JavaDoc((short)0)
2019        );
2020        modifiedCompoundBooking.clearValues("lockModifiedAt").add(
2021            DateFormat.getInstance().format(new Date JavaDoc())
2022        );
2023    }
2024    
2025    //-----------------------------------------------------------------------
2026
// Members
2027
//-----------------------------------------------------------------------
2028
public static final short BOOKING_TYPE_STANDARD = 10;
2029    public static final short BOOKING_TYPE_CLOSING = 20;
2030    public static final short BOOKING_TYPE_REVERSAL = 30;
2031    
2032    private static final short BOOKING_STATUS_PENDING = 1;
2033    private static final short BOOKING_STATUS_PROCESSED = 2;
2034        
2035    // Goods are issued to delivery.
2036
// Goods are returned from delivery
2037
public static final short DEPOT_USAGE_GOODS_ISSUE = 1;
2038    public static final short DEPOT_USAGE_GOODS_RETURN = 2;
2039    public static final short DEPOT_USAGE_GOODS_DELIVERY = 3;
2040    // Work effort
2041
public static final short DEPOT_USAGE_WORK_EFFORT = 10;
2042    
2043    private final Model_1_0 model;
2044    private final OpenCrxKernel_1 plugin;
2045    private final RequestCollection delegation;
2046    private final RefPackage_1_0 rootPkg;
2047        
2048}
2049
2050//--- End of File -----------------------------------------------------------
2051
Popular Tags