public function getCandidateEntityByCrpId($id)
 {
     if (!count($candidates = $this->getOsCandidatesById($id))) {
         return null;
     }
     //try to find entity by fec_id
     $fecIds = array();
     foreach ($candidates as $candidate) {
         if (!$candidate['fec_id'] || !$candidate['name_last']) {
             continue;
         }
         if ($entity = $this->getCandidateEntityByFecId($candidate['fec_id'], $candidate['name_last'])) {
             return $entity;
         }
         $fecIds[] = $candidate['fec_id'];
     }
     $candidate = $candidates[0];
     if ($this->debugMode) {
         print "+ Creating new entity for person " . $id . " (" . $candidate['name'] . ")\n";
     }
     $entity = new Entity();
     $entity->addExtension('Person');
     $entity->addExtension('PoliticalCandidate');
     $entity->name_last = $candidate['name_last'];
     $entity->name_first = $candidate['name_first'];
     $entity->name_middle = $candidate['name_middle'];
     $entity->name_suffix = $candidate['name_suffix'];
     $entity->crp_id = $id;
     foreach ($fecIds as $fecId) {
         $map = array('P' => 'pres_fec_id', 'S' => 'senate_fec_id', 'H' => 'house_fec_id');
         $code = substr($fecId, 0, 1);
         if (@($field = $map[$code])) {
             $entity->{$field} = $fecId;
         }
     }
     $entity->save();
     if (!($district = PoliticalDistrictTable::getFederalDistrict($state, $district))) {
         if ($state = AddressStateTable::retrieveByText($state)) {
             $district = new PoliticalDistrict();
             $district->state_id = $state['id'];
             $district->federal_district = $district;
             $district->save();
         }
     }
     if ($district) {
         $pc = $entity->getExtensionObject('PoliticalCandidate');
         $cd = new CandidateDistrict();
         $cd->candidate_id = $pc->id;
         $cd->district_id = $district->id;
         $cd->save();
     }
     return $entity;
 }
 private function getTransactionDetails($org, $fedspending_id)
 {
     if (!$this->browser->get($this->fedSpendingSearchUrl, array('record_id' => $fedspending_id, 'datype' => 'X', 'detail' => '4'))->responseIsError()) {
         $response_url = $this->browser->getUrlInfo();
         $response_url_str = "http://" . $response_url['host'] . $response_url['path'] . "?" . $response_url['query'];
         $this->printDebug("Transaction #{$fedspending_id} http://" . $response_url['host'] . $response_url['path'] . "?" . $response_url['query']);
         $text = $this->browser->getResponseText();
         $this->browser->setResponseText(iconv('ISO-8859-1', 'UTF-8', $this->browser->getResponseText()));
         $xml = $this->browser->getResponseXml();
     } else {
         $this->printDebug("Couldn't get " . $this->fedSpendingSearchUrl);
         return false;
     }
     $obligated_amount = $xml->xpath('/fedspendingSearchResults/data/record/amounts/obligatedAmount');
     $maj_agency_cat = $xml->xpath('/fedspendingSearchResults/data/record/purchaser_information/maj_agency_cat');
     $contracting_agency = $xml->xpath('/fedspendingSearchResults/data/record/purchaser_information/contractingOfficeAgencyID');
     $psc_cat = $xml->xpath('/fedspendingSearchResults/data/record/product_or_service_information/psc_cat');
     $signed_date = $xml->xpath('/fedspendingSearchResults/data/record/contract_information/signedDate');
     $descriptionOfContractRequirement = $xml->xpath('/fedspendingSearchResults/data/record/contract_information/descriptionOfContractRequirement');
     $current_completion_date = $xml->xpath('/fedspendingSearchResults/data/record/contract_information/currentCompletionDate');
     $state_code = $xml->xpath('/fedspendingSearchResults/data/record/principal_place_of_performance/stateCode');
     $place_of_performance_congressional_district = $xml->xpath('/fedspendingSearchResults/data/record/principal_place_of_performance/placeOfPerformanceCongressionalDistrict');
     foreach ($obligated_amount as $key => $dont_use) {
         $gov_name = $this->cleanGovtBodyName($maj_agency_cat[$key]);
         $gov_agency = $this->getGovernmentBodyEntity($gov_name, $maj_agency_cat[$key]);
         if ($gov_agency) {
             //$this->printDebug("Found existing Government Agency" . $gov_agency->name);
         } else {
             $gov_name = $this->cleanGovtBodyName($maj_agency_cat[$key]);
             $this->printDebug($gov_name);
             $gov_agency = $this->addGovernmentBodyEntity($gov_name, $maj_agency_cat[$key]);
             $this->printDebug("Creating new Government Agency: " . $gov_agency->name);
             $gov_agency->addReference(self::$baseContractorUrl . $org->fedspending_id, null, array('name', 'parent_id'), 'FedSpending.org');
         }
         if (!$gov_agency) {
             $this->printDebug("Error creating Government Agency");
             return false;
         }
         $sub_agency_name = $this->cleanGovtBodyName($contracting_agency[$key]);
         $sub_agency = $this->getGovernmentBodyEntity($sub_agency_name, $contracting_agency[$key]);
         if ($sub_agency_name == $gov_agency->name) {
             $sub_agency = $gov_agency;
         }
         if (!$sub_agency) {
             $sub_agency = $this->addGovernmentBodyEntity($sub_agency_name, $contracting_agency[$key], $gov_agency->id);
             $this->printDebug("Creating new sub-agency: " . $sub_agency->name);
             $sub_agency->addReference(self::$baseContractorUrl . $org->fedspending_id, null, array('name', 'parent_id'), 'FedSpending.org');
         }
         if (!$sub_agency) {
             $this->printDebug("Error creating Government Agency");
             return false;
         }
         try {
             $district = null;
             $state = explode(': ', $state_code[$key]);
             $federal_district = explode(': ', $place_of_performance_congressional_district[$key]);
             $state = $state[0];
             $federal_district = $federal_district[0];
             $filing = new FedspendingFiling();
             $filing->goods = $descriptionOfContractRequirement[$key];
             $filing->amount = abs($obligated_amount[$key]);
             if ($filing->amount < 1000) {
                 $this->printDebug('amount under $1000, rolling back');
                 return 'under_1000';
             }
             //$this->printDebug("state: " . $state . " and district: " . $federal_district);
             if ($district = PoliticalDistrictTable::getFederalDistrict($state, $federal_district)) {
                 //$this->printDebug("found " . $district->id);
                 $filing->District = $district;
             } elseif (trim($state) && trim($federal_district)) {
                 try {
                     $district = PoliticalDistrictTable::addFederalDistrict($state, $federal_district);
                     $this->printDebug("Adding District " . $state . " #" . $district->id);
                     $filing->District = $district;
                 } catch (Exception $e) {
                     throw $e;
                 }
             }
             $filing->fedspending_id = $fedspending_id;
             $filing->start_date = LsDate::formatFromText($signed_date[$key]);
             $filing->end_date = LsDate::formatFromText($current_completion_date[$key]);
             $relationship = null;
             if ($relationship = $org->getRelationshipsWithQuery($sub_agency, RelationshipTable::TRANSACTION_CATEGORY)->fetchOne()) {
                 $relationship->addFedspendingFiling($filing);
             } else {
                 $relationship = new Relationship();
                 $relationship->Entity1 = $org;
                 $relationship->Entity2 = $sub_agency;
                 $relationship->setCategory('Transaction');
                 $relationship->description1 = 'Contractor';
                 $relationship->description2 = 'Client';
                 $relationship->save();
                 $relationship->addReference(self::$baseContractorUrl . $org->fedspending_id, null, array('start_date', 'end_date', 'amount', 'goods'), 'FedSpending.org');
                 $relationship->addFedspendingFiling($filing);
             }
             $filing->save();
             return true;
         } catch (Exception $e) {
             throw $e;
         }
     }
 }