def initFromObject(cls, propertyObject, propertyID=None):
        if 'addressCoordinate' in propertyObject:
            longitude = propertyObject['addressCoordinate']['lon']
            lattitude = propertyObject['addressCoordinate']['lat']
        else:
            longitude = None
            lattitude = None

        photos = []
        #Create File Array from the Photos Object inside the propertyObject
        for photo in propertyObject['photos']:
            propertyImage = File(FILE_TYPE_Images, OBJECT_Property, propertyID,
                                 None, 'Property ' + photo['imageType'], None)
            propertyImage.addImageDetails(photo['advertId'], photo['date'],
                                          photo['fullUrl'], None)
            photos.append(propertyImage)

        new_property = cls(
            propertyObject['id'], propertyObject.get("cadastreType"),
            VarIf(propertyObject['status'] == PROPERTY_MARKET_STATUS_ONMARKET,
                  True, False),
            Address(propertyObject['address'], propertyObject['streetName'],
                    propertyObject['suburb'], propertyObject['streetNumber'],
                    propertyObject.get("zone"),
                    propertyObject.get("lotNumber"), longitude, lattitude,
                    None), propertyObject.get("areaSize"),
            propertyObject.get('numBedrooms'),
            propertyObject.get('numBathrooms'), propertyObject.get('features'),
            json.dumps(propertyObject), propertyObject.get('history'), photos)
        return new_property
Exemple #2
0
def StoreListings( listingObject ):

    #Prepare the secondary dictionaries
    listing_sales = listingObject.get( 'saleDetails' )
    lisitng_inspections = listingObject.get( 'inspectionDetails' )
    listing_prices = listingObject.get( 'priceDetails' )

    try:
        #Insert the raw listing first.
        #Get the listing_status
        listing_status = QueryWithSingleValue( 'listing_status_lkp', 'description', listingObject['status'], 'listing_status_id', True )

        #build the JSON from listingObject
        raw_listing_JSON = json.dumps( listingObject )

        #Get the value that will be used with listing_insert_statement
        listings_id = returnNextSerialID( 'listings', 'listings_id' )

        if lisitng_inspections is not None:
            isByAppointmentOnly = lisitng_inspections.get( 'isByAppointmentOnly' )
        else:
            isByAppointmentOnly = None

        cur.execute( """ INSERT INTO listings( domain_listings_id, headline, price_displayed, display_price, price, price_from, price_to, seo_url, listing_objective,
                                                            listing_status, land_area, building_area, energy_efficiency, is_new_development, date_updated, date_created,
                                                            entered_when, entered_by, raw_listing, inspection_appointment_only )
                         VALUES( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, to_timestamp( %s, 'YYYY-MM-DD HH24:MI:SS' ), to_timestamp( %s, 'YYYY-MM-DD HH24:MI:SS' ), current_timestamp, 1, %s, %s ) """,
                         ( listingObject.get( 'id' ), listingObject.get( 'headline' ), listing_prices.get( 'canDisplayPrice' ), listing_prices.get( 'displayPrice' ), listing_prices.get( 'price' ), 
                           listing_prices.get( 'priceFrom' ), listing_prices.get( 'priceTo' ), listingObject.get( 'seoUrl' ), listingObject.get( 'objective' ), listing_status, listingObject.get( 'landAreaSqm'), 
                           listingObject.get( 'buildingAreaSqm' ), listingObject.get( 'energyEfficiencyRating' ), listingObject.get( 'isNewDevelopment' ), convertJSONDate(listingObject['dateUpdated']),
                           convertJSONDate(listingObject['dateListed']), cleanForSQL(raw_listing_JSON), isByAppointmentOnly ) )

        #Insert the Features if the listing contains any.
        #Set the object type
        #Only do this if the listing already has a features object.
        if 'features' in listingObject:
            link_object_type = OBJECT_Listing
            for feature in listingObject['features']:
                storeFeatures( listings_id, link_object_type, feature )

        if 'media' in listingObject:
            #Store any media attached to the listing
            for media in listingObject['media']:
                mediaObject = File( FILE_TYPE_Images, OBJECT_Listing, str(listings_id), None, "listing_" + media['type'] )
                mediaObject.addImageDetails( None, None, media['url'] )
                mediaObject.storeFile( False )

        #Store Listing Sales Information.
        #First, we need to check if the listings has any sales information attached to it.
        if listing_sales is not None:
            storeListingSalesDetails( listing_sales, listings_id )

        #Store the Inspection information (if the listing_inspections array is not None)
        if lisitng_inspections is not None:
            storeInspectionDetails( listings_id, lisitng_inspections )

        return listings_id
    except(Exception, psycopg2.DatabaseError) as error:
        print("Error in INSERTING New Listing with Domain Listing ID " + "\n" + "Error: " + error )
        return None
    def convertToClasses(self):
        """
        This Function converts all instance variables of the Agency Object that are meant to be classes...(i.e agency_banner) into their respective class.
        (These includes the Contact Details and Files Classes)

        """
        #Check to see if the instance has its agency_id set or has already had its variables converted into classes.
        try:
            if self.agency_id is None or self.classesConverted == True:
                raise Exception(
                    "Cannot convert classes due to them already being converted or Agency Instance having a Null Agency ID"
                )
            else:
                agency_banner = File(FILE_TYPE_Images, OBJECT_Agency,
                                     self.agency_id, None, "agency_banner")
                agency_banner.addImageDetails(None, None, self.agency_banner)
                self.agency_banner = agency_banner

                self.agency_website = ContactDetails('agency_website',
                                                     OBJECT_Agency,
                                                     self.agency_id,
                                                     self.agency_website)

                agency_logo_standard = File(FILE_TYPE_Images, OBJECT_Agency,
                                            self.agency_id, None,
                                            "agency_logo_standard")
                agency_logo_standard.addImageDetails(None, None,
                                                     self.agency_logo_standard)
                self.agency_logo_standard = agency_logo_standard

                self.contact_details_converted = []
                for contactType, detailsType in self.contact_details.items():
                    #For now, only store dictionaries. We can handle exceptions by logging them to a debug file.
                    if isinstance(detailsType, dict):
                        for contact, details in detailsType.items():
                            if details != '':
                                self.contact_details_converted.append(
                                    ContactDetails(
                                        'agency_' + contactType + '_' +
                                        contact, OBJECT_Agency, self.agency_id,
                                        details))
                    #else:
                    #    self.contact_details_converted.append( ContactDetails( 'agency_' + contactType + '_' + contact, self.agency_id, OBJECT_Agency, details ) )
                self.classesConverted = True

        except (Exception) as error:
            print(error)
    def storeAgent(self, commit):
        try:
            self.agent_id = returnNextSerialID('agents', 'agent_id')
            #Stores information contained inside the Agent Object into the Agents table.
            cur.execute(
                """INSERT INTO agents( domain_agent_id, entered_when, first_name, last_name, profile_text )
                            VALUES( %s, current_timestamp, %s, %s, %s )""",
                (self.domain_agent_id, cleanForSQL(self.first_name),
                 cleanForSQL(self.last_name), self.profile_text))
            #Store the link between the Agent and the Agency inside the agencies_agent table.
            cur.execute(
                """INSERT INTO agencies_agent( agency_id, agent_id, entered_when )
                            VALUES( %s, %s, current_timestamp)""",
                (self.agency_id, self.agent_id))

            if self.email is not None:
                #Store the agent's emaia
                contactDetails_email = ContactDetails("agent_email",
                                                      OBJECT_Agent,
                                                      self.agent_id,
                                                      self.email)
                if not contactDetails_email.storeContactDetails(False):
                    raise Exception(psycopg2.DatabaseError)

            if self.phone is not None:
                #Store the agent's phone number
                contactDetails_phone = ContactDetails("agent_phone_number",
                                                      OBJECT_Agent,
                                                      self.agent_id,
                                                      self.phone)
                if not contactDetails_phone.storeContactDetails(False):
                    raise Exception(psycopg2.DatabaseError)

            if self.facebook_url is not None:

                contactDetails_facebook = ContactDetails(
                    "agent_facebook_url", OBJECT_Agent, self.agent_id,
                    self.facebook_url)
                #Attempt to save the facebook details
                if not contactDetails_facebook.storeContactDetails(False):
                    raise Exception(psycopg2.DatabaseError)

            if self.twitter_url is not None:
                contactDetails_twitter = ContactDetails(
                    "agent_twitter_url", OBJECT_Agent, self.agent_id,
                    self.twitter_url)
                #Attempt to save the twitter details
                if not contactDetails_twitter.storeContactDetails(False):
                    raise Exception(psycopg2.DatabaseError)

            if self.photo is not None:

                #Save the mugshot and agent photo.
                file_agentPhoto = File(FILE_TYPE_Images, OBJECT_Agent,
                                       self.agent_id, None, "agent_photo")
                file_agentPhoto.addImageDetails(None, None, self.photo)
                if not file_agentPhoto.storeFile(False):
                    raise Exception(psycopg2.DatabaseError)

            if self.mugshot_url is not None:

                file_agentMugShot = File(FILE_TYPE_Images, OBJECT_Agent,
                                         self.agent_id, None, "agent_mugshot")
                file_agentMugShot.addImageDetails(None, None, self.mugshot_url)
                if not file_agentMugShot.storeFile(False):
                    raise Exception(psycopg2.DatabaseError)

            if commit:
                conn.commit()

            return self.agent_id

        except (Exception, psycopg2.DatabaseError) as error:
            print("Error in INSERTING New Agent " + self.first_name + " " +
                  self.last_name + "\n" + error)
            return None