1    package com.instantbank.collections.customerInfo.ejb;
2    
3    import java.io.ByteArrayInputStream;
4    import java.io.PrintWriter;
5    import java.io.StringWriter;
6    import java.sql.Connection;
7    import java.sql.PreparedStatement;
8    import java.sql.ResultSet;
9    import java.sql.SQLException;
10   import java.sql.Statement;
11   import javax.ejb.CreateException;
12   import javax.ejb.EJBContext;
13   import javax.ejb.SessionBean;
14   import javax.ejb.SessionContext;
15   import oracle.xml.parser.v2.DOMParser;
16   import oracle.xml.parser.v2.XMLDocument;
17   import oracle.xml.parser.v2.XMLNode;
18   import org.w3c.dom.Element;
19   import org.w3c.dom.Node;
20   import org.w3c.dom.NodeList;
21   import com.instantbank.collections.util.DataAccess;
22   import com.instantbank.collections.util.InstantbankException;
23   import com.instantbank.collections.util.ServiceLocator;
24   import com.instantbank.collections.util.StringFormat;
25   import com.instantbank.collections.util.UniqueIDGenerator;
26   import com.instantbank.collections.util.XMLDataAccess;
27   import com.instantbank.collections.util.XMLUtils;
28   
29   public class CustomerInfoServicesBean
30       implements SessionBean {
31     private EJBContext context;
32     private long changedBy;
33   
34   
35     public CustomerInfoServicesBean() { }
36   
37   
38     private void createCustomerStatus(
39                                       DataAccess dataAccess,
40                                       String code,
41                                       String description,
42                                       Long companyId
43                                       ) throws InstantbankException {
44   
45       Connection con = null;
46       PreparedStatement ps = null;
47       ResultSet result = null;
48       String sql;
49   
50       try {
51         con = ServiceLocator.instance().getConnection();
52         sql = "insert into ";
53         sql += "customer_statuses( ";
54         sql += "cst_id, ";
55         sql += "cst_cmp_id, ";
56         sql += "cst_code, ";
57         sql += "cst_description, ";
58         sql += "cst_last_changed_by, ";
59         sql += "cst_last_changed_date)  ";
60         sql += "values (?,?,?,?,?,sysdate)";
61         ps = con.prepareStatement(sql);
62         ps.setLong(1, UniqueIDGenerator.instance().getNextId());
63         ps.setLong(2, companyId.longValue());
64         ps.setString(3, code);
65         ps.setString(4, description);
66         ps.setLong(5, changedBy);
67         int n = ps.executeUpdate();
68         if(n != 1) {
69           throw new InstantbankException("231001", "Failed to update customer status to the database");
70         }
71       }
72       catch(Exception e) {
73         this.context.setRollbackOnly();
74         throw new InstantbankException(e, "231002", "Failed to add customer status to the database");
75       }
76       finally {
77         try {
78           if(ps != null) {
79             ps.close();
80           }
81           if(con != null) {
82             con.close();
83           }
84         }
85         catch(SQLException se) {
86           se.printStackTrace();
87         }
88       }
89     }
90   
91   
92     private void deleteCustomerStatus(DataAccess dataAccess, String id) throws InstantbankException {
93       Connection con = null;
94       PreparedStatement ps = null;
95       ResultSet result = null;
96       String sql;
97   
98       try {
99         con = ServiceLocator.instance().getConnection();
100        sql = "delete ";
101        sql += "customer_statuses ";
102        sql += "where ";
103        sql += "cst_id = ? ";
104        ps = con.prepareStatement(sql);
105        ps.setString(1, id);
106        int n = ps.executeUpdate();
107        if(n != 1) {
108          throw new InstantbankException("231003", "Failed to update customer statuses to the database");
109        }
110      }
111      catch(Exception e) {
112        this.context.setRollbackOnly();
113        throw new InstantbankException(e, "231004", "Failed to delete customer statuses to the database");
114      }
115      finally {
116        try {
117          if(ps != null) {
118            ps.close();
119          }
120          if(con != null) {
121            con.close();
122          }
123        }
124        catch(SQLException se) {
125          se.printStackTrace();
126        }
127      }
128    }
129  
130  
131    public String getCorporation(Long companyId, Long corpId, Long addressId) throws InstantbankException {
132      Node node;
133      String query;
134      Element root;
135      XMLDataAccess xda = null;
136      XMLDocument xmlDoc;
137      DataAccess da = null;
138      Statement st = null;
139      ResultSet rs = null;
140      Long stateId = null;
141  
142      try {
143        xda = new XMLDataAccess("");
144        xda.connect();
145        query = "SELECT ";
146        query += "corp_id Id, ";
147        query += "corp_name Name, ";
148        query += "corp_email Email, ";
149        query += "corp_cst_id StatusId ";
150        query += "FROM ";
151        query += "corporations ";
152        query += "WHERE ";
153        query += "(corp_id = " + corpId.toString() + ") and ";
154        query += "(corp_cmp_id = " + companyId.toString() + ")";
155        xmlDoc = xda.makeXMLSelect(query, "Corporation", "Info");
156        root = xmlDoc.getDocumentElement();
157        node = root.getFirstChild();
158        if(addressId != null) {
159          da = new DataAccess();
160          da.connect();
161          st = da.getConnection().createStatement();
162          query = "SELECT add_stt_id FROM addresses WHERE add_id=" + addressId.toString();
163          rs = st.executeQuery(query);
164          if(rs.next()) {
165            stateId = new Long(rs.getLong(1));
166            if(rs.wasNull()) {
167              stateId = null;
168            }
169          }
170          if(stateId != null) {
171            query = "SELECT ";
172            query += "add_id AddressId, ";
173            query += "add_line1 Address1, ";
174            query += "add_line2 Address2, ";
175            query += "add_city City, ";
176            query += "add_stt_id StateId, ";
177            query += "stt_code StateCode, ";
178            query += "add_zip_code ZipCode, ";
179            query += "stt_coun_id CountryId, ";
180            query += "add_adt_code AddressType, ";
181            query += "(select phn_number from phone_numbers where phn_add_id = add_id) Phone ";
182            query += "FROM ";
183            query += "addresses, ";
184            query += "states ";
185            query += "WHERE ";
186            query += "(add_id = " + addressId.toString() + ")";
187            query += " and (stt_id = add_stt_id)";
188          }
189          else {
190            query = "SELECT ";
191            query += "add_id AddressId, ";
192            query += "add_line1 Address1, ";
193            query += "add_line2 Address2, ";
194            query += "add_city City, ";
195            query += "add_zip_code ZipCode, ";
196            query += "add_adt_code AddressType, ";
197            query += "(select phn_number from phone_numbers where phn_add_id = add_id) Phone ";
198            query += "FROM ";
199            query += "addresses ";
200            query += "WHERE ";
201            query += "(add_id = " + addressId.toString() + ")";
202          }
203        }
204        else {
205          query = "SELECT ";
206          query += "phn_number Phone ";
207          query += "FROM ";
208          query += "phone_numbers,";
209          query += "corporation_phones ";
210          query += "WHERE ";
211          query += "coph_corp_id = " + corpId.toString() + " and ";
212          query += "coph_phn_id = phn_id";
213        }
214        return xda.getXml(query, "Address", "AddressInfo", node);
215      }
216      catch(Exception e) {
217        this.context.setRollbackOnly();
218        throw new InstantbankException(e, "231005", "Failed to get status.");
219      }
220      finally {
221        try {
222          if(rs != null) {
223            rs.close();
224          }
225          if(st != null) {
226            st.close();
227          }
228          if(da != null) {
229            da.disconnect();
230          }
231          if(xda != null) {
232            xda.disconnect();
233          }
234        }
235        catch(Exception e) {}
236      }
237    }
238  
239  
240    public String getCustomer(Long companyId, Long custId, Long addressId) throws InstantbankException {
241      Node node;
242      Element root;
243      String query;
244      String xml;
245      XMLDataAccess xda = null;
246      XMLDocument xmlDoc;
247      DOMParser docParser = new DOMParser();
248      ByteArrayInputStream stream;
249  
250      DataAccess da = null;
251      Statement st = null;
252      ResultSet rs = null;
253      Long stateId = null;
254  
255      try {
256        xda = new XMLDataAccess("");
257        xda.connect();
258        query = "SELECT ";
259        query += "cust_id Id, ";
260        query += "cust_first_name FirstName, ";
261        query += "cust_middle_name MiddleName, ";
262        query += "cust_last_name LastName, ";
263        query += "cust_generation_code Generation, ";
264        query += "cust_cst_id StatusId, ";
265        query += "to_char(cust_birthdate,'mm-dd-yyyy') BirthDate, ";
266        query += "cust_email Email, ";
267        query += "cust_ssn ssn, ";
268        query += "cust_drivers_license DriversLicense, ";
269        // RGEE
270        query += "cust_name_key NameKey ";
271        //
272        query += "FROM ";
273        query += "customers ";
274        query += "WHERE ";
275        query += "(cust_id = " + custId.toString() + ") and ";
276        query += "(cust_cmp_id = " + companyId.toString() + ") ";
277  
278        xml = xda.getXml(query, "Customer", "Info");
279        stream = new ByteArrayInputStream(xml.getBytes());
280        docParser.setValidationMode(false);
281        docParser.parse(stream);
282        xmlDoc = docParser.getDocument();
283        root = xmlDoc.getDocumentElement();
284        node = root.getFirstChild();
285  
286        if(addressId != null) {
287          da = new DataAccess();
288          da.connect();
289          st = da.getConnection().createStatement();
290          query = "SELECT add_stt_id FROM addresses WHERE add_id=" + addressId.toString();
291          rs = st.executeQuery(query);
292          if(rs.next()) {
293            stateId = new Long(rs.getLong(1));
294            if(rs.wasNull()) {
295              stateId = null;
296            }
297          }
298  
299          if(stateId != null) {
300            query = "SELECT ";
301            query += "add_id AddressId, ";
302            query += "add_line1 Address1, ";
303            query += "add_line2 Address2, ";
304            query += "add_city City, ";
305            query += "add_stt_id StateId, ";
306            query += "stt_code StateCode, ";
307            query += "add_zip_code ZipCode, ";
308            query += "stt_coun_id CountryId, ";
309            query += "add_adt_code AddressType, ";
310            query += "add_ast_code AccommodationStatusId, ";
311            query += "add_months_there TimeInResidence, ";
312            query += "to_char(add_start_date,'mm-dd-yyyy') StartDate, ";
313            query += "to_char(add_end_date,'mm-dd-yyyy') EndDate, ";
314            query += "(select phn_number from phone_numbers where ";
315            query += "phn_add_id = add_id and phn_pht_code ='HO' and ROWNUM = 1) HomePhone ";
316            query += "FROM ";
317            query += "addresses, states ";
318            query += "WHERE ";
319            query += "(stt_id = add_stt_id) and ";
320            query += "(add_id = " + addressId.toString() + ") ";
321          }
322          else {
323            query = "SELECT ";
324            query += "add_id AddressId, ";
325            query += "add_line1 Address1, ";
326            query += "add_line2 Address2, ";
327            query += "add_city City, ";
328            query += "add_zip_code ZipCode, ";
329            query += "add_adt_code AddressType, ";
330            query += "add_ast_code AccommodationStatusId, ";
331            query += "add_months_there TimeInResidence, ";
332            query += "to_char(add_start_date,'mm-dd-yyyy') StartDate, ";
333            query += "to_char(add_end_date,'mm-dd-yyyy') EndDate, ";
334            query += "(select phn_number from phone_numbers where phn_add_id = add_id) HomePhone ";
335            query += "FROM ";
336            query += "addresses ";
337            query += "WHERE ";
338            query += "(add_id = " + addressId.toString() + ")";
339          }
340        }
341        else {
342          query = "select phn_number HomePhone from phone_numbers,customer_phones where ";
343          query += "cph_cust_id = " + custId.toString() + " and phn_id = cph_phn_id ";
344          query += "and phn_pht_code ='HO' and ROWNUM = 1  ";
345        }
346  
347        xmlDoc = xda.makeXMLSelect(query, "Address", "AddressInfo", node);
348        root = xmlDoc.getDocumentElement();
349        node = root.getFirstChild();
350  
351        query = " SELECT ";
352        query += "phn_id phoneId, ";
353        query += "phn_number phoneNumber, ";
354        query += "phn_extension phoneExtension, ";
355        query += "phn_pht_code phoneType ";
356        query += "FROM ";
357        query += "customer_phones, ";
358        query += "phone_numbers ";
359        query += "WHERE ";
360        query += "(cph_cust_id = " + custId.toString() + ") and ";
361        query += "(phn_id = cph_phn_id)";
362        xmlDoc = xda.makeXMLSelect(query, "PhoneList", "Phone", node);
363        root = xmlDoc.getDocumentElement();
364        node = root.getFirstChild();
365  
366        query = "SELECT ";
367        query += "coc_description description, ";
368        query += "coc_employer employer, ";
369        query += "coc_months_there timeJob, ";
370        query += "coc_income income ";
371        query += "FROM ";
372        query += "customer_occupations ";
373        query += "WHERE ";
374        query += "(coc_cust_id = " + custId.toString() + ") and ";
375        query += "(coc_status = 'PR')";
376        return xda.getXml(query, "Occupation", "OccupationInfo", node);
377      }
378      catch(Exception e) {
379        this.context.setRollbackOnly();
380        throw new InstantbankException(e, "231004", "Failed to retrieve customer");
381      }
382      finally {
383        try {
384          if(rs != null) {
385            rs.close();
386          }
387          if(st != null) {
388            st.close();
389          }
390          if(da != null) {
391            da.disconnect();
392          }
393          if(xda != null) {
394            xda.disconnect();
395          }
396        }
397        catch(Exception e) {
398        }
399      }
400    }
401  
402  
403    public String getCustomerStatuses(Long companyId) throws InstantbankException {
404      String customersStatusesXmlString = "";
405      String query;
406      StringWriter sw = new StringWriter();
407      XMLDataAccess xda = null;
408      XMLDocument xmlDoc;
409      PrintWriter pw = new PrintWriter(sw);
410      try {
411        xda = new XMLDataAccess("");
412        xda.connect();
413        query = "SELECT ";
414        query += "cst_id StatusId, ";
415        query += "cst_code StatusCode, ";
416        query += "cst_description StatusDescription ";
417        query += "FROM ";
418        query += "customer_statuses ";
419        query += "WHERE ";
420        query += "cst_cmp_id = " + companyId.toString();
421        query += " ORDER BY upper(StatusCode) ";
422        xmlDoc = xda.makeXMLSelect(query, "CustomerStatusesList", "CustomerStatus");
423        xmlDoc.print(pw);
424        customersStatusesXmlString = sw.toString();
425        return customersStatusesXmlString;
426      }
427      catch(Exception e) {
428        this.context.setRollbackOnly();
429        throw new InstantbankException(e, "231005", "Failed to retrieve customer status");
430      }
431      finally {
432        try {
433          if(xda != null) {
434            xda.disconnect();
435          }
436        }
437        catch(Exception e) {
438        }
439      }
440    }
441  
442  
443    private void modifyCustomerStatus(DataAccess dataAccess, String id, String code, String name) throws InstantbankException {
444      Connection con = null;
445      PreparedStatement ps = null;
446      ResultSet result = null;
447      String sql;
448  
449      try {
450        con = ServiceLocator.instance().getConnection();
451        sql = "update ";
452        sql += "customer_statuses ";
453        sql += "set ";
454        sql += "cst_code = ? ";
455        sql += " , cst_description = ? ";
456        sql += " , cst_last_changed_by = ? ";
457        sql += " , cst_last_changed_date = sysdate  ";
458        sql += "where ";
459        sql += "cst_id = ? ";
460        ps = con.prepareStatement(sql);
461        ps.setString(1, code);
462        ps.setString(2, name);
463        ps.setLong(3, changedBy);
464        ps.setString(4, id);
465        int n = ps.executeUpdate();
466        if(n != 1) {
467          throw new InstantbankException("231006", "Failed to update customer status to the database");
468        }
469      }
470      catch(Exception e) {
471        throw new InstantbankException(e, "231015", "Failed to modify customer status to the database");
472      }
473    }
474  
475  
476    public String saveCorporation(String data, Long companyId) throws InstantbankException {
477      Long addressId = null;
478      NodeList addressesList;
479      Long corpId = null;
480      XMLDocument corporationXml;
481      XMLNode currentNode;
482      DataAccess dataAccess = null;
483      String query;
484      XMLNode root;
485  
486      try {
487        dataAccess = new DataAccess();
488        dataAccess.connect();
489        corporationXml = XMLUtils.getXMLDocument(data);
490        root = (XMLNode)corporationXml.getDocumentElement();
491  
492        if(!root.valueOf("./Id").equals("")) {
493          corpId = new Long(root.valueOf("./Id"));
494        }
495  
496        if(corpId == null) {
497          corpId = new Long(UniqueIDGenerator.instance().getNextId());
498          query = "INSERT INTO ";
499          query += "corporations ( ";
500          query += "corp_id, ";
501          query += "corp_cmp_id, ";
502          query += "corp_cst_id, ";
503          query += "corp_name, ";
504          query += "corp_email ) ";
505          query += "VALUES ( ";
506          query += corpId.toString() + ", ";
507          query += companyId.toString() + ", ";
508          query += root.valueOf("./StatusId") + ",";
509          query += "'" + StringFormat.toSafeOracleString(root.valueOf("./Name")) + "',";
510          query += "'" + StringFormat.toSafeOracleString(root.valueOf("./Email")) + "'";
511          query += ")";
512          dataAccess.makeInsert(query);
513        }
514        else {
515          query = "UPDATE ";
516          query += "corporations ";
517          query += "SET ";
518          query += "corp_cst_id = " + root.valueOf("./StatusId") + ", ";
519          query += "corp_name = '" + StringFormat.toSafeOracleString(root.valueOf("./Name")) + "', ";
520          query += "corp_email = '" + StringFormat.toSafeOracleString(root.valueOf("./Email")) + "'  ";
521          query += "WHERE ";
522          query += "corp_id = " + corpId.toString();
523          dataAccess.makeUpdate(query);
524        }
525        currentNode = (XMLNode)((((Element)root).getElementsByTagName("Address")).item(0));
526        if(currentNode.valueOf("Line1").equals("") && currentNode.valueOf("Line2").equals("")) {
527          addressId = null;
528          saveCorporationPhone(dataAccess, corpId, currentNode);
529          return ("<saveInfo><corpId>" + corpId.toString() + "</corpId><addressId></addressId></saveInfo>");
530        }
531        else {
532          addressId = saveCorporationAddress(dataAccess, corpId, currentNode);
533          return ("<saveInfo><corpId>" + corpId.toString() + "</corpId><addressId>" + addressId.toString() + "</addressId></saveInfo>");
534        }
535  
536      }
537      catch(Exception e) {
538        this.context.setRollbackOnly();
539        throw new InstantbankException(e, "231008", "Failed to save customer.");
540      }
541      finally {
542        try {
543          if(dataAccess != null) {
544            dataAccess.disconnect();
545          }
546        }
547        catch(Exception e) {
548        }
549      }
550    }
551  
552  
553    private Long saveCorporationAddress(DataAccess dataAccess, Long corpId, XMLNode data) throws InstantbankException {
554      Long addressId = null;
555      Long phoneId = null;
556      String query = "";
557      ResultSet rs = null;
558      Statement st = null;
559      Long stateId = new Long(0);
560      int updatedRecords = 0;
561  
562      try {
563        st = dataAccess.getConnection().createStatement();
564        if(!data.valueOf("./StateCode").equals("")) {
565          query = "SELECT stt_id FROM states WHERE stt_code = '" + data.valueOf("./StateCode") + "' AND stt_coun_id = '" + data.valueOf("./CountryId") + "'";
566          rs = st.executeQuery(query);
567  
568          if(rs.next()) {
569            stateId = new Long(rs.getLong(1));
570          }
571        }
572  
573        if(data.valueOf("./Id").equals("")) {
574          addressId = new Long(UniqueIDGenerator.instance().getNextId());
575          query = "INSERT INTO addresses ( ";
576          query += "add_id, ";
577          query += "add_line1, ";
578          query += "add_line2, ";
579          query += "add_city, ";
580          query += "add_stt_id, ";
581          query += "add_zip_code, ";
582          query += "add_adt_code ";
583          query += ") VALUES ( ";
584          query += addressId.toString() + ",";
585          query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Line1")) + "',";
586          query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Line2")) + "',";
587          query += "'" + StringFormat.toSafeOracleString(data.valueOf("./City")) + "',";
588          if(stateId.longValue() == 0) {
589            query += "NULL, ";
590          }
591          else {
592            query += stateId.toString() + ", ";
593          }
594          if(data.valueOf("./ZipCode").length() > 0) {
595            query += data.valueOf("./ZipCode") + ", 'PR'";
596          }
597          else {
598            query += "NULL, 'PR'";
599          }
600          query += ")";
601          dataAccess.makeInsert(query);
602  
603          query = "INSERT INTO corporation_addresses ( ";
604          query += "coad_corp_id, ";
605          query += "coad_add_id ";
606          query += ") VALUES ( ";
607          query += corpId.toString() + ", ";
608          query += addressId.toString();
609          query += ")";
610          dataAccess.makeInsert(query);
611  
612          phoneId = new Long(UniqueIDGenerator.instance().getNextId());
613          query = "INSERT INTO ";
614          query += "phone_numbers ( ";
615          query += "phn_id, ";
616          query += "phn_add_id, ";
617          query += "phn_pht_code, ";
618          query += "phn_number, ";
619          query += "phn_extension ) ";
620          query += "VALUES ( ";
621          query += phoneId.toString() + ", ";
622          query += addressId.toString() + ",";
623          query += "'PR',";
624          query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Phone")) + "',";
625          query += "'')";
626          dataAccess.makeInsert(query);
627  
628          query = "INSERT INTO ";
629          query += "corporation_phones ( ";
630          query += "coph_corp_id, ";
631          query += "coph_phn_id ) ";
632          query += "VALUES ( ";
633          query += corpId.toString() + ", ";
634          query += phoneId.toString() + ")";
635          dataAccess.makeInsert(query);
636        }
637        else {
638          addressId = new Long(data.valueOf("./Id"));
639          query = "UPDATE ";
640          query += "phone_numbers ";
641          query += "SET ";
642          query += "phn_number = '" + StringFormat.toSafeOracleString(data.valueOf("./Phone")) + "' ";
643          query += "WHERE ";
644          query += "phn_add_id = " + addressId.toString() + " AND ";
645          query += "phn_pht_code = 'PR'";
646          updatedRecords = dataAccess.makeUpdate(query);
647  
648          if(!(updatedRecords > 0)) {
649            phoneId = new Long(UniqueIDGenerator.instance().getNextId());
650            query = "INSERT INTO ";
651            query += "phone_numbers ( ";
652            query += "phn_id, ";
653            query += "phn_add_id, ";
654            query += "phn_pht_code, ";
655            query += "phn_number, ";
656            query += "phn_extension) ";
657            query += "VALUES (";
658            query += phoneId.toString() + ", ";
659            query += addressId.toString() + ", '";
660            query += "PR', '";
661            query += StringFormat.toSafeOracleString(data.valueOf("./Phone")) + "', '')";
662  
663            dataAccess.makeInsert(query);
664  
665            query = "INSERT INTO ";
666            query += "corporation_phones (";
667            query += "coph_corp_id, coph_phn_id ) ";
668            query += "VALUES (";
669            query += corpId.toString() + ", ";
670            query += phoneId.toString() + ")";
671  
672            dataAccess.makeInsert(query);
673          }
674  
675          query = "UPDATE ";
676          query += "addresses ";
677          query += "SET ";
678          query += "add_line1 = '" + StringFormat.toSafeOracleString(data.valueOf("./Line1")) + "',";
679          query += "add_line2 = '" + StringFormat.toSafeOracleString(data.valueOf("./Line2")) + "',";
680          query += "add_city = '" + StringFormat.toSafeOracleString(data.valueOf("./City")) + "',";
681          if(stateId.longValue() == 0) {
682            query += "add_stt_id = NULL, ";
683          }
684          else {
685            query += "add_stt_id = " + stateId.toString() + ",";
686          }
687          query += "add_zip_code = '" + data.valueOf("./ZipCode") + "' ";
688          query += "WHERE ";
689          query += "add_id = " + addressId.toString();
690  
691          dataAccess.makeInsert(query);
692        }
693        return addressId;
694      }
695      catch(Exception e) {
696        this.context.setRollbackOnly();
697        throw new InstantbankException(e, "231009", "Failed to save customer addrees.");
698      }
699      finally {
700        try {
701          if(rs != null) {
702            rs.close();
703          }
704          if(st != null) {
705            st.close();
706          }
707        }
708        catch(Exception e) {
709        }
710      }
711    }
712  
713  
714    private void saveCorporationPhone(DataAccess dataAccess, Long corpId, XMLNode data) throws InstantbankException {
715      Long phoneId = null;
716      String query = "";
717      ResultSet rs = null;
718      Statement st = null;
719      Long stateId = new Long(0);
720      int updatedRecords = 0;
721  
722      try {
723  
724        query = "UPDATE ";
725        query += "phone_numbers ";
726        query += "SET ";
727        query += "phn_number = '" + StringFormat.toSafeOracleString(data.valueOf("./Phone")) + "' ";
728        query += "WHERE ";
729        query += "phn_id in (select coph_phn_id from corporation_phones where coph_corp_id = " + corpId.toString() + ") AND ";
730        query += "phn_add_id is NULL AND ";
731        query += "phn_pht_code = 'PR'";
732  
733        updatedRecords = dataAccess.makeUpdate(query);
734  
735        if(!(updatedRecords > 0)) {
736          phoneId = new Long(UniqueIDGenerator.instance().getNextId());
737          query = "INSERT INTO ";
738          query += "phone_numbers ( ";
739          query += "phn_id, ";
740          query += "phn_add_id, ";
741          query += "phn_pht_code, ";
742          query += "phn_number, ";
743          query += "phn_extension) ";
744          query += "VALUES (";
745          query += phoneId.toString() + ", ";
746          query += "NULL, '";
747          query += "PR', '";
748          query += StringFormat.toSafeOracleString(data.valueOf("./Phone")) + "', '')";
749  
750          dataAccess.makeInsert(query);
751  
752          query = "INSERT INTO ";
753          query += "corporation_phones (";
754          query += "coph_corp_id, coph_phn_id ) ";
755          query += "VALUES (";
756          query += corpId.toString() + ", ";
757          query += phoneId.toString() + ")";
758  
759          dataAccess.makeInsert(query);
760        }
761      }
762      catch(Exception e) {
763        this.context.setRollbackOnly();
764        throw new InstantbankException(e, "231009", "Failed to save customer addrees.");
765      }
766      finally {
767        try {
768          if(rs != null) {
769            rs.close();
770          }
771          if(st != null) {
772            st.close();
773          }
774        }
775        catch(Exception e) {
776        }
777      }
778    }
779  
780  
781    public String saveCustomer(String data, Long companyId) throws InstantbankException {
782      Long addressId = null;
783      NodeList addressesList;
784      XMLNode currentNode;
785      Long custId = null;
786      XMLDocument customerXml;
787      DataAccess dataAccess = null;
788      boolean insertFlag = false;
789      NodeList occupationsList;
790      NodeList phonesList;
791      String query;
792      XMLNode root;
793      ResultSet rs = null;
794      Long tmpAddressId;
795  
796      try {
797  
798        dataAccess = new DataAccess();
799        dataAccess.connect();
800        customerXml = XMLUtils.getXMLDocument(data);
801        root = (XMLNode)customerXml.getDocumentElement();
802  
803        if(!root.valueOf("./Id").equals("")) {
804          custId = new Long(root.valueOf("./Id"));
805        }
806        else {
807          custId = null;
808        }
809  
810        if(custId == null) {
811          custId = new Long(UniqueIDGenerator.instance().getNextId());
812          query = " INSERT INTO customers (";
813          query += "cust_id, ";
814          query += "cust_cmp_id, ";
815          query += "cust_cst_id, ";
816          query += "cust_first_name, ";
817          query += "cust_middle_name, ";
818          query += "cust_last_name, ";
819          query += "cust_generation_code, ";
820          query += "cust_email, ";
821          query += "cust_ssn, ";
822          query += "cust_drivers_license, ";
823          query += "cust_birthdate ";
824          query += ") VALUES (";
825          query += custId.toString() + ", ";
826          query += companyId.toString() + ", ";
827          query += root.valueOf("./StatusId") + ", '";
828          query += StringFormat.toSafeOracleString(root.valueOf("./FirstName")) + "', '";
829          query += StringFormat.toSafeOracleString(root.valueOf("./MiddleName")) + "', '";
830          query += StringFormat.toSafeOracleString(root.valueOf("./LastName")) + "', '";
831          query += root.valueOf("./Generation") + "', '";
832          query += root.valueOf("./Email") + "', ";
833          query += root.valueOf("./SSN") + ", ";
834          query += "'" + StringFormat.toSafeOracleString(root.valueOf("./DriverLicense")) + "', ";
835          query += "TO_DATE('" + root.valueOf("./BirthDate") + "','mm-dd-yyyy')";
836          query += ")";
837          dataAccess.makeInsert(query);
838          insertFlag = true;
839        }
840        else {
841          query = "UPDATE customers SET ";
842          query += "cust_cst_id = " + root.valueOf("./StatusId") + ",";
843          query += "cust_first_name = '" + StringFormat.toSafeOracleString(root.valueOf("./FirstName")) + "',";
844          query += "cust_middle_name = '" + StringFormat.toSafeOracleString(root.valueOf("./MiddleName")) + "',";
845          query += "cust_last_name = '" + StringFormat.toSafeOracleString(root.valueOf("./LastName")) + "',";
846          query += "cust_generation_code = '" + root.valueOf("./Generation") + "',";
847          query += "cust_email = '" + root.valueOf("./Email") + "',";
848          query += "cust_ssn = " + root.valueOf("./SSN") + ",";
849          query += "cust_drivers_license = '" + root.valueOf("./DriverLicense") + "',";
850          query += "cust_birthdate = TO_DATE('" + root.valueOf("./BirthDate") + "','mm-dd-yyyy') ";
851          query += "WHERE ";
852          query += "CUST_ID = " + custId.toString();
853          dataAccess.makeUpdate(query);
854        }
855  
856        phonesList = root.selectNodes("./PhoneList/Phone");
857        for(int i = 0; i < phonesList.getLength(); i++) {
858          currentNode = (XMLNode)(phonesList.item(i));
859          saveCustomerPhone(dataAccess, custId, currentNode, false);
860        }
861  
862        addressesList = root.selectNodes("./AddressList/Address");
863        for(int i = 0; i < addressesList.getLength(); i++) {
864          currentNode = (XMLNode)(addressesList.item(i));
865          if(currentNode.valueOf("Line1").equals("") && currentNode.valueOf("Line2").equals("")) {
866            tmpAddressId = null;
867            saveCustomerPhone(dataAccess, custId, currentNode, true);
868          }
869          else {
870            tmpAddressId = saveCustomerAddress(dataAccess, custId, currentNode);
871          }
872          if(currentNode.valueOf("./Type").equals("PR")) {
873            addressId = tmpAddressId;
874          }
875          else if(addressId == null) {
876            addressId = tmpAddressId;
877          }
878        }
879  
880        occupationsList = root.selectNodes("./OccupationList/Occupation");
881        for(int i = 0; i < occupationsList.getLength(); i++) {
882          currentNode = (XMLNode)(occupationsList.item(i));
883          saveCustomerOccupation(dataAccess, custId, currentNode);
884        }
885        if(addressId != null) {
886          return ("<saveInfo><custId>" + custId.toString() + "</custId><addressId>" + addressId.toString() + "</addressId></saveInfo>");
887        }
888        else {
889          return ("<saveInfo><custId>" + custId.toString() + "</custId><addressId></addressId></saveInfo>");
890        }
891  
892      }
893      catch(Exception e) {
894        this.context.setRollbackOnly();
895        throw new InstantbankException(e, "231010", "Failed to save customer .");
896      }
897      finally {
898        try {
899          if(dataAccess != null) {
900            dataAccess.disconnect();
901          }
902        }
903        catch(Exception e) {
904        }
905      }
906    }
907  
908  
909    private Long saveCustomerAddress(DataAccess dataAccess, Long custId, XMLNode data) throws InstantbankException {
910      Long addressId = null;
911      boolean insertHomePhone = false;
912      Long phoneId = null;
913      String query = "";
914      ResultSet rs = null;
915      Statement st = null;
916      Long stateId = null;
917      int updatedRecords = 0;
918  
919      try {
920        st = dataAccess.getConnection().createStatement();
921        if(!data.valueOf("./StateCode").equals("")) {
922          query = "SELECT stt_id FROM states WHERE stt_code = '" + data.valueOf("./StateCode") + "' AND stt_coun_id = '" + data.valueOf("./CountryId") + "'";
923          rs = st.executeQuery(query);
924          if(rs.next()) {
925            stateId = new Long(rs.getLong(1));
926          }
927          else {
928            stateId = null;
929          }
930        }
931  
932        if(data.valueOf("./Id").equals("")) {
933          addressId = new Long(UniqueIDGenerator.instance().getNextId());
934          query = "INSERT INTO addresses (";
935          query += "add_id,";
936          query += "add_line1,";
937          query += "add_line2,";
938          query += "add_city,";
939          query += "add_stt_id,";
940          query += "add_zip_code,";
941          query += "add_months_there,";
942          query += "add_ast_code,";
943          query += "add_adt_code,";
944          query += "add_start_date,";
945          query += "add_end_date ";
946          query += ") VALUES (";
947          query += addressId.toString() + ",";
948          query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Line1")) + "',";
949          query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Line2")) + "',";
950          query += "'" + StringFormat.toSafeOracleString(data.valueOf("./City")) + "',";
951          query += (stateId == null ? "NULL" : stateId.toString()) + ",";
952          query += "'" + data.valueOf("./ZipCode") + "',";
953          query += data.valueOf("./TimeInResidence") + ",";
954          query += "'" + data.valueOf("./AccommodationStatusId") + "',";
955          query += "'" + data.valueOf("./Type") + "',";
956          query += ((!data.valueOf("./StartDate").equals("")) ? "TO_DATE('" + data.valueOf("./StartDate") + "','mm-dd-yyyy')" : "NULL") + ",";
957          query += ((!data.valueOf("./EndDate").equals("")) ? "TO_DATE('" + data.valueOf("./EndDate") + "','mm-dd-yyyy')" : "NULL");
958          query += ")";
959  
960          dataAccess.makeInsert(query);
961          query = "INSERT INTO customer_addresses (";
962          query += "cad_cust_id, ";
963          query += "cad_add_id ";
964          query += ") VALUES (";
965          query += custId.toString() + ",";
966          query += addressId.toString();
967          query += ")";
968          dataAccess.makeInsert(query);
969  
970          insertHomePhone = true;
971        }
972        else {
973          addressId = new Long(data.valueOf("./Id"));
974          query = "UPDATE addresses SET ";
975          query += "add_line1 = '" + StringFormat.toSafeOracleString(data.valueOf("./Line1")) + "',";
976          query += "add_line2 = '" + StringFormat.toSafeOracleString(data.valueOf("./Line2")) + "',";
977          query += "add_city = '" + StringFormat.toSafeOracleString(data.valueOf("./City")) + "',";
978          if(stateId != null) {
979            query += "add_stt_id = " + stateId.toString() + ",";
980          }
981          else {
982            query += "add_stt_id = null,";
983          }
984          query += "add_zip_code = '" + data.valueOf("./ZipCode") + "',";
985          query += "add_months_there = " + data.valueOf("./TimeInResidence") + ",";
986          query += "add_ast_code = '" + data.valueOf("./AccommodationStatusId") + "',";
987          query += "add_adt_code = '" + data.valueOf("./Type") + "',";
988          query += "add_start_date = " + ((!data.valueOf("./StartDate").equals("")) ? "TO_DATE('" + data.valueOf("./StartDate") + "','mm-dd-yyyy')" : "NULL") + ",";
989          query += "add_end_date = " + ((!data.valueOf("./EndDate").equals("")) ? "TO_DATE('" + data.valueOf("./EndDate") + "','mm-dd-yyyy')" : "NULL") + " ";
990          query += "WHERE add_id = " + addressId.toString();
991          updatedRecords = dataAccess.makeUpdate(query);
992  
993          query = "UPDATE phone_numbers SET ";
994          query += "phn_number = '" + data.valueOf("./HomePhone") + "' ";
995          query += "WHERE ";
996          query += "phn_add_id = " + addressId.toString() + " AND ";
997          query += "phn_pht_code = 'HO'";
998          updatedRecords = dataAccess.makeUpdate(query);
999          insertHomePhone = !(updatedRecords > 0);
1000       }
1001 
1002       if(insertHomePhone) {
1003 
1004         phoneId = new Long(UniqueIDGenerator.instance().getNextId());
1005         query = "INSERT INTO phone_numbers (";
1006         query += "phn_id,";
1007         query += "phn_add_id,";
1008         query += "phn_pht_code,";
1009         query += "phn_number,";
1010         query += "phn_extension ";
1011         query += ") VALUES (";
1012         query += phoneId.toString() + ",";
1013         query += addressId.toString() + ",";
1014         query += "'HO',";
1015         query += "'" + data.valueOf("./HomePhone") + "',";
1016         query += "''";
1017         query += ")";
1018         dataAccess.makeInsert(query);
1019 
1020         query = "INSERT INTO customer_phones (";
1021         query += "cph_cust_id,";
1022         query += "cph_phn_id ";
1023         query += ") VALUES (";
1024         query += custId.toString() + ",";
1025         query += phoneId.toString();
1026         query += ")";
1027         dataAccess.makeInsert(query);
1028       }
1029       return addressId;
1030     }
1031     catch(Exception e) {
1032       this.context.setRollbackOnly();
1033       throw new InstantbankException(e, "231011", "Failed to save customer Address.");
1034     }
1035     finally {
1036       try {
1037         if(rs != null) {
1038           rs.close();
1039         }
1040         if(st != null) {
1041           st.close();
1042         }
1043       }
1044       catch(Exception e) {
1045       }
1046     }
1047   }
1048 
1049 
1050   private void saveCustomerOccupation(DataAccess dataAccess, Long custId, XMLNode data) throws InstantbankException {
1051     Long cocId = null;
1052     String query = "";
1053     int updatedOccupations = 0;
1054 
1055     try {
1056       query = "UPDATE customer_occupations SET ";
1057       query += "coc_description = '" + StringFormat.toSafeOracleString(data.valueOf("./Description")) + "',";
1058       query += "coc_employer = '" + StringFormat.toSafeOracleString(data.valueOf("./Employer")) + "',";
1059       query += "coc_months_there = " + data.valueOf("./TimeJob") + ",";
1060       query += "coc_income = " + data.valueOf("./Income") + " ";
1061       query += "WHERE ";
1062       query += "coc_cust_id = " + custId.toString() + " AND ";
1063       query += "coc_status = 'PR'";
1064       updatedOccupations = dataAccess.makeUpdate(query);
1065 
1066       if(!(updatedOccupations > 0)) {
1067         cocId = new Long(UniqueIDGenerator.instance().getNextId());
1068         query = "INSERT INTO customer_occupations (";
1069         query += "coc_id, ";
1070         query += "coc_description, ";
1071         query += "coc_employer,";
1072         query += "coc_months_there, ";
1073         query += "coc_income,";
1074         query += "coc_status,";
1075         query += "coc_cust_id ";
1076         query += ") VALUES (";
1077         query += cocId.toString() + ",";
1078         query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Description")) + "',";
1079         query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Employer")) + "',";
1080         query += data.valueOf("./TimeJob") + ",";
1081         query += data.valueOf("./Income") + ", 'PR',";
1082         query += custId.toString();
1083         query += ")";
1084         dataAccess.makeInsert(query);
1085       }
1086     }
1087     catch(Exception e) {
1088       this.context.setRollbackOnly();
1089       throw new InstantbankException(e, "231012", "Failed to save customer occupations.");
1090     }
1091   }
1092 
1093 
1094   private void saveCustomerPhone(DataAccess dataAccess, Long custId, XMLNode data, boolean flagHome) throws InstantbankException {
1095     boolean insertHomePhone;
1096     Long phoneId = null;
1097     String query = "";
1098     int updatedRecords = 0;
1099 
1100     try {
1101       if(data.valueOf("./Id").equals("")) {
1102         phoneId = new Long(UniqueIDGenerator.instance().getNextId());
1103 
1104         if(flagHome) {
1105           query = "UPDATE phone_numbers SET ";
1106           query += "phn_number = '" + StringFormat.toSafeOracleString(data.valueOf("./HomePhone")) + "' ";
1107           query += "WHERE ";
1108           query += "phn_id in (select cph_phn_id from customer_phones where cph_cust_id= " + custId.toString() + ") AND ";
1109           query += "phn_add_id is null AND ";
1110           query += "phn_pht_code = 'HO'";
1111           updatedRecords = dataAccess.makeUpdate(query);
1112           insertHomePhone = !(updatedRecords > 0);
1113           if(insertHomePhone) {
1114             query = "INSERT INTO phone_numbers (";
1115             query += "phn_id,";
1116             query += "phn_pht_code,";
1117             query += "phn_number,";
1118             query += "phn_extension ";
1119             query += ") VALUES (";
1120             query += phoneId.toString() + ",";
1121             query += "'HO',";
1122             query += "'" + StringFormat.toSafeOracleString(data.valueOf("./HomePhone")) + "',";
1123             query += "null";
1124             query += ")";
1125             dataAccess.makeInsert(query);
1126           }
1127         }
1128         else {
1129           query = "INSERT INTO phone_numbers (";
1130           query += "phn_id,";
1131           query += "phn_pht_code,";
1132           query += "phn_number,";
1133           query += "phn_extension ";
1134           query += ") VALUES (";
1135           query += phoneId.toString() + ",";
1136           query += "'" + data.valueOf("./Type") + "',";
1137           query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Number")) + "',";
1138           query += "'" + StringFormat.toSafeOracleString(data.valueOf("./Extension")) + "'";
1139           query += ")";
1140 
1141           dataAccess.makeInsert(query);
1142         }
1143 
1144         if(updatedRecords == 0) {
1145           query = "INSERT INTO customer_phones (";
1146           query += "cph_cust_id, ";
1147           query += "cph_phn_id ";
1148           query += ") VALUES (";
1149           query += custId.toString() + ",";
1150           query += phoneId.toString();
1151           query += ")";
1152           dataAccess.makeInsert(query);
1153         }
1154       }
1155       else {
1156         phoneId = new Long(data.valueOf("./Id"));
1157         query = "UPDATE phone_numbers SET ";
1158         if(!flagHome) {
1159           query += "phn_number = '" + StringFormat.toSafeOracleString(data.valueOf("./Number")) + "',";
1160           query += "phn_extension = '" + StringFormat.toSafeOracleString(data.valueOf("./Extension")) + "' ";
1161         }
1162         else {
1163           query += "phn_number = '" + StringFormat.toSafeOracleString(data.valueOf("./HomePhone")) + "'";
1164         }
1165         query += "WHERE ";
1166         query += "phn_id = " + phoneId.toString();
1167         dataAccess.makeInsert(query);
1168       }
1169     }
1170     catch(Exception e) {
1171       this.context.setRollbackOnly();
1172       throw new InstantbankException(e, "231013", "Failed to save customer phone.");
1173     }
1174   }
1175 
1176 
1177   public void saveCustomerStatuses(Long companyId, Long userId, String xmlData) throws InstantbankException {
1178     DataAccess dataAccess = null;
1179     NodeList nlId;
1180     NodeList nlCode;
1181     NodeList nlName;
1182     NodeList nlStatus;
1183     int nlLength;
1184     XMLDocument xmlDoc;
1185     String id;
1186     String code;
1187     String name;
1188     String status;
1189 
1190     try {
1191       dataAccess = new DataAccess();
1192       dataAccess.connect();
1193       xmlDoc = XMLUtils.getXMLDocument(xmlData);
1194       changedBy = userId.longValue();
1195       nlId = xmlDoc.selectNodes("/CustomerStatusesList/CustomerStatus/id/text()");
1196       nlCode = xmlDoc.selectNodes("/CustomerStatusesList/CustomerStatus/code/text()");
1197       nlName = xmlDoc.selectNodes("/CustomerStatusesList/CustomerStatus/description/text()");
1198       nlStatus = xmlDoc.selectNodes("/CustomerStatusesList/CustomerStatus/status/text()");
1199       nlLength = nlCode.getLength();
1200       for(int i = 0; i < nlLength; i++) {
1201         id = nlId.item(i).getNodeValue();
1202         code = nlCode.item(i).getNodeValue();
1203         name = nlName.item(i).getNodeValue();
1204         status = nlStatus.item(i).getNodeValue();
1205         if(status.equals("A")) {
1206           createCustomerStatus(dataAccess, code, name, companyId);
1207         }
1208         if(status.equals("D")) {
1209           deleteCustomerStatus(dataAccess, id);
1210         }
1211         if(status.equals("M")) {
1212           modifyCustomerStatus(dataAccess, id, code, name);
1213         }
1214       }
1215     }
1216     catch(Exception e) {
1217       this.context.setRollbackOnly();
1218       throw new InstantbankException(e, "231014", "Failed to save customer.");
1219     }
1220     finally {
1221       try {
1222         if(dataAccess != null) {
1223           dataAccess.disconnect();
1224         }
1225       }
1226       catch(Exception e) {
1227       }
1228     }
1229   }
1230 
1231 
1232   public void ejbCreate() throws CreateException {
1233     // TODO:  Add custom implementation.
1234   }
1235 
1236 
1237   public void ejbActivate() { }
1238 
1239 
1240   public void ejbPassivate() { }
1241 
1242 
1243   public void ejbRemove() { }
1244 
1245 
1246   public void setSessionContext(SessionContext ctx) {
1247     this.context = ctx;
1248   }
1249 
1250 }
1251 
1252