~fabiocbalbuquerque/sahana-agasti/web-services

« back to all changes in this revision

Viewing changes to apps/frontend/lib/util/agStaffImportNormalization.class.php

  • Committer: Chad Heuschober
  • Date: 2011-06-06 13:37:45 UTC
  • mfrom: (1.1.1244 trunk)
  • mto: This revision was merged to the branch mainline in revision 17.
  • Revision ID: chad.heuschober@mail.cuny.edu-20110606133745-850mdvnjtv392zta
Pulled in most recent batch of changes from the cuny sps trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
23
23
class agStaffImportNormalization extends agImportNormalization
24
24
{
25
25
  /**
26
 
   * This class's constructor.
27
 
   * @param string $tempTable The name of the temporary import table to use
28
 
   * @param string $logEventLevel An optional parameter dictating the event level logging to be used
29
 
   */
30
 
  public function __construct($tempTable, $logEventLevel = NULL)
31
 
  {
 
26
   * Method to return an instance of this class
 
27
   * @param string $tempTable The name of the temporary import table to use
 
28
   * @param string $logEventLevel An optional parameter dictating the event level logging to be used
 
29
   * @return self An instance of this class
 
30
   */
 
31
  public static function getInstance($tempTable, $logEventLevel = NULL)
 
32
  {
 
33
    $self = new self();
 
34
    $self->__init($tempTable, $logEventLevel);
 
35
    return $self;
 
36
  }
 
37
 
 
38
  /**
 
39
   * Method to return an instance of this class
 
40
   * @param string $tempTable The name of the temporary import table to use
 
41
   * @param string $logEventLevel An optional parameter dictating the event level logging to be used
 
42
   * @return self An instance of this class
 
43
   */
 
44
  public function __init($tempTable = NULL, $logEventLevel = NULL)
 
45
  {
 
46
    if (is_null($tempTable)) { $tempTable = 'temp_staff_import'; }
 
47
 
32
48
    // DO NOT REMOVE
33
 
    parent::__construct($tempTable, $logEventLevel);
 
49
    parent::__init($tempTable, $logEventLevel);
34
50
 
35
51
    // set the import components array as a class property
36
52
    $this->setImportComponents();
 
53
    $this->tempTableOptions = array('type' => 'MYISAM', 'charset' => 'utf8');
 
54
    $this->importHeaderStrictValidation = TRUE;
 
55
 
 
56
    $this->eh->setErrThreshold(100);
37
57
  }
38
58
 
39
59
  /**
40
 
   * Method to import staff from an excel file.
 
60
   * Imports staff from an excel file.
41
61
   */
42
 
  public function importStaffFromExcel()
 
62
  public function processXlsImportFile($importFile)
43
63
  {
44
 
    // @todo call agImportHelper (parent) import excel method
45
 
    // @todo Build temp table here --^
 
64
    // process the excel file and create a temporary table
 
65
    parent::processXlsImportFile($importFile);
46
66
 
47
67
    // start our iterator and initialize our select query
48
68
    $this->tempToRaw($this->buildTempSelectQuery());
60
80
   * Method to extend the import specification to include dynamic columns from the file headers
61
81
   * @param array $importFileHeaders A single-dimension array of import file headers / column names
62
82
   */
63
 
  protected function addDynamicColumns($importFileHeaders)
 
83
  protected function addDynamicColumns(array $importFileHeaders)
64
84
  {
65
85
    $dynamicColumns = array_diff($importFileHeaders, array_keys($this->importSpec));
66
86
    foreach($dynamicColumns as $column)
67
87
    {
68
88
      $this->importSpec[$column] = $this->dynamicFieldType;
 
89
      $this->eh->logInfo('Adding dynamic column {' . $column . '} to the import specification.');
69
90
    }
70
91
  }
71
92
 
80
101
    $importSpec['first_name'] = array('type' => "string", 'length' => 64);
81
102
    $importSpec['middle_name'] = array('type' => "string", 'length' => 64);
82
103
    $importSpec['last_name'] = array('type' => "string", 'length' => 64);
 
104
    $importSpec['mobile_phone'] = array('type' => "string", 'length' => 16);
83
105
    $importSpec['home_phone'] = array('type' => "string", 'length' => 16);
84
106
    $importSpec['home_email'] = array('type' => "string", 'length' => 255);
85
107
    $importSpec['work_phone'] = array('type' => "string", 'length' => 16);
146
168
    if (strlen($columnName) == 0)
147
169
    {
148
170
      $errMsg = "Column name {$oldColumnName} could not be parsed.";
149
 
      $this->logErr($errMsg, 1);
 
171
      $this->eh->logCrit($errMsg, 1);
150
172
      throw new Exception($errMsg);
151
173
    }
152
174
    return $columnName;
153
175
  }
154
176
 
155
177
  /**
 
178
   * This method is an extension of the parent validate column headers method allowing
 
179
   * domain-specific header validation.
 
180
   * @param array $importFileHeaders An array of import file headers.
 
181
   * @param string $sheetName The name of the sheet being validated.
 
182
   * @return boolean A boolean indicating un/successful validation of column headers.
 
183
   */
 
184
  protected function validateColumnHeaders(array $importFileHeaders, $sheetName)
 
185
  {
 
186
    // DO NOT REMOVE THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING
 
187
    $validated = parent::validateColumnHeaders($importFileHeaders, $sheetName);
 
188
 
 
189
    return $validated;
 
190
  }
 
191
 
 
192
  /**
156
193
   * Method to dynamically build a (mostly) static tempSelectQuery
157
 
   * @return <type>
 
194
   * @return string Returns a string query
158
195
   */
159
196
  protected function buildTempSelectQuery()
160
197
  {
173
210
  {
174
211
    // array( [order] => array(component => component name, helperClass => Name of the helper class, throwOnError => boolean, method => method name) )
175
212
    // setEntity creates entity, person, and staff records.
176
 
    $this->importComponents[] = array( 'component' => 'entity', 'throwOnError' => TRUE, 'method' => 'setEntities');
177
 
    $this->importComponents[] = array( 'component' => 'personName', 'throwOnError' => TRUE, 'method' => 'setPersonNames', 'helperClass' => 'agPersonNameHelper');
178
 
    $this->importComponents[] = array( 'component' => 'phone', 'throwOnError' => FALSE, 'method' => 'setEntityPhone', 'helperClass' => 'agEntityPhoneHelper');
179
 
    $this->importComponents[] = array( 'component' => 'email', 'throwOnError' => FALSE, 'method' => 'setEntityEmail', 'helperClass' => 'agEntityEmailHelper');
180
 
#    $this->importComponents[] = array( 'component' => 'address', 'throwOnError' => FALSE, 'method' => 'setEntityAddress', 'helperClass' => 'agEntityAddressHelper');
181
 
    $this->importComponents[] = array( 'component' => 'customField', 'throwOnError' => FALSE, 'method' => 'setPersonCustomField');
182
 
//    $this->importComponents[] = array( 'component' => 'staffResource', 'throwOnError' => TRUE, 'method' => 'setStaffResourceOrg');
183
 
    $this->importComponents[] = array( 'component' => 'staffResource', 'throwOnError' => FALSE, 'method' => 'setStaffResourceOrg');
 
213
    $this->importComponents[] = array(
 
214
      'component' => 'entity',
 
215
      'throwOnError' => TRUE,
 
216
      'method' => 'setEntities'
 
217
    );
 
218
    $this->importComponents[] = array(
 
219
      'component' => 'personName',
 
220
      'throwOnError' => TRUE,
 
221
      'method' => 'setPersonNames',
 
222
      'helperClass' => 'agPersonNameHelper'
 
223
    );
 
224
    $this->importComponents[] = array(
 
225
      'component' => 'phone',
 
226
      'throwOnError' => FALSE,
 
227
      'method' => 'setEntityPhone',
 
228
      'helperClass' => 'agEntityPhoneHelper'
 
229
    );
 
230
    $this->importComponents[] = array(
 
231
      'component' => 'email',
 
232
      'throwOnError' => FALSE,
 
233
      'method' => 'setEntityEmail',
 
234
      'helperClass' => 'agEntityEmailHelper'
 
235
    );
 
236
    $this->importComponents[] = array(
 
237
      'component' => 'address',
 
238
      'throwOnError' => FALSE,
 
239
      'method' => 'setEntityAddress',
 
240
      'helperClass' => 'agEntityAddressHelper'
 
241
    );
 
242
    $this->importComponents[] = array(
 
243
      'component' => 'customField',
 
244
      'throwOnError' => FALSE,
 
245
      'method' => 'setPersonCustomField'
 
246
    );
 
247
    $this->importComponents[] = array(
 
248
      'component' => 'staffResource',
 
249
      'throwOnError' => TRUE,
 
250
      'method' => 'setStaffResourceOrg'
 
251
    );
 
252
    $this->importComponents[] = array(
 
253
      'component' => 'personLanguage',
 
254
      'throwOnError' => FALSE,
 
255
      'method' => 'setPersonLanguage',
 
256
      'helperClass' => 'agPersonLanguageHelper'
 
257
    );
184
258
  }
185
259
 
186
260
 
246
320
    // we no longer need this array (used for the ->whereIN)
247
321
    unset($rawEntityIds);
248
322
 
 
323
    $this->eh->logDebug('{' . count($entities) . '} person entities found in the database.');
 
324
 
249
325
    //loop foreach $entities member
250
326
    foreach ($entities as $entityId => &$entityData)
251
327
    {
252
328
      // if staff id doesn't exist yet, make it so
253
329
      if (is_null($entityData[1]))
254
330
      {
 
331
        $this->eh->logDebug('Person ID {' . $entityData[0] . '} exists but is not staff. ' .
 
332
          'Creating staff record.');
255
333
        $entityData[1] = $this->createNewRec('agStaff', array('person_id' => $entityData[0]));
256
334
      }
257
335
    }
258
336
    
259
337
    // update our row keys array
 
338
    $this->eh->logDebug('Updating primary keys for found entities.');
260
339
    foreach ($this->importData as $rowId => &$rowData)
261
340
    {
262
341
      if (array_key_exists('entity_id', $rowData['_rawData']))
294
373
      {
295
374
        $createNew = TRUE;
296
375
      }
297
 
      elseif ($rawData['entity_id'] != $pKeys['entity_id'])
 
376
      elseif (!array_key_exists('entity_id', $pKeys) || $rawData['entity_id'] != $pKeys['entity_id'])
298
377
      {
299
378
        $createNew = TRUE;
300
379
        $warnBadEntity = TRUE;
302
381
 
303
382
      if ($createNew)
304
383
      {
 
384
 
 
385
        $this->eh->logDebug('Creating new entity for import rowId {' . $rowId . '}.');
305
386
        $fKeys = array();
306
387
        $pKeys['entity_id'] = $this->createNewRec('agEntity', $fKeys);
307
388
 
 
389
        $this->eh->logDebug('Creating new person for import Entity ID {' . $pKeys['entity_id'] . '}.');
308
390
        $fKeys = array('entity_id' => $pKeys['entity_id']);
309
391
        $pKeys['person_id'] = $this->createNewRec('agPerson', $fKeys);
310
392
 
 
393
        $this->eh->logDebug('Creating new staff for import Person ID {' . $pKeys['person_id'] . '}.');
311
394
        $fKeys = array('person_id' => $pKeys['person_id']);
312
395
        $pKeys['staff_id'] = $this->createNewRec('agStaff', $fKeys);
313
396
      }
317
400
      {
318
401
        $warnMsg = sprintf("Bad entity id (%s).  Generated a new entity id (%s).",
319
402
          $rawData['entity_id'], $pKeys['entity_id']);
320
 
        sfContext::getInstance()->getLogger()->warning($warnMsg);
 
403
        $this->eh->logWarning($warnMsg);
321
404
      }
322
405
    }
323
406
  }
385
468
  protected function setEntityEmail($throwOnError, Doctrine_Connection $conn)
386
469
  {
387
470
    // always start with any data maps we'll need so they're explicit
388
 
    $importEmailTypes = array('work_email'=>'work', 'home_email'=>'personal');
 
471
    $importEmailTypes = array('work_email' => 'work', 'home_email' => 'personal');
389
472
    $entityEmails = array();
390
473
    $results = array();
391
474
 
502
585
                             'state' => 'state', 'zip' => 'zip5', 'country' => 'country');
503
586
    $entityAddresses = array();
504
587
    $results = array();
 
588
    $errMsg = NULL;
505
589
 
506
590
    // let's get ahold of our helper object since we're going to use him/her a lot
507
591
    $eah =& $this->helperObjects['agEntityAddressHelper'];
524
608
    unset($val);
525
609
    unset($addressElements);
526
610
 
527
 
    // get our address standards
 
611
    // get our address standards and geo match scores
528
612
    $addressStandard = agGlobal::getParam('staff_import_address_standard');
529
 
    $addressStandardId = agAddressHelper::getAddressStandardIds($addressStandard);
 
613
    $addressStandardId = agAddressHelper::getAddressStandardIds(array($addressStandard));
530
614
    $addressStandardId = $addressStandardId[$addressStandard];
 
615
    $geoMatchScore = agGlobal::getParam('default_geo_match_score');
 
616
    $geoMatchScoreId = agGeoHelper::getGeoMatchScoreIds(array($geoMatchScore));
 
617
    $geoMatchScoreId = $geoMatchScoreId[$geoMatchScore];
531
618
 
532
619
    // loop through our raw data and build our entity address data
533
620
    foreach ($this->importData as $rowId => $rowData)
554
641
          }
555
642
        }
556
643
 
557
 
        if (count($homeAddr) > 0)
558
 
        {
559
 
          $entityAddresses[$entityId][] = array($importAddressTypes['home_address'], array($homeAddr, $addressStandardId));
560
 
        }
561
 
        if (count($workAddr) > 0)
562
 
        {
563
 
          $entityAddresses[$entityId][] = array($importAddressTypes['work_address'], array($workAddr, $addressStandardId));
 
644
        if ( count($homeAddr) > 0 && array_key_exists('home_latitude', $rowData['_rawData']) &&
 
645
               array_key_exists('home_longitude', $rowData['_rawData']) )
 
646
        {
 
647
          $homeAddrComp = array($homeAddr, $addressStandardId);
 
648
          $homeAddrComp[] = array( array( array($rowData['_rawData']['home_latitude'],
 
649
                                                $rowData['_rawData']['home_longitude'])),
 
650
                                          $geoMatchScoreId);
 
651
          $entityAddresses[$entityId][] = array($importAddressTypes['home_address'], $homeAddrComp);
 
652
        }
 
653
        else
 
654
        {
 
655
          // log our error
 
656
          $errMsg = sprintf('Missing home address/geo information from record id  %d', $rowId);
 
657
 
 
658
          if($throwOnError)
 
659
          {
 
660
            $this->eh->logErr($errMsg);
 
661
            throw new Exception($errMsg);
 
662
          }
 
663
          else
 
664
          {
 
665
            $this->eh->logWarning($errMsg);
 
666
          }
 
667
        }
 
668
 
 
669
        if ( count($workAddr) > 0 && array_key_exists('work_latitude', $rowData['_rawData']) &&
 
670
               array_key_exists('work_longitude', $rowData['_rawData']) )
 
671
        {
 
672
          $workAddrComp = array($workAddr, $addressStandardId);
 
673
          $workAddrComp[] = array( array( array($rowData['_rawData']['work_latitude'],
 
674
                                                $rowData['_rawData']['work_longitude'])),
 
675
                                          $geoMatchScoreId);
 
676
          $entityAddresses[$entityId][] = array($importAddressTypes['work_address'], $workAddrComp);
 
677
        }
 
678
        else
 
679
        {
 
680
          // log our error
 
681
          $errMsg = sprintf('Missing work address/geo information from record id  %d', $rowId);
 
682
 
 
683
          if($throwOnError)
 
684
          {
 
685
            $this->eh->logErr($errMsg);
 
686
            throw new Exception($errMsg);
 
687
          }
 
688
          else
 
689
          {
 
690
            $this->eh->logWarning($errMsg);
 
691
          }
564
692
        }
565
693
      }
566
694
    }
568
696
    // pick up some of our components / objects
569
697
    $keepHistory = agGlobal::getParam('staff_import_keep_history');
570
698
    $enforceStrict = agGlobal::getParam('enforce_strict_contact_formatting');
 
699
    $geoSourceId = agDoctrineQuery::create()
 
700
      ->select('gs.id')
 
701
        ->from('agGeoSource gs')
 
702
        ->where('gs.geo_source = ?', agGlobal::getParam('staff_import_geo_source'))
 
703
        ->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
571
704
 
572
705
    $addressGeo = array();
573
706
    // @TODO Handle geo upserts along with address.
574
707
 
575
708
    // execute the helper and finish
576
 
    $results = $eah->setEntityAddress($entityAddresses, $addressGeo, $keepHistory,  $enforceStrict, $throwOnError, $conn);
 
709
    $results = $eah->setEntityAddress($entityAddresses, $geoSourceId, $keepHistory,  $enforceStrict, $throwOnError, $conn);
577
710
    unset($entityAddresses);
578
711
 
579
712
    // @todo do your results reporting here
641
774
      }
642
775
    }
643
776
 
644
 
    $coll->save($conn);
 
777
   // here we check our current transaction scope and create a transaction or savepoint
 
778
    $useSavepoint = ($conn->getTransactionLevel() > 0) ? TRUE : FALSE;
 
779
    if ($useSavepoint)
 
780
    {
 
781
      $conn->beginTransaction(__FUNCTION__);
 
782
    }
 
783
    else
 
784
    {
 
785
      $conn->beginTransaction();
 
786
    }
 
787
 
 
788
    try
 
789
    {
 
790
      $coll->save($conn);
 
791
 
 
792
      // commit, being sensitive to our nesting
 
793
      if ($useSavepoint) { $conn->commit(__FUNCTION__); } else { $conn->commit(); }
 
794
    }
 
795
    catch(Exception $e)
 
796
    {
 
797
      // log our error
 
798
      $errMsg = sprintf('%s failed at: %s', __FUNCTION__, $e->getMessage());
 
799
      $this->eh->logErr($errMsg);
 
800
 
 
801
      // rollback
 
802
      if ($useSavepoint) { $conn->rollback(__FUNCTION__); } else { $conn->rollback(); }
 
803
 
 
804
      // ALWAYS throw an error, it's like stepping on a crack if you don't
 
805
      if($throwOnError)
 
806
      {
 
807
        throw new Exception($errMsg);
 
808
      }
 
809
    }
 
810
 
645
811
    unset($coll);
646
812
 
647
813
    // Now process person with new custom field if provided in import.
691
857
            ->addSelect('o.id')
692
858
          ->from('agOrganization o')
693
859
          ->execute(array(), agDoctrineQuery::HYDRATE_KEY_VALUE_PAIR);
 
860
    $organizationIds = array_change_key_case($organizationIds, CASE_LOWER);
694
861
 
695
862
    $stfRscTypeIds = agDoctrineQuery::create()
696
863
        ->select('srt.staff_resource_type')
697
864
            ->addSelect('srt.id')
698
865
          ->from('agStaffResourceType srt')
699
866
          ->execute(array(), agDoctrineQuery::HYDRATE_KEY_VALUE_PAIR);
 
867
    $stfRscTypeIds = array_change_key_case($stfRscTypeIds, CASE_LOWER);
700
868
 
701
869
    $stfRscStatusIds = agDoctrineQuery::create()
702
870
        ->select('srs.staff_resource_status')
703
871
            ->addSelect('srs.id')
704
872
          ->from('agStaffResourceStatus srs')
705
873
          ->execute(array(), agDoctrineQuery::HYDRATE_KEY_VALUE_PAIR);
 
874
    $stfRscStatusIds = array_change_key_case($stfRscStatusIds, CASE_LOWER);
706
875
 
707
876
    // Retrieve staff ids from raw data.
708
877
    $staffIds = array();
719
888
 
720
889
      if (is_null($errMsg))
721
890
      {
722
 
        $staffIds[$rowData['primaryKeys']['staff_id']] = $rowId;
 
891
        $staffIds[$rowData['primaryKeys']['staff_id']][$rowData['_rawData']['resource_type']] = $rowId;
723
892
      }
724
893
      else
725
894
      {
726
895
        // Capture error in error log.
727
 
        $this->logErr($errMsg);
 
896
        $this->eh->logErr($errMsg);
728
897
 
729
898
        if($throwOnError)
730
899
        {
743
912
    foreach($coll AS $index => &$record)
744
913
    {
745
914
      $stfId = $record['staff_id'];
746
 
      $rawData = $this->importData[$staffIds[$stfId]]['_rawData'];
747
 
      $rscTypeId = $stfRscTypeIds[$rawData['resource_type']];
 
915
      $stfRscType = array_search($record['staff_resource_type_id'], $stfRscTypeIds);
748
916
 
749
 
      if ( $record['staff_resource_type_id'] == $rscTypeId )
 
917
      if (isset($staffIds[$stfId][$stfRscType]))
750
918
      {
751
 
        $orgId = $organizationIds[$rawData['organization']];
 
919
        $rawData = $this->importData[$staffIds[$stfId][$stfRscType]]['_rawData'];
 
920
 
 
921
        // Check if import organization is valid.
 
922
        if (!array_key_exists(strtolower($rawData['organization']), $organizationIds))
 
923
        {
 
924
          $errMsg = sprintf('Invalid organization %s from record id %d.',
 
925
                               $rawData['organization'], $staffIds[$stfId]);
 
926
 
 
927
          // Capture error in error log.
 
928
          $this->eh->logErr($errMsg);
 
929
 
 
930
          if($throwOnError)
 
931
          {
 
932
            throw new Exception($errMsg);
 
933
          }
 
934
          else
 
935
          {
 
936
            continue;
 
937
          }
 
938
        }
 
939
 
 
940
        // Check if import staff resource status is valid.
 
941
        if (!array_key_exists(strtolower($rawData['resource_status']), $stfRscStatusIds))
 
942
        {
 
943
          $errMsg = sprintf('Invalid staff resource status %s from record id %d.',
 
944
                               $rawData['resource_status'], $staffIds[$stfId]);
 
945
 
 
946
          // Capture error in error log.
 
947
          $this->eh->logErr($errMsg);
 
948
 
 
949
          if($throwOnError)
 
950
          {
 
951
            throw new Exception($errMsg);
 
952
          }
 
953
          else
 
954
          {
 
955
            continue;
 
956
          }
 
957
        }
 
958
 
 
959
        $orgId = $organizationIds[strtolower($rawData['organization'])];
752
960
        $record['organization_id'] = $orgId;
753
 
        $stfRscStatusId = $stfRscStatusIds[$rawData['resource_status']];
 
961
        $stfRscStatusId = $stfRscStatusIds[strtolower($rawData['resource_status'])];
754
962
        $record['staff_resource_status_id'] = $stfRscStatusId;
755
 
        unset($staffIds[$stfId]);
756
 
      }
757
 
    }
758
 
 
759
 
    $coll->save($conn);
 
963
        unset($staffIds[$stfId][$stfRscType]);
 
964
      }
 
965
    }
 
966
 
 
967
    // here we check our current transaction scope and create a transaction or savepoint
 
968
    $useSavepoint = ($conn->getTransactionLevel() > 0) ? TRUE : FALSE;
 
969
    if ($useSavepoint)
 
970
    {
 
971
      $conn->beginTransaction(__FUNCTION__);
 
972
    }
 
973
    else
 
974
    {
 
975
      $conn->beginTransaction();
 
976
    }
 
977
 
 
978
    try
 
979
    {
 
980
      $coll->save($conn);
 
981
      
 
982
      // commit, being sensitive to our nesting
 
983
      if ($useSavepoint) { $conn->commit(__FUNCTION__); } else { $conn->commit(); }
 
984
    }
 
985
    catch(Exception $e)
 
986
    {
 
987
      // log our error
 
988
      $errMsg = sprintf('%s failed at: %s', __FUNCTION__, $e->getMessage());
 
989
      $this->eh->logErr($errMsg);
 
990
 
 
991
      // rollback
 
992
      if ($useSavepoint) { $conn->rollback(__FUNCTION__); } else { $conn->rollback(); }
 
993
 
 
994
      // ALWAYS throw an error, it's like stepping on a crack if you don't
 
995
      if($throwOnError)
 
996
      {
 
997
        throw new Exception($errMsg);
 
998
      }
 
999
    }
 
1000
 
760
1001
    unset($coll);
761
1002
 
762
1003
    // Now $staffIds are left with new staff resources.
763
 
    foreach($staffIds AS $stfId => $rowId)
 
1004
    foreach($staffIds AS $stfId => $stfResources)
764
1005
    {
765
 
      $rawData = $this->importData[$staffIds[$stfId]]['_rawData'];
766
 
      $fKeys = array();
767
 
      $fKeys['staff_id'] = $stfId;
768
 
      $fKeys['organization_id'] = $organizationIds[$rawData['organization']];
769
 
      $fKeys['staff_resource_type_id'] = $stfRscTypeIds[$rawData['resource_type']];
770
 
      $fKeys['staff_resource_status_id'] = $stfRscStatusIds[$rawData['resource_status']];
771
 
 
772
 
      $staffResource = $this->createNewRec('agStaffResource', $fKeys);
 
1006
      foreach ($stfResources AS $stfRsc => $rowId)
 
1007
      {
 
1008
        $rawData = $this->importData[$rowId]['_rawData'];
 
1009
 
 
1010
        // Check if import resource type is valid.
 
1011
        if (!array_key_exists(strtolower($rawData['resource_type']), $stfRscTypeIds))
 
1012
        {
 
1013
          $errMsg = sprintf('Invalid resource type %s from record id %d.',
 
1014
                               $rawData['resource_type'], $staffIds[$stfId]);
 
1015
 
 
1016
          // Capture error in error log.
 
1017
          $this->eh->logErr($errMsg);
 
1018
 
 
1019
          if($throwOnError)
 
1020
          {
 
1021
            throw new Exception($errMsg);
 
1022
          }
 
1023
          else
 
1024
          {
 
1025
            continue;
 
1026
          }
 
1027
        }
 
1028
 
 
1029
        // Check if import organization is valid.
 
1030
        if (!array_key_exists(strtolower($rawData['organization']), $organizationIds))
 
1031
        {
 
1032
          $errMsg = sprintf('Invalid organization %s from record id %d.',
 
1033
                               $rawData['organization'], $staffIds[$stfId]);
 
1034
 
 
1035
          // Capture error in error log.
 
1036
          $this->eh->logErr($errMsg);
 
1037
 
 
1038
          if($throwOnError)
 
1039
          {
 
1040
            throw new Exception($errMsg);
 
1041
          }
 
1042
          else
 
1043
          {
 
1044
            continue;
 
1045
          }
 
1046
        }
 
1047
 
 
1048
        // Check if import staff resource status is valid.
 
1049
        if (!array_key_exists(strtolower($rawData['resource_status']), $stfRscStatusIds))
 
1050
        {
 
1051
          $errMsg = sprintf('Invalid staff resource status %s from record id %d.',
 
1052
                               $rawData['resource_status'], $staffIds[$stfId]);
 
1053
 
 
1054
          // Capture error in error log.
 
1055
          $this->eh->logErr($errMsg);
 
1056
 
 
1057
          if($throwOnError)
 
1058
          {
 
1059
            throw new Exception($errMsg);
 
1060
          }
 
1061
          else
 
1062
          {
 
1063
            continue;
 
1064
          }
 
1065
        }
 
1066
 
 
1067
        $fKeys = array();
 
1068
        $fKeys['staff_id'] = $stfId;
 
1069
        $fKeys['organization_id'] = $organizationIds[strtolower($rawData['organization'])];
 
1070
        $fKeys['staff_resource_type_id'] = $stfRscTypeIds[strtolower($rawData['resource_type'])];
 
1071
        $fKeys['staff_resource_status_id'] = $stfRscStatusIds[strtolower($rawData['resource_status'])];
 
1072
 
 
1073
        $staffResource = $this->createNewRec('agStaffResource', $fKeys);
 
1074
      }
773
1075
    }
774
1076
 
775
1077
  }
776
1078
 
777
 
  public function testDataNorm()
 
1079
  /**
 
1080
   * Method to set person language during staff import.
 
1081
   * @param boolean $throwOnError Parameter sometimes used by import normalization methods to
 
1082
   * control whether or not errors will be thrown.
 
1083
   * @param Doctrine_Connection $conn A doctrine connection for data manipulation.
 
1084
   */
 
1085
  protected function setPersonLanguage($throwOnError, Doctrine_Connection $conn)
778
1086
  {
779
 
    $this->setLogEventLevel(self::EVENT_INFO);
780
 
    $_rawData1 = array('entity_id' => '3',
781
 
                      'first_name' => 'Mork',
782
 
//                      'middle_name' => '',
783
 
                      'last_name' => 'Ork',
784
 
                      'mobile_phone' => '123.123.1234',
785
 
//                      'home_phone' => '',
786
 
                      'home_email' => 'mork.ork@home.com',
787
 
//                      'work_phone' => '',
788
 
//                      'work_email' => '',
789
 
                      'home_address_line_1' => '5 Silly Lane Street',
790
 
                      'home_address_city' => 'Inwood',
791
 
                      'home_address_state' => 'Bronze',
792
 
                      'home_address_country' => 'United States of America',
793
 
                      'work_address_line_1' => '5 Silly Man',
794
 
                      'work_address_line_2' => 'In rooom 728',
795
 
                      'work_address_city' => 'New York',
796
 
                      'work_address_state' => 'NY',
797
 
                      'work_address_zip' => '10013',
798
 
                      'work_address_country' => 'United States of America',
799
 
                      'organization' => 'GOAL',
800
 
                      'resource_type' => 'Medical Nurse',
801
 
                      'resource_status' => 'active',
802
 
                      'drivers_license_class' => 'Class A',
803
 
                      'civil_service_title' => 'Court Clerk'
804
 
                     );
805
 
 
806
 
    $_rawData2 = array('entity_id' => '183',
807
 
                      'first_name' => 'Ork',
808
 
                      'middle_name' => 'Mork',
809
 
//                      'last_name' => '',
810
 
//                      'mobile_phone' => '',
811
 
                      'home_phone' => '(222) 222-1234',
812
 
//                      'home_email' => '',
813
 
                      'work_phone' => '(212) 234-2344 x234',
814
 
                      'work_address_line_1' => '235 President Pl',
815
 
                      'work_address_city' => 'New York',
816
 
                      'work_address_state' => 'NY',
817
 
                      'work_address_zip' => '11001',
818
 
                      'work_address_country' => 'United States of America',
819
 
                      'organization' => 'volunteer',
820
 
                      'resource_type' => 'Specialist',
821
 
                      'resource_status' => 'inactive',
822
 
                      'civil_service_title' => 'Judge'
823
 
                     );
824
 
 
825
 
    $_rawData3 = array('entity_id' => '11',
826
 
//                      'first_name' => '',
827
 
//                      'middle_name' => '',
828
 
//                      'last_name' => '',
829
 
//                      'mobile_phone' => '',
830
 
//                      'home_phone' => '',
831
 
//                      'home_email' => '',
832
 
                      'work_phone' => '333.3333.3333.',
833
 
//                      'work_email' => '',
834
 
                      'new custom field' => 'smiley face'
835
 
                     );
836
 
 
837
 
    $_rawData4 = array('entity_id' => '4983',
838
 
                      'first_name' => 'Ae432',
839
 
                      'middle_name' => 'LinjaAA  ',
840
 
                      'last_name' => '   asdkfjkl;   ',
841
 
                      'mobile_phone' => '999.9999.9999',
842
 
//                      'home_phone' => '',
843
 
//                      'home_email' => '',
844
 
                      'work_phone' => '222.3333.4444 x342',
845
 
                      'work_email' => 'Linjawork.com',
846
 
                      'organization' => 'CHAD',
847
 
                      'resource_type' => 'Medical Assistant',
848
 
                      'resource_status' => 'Bouncing',
849
 
                      'pms_id' => 'P23423452'
850
 
                     );
851
 
 
852
 
    $_rawData5 = array('entity_id' => '392',
853
 
                      'first_name' => 'Aimee',
854
 
//                      'middle_name' => '',
855
 
                      'last_name' => 'Adu',
856
 
//                      'mobile_phone' => '',
857
 
//                      'home_phone' => '',
858
 
//                      'home_email' => '',
859
 
//                      'work_phone' => '',
860
 
                      'work_email' => 'aimeeemailnow@work.com'
861
 
                     );
862
 
 
863
 
    $this->importData[1] = array( '_rawData' => $_rawData1, 'primaryKey' => array(), 'success' => 0);
864
 
    $this->importData[2] = array( '_rawData' => $_rawData2, 'primaryKey' => array(), 'success' => 0);
865
 
    $this->importData[3] = array( '_rawData' => $_rawData3, 'primaryKey' => array(), 'success' => 0);
866
 
    $this->importData[4] = array( '_rawData' => $_rawData4, 'primaryKey' => array(), 'success' => 0);
867
 
    $this->importData[5] = array( '_rawData' => $_rawData5, 'primaryKey' => array(), 'success' => 0);
868
 
 
869
 
    $this->clearNullRawData();
870
 
    $this->normalizeData();
871
 
    print_r($this->getEvents());
 
1087
    // always start with any data maps we'll need so they're explicit
 
1088
    $importLanguageComponents = array( 'language_1' => array( 'l1_speak' => 'speak', 
 
1089
                                                              'l1_read' => 'read', 
 
1090
                                                              'l1_write' => 'write'),
 
1091
                                       'language_2' => array( 'l2_speak' => 'speak', 
 
1092
                                                              'l2_read' => 'read', 
 
1093
                                                              'l2_write' => 'write'),
 
1094
                                       'language_3' => array( 'l3_speak' => 'speak', 
 
1095
                                                              'l3_read' => 'read', 
 
1096
                                                              'l3_write' => 'write')
 
1097
                                     );
 
1098
 
 
1099
    $personLanguages = array();
 
1100
    $results = array();
 
1101
 
 
1102
    // let's get ahold of our helper object since we're going to use him/her a lot
 
1103
    $plh =& $this->helperObjects['agPersonLanguageHelper'];
 
1104
 
 
1105
 
 
1106
    // loop through our raw data and build our person language data
 
1107
    foreach ($this->importData as $rowId => $rowData)
 
1108
    {
 
1109
      if (array_key_exists('person_id', $rowData['primaryKeys']))
 
1110
      {
 
1111
        // this just makes it easier to use
 
1112
        $personId = $rowData['primaryKeys']['person_id'];
 
1113
 
 
1114
        // Always initialize $languageComponents as an empty array.  Assign an empty array to
 
1115
        // $personLanguages only if no language was specified from import.
 
1116
        $languageComponents = array();
 
1117
        foreach($importLanguageComponents as $importLanguage => $langComponents)
 
1118
        {
 
1119
          if (array_key_exists($importLanguage, $rowData['_rawData']))
 
1120
          {
 
1121
            // Always initialize $formatCompetencies as an emtpy array. Assign an emtpy array to
 
1122
            // $languageComponents only if no format/competency details is specified for the
 
1123
            // language from import.
 
1124
            $formatCompetencies = array();
 
1125
            foreach ($langComponents as $importFormat => $dbFormat)
 
1126
            {
 
1127
              if (array_key_exists($importFormat, $rowData['_rawData']))
 
1128
              {
 
1129
                $formatCompetencies[$dbFormat] = $rowData['_rawData'][$importFormat];
 
1130
              }
 
1131
            }
 
1132
            $languageComponents[] = array($rowData['_rawData'][$importLanguage], $formatCompetencies);
 
1133
          }
 
1134
        }
 
1135
        $personLanguages[$personId] = $languageComponents;
 
1136
      }
 
1137
    }
 
1138
 
 
1139
    // pick up some of our components / objects
 
1140
    $keepHistory = agGlobal::getParam('staff_import_keep_history');
 
1141
    $createEdgeTableValues = agGlobal::getParam('create_edge_table_values');;
 
1142
 
 
1143
    // execute the helper and finish
 
1144
    $results = $plh->setPersonLanguages($personLanguages, $keepHistory, $createEdgeTableValues, $throwOnError, $conn);
 
1145
    unset($personLanguages);
 
1146
 
 
1147
    // @todo do your results reporting here
872
1148
  }
 
1149
 
873
1150
}
 
 
b'\\ No newline at end of file'