load($temp_name); foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) { $data = $worksheet->toArray(''); break; } } $headers = $data[0]; // Logger(json_encode($headers, true)); unset($data[0]); $bodyValues = $data; foreach ($bodyValues as $key => $row) { $is_row_empty = true; foreach ($row as $value) { if (!empty($value) && $value !== 0) { $is_row_empty = false; } } if ($is_row_empty) { unset($bodyValues[$key]); } } $index = 0; foreach ($headers as $header) { foreach ($mapping_fields as $key => $value) { if ($header === $value) { $mapping_fields[$key] = $index; } } $index++; } if (!is_numeric($import['house_name_to_id'])) { $import['house_name_to_id'] = json_decode($import['house_name_to_id'], true); } $import['dynamic_fields'] = json_decode($import['dynamic_fields'], true); mapData( $mapping_fields, $bodyValues, $import['house_name_to_id'], $import['dynamic_fields'], $import['user_id'] ); updateImportHouse([ 'status' => 'done', ], $import_id); } } // Logger("END with import_id: $import_id"); } else { // Logger("Parameter import_id is missing. (complex_house_import - id)"); exit(1); } function save_room($room) { // Logger(json_encode($room, true)); $strArray = []; $position = 0; $floorLastRoomInfo = mysql_fetch_assoc(mysql_query("SELECT position FROM complex_rooms WHERE complex_rooms.floor_id = {$room['floor_id']} ORDER BY position DESC LIMIT 1")); if ($floorLastRoomInfo) { if (!isset($room['id']) || !$room['position']) { $position = $floorLastRoomInfo['position']; } else { $position = $room['position'] - 1; } } foreach ($room as $key => $value) { if ($key == 'id' || empty($value)) { continue; } if (is_string($value)) { $strArray[] = "$key='$value'"; } else { $strArray[] = "$key=$value"; } } $position = $position + 1; $strArray[] = "position='$position'"; $str = implode(', ', $strArray); if (isset($room['id']) && $room['id']) { if (isset($room['complex_status_id'])) { $sql = "UPDATE requisitions SET complex_status_id = {$room['complex_status_id']} WHERE complex_room_id={$room['id']}"; mysql_query($sql); } $sql = "UPDATE complex_rooms SET $str WHERE id={$room['id']}"; $q = mysql_query($sql); return $room['id']; } $sql = "INSERT INTO complex_rooms SET {$str} "; $q = mysql_query($sql); return mysql_insert_id(); } function getJWId($table, $column, $value, $where = '') { if (is_string($value)) { $value = "'$value'"; } $sql = "SELECT id FROM $table WHERE $column = $value $where"; $query = mysql_query($sql); $result = mysql_fetch_assoc($query); if ($table == 'decoration_types' && !$result) { $sql = "INSERT INTO $table set $column = $value"; $query = mysql_query($sql); $result = mysql_fetch_assoc($query); } return $result ? (int)$result['id'] : $result; } function mapData($mapping, $values, $house_name_to_id, $dynamic_fields, $user_id) { // Logger("parararamparam"); // Logger(json_encode($mapping, true)); // Logger(json_encode($values, true)); // Logger("START with values: json_encode($values)"); $room_keys = [ 'number', 'rooms_count', 'area', 'total_amount', "layout_code", "payment_types", "layout_feature", "on_site_number", "description", "estimated_area", "living_area", "kitchen_area", "loggias_count", "balconies_count", "combined_bathrooms_count", "seperated_bathrooms_count", "bti_room_number", "bti_total_area", "area_without_balcony", "hallway_area", "ceiling_height", "mortgage", "total_area_excl_living", "total_bathroom_area", "total_balcony_loggia_area", "installment_price", ]; $room_id_keys = [ "decoration_id", "windows_placement_id", "floor_id", "entrance_id" ]; $room_id_keys_to_table = [ "decoration_id" => [ 'table' => 'decoration_types', 'column' => 'name', ], "windows_placement_id" => [ 'table' => 'complex_rooms_windows_placements', 'column' => 'name' ], "floor_id" => [ 'table' => 'complex_floors', 'column' => 'position' ], "entrance_id" => [ 'table' => 'complex_entrances', 'column' => 'position' ], ]; $room_dynamic_keys = [ 'complex_status_id', 'type', ]; $use_one_house = is_numeric($house_name_to_id); foreach ($values as $row) { $room = []; $entranceValue = null; $floorValue = null; $room_number = null; $room_id = null; $oldRoom = null; // Logger(json_encode([$row, $values], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); $house_id = $house_name_to_id; foreach ($mapping as $key => $index) { $value = trim($row[$index]); // Logger(json_encode([$mapping, $value], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); if($key == "rooms_areas" || $key == "bathrooms_areas" || $key == "loggias_balconys_areas" || $key == "rooms_note") continue; if (in_array($key, $room_keys)) { if ($key == 'number') { $room_number = $value; } if ($key == 'layout_feature') { if($value == "Студия"){ $room[$key] = "studio"; } if($value == "Европланировка"){ $room[$key] = "european_layout"; } if($value == "Свободная планировка"){ $room[$key] = "available"; } continue; } if ($key == 'total_amount') { $room[$key] = preg_replace('/\D/', '', $value); } else { $room[$key] = $value; } } else if (in_array($key, $room_id_keys)) { if (in_array($key, ['floor_id', 'entrance_id'])) { if ($key == 'floor_id') { $floorValue = trim($value); } if ($key == 'entrance_id') { $entranceValue = trim($value); } } else { $room[$key] = getJWId($room_id_keys_to_table[$key]['table'], $room_id_keys_to_table[$key]['column'], $value); } } else if (in_array($key, $room_dynamic_keys)) { if ($key == 'complex_status_id') { // убираем пробелы из ключей $dynamic_fields[$key] = (object) array_combine( array_map('trim', array_keys((array)$dynamic_fields[$key])), array_values((array)$dynamic_fields[$key]) ); $trimmedValue = trim($value); Logger(json_encode([$dynamic_fields[$key], $trimmedValue], JSON_UNESCAPED_UNICODE)); // безопасно обращаемся к объекту $room[$key] = $dynamic_fields[$key]->$trimmedValue ; } else{ $room[$key] = $dynamic_fields[$key][$value]; } } else if ($key == 'house_name') { $house_id = $house_name_to_id[$value]; } } $payment_types = ["FULL"]; // всегда по умолчанию FULL // проверяем Ипотеку if (isset($mapping['mortgage'])) { $mortgageValue = $row[$mapping['mortgage']]; if ($mortgageValue === 'да'|| $mortgageValue === 'ДА'|| $mortgageValue === 'Да'|| $mortgageValue === 'дА') { $payment_types[] = "MORTGAGE"; } } unset($room['mortgage']); // проверяем Рассрочку if (isset($mapping['installment_price'])) { $installmentValue = preg_replace('/\D/', '', $row[$mapping['installment_price']]); if (is_numeric($installmentValue) && (int)$installmentValue > 0) { $payment_types[] = "INSTALLMENT"; } } // Logger(json_encode($mapping, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); $room['payment_types'] = json_encode($payment_types, JSON_UNESCAPED_UNICODE); $entrance_id = getJWId($room_id_keys_to_table['entrance_id']['table'], $room_id_keys_to_table['entrance_id']['column'], $entranceValue, " AND complex_house_id = $house_id "); $floor_id = null; if ($room_number) { $oldRoom = findRoomByNumber($room_number, $house_id); $room_id = $oldRoom['id']; $room['position'] = $oldRoom['position']; } if ($room_id) { $room['id'] = $room_id; if ($entrance_id == $oldRoom['entrance_id']) { $floor_id = getJWId($room_id_keys_to_table['floor_id']['table'], $room_id_keys_to_table['floor_id']['column'], $floorValue, " AND complex_entrance_id = $entrance_id "); } else if (!$entrance_id) { // Logger("INSERT INTO complex_entrances SET complex_house_id = $house_id, position = $entranceValue, name = 'Подъезд {$entranceValue}'"); mysql_query("INSERT INTO complex_entrances SET complex_house_id = $house_id, position = $entranceValue, name = 'Подъезд {$entranceValue}'"); $entrance_id = mysql_insert_id(); } } else { if (!$entrance_id) { // Logger("INSERT INTO complex_entrances SET complex_house_id = $house_id, position = $entranceValue, name = 'Подъезд {$entranceValue}'"); mysql_query("INSERT INTO complex_entrances SET complex_house_id = $house_id, position = $entranceValue, name = 'Подъезд {$entranceValue}'"); $entrance_id = mysql_insert_id(); } // Logger("entrance_id : $entrance_id"); $floor_id = getJWId($room_id_keys_to_table['floor_id']['table'], $room_id_keys_to_table['floor_id']['column'], $floorValue, " AND complex_entrance_id = $entrance_id "); } if (!$floor_id) { mysql_query("INSERT INTO complex_floors SET complex_entrance_id = $entrance_id, position = $floorValue"); $floor_id = mysql_insert_id(); } $room['floor_id'] = $floor_id; $room_id = save_room($room); if (isset($mapping['rooms_note'])) { saveRoomNotes($room_id,$row[$mapping['rooms_note']]); } if (isset($mapping['rooms_areas'])) { saveRoomAttributes($room_id, 'rooms_areas', $row[$mapping['rooms_areas']]); } if (isset($mapping['bathrooms_areas'])) { saveRoomAttributes($room_id, 'bathrooms_areas', $row[$mapping['bathrooms_areas']]); } if (isset($mapping['loggias_balconys_areas'])) { saveRoomAttributes($room_id, 'loggias_balconys_areas', $row[$mapping['loggias_balconys_areas']]); } // Logger("done with room_id: " . json_encode($room, true)); // Logger("done with house_id: $house_id"); if (isset($mapping['layout_code'])) { $layout_code = trim($row[$mapping['layout_code']]); // Logger(json_encode($layout_code, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); $plan_id = null; if ($layout_code && $house_id) { $layout_code_escaped = mysql_real_escape_string($layout_code); $sql = "SELECT id FROM complex_house_plans WHERE code = '$layout_code_escaped' AND house_id = $house_id LIMIT 1"; $query = mysql_query($sql); $result = mysql_fetch_assoc($query); if ($result) { $plan_id = (int)$result['id']; } } // Если нашли plan_id и есть room_id, вставляем связь if ($plan_id && $room_id) { // Проверяем, есть ли уже запись $checkSql = "SELECT 1 FROM complex_rooms_plans WHERE room_id = $room_id AND plan_id = $plan_id LIMIT 1"; $checkQuery = mysql_query($checkSql); if (!mysql_fetch_assoc($checkQuery)) { $insertSql = "INSERT INTO complex_rooms_plans SET room_id = $room_id, plan_id = $plan_id"; mysql_query($insertSql); // Logger("Inserted room_id $room_id with plan_id $plan_id"); } else { // Logger("Relation room_id $room_id and plan_id $plan_id already exists"); } } } } } function saveRoomNotes($room_id, $note){ if (!$note) return; $sql = sprintf( "INSERT INTO complex_room_notes SET room_id = %d, note = '%s'", (int)$room_id, mysql_real_escape_string($note) ); // Logger(json_encode($sql, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); mysql_query($sql); } function saveRoomAttributes($room_id, $type, $value) { if (!$value) return; // Разбираем строку в зависимости от типа $items = explode(';', $value); foreach ($items as $item) { $item = trim($item); if (!$item) continue; // Logger(json_encode([$items, $item], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); $name = null; $area = null; if ($type === 'loggias_balconys_areas') { // формат: "лоджия:84.25" или "балкон:12.6" if (strpos($item, ':') !== false) { list($name, $area) = explode(':', $item); $name = trim($name); if($name == "Лоджия"){ $name = "loggia"; } if($name == "Балкон"){ $name = "balcony"; } $area = trim($area); // Logger(json_encode([$name, $area], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); } else { $area = $item; // если без имени // Logger(json_encode([$name, $area], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); } } else if($type === "rooms_areas") { $name = "room"; $area = $item; // Logger(json_encode([$item, $area], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); } else if($type === "bathrooms_areas") { $name = "bathroom"; $area = $item; // Logger(json_encode([$item, $area], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); } // если area нет или не число — пропускаем if (!$area || !is_numeric($area)) { continue; } // Вставляем в таблицу $sql = sprintf( "INSERT INTO complex_rooms_attribute SET attribute_type = %s, complex_room_id = %d, area = %s", $name ? ("'" . mysql_real_escape_string($name) . "'") : "NULL", (int)$room_id, is_numeric($area) ? $area : "NULL" ); // Logger(json_encode($sql, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); mysql_query($sql); } } function findRoomByNumber($room_number, $house_id) { if ($house_id) { $find = mysql_query("SELECT complex_rooms.position as position, complex_rooms.id, complex_rooms.floor_id, complex_entrances.id as entrance_id FROM complex_rooms JOIN complex_floors ON complex_floors.id = complex_rooms.floor_id JOIN complex_entrances ON complex_floors.complex_entrance_id = complex_entrances.id JOIN complex_houses ON complex_entrances.complex_house_id = complex_houses.id WHERE complex_houses.id = $house_id AND complex_rooms.number = '{$room_number}' "); $row = mysql_fetch_assoc($find); return $row; } } function parseCsv($input) { $possibleSeparators = [',', ';', "\t", '|']; $separatorCounts = []; $for_first_line = fopen('php://memory', 'rw'); fwrite($for_first_line, $input); fseek($for_first_line, 0); $firstLine = fgets($for_first_line); fclose($for_first_line); $temp = fopen('php://memory', 'rw'); fwrite($temp, $input); fseek($temp, 0); $res = array(); foreach ($possibleSeparators as $separator) { $columns = str_getcsv($firstLine, $separator); $separatorCounts[$separator] = count($columns); } $mostLikelySeparator = array_search(max($separatorCounts), $separatorCounts); while (($data = fgetcsv($temp, null, $mostLikelySeparator)) !== false) { $res[] = $data; } fclose($temp); return $res; } function detectCsvSeparator($temp) { // Possible separators to test $possibleSeparators = [',', ';', "\t", '|']; $separatorCounts = []; // Open the file for reading if (($handle = $temp) === false) { return false; // Error opening file } // Read the first line of the file $firstLine = fgets($handle); fclose($handle); // Test each separator foreach ($possibleSeparators as $separator) { $columns = str_getcsv($firstLine, $separator); $separatorCounts[$separator] = count($columns); } // Find the separator with the most columns $mostLikelySeparator = array_search(max($separatorCounts), $separatorCounts); return $mostLikelySeparator; } function Logger($message) { $timestamp = date('Y-m-d H:i:s'); print("[$timestamp] $message \n"); } function endsWith($haystack, $needle) { $length = strlen($needle); return $length > 0 ? substr($haystack, -$length) === $needle : true; } function updateImportHouse($data, $import_id) { // complex_house_import if ($data && $import_id) { $sql = []; foreach ($data as $key => $value) { if (is_string($value)) { $sql[] = "$key='$value'"; } else { $sql[] = "$key=$value"; } } $sql = implode(' ,', $sql); $sql = "UPDATE complex_house_import SET $sql WHERE id={$import_id}"; return mysql_query($sql); } return false; } exit(0);