<s> from corehq . apps . products . models import Product , SQLProduct <EOL> from django . utils . translation import ugettext as _ <EOL> from corehq . apps . programs . models import Program <EOL> def import_products ( domain , importer ) : <EOL> from corehq . apps . products . views import ProductFieldsView <EOL> results = { '<STR_LIT>' : [ ] , '<STR_LIT>' : [ ] } <EOL> to_save = [ ] <EOL> product_count = <NUM_LIT:0> <EOL> seen_codes = set ( ) <EOL> program_ids = [ program . _id for program in Program . by_domain ( domain ) ] <EOL> codes = { <EOL> row [ '<STR_LIT:code>' ] : row [ '<STR_LIT>' ] <EOL> for row in SQLProduct . objects . filter ( domain = domain , is_archived = False ) . values ( '<STR_LIT:code>' , '<STR_LIT>' ) <EOL> } <EOL> custom_data_validator = ProductFieldsView . get_validator ( domain ) <EOL> for row in importer . worksheet : <EOL> try : <EOL> p = Product . from_excel ( row , custom_data_validator ) <EOL> except Exception , e : <EOL> results [ '<STR_LIT>' ] . append ( <EOL> _ ( u'<STR_LIT>' . format ( <EOL> name = row [ '<STR_LIT:name>' ] or '<STR_LIT>' , <EOL> ex = e , <EOL> ) ) <EOL> ) <EOL> continue <EOL> importer . add_progress ( ) <EOL> if not p : <EOL> continue <EOL> if not p . domain : <EOL> p . domain = domain <EOL> elif p . domain != domain : <EOL> results [ '<STR_LIT>' ] . append ( <EOL> _ ( u"<STR_LIT>" ) . format ( <EOL> product_name = p . name <EOL> ) <EOL> ) <EOL> continue <EOL> if p . code : <EOL> if ( p . code in codes and codes [ p . code ] != p . get_id ) or ( p . code in seen_codes ) : <EOL> results [ '<STR_LIT>' ] . append ( _ ( <EOL> u"<STR_LIT>" <EOL> ) . format ( <EOL> product_name = p . name <EOL> ) ) <EOL> continue <EOL> if p . code not in codes : <EOL> seen_codes . add ( p . code ) <EOL> if p . program_id and p . program_id not in program_ids : <EOL> results [ '<STR_LIT>' ] . append ( _ ( <EOL> u"<STR_LIT>" <EOL> ) . format ( <EOL> product_name = p . name , <EOL> program_id = p . program_id <EOL> ) ) <EOL> continue <EOL> product_count += <NUM_LIT:1> <EOL> to_save . append ( p ) <EOL> if len ( to_save ) > <NUM_LIT> : <EOL> Product . bulk_save ( to_save ) <EOL> for couch_product in to_save : <EOL> couch_product . sync_to_sql ( ) <EOL> to_save = [ ] <EOL> if to_save : <EOL> Product . bulk_save ( to_save ) <EOL> for couch_product in to_save : <EOL> couch_product . sync_to_sql ( ) <EOL> if product_count : <EOL> results [ '<STR_LIT>' ] . insert ( <EOL> <NUM_LIT:0> , <EOL> _ ( '<STR_LIT>' <EOL> '<STR_LIT>' ) . format ( <EOL> number_of_products = product_count , errors = len ( results [ '<STR_LIT>' ] ) <EOL> ) <EOL> ) <EOL> return results </s>
