# Path: HPCStats/Exceptions.py
# class HPCStatsSourceError(HPCStatsException):
# 
#     """Class for source errors exceptions in HPCStats"""
# 
#     def __init__(self, msg):
# 
#         super(HPCStatsSourceError, self).__init__(msg)
# 
# Path: HPCStats/Importer/BusinessCodes/BusinessCodeImporter.py
# class BusinessCodeImporter(Importer):
# 
#     """This is the base class common to all HPCStats BusinessCode importers.
#        It defines a common set of attributes and generic methods.
#     """
# 
#     def __init__(self, app, db, config):
# 
#         super(BusinessCodeImporter, self).__init__(app, db, config, None)
# 
#         self.businesses = None
# 
#     def find(self, search):
#         """Search for a Business over the list of Businesses loaded by importer
#            in self.businesses attribute. Returns None if not found.
#         """
# 
#         for business in self.businesses:
#             if business == search:
#                 return business
#         return None
# 
# Path: HPCStats/Model/Business.py
# class Business(object):
# 
#     """Model class for the Business table."""
# 
#     def __init__(self, code, description):
# 
#         self.code = code
#         self.description = description
#         self.exists = None
# 
#     def __str__(self):
#         if self.description == None:
#             description = "(empty)"
#         else:
#             description = self.description
#         return self.code + " - " + description
# 
#     def __eq__(self, other):
# 
#         return other.code == self.code
# 
#     def existing(self, db):
#         """Returns True if the business already exists in database (with same
#            code), or False if not.
#         """
# 
#         req = """
#                 SELECT business_code
#                   FROM Business
#                  WHERE business_code = %s
#               """
#         params = ( self.code, )
#         db.execute(req, params)
#         nb_rows = db.cur.rowcount
#         if nb_rows == 0:
#             logger.debug("business %s not found in DB", str(self))
#             self.exists = False
#         elif nb_rows > 1:
#             raise HPCStatsDBIntegrityError(
#                     "several businesses found in DB for account %s" \
#                       % (str(self)))
#         else:
#             logger.debug("business %s found in DB", str(self))
#             self.exists = True
#         return self.exists
# 
#     def save(self, db):
#         """Insert Business in database. It first makes sure that the Business
#            does not already exist in database yet by calling
#            Business.existing() method if needed. If the business already exists
#            in database, it raises HPCStatsRuntimeError.
#         """
# 
#         if self.exists is None: # not checked yet
#             self.existing(db)
#         if self.exists is True:
#             raise HPCStatsRuntimeError(
#                     "could not insert business %s since already existing in "\
#                     "database" % (str(self)))
# 
#         logger.info("creating business code %s" % str(self))
# 
#         req = """
#                 INSERT INTO Business ( business_code,
#                                        business_description )
#                 VALUES (%s, %s)
#               """
#         params = ( self.code, self.description )
#         #print db.cur.mogrify(req, params)
#         db.execute(req, params)
#         self.exists = True
# 
#     def update(self, db):
#         """Update Business description in database. Raises HPCStatsRuntimeError
#            if exists is False.
#         """
# 
#         if self.exists is None: # not checked yet
#             self.existing(db)
#         if self.exists is False:
#             raise HPCStatsRuntimeError(
#                     "could not update business %s since not found in " \
#                     "database" \
#                       % (str(self)))
# 
#         logger.debug("updating business code %s" % str(self))
# 
#         req = """
#                 UPDATE Business
#                    SET business_description = %s
#                  WHERE business_code = %s
#               """
#         params = ( self.description,
#                    self.code )
#         #print db.cur.mogrify(req, params)
#         db.execute(req, params)


import os
import csv
from HPCStats.Exceptions import HPCStatsSourceError
from HPCStats.Importer.BusinessCodes.BusinessCodeImporter import BusinessCodeImporter
from HPCStats.Model.Business import Business
        """Check if CSV file exists and is a proper flat file."""

        if not os.path.isfile(self._business_file):
            raise HPCStatsSourceError( \
                    "business CSV file %s does not exist" \
                      % (self._business_file))

    def load(self):
        """Load BusinessCodes from CSV files in businesses attribute. Raise
           HPCStatsSourceError if error in encountered.
        """

        self.businesses = []

        self.check()

        with open(self._business_file, 'r') as csvfile:

            file_reader = csv.reader(csvfile, delimiter=';', quotechar='|')
            for row in file_reader:
                if len(row) != 2:
                    raise HPCStatsSourceError( \
                            "business line format in CSV is invalid")
                code = row[0].strip()
                description = row[1].strip()
                if len(code) == 0:
                    raise HPCStatsSourceError( \
                            "business code in CSV is empty")
                if len(description) == 0:
                    description = None

# Path: HPCStats/Exceptions.py
# class HPCStatsSourceError(HPCStatsException):
# 
#     """Class for source errors exceptions in HPCStats"""
# 
#     def __init__(self, msg):
# 
#         super(HPCStatsSourceError, self).__init__(msg)
# 
# Path: HPCStats/Importer/BusinessCodes/BusinessCodeImporter.py
# class BusinessCodeImporter(Importer):
# 
#     """This is the base class common to all HPCStats BusinessCode importers.
#        It defines a common set of attributes and generic methods.
#     """
# 
#     def __init__(self, app, db, config):
# 
#         super(BusinessCodeImporter, self).__init__(app, db, config, None)
# 
#         self.businesses = None
# 
#     def find(self, search):
#         """Search for a Business over the list of Businesses loaded by importer
#            in self.businesses attribute. Returns None if not found.
#         """
# 
#         for business in self.businesses:
#             if business == search:
#                 return business
#         return None
# 
# Path: HPCStats/Model/Business.py
# class Business(object):
# 
#     """Model class for the Business table."""
# 
#     def __init__(self, code, description):
# 
#         self.code = code
#         self.description = description
#         self.exists = None
# 
#     def __str__(self):
#         if self.description == None:
#             description = "(empty)"
#         else:
#             description = self.description
#         return self.code + " - " + description
# 
#     def __eq__(self, other):
# 
#         return other.code == self.code
# 
#     def existing(self, db):
#         """Returns True if the business already exists in database (with same
#            code), or False if not.
#         """
# 
#         req = """
#                 SELECT business_code
#                   FROM Business
#                  WHERE business_code = %s
#               """
#         params = ( self.code, )
#         db.execute(req, params)
#         nb_rows = db.cur.rowcount
#         if nb_rows == 0:
#             logger.debug("business %s not found in DB", str(self))
#             self.exists = False
#         elif nb_rows > 1:
#             raise HPCStatsDBIntegrityError(
#                     "several businesses found in DB for account %s" \
#                       % (str(self)))
#         else:
#             logger.debug("business %s found in DB", str(self))
#             self.exists = True
#         return self.exists
# 
#     def save(self, db):
#         """Insert Business in database. It first makes sure that the Business
#            does not already exist in database yet by calling
#            Business.existing() method if needed. If the business already exists
#            in database, it raises HPCStatsRuntimeError.
#         """
# 
#         if self.exists is None: # not checked yet
#             self.existing(db)
#         if self.exists is True:
#             raise HPCStatsRuntimeError(
#                     "could not insert business %s since already existing in "\
#                     "database" % (str(self)))
# 
#         logger.info("creating business code %s" % str(self))
# 
#         req = """
#                 INSERT INTO Business ( business_code,
#                                        business_description )
#                 VALUES (%s, %s)
#               """
#         params = ( self.code, self.description )
#         #print db.cur.mogrify(req, params)
#         db.execute(req, params)
#         self.exists = True
# 
#     def update(self, db):
#         """Update Business description in database. Raises HPCStatsRuntimeError
#            if exists is False.
#         """
# 
#         if self.exists is None: # not checked yet
#             self.existing(db)
#         if self.exists is False:
#             raise HPCStatsRuntimeError(
#                     "could not update business %s since not found in " \
#                     "database" \
#                       % (str(self)))
# 
#         logger.debug("updating business code %s" % str(self))
# 
#         req = """
#                 UPDATE Business
#                    SET business_description = %s
#                  WHERE business_code = %s
#               """
#         params = ( self.description,
#                    self.code )
#         #print db.cur.mogrify(req, params)
#         db.execute(req, params)


# Path: HPCStats/Importer/BusinessCodes/BusinessCodeImporterCSV.py
import os
import csv
from HPCStats.Exceptions import HPCStatsSourceError
from HPCStats.Importer.BusinessCodes.BusinessCodeImporter import BusinessCodeImporter
from HPCStats.Model.Business import Business

        """Check if CSV file exists and is a proper flat file."""

        if not os.path.isfile(self._business_file):
            raise HPCStatsSourceError( \
                    "business CSV file %s does not exist" \
                      % (self._business_file))

    def load(self):
        """Load BusinessCodes from CSV files in businesses attribute. Raise
           HPCStatsSourceError if error in encountered.
        """

        self.businesses = []

        self.check()

        with open(self._business_file, 'r') as csvfile:

            file_reader = csv.reader(csvfile, delimiter=';', quotechar='|')
            for row in file_reader:
                if len(row) != 2:
                    raise HPCStatsSourceError( \
                            "business line format in CSV is invalid")
                code = row[0].strip()
                description = row[1].strip()
                if len(code) == 0:
                    raise HPCStatsSourceError( \
                            "business code in CSV is empty")
                if len(description) == 0:
                    description = None

                business = Business(code, description)