Merge pull request #7982 from jitendrapurohit/CRM-18183
[civicrm-core.git] / sql / GenerateData.php
index c97f00b7b66defff42b4f1bd57dcdeee7cc8812e..9c31888fc7981415a5956a6d4b978f7f3f30757b 100644 (file)
@@ -1,29 +1,29 @@
 <?php
-/*
- +--------------------------------------------------------------------+
| CiviCRM version 4.6                                                |
- +--------------------------------------------------------------------+
- | Copyright CiviCRM LLC (c) 2004-2015                                |
- +--------------------------------------------------------------------+
- | This file is a part of CiviCRM.                                    |
- |                                                                    |
- | CiviCRM is free software; you can copy, modify, and distribute it  |
- | under the terms of the GNU Affero General Public License           |
- | Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
- |                                                                    |
- | CiviCRM is distributed in the hope that it will be useful, but     |
- | WITHOUT ANY WARRANTY; without even the implied warranty of         |
- | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
- | See the GNU Affero General Public License for more details.        |
- |                                                                    |
- | You should have received a copy of the GNU Affero General Public   |
- | License and the CiviCRM Licensing Exception along                  |
- | with this program; if not, contact CiviCRM LLC                     |
- | at info[AT]civicrm[DOT]org. If you have questions about the        |
- | GNU Affero General Public License or the licensing of CiviCRM,     |
- | see the CiviCRM license FAQ at http://civicrm.org/licensing        |
- +--------------------------------------------------------------------+
-*/
+/**
+--------------------------------------------------------------------+
* | CiviCRM version 4.7                                                |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2015                                |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM.                                    |
|                                                                    |
| CiviCRM is free software; you can copy, modify, and distribute it  |
| under the terms of the GNU Affero General Public License           |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception.   |
|                                                                    |
| CiviCRM is distributed in the hope that it will be useful, but     |
| WITHOUT ANY WARRANTY; without even the implied warranty of         |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.               |
| See the GNU Affero General Public License for more details.        |
|                                                                    |
| You should have received a copy of the GNU Affero General Public   |
| License and the CiviCRM Licensing Exception along                  |
| with this program; if not, contact CiviCRM LLC                     |
| at info[AT]civicrm[DOT]org. If you have questions about the        |
| GNU Affero General Public License or the licensing of CiviCRM,     |
| see the CiviCRM license FAQ at http://civicrm.org/licensing        |
+--------------------------------------------------------------------+
+ */
 
 /**
  *
@@ -124,7 +124,7 @@ class CRM_GCD {
   /**
    * Class constructor
    */
-  function __construct() {
+  public function __construct() {
     // initialize all the vars
     $this->numIndividual = self::INDIVIDUAL_PERCENT * self::NUM_CONTACT / 100;
     $this->numHousehold = self::HOUSEHOLD_PERCENT * self::NUM_CONTACT / 100;
@@ -132,7 +132,7 @@ class CRM_GCD {
     $this->numStrictIndividual = $this->numIndividual - ($this->numHousehold * self::NUM_INDIVIDUAL_PER_HOUSEHOLD);
 
     // Parse data file
-    foreach((array) simplexml_load_file(self::DATA_FILENAME) as $key => $val) {
+    foreach ((array) simplexml_load_file(self::DATA_FILENAME) as $key => $val) {
       $val = (array) $val;
       $this->sampleData[$key] = (array) $val['item'];
     }
@@ -211,13 +211,13 @@ class CRM_GCD {
     1 => array(
       1 => 'Mrs.',
       2 => 'Ms.',
-      4 => 'Dr.'
+      4 => 'Dr.',
     ),
     // Male
     2 => array(
       3 => 'Mr.',
       4 => 'Dr.',
-    )
+    ),
   );
   private $suffix = array(1 => 'Jr.', 2 => 'Sr.', 3 => 'II', 4 => 'III');
   private $gender = array(1 => 'female', 2 => 'male');
@@ -266,7 +266,13 @@ class CRM_GCD {
    * @return string
    */
 
-  // get a randomly generated string
+  /**
+   * Get a randomly generated string.
+   *
+   * @param int $size
+   *
+   * @return string
+   */
   private function randomString($size = 32) {
     $string = "";
 
@@ -306,7 +312,7 @@ class CRM_GCD {
     }
     if (!$items) {
       echo "Error: no items found for '$key'\n";
-      return;
+      return FALSE;
     }
     return $items[mt_rand(0, count($items) - 1)];
   }
@@ -358,7 +364,7 @@ class CRM_GCD {
    *   and today
    *
    * @param  int $startDate Start Date in Unix timestamp
-   * @param  int $endDate   End Date in Unix timestamp
+   * @param  int $endDate End Date in Unix timestamp
    * @access private
    *
    * @return string randomly generated date in the format "Ymd"
@@ -465,7 +471,7 @@ class CRM_GCD {
   /**
    * Fetch contact type based on stored mapping
    * @param $id
-   * @return
+   * @return string $type
    */
   private function getContactType($id) {
     foreach (array('Individual', 'Household', 'Organization') as $type) {
@@ -880,7 +886,6 @@ class CRM_GCD {
 
       $params['street_address'] = $params['street_number'] . $params['street_number_suffix'] . " " . $params['street_name'] . " " . $params['street_type'] . " " . $params['street_number_postdirectional'];
 
-
       if ($params['location_type_id'] == self::MAIN) {
         $params['supplemental_address_1'] = $this->randomItem('supplemental_addresses_1');
       }
@@ -893,7 +898,7 @@ class CRM_GCD {
         $params['postal_code'],
         $params['geo_code_1'],
         $params['geo_code_2'],
-      ) = $this->getZipCodeInfo();
+        ) = $this->getZipCodeInfo();
 
       $this->_addDAO('Address', $params);
       $params['state'] = $this->states[$params['state_province_id']];
@@ -952,7 +957,7 @@ class CRM_GCD {
    * @return array
    */
   private function _addWebsite($cid, $name) {
-    $part = array_pad(split(' ', strtolower($name)), 3, '');
+    $part = array_pad(explode(' ', strtolower($name)), 3, '');
     if (count($part) > 3) {
       // Abbreviate the place name if it's two words
       $domain = $part[0][0] . $part[1][0] . $part[2] . $part[3];
@@ -963,9 +968,11 @@ class CRM_GCD {
         case 1:
           $domain = $part[0] . $part[1] . $part[2];
           break;
+
         case 2:
           $domain = $part[0] . $part[1];
           break;
+
         case 3:
           $domain = $part[0] . $part[2];
           break;
@@ -1001,18 +1008,23 @@ class CRM_GCD {
       case 1:
         $email = $first . $last;
         break;
+
       case 2:
         $email = "$last.$first";
         break;
+
       case 3:
         $email = $last . $f;
         break;
+
       case 4:
         $email = $first . $l;
         break;
+
       case 5:
         $email = "$last.$m$first";
         break;
+
       case 6:
         $email = "$f$m$last";
         break;
@@ -1092,7 +1104,6 @@ class CRM_GCD {
       // always add members
       $groupContact->status = 'Added';
 
-
       $subscriptionHistory = new CRM_Contact_DAO_SubscriptionHistory();
       $subscriptionHistory->contact_id = $groupContact->contact_id;
 
@@ -1201,7 +1212,6 @@ class CRM_GCD {
         $activityDAO->activity_type_id = $activityTypeID;
         $activityDAO->subject = "Subject for $activity[$activityTypeID]";
         $activityDAO->activity_date_time = $this->randomDate();
-        $activityDAO->duration = mt_rand(1, 6);
         $activityDAO->status_id = 2;
         $this->_insert($activityDAO);
 
@@ -1225,7 +1235,7 @@ class CRM_GCD {
   /**
    * @return array
    */
-  function getZipCodeInfo() {
+  public function getZipCodeInfo() {
 
     if (!$this->stateMap) {
       $query = 'SELECT id, name, abbreviation from civicrm_state_province where country_id = 1228';
@@ -1261,7 +1271,7 @@ class CRM_GCD {
    *
    * @return array
    */
-  static function getLatLong($zipCode) {
+  public static function getLatLong($zipCode) {
     $query = "http://maps.google.com/maps?q=$zipCode&output=js";
     $userAgent = "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0";
 
@@ -1365,16 +1375,16 @@ VALUES
         }
         $dateFactor = ($count * ($YearFactor) * ($YearFactor) * ($YearFactor));
         $startDate = date('Y-m-d', mktime(0, 0, 0,
-            date('m'),
-            (date('d') - ($dateFactor)),
-            (date('Y') - ($YearFactor))
-          ));
+          date('m'),
+          (date('d') - ($dateFactor)),
+          (date('Y') - ($YearFactor))
+        ));
         $partOfDate = explode('-', $startDate);
         $endDate = date('Y-m-d', mktime(0, 0, 0,
-            $partOfDate[1],
-            ($partOfDate[2] - 1),
-            ($partOfDate[0] + ($YearFactor))
-          ));
+          $partOfDate[1],
+          ($partOfDate[2] - 1),
+          ($partOfDate[0] + ($YearFactor))
+        ));
 
         $membership .= "( {$randomContacts[$count]}, {$membershipTypeId}, '{$startDate}', '{$startDate}', '{$endDate}', '{$source}', {$membershipStatusId})";
         $activity .= "( {$activitySourceId}, 7, '{$membershipTypeName}', '{$startDate} 00:00:00', NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 2 )";
@@ -1411,7 +1421,7 @@ VALUES
    *
    * @return string
    */
-  static function repairDate($date) {
+  public static function repairDate($date) {
     $dropArray = array('-' => '', ':' => '', ' ' => '');
     return strtr($date, $dropArray);
   }
@@ -1828,37 +1838,36 @@ order by cc.id; ";
     $this->_query($query);
   }
 
-  private function addContributionFinancialItem() {
-
-    $sql = " SELECT cc.id contribution_id, cli.id as line_item_id, cc.contact_id, cc.receive_date, cc.total_amount, cc.currency, cli.label, cli.financial_type_id,  cefa.financial_account_id, cc.payment_instrument_id, cc.check_number, cc.trxn_id
-FROM `civicrm_contribution` cc
-INNER JOIN civicrm_line_item cli ON cli.entity_id = cc.id and cli.entity_table = 'civicrm_contribution'
-INNER JOIN civicrm_entity_financial_account cefa ON cefa.entity_id =  cli.financial_type_id
-WHERE cefa.account_relationship = 1; ";
-    $result = CRM_Core_DAO::executeQuery($sql);
+  private function addAccountingEntries() {
+    $components = array('contribution', 'membership', 'participant');
+    $select = 'SELECT contribution.id contribution_id, cli.id as line_item_id, contribution.contact_id, contribution.receive_date, contribution.total_amount, contribution.currency, cli.label,
+      cli.financial_type_id,  cefa.financial_account_id, contribution.payment_instrument_id, contribution.check_number, contribution.trxn_id';
+    $where = 'WHERE cefa.account_relationship = 1';
     $financialAccountId = CRM_Financial_BAO_FinancialTypeAccount::getInstrumentFinancialAccount();
-    $this->addFinancialItem($result, $financialAccountId);
-  }
-
-  private function addParticipantFinancialItem() {
-
-    $sql = " SELECT cpp.contribution_id, cli.id as line_item_id, cp.contact_id, now() as receive_date, cp.fee_amount as total_amount, cp.fee_currency as currency, cli.label, cli.financial_type_id, cefa.financial_account_id, 4 as payment_instrument_id, NULL as check_number, NULL as trxn_id
-FROM `civicrm_participant` cp
-INNER JOIN civicrm_participant_payment cpp ON cpp.participant_id = cp.id
-INNER JOIN civicrm_line_item cli ON cli.entity_id = cp.id and cli.entity_table = 'civicrm_participant'
-INNER JOIN civicrm_entity_financial_account cefa ON cefa.entity_id =  cli.financial_type_id
-WHERE cefa.account_relationship = 1";
-    $result = CRM_Core_DAO::executeQuery($sql);
-    $this->addFinancialItem($result);
+    foreach ($components as $component) {
+      if ($component == 'contribution') {
+        $from = 'FROM `civicrm_contribution` contribution';
+      }
+      else {
+        $from = " FROM `civicrm_{$component}` {$component}
+          INNER JOIN civicrm_{$component}_payment cpp ON cpp.{$component}_id = {$component}.id
+          INNER JOIN civicrm_contribution contribution on contribution.id = cpp.contribution_id";
+      }
+      $from .= " INNER JOIN civicrm_line_item cli ON cli.entity_id = {$component}.id and cli.entity_table = 'civicrm_{$component}'
+        INNER JOIN civicrm_entity_financial_account cefa ON cefa.entity_id =  cli.financial_type_id ";
+      $sql = " {$select} {$from} {$where} ";
+      $result = CRM_Core_DAO::executeQuery($sql);
+      $this->addFinancialItem($result, $financialAccountId);
+    }
   }
 
   /**
    * @param $result
    * @param null $financialAccountId
    */
-  private function addFinancialItem($result, $financialAccountId = NULL) {
+  private function addFinancialItem($result, $financialAccountId) {
     $defaultFinancialAccount = CRM_Core_DAO::singleValueQuery("SELECT id FROM civicrm_financial_account WHERE is_default = 1");
-    while($result->fetch()){
+    while ($result->fetch()) {
       $trxnParams = array(
         'trxn_date' => CRM_Utils_Date::processDate($result->receive_date),
         'total_amount' => $result->total_amount,
@@ -1868,7 +1877,8 @@ WHERE cefa.account_relationship = 1";
         'contribution_id' => $result->contribution_id,
         'to_financial_account_id' => empty($financialAccountId[$result->payment_instrument_id]) ? $defaultFinancialAccount : $financialAccountId[$result->payment_instrument_id],
         'payment_instrument_id' => $result->payment_instrument_id,
-        'check_number' => $result->check_number
+        'check_number' => $result->check_number,
+        'is_payment' => 1,
       );
       $trxn = CRM_Core_BAO_FinancialTrxn::create($trxnParams);
       $financialItem = array(
@@ -1880,11 +1890,11 @@ WHERE cefa.account_relationship = 1";
         'contact_id' => $result->contact_id,
         'entity_table' => 'civicrm_line_item',
         'description' => $result->label,
-        'financial_account_id' => $result->financial_account_id
+        'financial_account_id' => $result->financial_account_id,
       );
       $trxnId['id'] = $trxn->id;
-      CRM_Financial_BAO_FinancialItem::create($financialItem, null, $trxnId);
-  }
+      CRM_Financial_BAO_FinancialItem::create($financialItem, NULL, $trxnId);
+    }
   }
 
   private function addLineItemParticipants() {
@@ -1932,7 +1942,7 @@ AND    a.source_record_id = c.id
 AND    a.details = 'Membership Payment'
 ";
     $this->_query($sql);
-}
+  }
 
   private function addParticipantPayment() {
     $maxContribution = CRM_Core_DAO::singleValueQuery("select max(id) from civicrm_contribution");
@@ -1965,6 +1975,7 @@ AND    a.details = 'Participant Payment'
 ";
     $this->_query($sql);
   }
+
 }
 
 /**
@@ -2006,9 +2017,8 @@ $gcd->generate('PCP');
 $gcd->generate('SoftContribution');
 $gcd->generate('Pledge');
 $gcd->generate('PledgePayment');
-$gcd->generate('ContributionFinancialItem');
 $gcd->generate('Participant');
 $gcd->generate('ParticipantPayment');
 $gcd->generate('LineItemParticipants');
-$gcd->generate('ParticipantFinancialItem');
+$gcd->generate('AccountingEntries');
 echo ("Ending data generation on " . date("F dS h:i:s A") . "\n");