eerste migratie mollie customers

This commit is contained in:
ErikHommel 2021-12-09 17:41:13 +01:00
parent ebb97de46b
commit 32d226e192
11 changed files with 1079 additions and 23 deletions

View File

@ -0,0 +1,229 @@
<?php
use CRM_Bij1migratie_ExtensionUtil as E;
/**
* Class BIJ1 migratie service
*
* @author Erik Hommel (CiviCooP) <erik.hommel@civicoop.org>
* @date 9 Dec 021
* @license AGPL-3.0
*/
class CRM_Bij1migratie_Bij1MigratieService {
/**
* @var CRM_Bij1migratie_Bij1MigratieService
*/
protected static $singleton;
protected $_mijnheerAanhef = NULL;
protected $_mevrouwAanhef = NULL;
protected $_manGeslacht = NULL;
protected $_onbekendGeslacht = NULL;
protected $_vrouwGeslacht = NULL;
protected $_financialTypeId = NULL;
protected $_completedContributionStatusId = NULL;
protected $_migratieGroupId = NULL;
/**
* CRM_Bij1migratie_Bij1MigratieService constructor.
*/
public function __construct() {
if (!self::$singleton) {
self::$singleton = $this;
}
}
/**
* @return \CRM_Bij1migratie_Bij1MigratieService
*/
public static function getInstance() {
if (!self::$singleton) {
self::$singleton = new CRM_Bij1migratie_Bij1MigratieService();
}
return self::$singleton;
}
/**
* @param int $id
*/
public function setMigratieGroepId(int $id) {
$this->_migratieGroupId = $id;
}
/**
* @return null
*/
public function getMigratieGroepId() {
return $this->_migratieGroupId;
}
/**
* @param int $value
*/
public function setMijnheerAanhef(int $value) {
$this->_mijnheerAanhef = $value;
}
/**
* @return null
*/
public function getMijnheerAanhef() {
return $this->_mijnheerAanhef;
}
/**
* @param int $value
*/
public function setMevrouwAanhef(int $value) {
$this->_mevrouwAanhef = $value;
}
/**
* @return null
*/
public function getMevrouwAanhef() {
return $this->_mevrouwAanhef;
}
/**
* @param int $value
*/
public function setManGeslacht(int $value) {
$this->_manGeslacht = $value;
}
/**
* @return null
*/
public function getManGeslacht() {
return $this->_manGeslacht;
}
/**
* @param int $value
*/
public function setOnbekendGeslacht(int $value) {
$this->_onbekendGeslacht = $value;
}
/**
* @return null
*/
public function getOnbekendGeslacht() {
return $this->_onbekendGeslacht;
}
/**
* @param int $value
*/
public function setVrouwGeslacht(int $value) {
$this->_vrouwGeslacht = $value;
}
/**
* @return null
*/
public function getVrouwGeslacht() {
return $this->_vrouwGeslacht;
}
/**
* @param int $id
*/
public function setFinancialTypeId(int $id) {
$this->_financialTypeId = $id;
}
/**
* @return null
*/
public function getFinancialTypeId() {
return $this->_financialTypeId;
}
/**
* @param int $id
*/
public function setCompletedContributionStatusId(int $id) {
$this->_completedContributionStatusId = $id;
}
/**
* @return null
*/
public function getCompletedContributionStatusId() {
return $this->_completedContributionStatusId;
}
/**
* Function om mogelijke separatoren voor csv bestand op te halen
*
* @return string[]
*/
public function getSeparatorList() {
return [",", ";", ":", "~"];
}
/**
* Method om de separator voor het csv bestand te halen
*
* @param $separatorId
* @return string
*/
public function getSeparator($separatorId) {
switch ($separatorId) {
case 0:
return ",";
case 1:
return ";";
case 3:
return ":";
case 2:
return "~";
default:
return "";
}
}
/**
* Method om formValues te schonen
*
* @param $sourceValues
* @return array
*/
public function cleanFormValues($sourceValues) {
$result = [];
foreach ($sourceValues as $sourceKey => $sourceValue) {
if ($sourceKey != "qfKey" && $sourceKey != "entryURL" && substr($sourceKey,0,4) != "_qf_") {
$result[$sourceKey] = $sourceValue;
}
}
return $result;
}
/**
* Method om de migratie kolommen op te halen
*
* @param string $migratieType
* @return false|array
* @throws
*/
public function getMigratieColumns(string $migratieType) {
switch ($migratieType) {
case "A":
$type = "airtable";
break;
case "B":
$type = "betalingen";
break;
default:
$type = "contacten";
break;
}
$container = CRM_Extension_System::singleton()->getFullContainer();
$jsonFile = $container->getPath('bij1migratie').'/mapping/' . strtolower($type) . '.json';
if (file_exists($jsonFile)) {
return json_decode(file_get_contents($jsonFile));
}
return FALSE;
}
}

View File

@ -0,0 +1,243 @@
<?php
use CRM_Bij1migratie_ExtensionUtil as E;
/**
* Class voor BIJ1 migratie CSV import
*
* @author Erik Hommel (CiviCooP) <erik.hommel@civicoop.org>
* @date 9 dec 2021
* @license AGPL-3.0
*/
class CRM_Bij1migratie_CsvFile {
private $_separator = NULL;
private $_fileName = NULL;
private $_usesHeaders = NULL;
private $_rowNumber = NULL;
private $_headers = [];
private $_migratieType = NULL;
public $csv = NULL;
/**
* Method to initialize
*
* @param string $fileName
* @param string $migratieType
* @param bool $usesHeaders
* @param string $separator
*/
public function initialize(string $fileName, string $migratieType, bool $usesHeaders = FALSE, string $separator = "~") {
$this->_fileName = $fileName;
$this->_separator = $separator;
$this->_usesHeaders = $usesHeaders;
$this->_rowNumber = 0;
$this->_migratieType = $migratieType;
}
/**
* Method to get the headers (and numbers if none found)
*
* @throws Exception if file can not be opened
*/
public function getHeaders() {
$headers = [];
$i = 0;
$this->open();
if ($this->_usesHeaders) {
$data = fgetcsv($this->csv, 0, $this->_separator);
foreach ($data as $key => $value) {
if ($value) {
$headers[] = $value;
$i++;
}
else {
$i++;
$headers[] = "csv column " . $i;
}
}
}
else {
$data = fgetcsv($this->csv, 0, $this->_separator);
$count = count($data);
while ($i < $count) {
$i++;
$headers[] = "csv column " . $i;
}
}
$this->close();
return $headers;
}
/**
* Method to open the file for read
*
* @throws Exception when file can not be opened
* @return bool
*/
public function open() {
$this->csv = fopen($this->_fileName, 'r');
if ($this->csv) {
return TRUE;
}
return FALSE;
}
/**
* Method to read the next line and return an array with data
*
* @param string $tableName
* @return array|bool
*/
public function readNext(string $tableName) {
$this->_rowNumber++;
// if row 1 complete mapping and if headers, skip
if ($this->_rowNumber == 1) {
$data = fgetcsv($this->csv, 0, $this->_separator);
$this->setHeaders($data);
if (!$this->_usesHeaders) {
rewind($this->csv);
}
}
$data = fgetcsv($this->csv, 0, $this->_separator);
if ($tableName && $data) {
$this->sanitizeData($tableName, $data);
}
if ($data) {
return $data;
}
return FALSE;
}
/**
* Sanitize row: empty data if it contains invalid content
*
* @param string $tableName
* @param array $data
* @throws
*/
private function sanitizeData(string $tableName, array &$data) {
if (!empty($data)) {
$table = new CRM_Bij1migratie_ImportTable();
$columns = $table->getColumnNames($tableName);
foreach ($columns as $key => $name) {
switch ($this->_migratieType) {
case "A":
$this->sanitizeAirtable($name, $data);
break;
case "B":
$this->sanitizeBetalingen($name, $key, $data);
break;
case "P":
$this->sanitizePersonen($name, $data);
break;
}
}
foreach ($data as $key => $value) {
if (is_numeric($key)) {
unset($data[$key]);
}
}
}
}
private function sanitizeAirtable(string $name, array &$data) {
}
/**
* Method om data voor betalingen samen te stellen
*
* @param string $name
* @param string $key
* @param array $data
* @throws
*/
private function sanitizeBetalingen(string $name, string $key, array &$data) {
switch ($name) {
case "contact_id":
$contactId = Civi::service('bij1Migratie')->haalContactIdMetMollieCustomerId((int) $data[0]);
if ($contactId) {
$data['contact_id'] = $contactId;
}
else {
$migratieDatum = new DateTime('now');
\Civi\Api4\MigratieLog::create()
->addValue('ssaskia_nummer', $data['ssaskia_nummer'])
->addValue('migratiedatum', $migratieDatum->format("Y-m-d"))
->addValue('type', 'giften')
->addValue('melding', 'FOUT, kon geen contact in CiviCRM vinden voor het ssaskia nummer')
->execute();
$data['contact_id'] = "onbekend";
}
break;
case "donatiebedrag":
$data['donatiebedrag'] = $data[1];
break;
case "donatiedatum":
try {
$donatieDatum = new DateTime($data[2]);
}
catch (Exception $ex) {
$donatieDatum = new DateTime("01-01-2000");
}
$data['donatiedatum'] = $donatieDatum->format('d-m-Y');
break;
case "mededeling":
$data['mededeling'] = $data[4];
break;
case "iban":
$data['iban'] = $data[3];
break;
}
}
/**
* Method om data voor personen samen te stellen
*
* @param string $name
* @param array $data
* @throws Exception
*/
private function sanitizePersonen(string $name, array &$data) {
switch ($name) {
case "mollie_customer_id":
$data[$name] = $data[0];
break;
case "achternaam":
$naamDelen = explode(" ", $data[1]);
if (count($naamDelen) > 1) {
$data['voornaam'] = trim($naamDelen[0]);
unset($naamDelen[0]);
$data['achternaam'] = trim(implode(" ", $naamDelen));
}
else {
if (!empty($naamDelen[0])) {
$data['achternaam'] = trim($naamDelen[0]);
}
else {
$data['achternaam'] = "Onbekend " . rand(0,9999);
}
$data['voornaam'] = "Onbekend " . rand(0,9999);
}
break;
case "email":
$data[$name] = $data[2];
break;
}
}
/**
* Method to close the file
*/
public function close() {
fclose($this->csv);
}
/**
* Method to set the headers of the csv file
*
* @param $headers
*/
private function setHeaders($headers) {
$this->_headers = $headers;
}
}

View File

@ -0,0 +1,144 @@
<?php
use CRM_Bij1migratie_ExtensionUtil as E;
/**
* Form controller class
*
* @see https://docs.civicrm.org/dev/en/latest/framework/quickform/
*/
class CRM_Bij1migratie_Form_CsvSelect extends CRM_Core_Form {
private $_tableName = NULL;
/**
* Overridden parent method to build the form
*/
public function buildQuickForm() {
$this->add('file', 'csv_file', E::ts('Migratie bestand (CSV)'), [], TRUE);
$this->addRule('csv_file', E::ts('Bestand moet CSV formaat hebben'), 'utf8File');
$this->addRule('csv_file', E::ts('Er moet een geldig bestand geladen worden.'), 'uploadedfile');
$this->add('advcheckbox', 'first_row_headers', E::ts('Bevat de eerste rij kolomkoppen?'));
$separatorList = Civi::service('bij1Migratie')->getSeparatorList();
$this->add('select', 'migratie_type', E::ts('Soort migratie'), ['A' => 'Airtable', 'P' => 'Mollie klanten', 'B' => 'Betalingen'] , TRUE);
$this->add('select', 'separator_id', E::ts('Scheidingsteken voor velden'), $separatorList , TRUE);
$this->addButtons([
['type' => 'next', 'name' => E::ts('Next'), 'isDefault' => TRUE],
['type' => 'cancel', 'name' => E::ts('Cancel')],
]);
parent::buildQuickForm();
}
/**
* Overridden parent method to set default values
*
* @return array
*/
public function setDefaultValues() {
$defaults = [];
$defaults['first_row_headers'] = TRUE;
$defaults['separator_id'] = 1;
return $defaults;
}
/**
* Overridden parent method to add validation rules
*
*/
public function addRules() {
$this->addFormRule(['CRM_Bij1migratie_Form_CsvSelect', 'validateCsvFile']);
}
/**
* Overridden parent method to prepare the form
*/
public function preProcess() {
CRM_Utils_System::setTitle("BIJ1 - CiviCRM migratie - kies CSV bestand");
parent::preProcess(); // TODO: Change the autogenerated stub
}
/**
* Overridden parent method to process the form
*/
public function postProcess() {
set_time_limit(0);
// send csv data to upload table
$table = $this->populateTable(Civi::service('bij1Migratie')->getSeparator($this->_submitValues['separator_id']));
if ($table) {
CRM_Bij1migratie_Migratie::migreer($this->_submitValues['migratie_type'], $this->_tableName);
}
parent::postProcess();
}
/**
* Method to get only bit before . for filename
*
* @param $fileName
* @return string
*/
private function sanitizeFileName($fileName) {
$fileName = trim(strtolower($fileName));
$parts = explode(".", $fileName);
$fileName = $parts[0];
$invalids = [" ", "/", "\\", "#", "~", "`", "@", "%", "^", "&", "*", "(", ")", "{", "}", "[", "]", "<", ">", "?", ",", ":", ";"];
foreach ($invalids as $invalid) {
$fileName = str_replace($invalid, "_", $fileName);
}
if (strlen($fileName) > 53) {
$fileName = substr($fileName, 0, 53);
}
return $fileName;
}
/**
* Method to populate table with data from selected csv file
*
* @param $separator
* @return bool
* @throws Exception
*/
private function populateTable($separator) {
$table = new CRM_Bij1migratie_ImportTable();
$table->generateTableName($this->sanitizeFileName($this->_submitFiles['csv_file']['name']));
$this->_tableName = $table->getTableName();
$csv = new CRM_Bij1migratie_CsvFile();
$csv->initialize($this->_submitFiles['csv_file']['tmp_name'], $this->_submitValues['migratie_type'], $this->_submitValues['first_row_headers'], $separator);
$table->createTable($this->_submitValues['migratie_type']);
$csv->open();
while (!feof($csv->csv)) {
$data = $csv->readNext($this->_tableName);
if (!empty($data)) {
$table->writeRow($data);
}
}
$csv->close();
return TRUE;
}
/**
* Method to validate if file has the correct ext and can be opened
*
* @param $fields
* @param $files
* @return bool|array
* @throws
*/
public static function validateCsvFile($fields, $files) {
$ext = pathinfo($files['csv_file']['name'], PATHINFO_EXTENSION);
if ($ext != "csv" && $ext != "txt") {
$errors['csv_file'] = "Alleen CSV bestanden kunnen gemigreerd worden.";
return $errors;
}
if (!isset($files['csv_file']['tmp_name'])) {
$errors['csv_file'] = "Er lijkt geen bestand geladen te zijn.";
return $errors;
}
$check = fopen($files['csv_file']['tmp_name'], 'r');
if (!$check) {
$errors['csv_file'] = "Kan het CSV bestand niet openen.";
return $errors;
}
fclose($check);
return TRUE;
}
}

View File

@ -0,0 +1,163 @@
<?php
use CRM_Bij1migratie_ExtensionUtil as E;
/**
* Class voor de tabel uit de csv import (BIJ1 migratie)
*
* @author Erik Hommel (CiviCooP) <erik.hommel@civicoop.org>
* @date 9 dec 2021
* @license AGPL-3.0
*/
class CRM_Bij1migratie_ImportTable {
private $_tableName;
/**
* Method to generate the name of the table
*
* @param string $fileName
*/
public function generateTableName(string $fileName) {
$tableName = strtolower(substr($fileName,0,48)) . "_" . date('YmdHis');
// check if table already exists and if so, and random number to name
if (CRM_Core_DAO::checkTableExists($tableName)) {
$tableName .= "_" . rand(0,99);
}
$this->_tableName = $tableName;
}
/**
* Method to set the table name
*
* @param $tableName
*/
public function setTableName($tableName) {
$this->_tableName = $tableName;
}
/**
* Method to get the table name
*
* @return mixed
*/
public function getTableName() {
return $this->_tableName;
}
/**
* Method to create the table
*
* @param string $migratieType
*/
public function createTable(string $migratieType) {
$headers = Civi::service('bij1Migratie')->getMigratieColumns($migratieType);
// create a column for each header
$columns = ['id int UNSIGNED NOT NULL AUTO_INCREMENT'];
foreach ($headers as $civiName => $sourceName) {
$columns[] = $civiName . " VARCHAR(256)";
}
// if table exists, drop old one
if (CRM_Core_DAO::checkTableExists($this->_tableName)) {
$this->destroy();
}
$create = "CREATE TABLE " . $this->_tableName . " (" . implode(", ", $columns) .", PRIMARY KEY (id) )";
CRM_Core_DAO::executeQuery($create);
}
/**
* Function to write row in table using data from incoming array
*
* @param $data
* @return bool
*/
public function writeRow($data) {
if (empty($data)) {
return FALSE;
}
if (!is_array($data)) {
$data = [$data];
}
$i = 0;
$elements = [];
$columns = [];
$queryParams = [];
foreach ($data as $key => $value) {
$value = CRM_Core_DAO::escapeString($value);
$i++;
$elements[] = "%" . $i;
$columns[] = $key;
$queryParams[$i] = [$value, "String"];
}
$query = "INSERT INTO ". $this->_tableName . " (" . implode(",", $columns) . ") VALUES (" . implode(",", $elements) . ")";
try {
CRM_Core_DAO::executeQuery($query,$queryParams);
}
catch (Exception $ex) {
CRM_Core_Session::setStatus("Kon geen migratie regel in tabel schrijven, check CiviCRM error log", "Kon migratierecord niet schrijven", "error");
Civi::log()->error("on geen migratie regel in tabel schrijven in " . __METHOD__ . ", foutboodschap: " . $ex->getMessage());
return FALSE;
}
return TRUE;
}
/**
* Method to get all rows
*
* @param string $migratieType
* @param string $tableName
* @return array|false
*/
public function getAllRows(string $migratieType, string $tableName) {
if ($tableName) {
$result = [];
$dao = NULL;
if ($migratieType == "P") {
$query = "SELECT * FROM " . $tableName;
$dao = CRM_Core_DAO::executeQuery($query);
}
if ($migratieType == "B") {
$query = "SELECT * FROM " . $tableName;
$dao = CRM_Core_DAO::executeQuery($query);
}
while ($dao->fetch()) {
$result[] = Civi::service('bij1Algemeen')->moveDaoToArray($dao);
}
return $result;
}
return FALSE;
}
/**
* Method to get the column names
*
* @param string $tableName
* @return array
*/
public function getColumnNames(string $tableName) {
$result = [];
if (empty($tableName)) {
$tableName = $this->_tableName;
}
if ($tableName) {
$dao = CRM_Core_DAO::executeQuery("SHOW COLUMNS FROM " . $tableName);
while ($dao->fetch()) {
if ($dao->Field != "id") {
$result[] = $dao->Field;
}
}
}
return $result;
}
/**
* Method to drop table
*/
public function destroy() {
if ($this->_tableName) {
CRM_Core_DAO::executeQuery("DROP TABLE IF EXISTS " . $this->_tableName);
}
}
}

213
CRM/Bij1migratie/Migratie.php Executable file
View File

@ -0,0 +1,213 @@
<?php
use CRM_Bij1migratie_ExtensionUtil as E;
/**
* Verwerking van migratie
*/
class CRM_Bij1migratie_Migratie {
/**
* Method om data te migreren
*
* @param string $migratieType
* @param string $tableName
* @throws
*/
public static function migreer(string $migratieType, string $tableName) {
set_time_limit(0);
$table = new CRM_Bij1migratie_ImportTable();
$data = $table->getAllRows($migratieType, $tableName);
$migratieDatum = new DateTime('now');
if ($data) {
foreach ($data as $rij) {
if (!empty($rij)) {
try {
if ($migratieType == "P") {
$rij['locatietype_id'] = Civi::service('bij1Algemeen')->getDefaultLocationTypeId();
$result = civicrm_api3('FormProcessor', 'bij1_contacten_migratie', $rij);
\Civi\Api4\MigratieLog::create()
->addValue('mollie_customer_id', $rij['mollie_customer_id'])
->addValue('migratiedatum', $migratieDatum->format("y-m-d"))
->addValue('type', 'personen')
->addValue('melding', 'Gemigreerd')
->execute();
}
if ($migratieType == "B") {
if (!self::bestaatBetaling($rij)) {
civicrm_api3('FormProcessor', 'bij1_migratie_giften', $rij);
self::maakBankrekening($migratieDatum, $rij);
\Civi\Api4\MigratieLog::create()
->addValue('ssaskia_nummer', $rij['contact_id'])
->addValue('migratiedatum', $migratieDatum->format("y-m-d"))
->addValue('type', 'giften')
->addValue('melding', 'Gift van '. $rij['bedrag'] . ' op datum ' . $rij['donatie_datum'] . 'gemigreerd.')
->execute();
}
}
}
catch (CiviCRM_API3_Exception $ex) {
\Civi\Api4\MigratieLog::create()
->addValue('mollie_customer_id', $rij['mollie_customer_id'])
->addValue('migratiedatum', $migratieDatum->format("y-m-d"))
->addValue('type', 'personen')
->addValue('melding', 'FOUT, melding van FormProcessor API call: ' . $ex->getMessage())
->execute();
}
}
}
}
}
/**
* Method om te beoordelen of gift al bestaat voor contact
*
* @param $betaling
* @return bool
* @throws Exception
*/
public static function bestaatBetaling($betaling) {
$verplichten = ["contact_id", "donatiebedrag", "donatiedatum"];
foreach ($verplichten as $verplicht) {
if (!isset($gift[$verplicht]) || empty($gift[$verplicht])) {
return FALSE;
}
$receiveDate = new DateTime($gift['donatiedatum']);
$query = "SELECT COUNT(*) FROM civicrm_contribution WHERE contact_id = %1 AND receive_date = %2 AND total_amount = %3";
$count = CRM_Core_DAO::singleValueQuery($query, [
1 => [(int) $gift['contact_id'], "Integer"],
2 => [$receiveDate->format("Y-m-d"), "String"],
3 => [$gift['donatiebedrag'], "String"],
]);
if ($count > 0) {
return TRUE;
}
}
return FALSE;
}
/**
* Method om te bepalen of de persoon al bestaat
*
* @param int $ssaskiaNummer
* @return bool
*/
public static function bestaatPersoon(int $ssaskiaNummer) {
$query = "SELECT COUNT(*) FROM civicrm_value_pax_contact_data WHERE ssaskia_nummer = %1";
$count = CRM_Core_DAO::singleValueQuery($query, [1 => [$ssaskiaNummer, "Integer"]]);
if ($count > 0) {
return TRUE;
}
return FALSE;
}
/**
* Method om migratie groep aan te maken
*/
public function maakMigratieGroepen() {
$query = "SELECT COUNT(*) FROM civicrm_group WHERE name = %1";
$count = CRM_Core_DAO::singleValueQuery($query, [1 => ["pax_migratie_groep", "String"]]);
if ($count == 0) {
try {
\Civi\Api4\Group::create()
->addValue('name', 'pax_migratie_groep')
->addValue('title', 'CiviCRM Migratie')
->addValue('description', 'Groep met personen en organisaties die tijdens de migratie aangemaakt werden')
->addValue('is_active', TRUE)
->addValue('is_reserved', TRUE)
->execute();
}
catch (API_Exception $ex) {
Civi::log()->error(E::ts("Kon geen groep voor migratie aanmaken, fout van API4 Group create: ") . $ex->getMessage());
}
}
$count = CRM_Core_DAO::singleValueQuery($query, [1 => ["pax_dm_mag", "String"]]);
if ($count == 0) {
try {
\Civi\Api4\Group::create()
->addValue('name', 'pax_dm_mag')
->addValue('title', 'DM Mag')
->addValue('description', 'Groep van personen die in sSaskia de vlag DM mag aan hadden staan')
->addValue('is_active', TRUE)
->addValue('is_reserved', TRUE)
->execute();
}
catch (API_Exception $ex) {
Civi::log()->error(E::ts("Kon geen groep voor dm mag aanmaken, fout van API4 Group create: ") . $ex->getMessage());
}
}
$count = CRM_Core_DAO::singleValueQuery($query, [1 => ["pax_post_mag", "String"]]);
if ($count == 0) {
try {
\Civi\Api4\Group::create()
->addValue('name', 'pax_post_mag')
->addValue('title', 'Post Mag')
->addValue('description', 'Groep van personen die in sSaskia de vlag post mag aan hadden staan')
->addValue('is_active', TRUE)
->addValue('is_reserved', TRUE)
->execute();
}
catch (API_Exception $ex) {
Civi::log()->error(E::ts("Kon geen groep voor post mag aanmaken, fout van API4 Group create: ") . $ex->getMessage());
}
}
}
/**
* Method om bankrekening toe te voegen
*
* @param DateTime $migratieDatum
* @param array $rij
* @throws API_Exception
*/
public static function maakBankrekening(DateTime $migratieDatum, array $rij) {
if (isset($rij['iban']) && !empty($rij['iban']) && isset($rij['contact_id']) && !empty($rij['contact_id'])) {
$iban = trim($rij['iban']);
$contactId = (int) $rij['contact_id'];
// alleen als rekeningnummer nog niet bestaat voor de donor
if (!self::bestaatBankrekening($contactId, $iban)) {
try {
$rekening = civicrm_api3('BankingAccount', 'create', [
'contact_id' => $contactId,
'description' => 'rekening vanuit migratie sSaskia',
'created_date' => date('YmdHis'),
'data_raw' => '{}',
]);
// add a reference
civicrm_api3('BankingAccountReference', 'create', [
'reference' => $rij['iban'],
'reference_type_id' => Civi::service('paxMigratie')->getIbanAccountReference(),
'ba_id' => $rekening['id'],
]);
} catch (CiviCRM_API3_Exception $ex) {
\Civi\Api4\MigratieLog::create()
->addValue('ssaskia_nummer', $rij['ssaskia_nummer'])
->addValue('migratiedatum', $migratieDatum->format("y-m-d"))
->addValue('type', 'giften')
->addValue('melding', 'FOUT, geen bankrekening aan kunnen maken voor ssaskia_nummer ' . $rij['ssaskia_nummer'] . ' met IBAN ' . $rij['iban'])
->execute();
}
}
}
}
/**
* Method om te bekijken of het rekening nummer al bestaat voor het contact
*
* @param int $contactId
* @param string $rekening
* @return bool
*/
public static function bestaatBankrekening(int $contactId, string $rekening) {
$query = "SELECT COUNT(*)
FROM civicrm_bank_account cba
JOIN civicrm_bank_account_reference cbar ON cba.id = cbar.ba_id
WHERE cba.contact_id = %1 AND cbar.reference = %2";
$count = CRM_Core_DAO::singleValueQuery($query, [
1 => [$contactId, "Integer"],
2 => [$rekening, "String"],
]);
if ($count > 0) {
return TRUE;
}
return FALSE;
}
}

View File

@ -10,10 +10,15 @@ class CRM_Bij1migratie_Upgrader extends CRM_Bij1migratie_Upgrader_Base {
// upgrade tasks. They are executed in order (like Drupal's hook_update_N).
/**
* Example: Run an external SQL script when the module is installed.
*
* Maak migratie groep aan als geinstalleerd
*/
public function install() {
$this->executeSqlFile('sql/myinstall.sql');
$groep = new CRM_Bij1algemeen_Groep();
$groep->maakGroep([
'name' => "bij1_migratie",
'title' => "Migratie CiviCRM",
'description' => "Deze groep bevat alle contacten aangemaakt tijdens de migratie naar CiviCRM",
]);
}
/**

View File

@ -19,34 +19,14 @@ class Bij1MigratieContainer implements CompilerPassInterface {
public function process(ContainerBuilder $container) {
$definition = new Definition('CRM_Bij1migratie_Bij1MigratieService');
$definition->setFactory(['CRM_Bij1migratie_Bij1MigratieService', 'getInstance']);
$definition->addMethodCall('setContactType', ["Individual"]);
$this->setAanhef($definition);
$this->setGeslacht($definition);
$this->setFinancieelType($definition);
$this->setContributionStatus($definition);
$this->setPaymentInstrument($definition);
$definition->setPublic(TRUE);
$container->setDefinition('bij1Migratie', $definition);
}
/**
* Zet property voor betaal methode Mollie
*
* @param $definition
*/
private function setPaymentInstrument(&$definition) {
$query = "SELECT cov.value
FROM civicrm_option_group AS cog JOIN civicrm_option_value AS cov ON cog.id = cov.option_group_id
WHERE cog.name = %1 AND cov.name = %2;";
$id = \CRM_Core_DAO::singleValueQuery($query, [
1 => ["payment_instrument", "String"],
2 => ["Cash", "String"]
]);
if ($id) {
$definition->addMethodCall('setCashPaymentMethodId', [(int) $id]);
}
}
/**
* Zet property voor contributie status gereed
*

View File

@ -4,6 +4,33 @@ require_once 'bij1migratie.civix.php';
// phpcs:disable
use CRM_Bij1migratie_ExtensionUtil as E;
// phpcs:enable
use \Symfony\Component\DependencyInjection\ContainerBuilder;
use \Symfony\Component\DependencyInjection\Definition;
/**
* Implements hook_civicrm_container()
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_container/
*/
function bij1migratie_civicrm_container(ContainerBuilder $container) {
$container->addCompilerPass(new Civi\Bij1migratie\Bij1MigratieContainer());
}
/**
* Implements hook_civicrm_navigationMenu().
*
* @link https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_navigationMenu/
*/
function bij1migratie_civicrm_navigationMenu(&$menu) {
_bij1migratie_civix_insert_navigation_menu($menu, 'Administer', [
'label' => E::ts('Migratie Bij1 -> CiviCRM'),
'name' => 'bij1_migratie',
'url' => CRM_Utils_System::url('civicrm/bij1migratie/form/csvselect', 'reset=1', TRUE),
'permission' => 'administer CiviCRM',
'operator' => 'OR',
'separator' => 0,
]);
}
/**
* Implements hook_civicrm_config().

6
mapping/contacten.json Executable file
View File

@ -0,0 +1,6 @@
{
"voornaam": "voornaam",
"achternaam": "achternaam",
"email": "email",
"mollie_customer_id": "id"
}

View File

@ -0,0 +1,37 @@
<div class="crm-block crm-form-block">
<div class="help-block" id="help">
{ts}Selecteer het import bestand (type CSV), of de eerste rij de kolomkoppen bevat en welk teken gebruikt wordt als veldscheiding.{/ts}<br />
</div>
<div class="crm-submit-buttons">
{include file="CRM/common/formButtons.tpl" location="top"}
</div>
<div class="crm-section csv_file_section">
<div class="label">{$form.migratie_type.label}</div>
<div class="content">{$form.migratie_type.html}</div>
<div class="clear"></div>
</div>
<div class="crm-section csv_file_section">
<div class="label">{$form.csv_file.label}</div>
<div class="content">{$form.csv_file.html}</div>
<div class="clear"></div>
</div>
<div class="crm-section first_row_headers_section">
<div class="label">{$form.first_row_headers.label}</div>
<div class="content">{$form.first_row_headers.html}</div>
<div class="clear"></div>
</div>
<div class="crm-section separator_id_section">
<div class="label">{$form.separator_id.label}</div>
<div class="content">{$form.separator_id.html}</div>
<div class="clear"></div>
</div>
{* FOOTER *}
<div class="crm-submit-buttons">
{include file="CRM/common/formButtons.tpl" location="bottom"}
</div>
</div>

View File

@ -0,0 +1,9 @@
<?xml version="1.0"?>
<menu>
<item>
<path>civicrm/bij1migratie/form/csvselect</path>
<page_callback>CRM_Bij1migratie_Form_CsvSelect</page_callback>
<title>CsvSelect</title>
<access_arguments>access CiviCRM</access_arguments>
</item>
</menu>