os := import("os") fmt := import("fmt") json := import("json") cjson := import("cjson") log := import("log") contact_field_id := 231711 company_field_id := 1300614 lead_field_id := 686597 dec := cjson.new_decoder("") patch := [] add_patch := func(company_id, inn, reason) { log.printf("%d %q %q\n", company_id, string(inn), reason) company := {} company.id = company_id company.__reason = reason company.custom_fields_values = [{ field_id: company_field_id, values: [{ value: inn }] }] patch += [company] } find_by_field_id := func(id, fields){ for _, field in fields { if field.field_id == id { return field.values[0].value } } } is_field_correct := func(value){ if !int(value) { return false } str := string(value) if len(str) <9 || len(str) > 12 { return false } return true } format_empty := func(...values){ ret := "" for _, value in values { if !value { ret += " " } else { ret += string(value) + " " } } return ret } i := 0 for { i++ //log.println("Checking", i) h := dec.decode() if !h { break } //fmt.println(i, " reachd", company_inn) company_inn := find_by_field_id( company_field_id, h.company.custom_fields_values) contact_inn := find_by_field_id( contact_field_id, h.main_contact.custom_fields_values ) lead_inn := find_by_field_id( lead_field_id, h.lead.custom_fields_values ) //log.println(format_empty(i, company_inn, contact_inn, lead_inn)) if !h.company || int(company_inn) { continue } // Adding lead INN if no contact INN. if !int(contact_inn) { if !lead_inn || !is_field_correct(lead_inn) { continue } add_patch( h.company.id, lead_inn, fmt.sprintf("Взято из лида (%d)", h.lead.id) ) continue } // Adding contact INN if no lead INN. if !int(lead_inn) { if !is_field_correct(contact_inn) { continue } add_patch( h.company.id, contact_inn, fmt.sprintf( "Взято из контакта (%d)", h.main_contact.id ) ) } else { // Here we have both. if int(contact_inn) != int(lead_inn) { continue } if !is_field_correct(contact_inn) { continue } add_patch( h.company.id, contact_inn, fmt.sprintf("Взято из контакта и лида (%d, %d)", h.main_contact.id, h.lead.id) ) } } //patch = patch[:500] //fmt.println(len(patch)) log.println("Summarized got", len(patch), "companies") bts := json.indent(json.encode(patch), "", " ") fmt.println(string(bts))