コード例 #1
0
class RoleModel(BasicModel):
    name = Fields.StringProperty(required=True, verbose_name=u'識別名稱')
    title = Fields.StringProperty(required=True, verbose_name=u'角色名稱')
    prohibited_actions = Fields.TextProperty(verbose_name=u'禁止的操作', default='')
    level = Fields.IntegerProperty(verbose_name=u'權限等級', default=0)

    @classmethod
    def create_role(cls, name, title, level, prohibited_actions):
        n = cls()
        n.name = name
        n.title = title
        n.level = level
        n.prohibited_actions = prohibited_actions
        n.put()
        return n

    @classmethod
    def get_role(cls, name):
        a = cls.query(cls.name == name).get()
        return a

    @classmethod
    def get_list(cls):
        return cls.query(cls.level < 1000).order(cls.level, -cls.sort)

    @classmethod
    def find_lowest_level(cls):
        return cls.query().order(cls.level).get()
コード例 #2
0
class StockHistoryDetailModel(BasicModel):
    class Meta:
        label_name = {
            'is_enable': u'啟用',
            'title': u'完整規格名稱',
        }

    history = Fields.KeyProperty(verbose_name=u'歷史記錄', kind=StockHistoryModel)
    product_name = Fields.StringProperty(verbose_name=u'產品名稱')
    product_image = Fields.StringProperty(verbose_name=u'產品圖片')
    sku_object = Fields.KeyProperty(verbose_name=u'SKU 對象')
    spec_full_name = Fields.SearchingHelperProperty(verbose_name=u'完整規格名稱', target='sku_object', target_field_name='spec_full_name')
    sku_full_name = Fields.SearchingHelperProperty(verbose_name=u'sku 編號', target='sku_object', target_field_name='sku_full_name')
    operation_type = Fields.StringProperty(verbose_name=u'操作類型')  # 出庫、入庫、轉倉
    warehouse = Fields.StringProperty(verbose_name=u'倉庫')
    warehouse_target = Fields.StringProperty(verbose_name=u'目標倉庫')
    quantity = Fields.IntegerProperty(verbose_name=u'數量')

    @classmethod
    def all_with_history(cls, history):
        return cls.query(cls.history == history.key).order(-cls.sort)

    @property
    def sku_instance(self):
        if not hasattr(self, '_sku'):
            self._sku = self.sku_object.get()
        return self._sku
コード例 #3
0
ファイル: config_model.py プロジェクト: argeweb/plugin-mail
class ConfigModel(BasicConfigModel):
    class Meta:
        tab_pages = [
            u'系統收件人',
            u'Google App Engine',
            u'MailGun',
            # u'SendGrid', u'other'
        ]

    title = Fields.HiddenProperty(verbose_name=u'設定名稱', default=u'郵件相關設定')
    use = Fields.IntegerProperty(verbose_name=u'服務類型', default=0)

    system_recipient_1 = Fields.StringProperty(verbose_name=u'系統收件人 1',
                                               tab_page=0,
                                               default=u'*****@*****.**')
    system_recipient_2 = Fields.StringProperty(verbose_name=u'系統收件人 2',
                                               tab_page=0,
                                               default=u'*****@*****.**')
    system_recipient_3 = Fields.StringProperty(verbose_name=u'系統收件人 3',
                                               tab_page=0,
                                               default=u'*****@*****.**')
    system_recipient_4 = Fields.StringProperty(verbose_name=u'系統收件人 4',
                                               tab_page=0,
                                               default=u'*****@*****.**')

    gae_sender_mail = Fields.StringProperty(verbose_name=u'寄件者 E-Mail',
                                            tab_page=1,
                                            default=u'*****@*****.**')
    gae_sender_name = Fields.StringProperty(verbose_name=u'寄件者名稱',
                                            tab_page=1,
                                            default=u'王小華')
    gae_helper = Fields.HtmlProperty(
        verbose_name=u'說明',
        tab_page=1,
        html=
        u'Google App Engine 每日可寄送 100 封(收件人),需至 <a href="https://console.cloud.google.com/appengine/settings?project" target="_blank">Google Cloud</a> 設定為 Email API 授權的寄件者。'
    )

    mg_sender_mail = Fields.StringProperty(verbose_name=u'寄件者 E-Mail',
                                           tab_page=2,
                                           default=u'*****@*****.**')
    mg_sender_name = Fields.StringProperty(verbose_name=u'寄件者名稱',
                                           tab_page=2,
                                           default=u'王小華')
    mg_domain = Fields.StringProperty(verbose_name=u'網域名稱',
                                      tab_page=2,
                                      default=u'domain.com')
    mg_api_key = Fields.StringProperty(verbose_name=u'Api Key',
                                       tab_page=2,
                                       default=u'key-as23XVCBDfg43sfgs')
    mg_helper = Fields.HtmlProperty(
        verbose_name=u'說明',
        tab_page=2,
        html=
        u'Mial Gun 每月可免費寄送 10,000 封信件,請至 <a href="https://www.mailgun.com/" target="_blank">Mial Gun</a> 申請相關 Api Key。'
    )
コード例 #4
0
ファイル: album_model.py プロジェクト: argeweb/plugin-album
class AlbumModel(BasicModel):
    name = Fields.StringProperty(verbose_name=u'識別名稱')
    title = Fields.StringProperty(verbose_name=u'相簿名稱')
    creator = Fields.ApplicationUserProperty(verbose_name=u'建立者')
    count = Fields.IntegerProperty(verbose_name=u'相片數量', default=0)

    @property
    def get_first_img(self):
        return '/plugins/album/static/empty-album.png'

    def insert_photo(self, ndb_item):
        from ..models.album_relation_model import AlbumRelationModel
        if ndb_item is None:
            return
        n = AlbumRelationModel()
        n.album = self.key
        n.file = ndb_item.key
        n.put()
        self.count += 1
        self.put()

    def all_photo(self):
        from ..models.album_relation_model import get_all_file_with_album
        return get_all_file_with_album(self.key)
コード例 #5
0
class StockKeepingUnitModel(BasicModel):
    class Meta:
        label_name = {
            'is_enable': u'啟用',
            'title': u'完整規格名稱',
            'sku_full_name': u'sku 完整編號'
        }

    name = Fields.StringProperty(verbose_name=u'識別名稱')
    product_no = Fields.StringProperty(verbose_name=u'產品編號')
    sku_no = Fields.StringProperty(verbose_name=u'sku 編號')
    spec_full_name = Fields.StringProperty(verbose_name=u'完整規格名稱')
    image = Fields.ImageProperty(verbose_name=u'圖片')
    use_price = Fields.BooleanProperty(verbose_name=u'使用獨立銷售價格', default=False)
    price = Fields.FloatProperty(verbose_name=u'獨立銷售價格', default=-1)
    use_cost = Fields.BooleanProperty(verbose_name=u'使用成本', default=False)
    cost = Fields.FloatProperty(verbose_name=u'成本', default=0.0)
    quantity = Fields.IntegerProperty(verbose_name=u'現存數量', default=0)
    estimate = Fields.IntegerProperty(verbose_name=u'預估數量', default=0)
    in_order_quantity = Fields.IntegerProperty(verbose_name=u'在訂單中的數量',
                                               default=0)
    pre_order_quantity = Fields.IntegerProperty(verbose_name=u'在預購中的數量',
                                                default=0)
    low_stock_quantity = Fields.IntegerProperty(verbose_name=u'庫存警戒線',
                                                default=-1)
    last_in_quantity = Fields.IntegerProperty(verbose_name=u'最後入庫數量',
                                              default=0)
    last_in_datetime = Fields.DateTimeProperty(verbose_name=u'最後入庫時間',
                                               auto_now_add=True)
    last_out_quantity = Fields.IntegerProperty(verbose_name=u'最後出庫數量',
                                               default=0)
    last_out_datetime = Fields.DateTimeProperty(verbose_name=u'最後入庫時間',
                                                auto_now_add=True)

    is_enable = Fields.BooleanProperty(verbose_name=u'顯示於前台', default=True)
    can_be_purchased = Fields.BooleanProperty(verbose_name=u'可購買',
                                              default=True)

    use_automatic_increment = Fields.BooleanProperty(verbose_name=u'自動增量',
                                                     default=False)
    automatic_increment_quantity = Fields.IntegerProperty(
        verbose_name=u'增量的數量', default=0)
    product = Fields.SearchingHelperProperty(verbose_name=u'所屬產品',
                                             target='product_object',
                                             target_field_name='title')
    product_object = Fields.KeyProperty(verbose_name=u'所屬產品',
                                        kind=ProductModel)
    spec_name_1 = Fields.HiddenProperty(verbose_name=u'規格名稱 1')
    spec_name_2 = Fields.HiddenProperty(verbose_name=u'規格名稱 2')
    spec_name_3 = Fields.HiddenProperty(verbose_name=u'規格名稱 3')
    spec_name_4 = Fields.HiddenProperty(verbose_name=u'規格名稱 4')
    spec_name_5 = Fields.HiddenProperty(verbose_name=u'規格名稱 5')
    spec_value_1 = Fields.HiddenProperty(verbose_name=u'規格值 1')
    spec_value_2 = Fields.HiddenProperty(verbose_name=u'規格值 2')
    spec_value_3 = Fields.HiddenProperty(verbose_name=u'規格值 3')
    spec_value_4 = Fields.HiddenProperty(verbose_name=u'規格值 4')
    spec_value_5 = Fields.HiddenProperty(verbose_name=u'規格值 5')

    @property
    def sku_full_name(self):
        product_no = u''
        if self.product_no is not u'' and self.product_no is not None:
            product_no = '%s' % self.product_no
        sku_post_name = u''
        if self.name is not u'' and self.name is not None:
            sku_post_name = self.name
        if self.sku_no is not u'' and self.sku_no is not None:
            sku_post_name = self.sku_no
        if product_no is not u'' and sku_post_name is not u'':
            return '%s-%s' % (product_no, sku_post_name)
        return '%s%s' % (product_no, sku_post_name)

    def before_put(self):
        super(StockKeepingUnitModel, self).before_put()
        product_no = u''
        cat = self.product_object
        if cat is not None:
            try:
                cat = cat.get()
                product_no = cat.product_no
            except:
                pass
        spec_list = (u'%s' % self.spec_full_name).split(u',')
        i = 0
        setattr(self, 'product_no', product_no)
        for index in range(0, len(spec_list)):
            spec = spec_list[index].split(u':')
            setattr(self, 'spec_name_%s' % (index + 1), spec[0])
            setattr(self, 'spec_value_%s' % (index + 1), spec[1])

    @property
    def title(self):
        return self.spec_full_name

    @property
    def quantity_percent(self):
        quantity = self.quantity if self.quantity is not None else 0
        last_in_quantity = self.last_in_quantity if self.last_in_quantity is not None else 0
        if last_in_quantity == 0:
            return 0
        if last_in_quantity < self.low_stock_quantity:
            last_in_quantity = self.low_stock_quantity
        return int((float(quantity) / float(last_in_quantity)) * 10000) / 100.0

    @property
    def is_low_stock_level(self):
        quantity = self.quantity if self.quantity is not None else 0
        low_stock_quantity = self.low_stock_quantity if self.low_stock_quantity is not None else -1
        return quantity <= low_stock_quantity

    @classmethod
    def all_enable(cls, product=None, *args, **kwargs):
        cat = None
        if product:
            cat = ProductModel.get_by_name(product)
        if cat is None:
            return cls.query(cls.is_enable == True).order(-cls.sort)
        else:
            return cls.query(cls.product_object == cat.key,
                             cls.is_enable == True).order(-cls.sort)

    @classmethod
    def find_by_product(cls, product):
        return cls.query(cls.product_object == product.key).order(
            cls.spec_full_name)

    def change_estimate_quantity(self, sub_quantity=0, add_quantity=0):
        self.estimate = self.estimate - abs(sub_quantity) + abs(add_quantity)
        if self.estimate < 0:
            self.estimate = 0

    def change_pre_order_quantity(self, sub_quantity=0, add_quantity=0):
        self.pre_order_quantity = self.pre_order_quantity - abs(
            sub_quantity) + abs(add_quantity)
        if self.pre_order_quantity < 0:
            self.pre_order_quantity = 0

    def change_in_order_quantity(self, sub_quantity=0, add_quantity=0):
        self.in_order_quantity = self.in_order_quantity - abs(
            sub_quantity) + abs(add_quantity)
        if self.in_order_quantity < 0:
            self.in_order_quantity = 0

    @property
    def quantity_can_be_used(self):
        n = self.quantity - self.in_order_quantity - self.estimate
        if n < 0:
            return 0
        return n
コード例 #6
0
class ShoppingCartItemModel(BasicModel):
    cart = Fields.KeyProperty(verbose_name=u'購物車', kind=ShoppingCartModel)
    spec = Fields.KeyProperty(verbose_name=u'產品規格',
                              kind=ProductSpecificationModel)
    user = Fields.ApplicationUserProperty(verbose_name=u'使用者')
    product_object = Fields.KeyProperty(verbose_name=u'所屬產品',
                                        kind=ProductModel)
    title = Fields.StringProperty(verbose_name=u'產品名稱', default=u'')
    product_name = Fields.StringProperty(verbose_name=u'產品名稱(系統)', default=u'')
    product_no = Fields.StringProperty(verbose_name=u'產品型號', default=u'')
    product_image = Fields.StringProperty(verbose_name=u'產品圖片', default=u'')
    price = Fields.FloatProperty(verbose_name=u'銷售價格', default=-1)
    cost = Fields.FloatProperty(verbose_name=u'成本', default=0.0)
    spec_full_name = Fields.StringProperty(verbose_name=u'完整規格名稱', default=u'')

    # 庫存相關
    try:
        from plugins.product_stock.models.stock_keeping_unit_model import StockKeepingUnitModel
    except ImportError:

        class StockKeepingUnitModel(BasicModel):
            pass

    sku = Fields.KeyProperty(verbose_name=u'最小庫存單位',
                             kind=StockKeepingUnitModel)
    sku_full_name = Fields.StringProperty(verbose_name=u'產品最小庫存名稱')
    expired_time = Fields.FloatProperty(verbose_name=u'庫存回收時間')
    quantity = Fields.IntegerProperty(verbose_name=u'數量', default=0)
    quantity_has_count = Fields.IntegerProperty(verbose_name=u'已計入庫存的數量',
                                                default=0)
    can_add_to_order = Fields.BooleanProperty(verbose_name=u'加至訂單中',
                                              default=False)

    try:
        from plugins.supplier.models.supplier_model import SupplierModel
    except ImportError:

        class SupplierModel(BasicModel):
            pass

    supplier = Fields.CategoryProperty(kind=SupplierModel, verbose_name=u'供應商')

    #  0=訂購(無庫存), 1=現貨, 2預購
    order_type = Fields.StringProperty(verbose_name=u'訂購方式')
    order_type_value = Fields.IntegerProperty(verbose_name=u'訂購方式(值)')

    size_1 = Fields.FloatProperty(verbose_name=u'長度(公分)', default=10.0)
    size_2 = Fields.FloatProperty(verbose_name=u'寬度(公分)', default=10.0)
    size_3 = Fields.FloatProperty(verbose_name=u'高度(公分)', default=10.0)
    weight = Fields.FloatProperty(verbose_name=u'重量(公斤)', default=10.0)

    @classmethod
    def get_or_create(cls, cart, user, product, spec, order_type=0):
        try:
            user_key = user.key
        except AttributeError:
            user_key = user
        item = cls.query(cls.cart == cart.key, cls.user == user_key,
                         cls.product_object == product.key,
                         cls.spec == spec.key,
                         cls.order_type_value == order_type).get()
        need_put = False
        if item is None:
            item = cls()
            item.cart = cart.key
            item.user = user_key
            item.product_object = product.key
            item.spec = spec.key
            item.order_type_value = order_type
            item.order_type = [u'訂購', u'現貨', u'預購'][order_type]
            item.spec_full_name = spec.full_name
            item.product_name = product.name
            item.product_image = product.image
            need_put = True
            if order_type == 0:
                item.can_add_to_order = True
        for field_name in [
                'title', 'product_no', 'price', 'cost', 'size_1', 'size_2',
                'size_3', 'weight'
        ]:
            if getattr(item, field_name) != getattr(product, field_name):
                setattr(item, field_name, getattr(product, field_name))
                need_put = True
        if need_put:
            item.put()
        return item

    @classmethod
    def get(cls, user, sku, order_type_value=0):
        return cls.query(cls.sku == sku.key, cls.user == user.key,
                         cls.order_type_value == order_type_value).get()

    @classmethod
    def get_or_create_with_spec(cls,
                                user,
                                spec,
                                quantity=0,
                                order_type_value=0):
        product = spec.product_object.get()
        item = cls.query(cls.sku == spec.key, cls.user == user.key,
                         cls.order_type_value == order_type_value).get()
        if item is None:
            item = cls()
            item.spec = spec.key
            item.user = user.key
            item.order_type_value = order_type_value
            item.product_object = product.key
            try:
                item.supplier = product.supplier.get().key
            except:
                pass
            if order_type_value == 0:
                item.order_type = u'訂購'
            else:
                item.order_type = u'預購'
        item._spec = spec
        item._product = product
        item.title = product.title
        item.product_no = product.product_no
        item.product_image = product.image
        item.spec_full_name = spec.spec_full_name
        item.change_quantity(quantity)
        item.put()
        return item

    @classmethod
    def all_with_user(cls, user):
        key = None
        if user is not None:
            key = user.key
        return cls.query(cls.user == key).order(-cls.sort)

    @classmethod
    def before_delete(cls, key):
        item = key.get()
        if item.order_type_value == 0:
            if item.quantity > 0:
                try:
                    sku = item.sku_instance
                    sku.change_estimate_quantity(item.quantity_has_count)
                    sku.put()
                except:
                    pass

    def volumetric_weight(self, divisor=6000.0):
        n = self.size_1 * self.size_2 * self.size_3 / float(divisor)
        return n

    @property
    def spec_instance(self):
        if not hasattr(self, '_spec'):
            self._spec = self.spec.get()
        return self._spec

    @property
    def sku_instance(self):
        if not hasattr(self, '_sku'):
            self._sku = self.sku.get()
        return self._sku

    @property
    def product_instance(self):
        if not hasattr(self, '_product'):
            self._product = self.spec_instance.product_object.get()
        return self._product

    def change_quantity(self, quantity):
        spec = self.spec_instance
        product = self.product_instance
        if self.order_type_value == 0:
            config = ConfigModel.get_config()
            if config.stock_recover:
                self.expired_time = time() + config.stock_recover_time
            else:
                self.expired_time = time() + 525600
            can_use_quantity = spec.quantity_can_be_used + int(
                self.quantity_has_count)
            old_quantity_has_count = self.quantity_has_count
            if can_use_quantity >= quantity and product.can_order:
                self.can_add_to_order = True
                self.quantity = quantity
                self.quantity_has_count = quantity
            else:
                self.can_add_to_order = False
                self.quantity = 0
                self.quantity_has_count = 0
            spec.change_estimate_quantity(sub_quantity=old_quantity_has_count,
                                          add_quantity=self.quantity)
            spec.put()
        else:
            if product.can_pre_order:
                self.can_add_to_order = True
                self.quantity = quantity
            else:
                self.can_add_to_order = False
                self.quantity = 0
            spec.change_pre_order_quantity(sub_quantity=int(
                self.quantity_has_count),
                                           add_quantity=self.quantity)
            spec.put()

    def quantity_can_be_order(self, user=None, sku=None):
        if sku is None:
            sku = self.sku.get()
        if self.order_type_value > 0:
            return 999
        if user and self.quantity is not None:
            c = sku.quantity_can_be_used + self.quantity
            if c > 0:
                return c
        return sku.quantity_can_be_used
コード例 #7
0
class StockKeepingUnitInWarehouseModel(BasicModel):
    class Meta:
        label_name = {
            'is_enable': u'啟用',
            'title': u'完整規格名稱',
            'sku_full_name': u'sku 編號'
        }

    sku = Fields.KeyProperty(kind=StockKeepingUnitModel,
                             verbose_name=u'所屬 SKU')
    warehouse = Fields.KeyProperty(kind=WarehouseModel, verbose_name=u'所屬倉庫')
    product = Fields.KeyProperty(kind=ProductModel, verbose_name=u'所屬產品')
    quantity = Fields.IntegerProperty(verbose_name=u'在庫數量', default=0)

    @classmethod
    def stock_in(cls, warehouse, sku, quantity):
        record = cls.get_or_create(sku=sku, warehouse=warehouse)
        record.quantity = int(record.quantity) + int(quantity)
        record.put()

        sku.quantity = sku.quantity + quantity
        sku.last_in_quantity = sku.quantity
        sku.last_in_datetime = datetime.now()
        sku.put()
        return record

    @classmethod
    def stock_out_check(cls, warehouse, sku, quantity, auto_fill=False):
        record = cls.get_or_create(sku=sku, warehouse=warehouse)
        c = record.quantity - quantity
        if c < 0 and auto_fill is False:
            raise ValueError(u'錯誤 [ %s ] 的數量不足 %s 個,缺少 %s 個' %
                             (sku.spec_full_name, str(quantity), str(-c)))

    @classmethod
    def stock_out(cls, warehouse, sku, quantity, auto_fill=False):
        record = cls.get_or_create(sku=sku, warehouse=warehouse)
        record.quantity = record.quantity - quantity
        record.put()

        sku.quantity = sku.quantity - quantity
        sku.last_out_quantity = sku.quantity
        sku.last_out_datetime = datetime.now()
        sku.put()
        return record

    @classmethod
    def get_or_create(cls, sku, warehouse, quantity=0):
        record = cls.query(cls.sku == sku.key,
                           cls.warehouse == warehouse.key).get()
        if record is None:
            record = cls()
            record.sku = sku.key
            record.product = sku.product_object
            record.warehouse = warehouse.key
            record.quantity = quantity
        record.put()
        return record

    @classmethod
    def get_all_with_product(cls, product, warehouse=None):
        if warehouse is None:
            return cls.query(cls.product == product.key)
        else:
            return cls.query(cls.product == product.key,
                             cls.warehouse == warehouse.key)

    @classmethod
    def create_sku_by_product(cls, product, warehouse=None):
        from stock_keeping_unit_model import StockKeepingUnitModel as SKU
        sku_list = SKU.query(SKU.product_object == product.key).fetch()
        sku_list_in_warehouse = []
        for item in sku_list:
            sku_list_in_warehouse.append(cls.get_or_create(item, warehouse))
        return sku_list_in_warehouse
コード例 #8
0
class UserContactDataModel(BasicModel):
    user = Fields.ApplicationUserProperty(verbose_name=u'使用者', is_lock=True)
    user_name_proxy = Fields.StringProperty(verbose_name=u'使用者名稱')
    user_email_proxy = Fields.StringProperty(verbose_name=u'E-Mail')
    user_avatar_proxy = Fields.ImageProperty(verbose_name=u'頭像')
    telephone = Fields.StringProperty(verbose_name=u'電話', default=u'')
    mobile = Fields.StringProperty(verbose_name=u'手機', default=u'')
    sex = Fields.StringProperty(verbose_name=u'性別', default=u'保密')
    address_country = Fields.StringProperty(verbose_name=u'國家', default=u'')
    address_city = Fields.StringProperty(verbose_name=u'縣市', default=u'')
    address_district = Fields.StringProperty(verbose_name=u'鄉鎮', default=u'')
    address_detail = Fields.StringProperty(verbose_name=u'地址', default=u'')
    address_zip = Fields.StringProperty(verbose_name=u'郵遞區號', default=u'')

    birthday_year = Fields.IntegerProperty(verbose_name=u'出生年', default=0)
    birthday_month = Fields.IntegerProperty(verbose_name=u'出生月', default=0)
    birthday_day = Fields.IntegerProperty(verbose_name=u'出生日', default=0)
    referrals = Fields.StringProperty(verbose_name=u'推薦人', default=u'')
    is_referrals_change = Fields.BooleanProperty(verbose_name=u'推薦人已修改', default=False)

    mobile_verification_code = Fields.HiddenProperty(verbose_name=u'手機驗証碼', default=u'')
    is_mobile_verified = Fields.BooleanProperty(verbose_name=u'手機是否已驗証', default=False)
    need_verification_mobile = Fields.HiddenProperty(verbose_name=u'需驗証的手機', default=u'')
    last_verified_mobile = Fields.HiddenProperty(verbose_name=u'最後驗証成功的手機', default=u'')

    email_verification_code = Fields.HiddenProperty(verbose_name=u'信箱驗証碼', default=u'')
    is_email_verified_proxy = Fields.BooleanProperty(verbose_name=u'信箱是否已驗証', default=False)
    need_verification_email = Fields.HiddenProperty(verbose_name=u'需驗証的信箱', default=u'')
    last_verified_email = Fields.HiddenProperty(verbose_name=u'最後驗証成功的信箱', default=u'')

    address_verification_code = Fields.HiddenProperty(verbose_name=u'地址驗証碼', default=u'')
    is_address_verified = Fields.BooleanProperty(verbose_name=u'地址是否已驗証', default=False)

    @classmethod
    def get_or_create(cls, user):
        r = cls.query(cls.user==user.key).get()
        if r is None:
            r = cls(user=user.key)
            r.user_name_proxy = user.name
            r.user_email_proxy = user.email
            r.user_avatar_proxy = user.avatar
            r.is_email_verified_proxy = user.is_email_verified
            r.put()
        r._user = user
        r.password = r._user.password
        r.old_password = r._user.password
        return r

    @property
    def user_instance(self):
        if not hasattr(self, '_user'):
            self._user = self.user.get()
        return self._user

    def update_user(self, user=None):
        if user is None:
            user = self.user_instance
        if user is None:
            return

        if hasattr(self, 'old_password') and self.old_password != self.password:
            user.password = self.password
            user.bycrypt_password()
            self.password = user.password
            self.old_password = user.password
        try:
            user.name = self.user_name_proxy
            user.email = self.user_email_proxy
            user.avatar = self.user_avatar_proxy
            user.is_email_verified = self.is_email_verified_proxy
        except:
            pass
        user.put()

    @property
    def user_name(self):
        if self.user_instance:
            return self.user_instance.name
        return u'該帳號已被刪除'

    @user_name.setter
    def user_name(self, value):
        self.user_name_proxy = value

    @property
    def email(self):
        if self.user_instance:
            return self.user_instance.email
        return u''

    @email.setter
    def email(self, value):
        self.user_email_proxy = value

    @property
    def avatar(self):
        if self.user_instance:
            return self.user_instance.avatar
        return u''

    @avatar.setter
    def avatar(self, value):
        self.user_avatar_proxy = value

    @property
    def is_email_verified(self):
        if self.user_instance:
            return self.user_instance.is_email_verified
        return False

    @is_email_verified.setter
    def is_email_verified(self, value):
        self.is_email_verified_proxy = value

    @classmethod
    def after_get(cls, key, item):
        if item.user_instance:
            item.user_name_proxy = item.user_instance.name
            item.user_email_proxy = item.user_instance.email
            item.user_avatar_proxy = item.user_instance.avatar
            item.is_email_verified_proxy = item.user_instance.is_email_verified
        else:
            item.user_name_proxy = u'該帳號已被刪除'

    def gen_email_verification_code(self, email):
        import random, string
        r = ''.join(random.choice(string.lowercase) for i in range(25))
        self.need_verification_email = email
        self.email_verification_code = u'%s-%s-%s-%s' % (r[0:4], r[5:9], r[10:14], r[15:19])

    def gen_mobile_verification_code(self, mobile):
        import random
        self.need_verification_mobile = mobile
        self.mobile_verification_code = u'%s' % (random.randint(100000, 999999))

    def verify_email(self, code):
        if self.email_verification_code == code:
            self.last_verified_email = self.need_verification_email
            self.is_email_verified_proxy = True
            self.user_email_proxy = self.last_verified_email
            self.user_instance.email = self.last_verified_email
            self.user_instance.is_email_verified = True
            self.user_instance.put()
            self.email_verification_code = ''
            self.put()
            return True
        return False

    def verify_mobile(self, code):
        if self.mobile_verification_code == code:
            self.last_verified_mobile = self.need_verification_mobile
            self.is_mobile_verified = True
            self.mobile_verification_code = ''
            self.put()
            return True
        return False

    @property
    def birthday(self):
        return '%d-%02d-%02d' % (self.birthday_year, self.birthday_month, self.birthday_day)
コード例 #9
0
class FileModel(BasicModel):
    class Meta:
        label_name = {
            'title': u'顯示名稱',
            'display_name': u'顯示名稱',
            'children': u'子項目',
            'path_as_url': u'URL'
        }

    name = Fields.StringProperty(verbose_name=u'名稱')
    path = Fields.StringProperty(verbose_name=u'檔案路徑')
    content_length = Fields.IntegerProperty(verbose_name=u'檔案大小', default=0)
    content_type = Fields.StringProperty(verbose_name=u'檔案類型', default='blob')
    content_language = Fields.StringProperty(verbose_name=u'語系')
    parent_resource = Fields.CategoryProperty(kind=selfReferentialModel,
                                              verbose_name=u'所屬目錄')
    is_collection = Fields.BooleanProperty(verbose_name=u'是否為目錄',
                                           default=False)
    is_root = Fields.BooleanProperty(verbose_name=u'是否為根目錄', default=False)
    created = Fields.DateTimeProperty(auto_now_add=True)
    modified = Fields.DateTimeProperty(auto_now=True)
    etag = Fields.StringProperty(verbose_name=u'ETag')
    resource_data = Fields.CategoryProperty(kind=FileDataModel,
                                            verbose_name=u'檔案實體')
    last_version = Fields.IntegerProperty(verbose_name=u'最新的版本', default=0)
    last_md5 = Fields.StringProperty(verbose_name=u'MD5', default=u'')
    file = Fields.BlobKeyProperty(verbose_name=u'BlobKey')
    theme = Fields.StringProperty(verbose_name=u'所屬樣式', default=u'')

    @property
    def abs_path(self):
        if self.is_collection is False:
            if str(self.path).startswith('themes/'):
                return '/assets/' + self.path
        return '/' + self.path

    @property
    def children(self):
        if self.is_collection:
            logging.info(self.key)
            return FileModel().all().filter(
                FileModel.parent_resource == self.key)
        else:
            return []

    @property
    def title(self):
        return self.name

    @property
    def display_name(self):
        return os.path.basename('%s' % self.path)

    @property
    def path_as_url(self):
        return pathname2url(self.path)

    @property
    def content_type_or_default(self):
        if self.is_collection:
            return 'httpd/unix-directory'
        else:
            mimetype = mimetypes.guess_type(self.path, strict=False)[0]
            return mimetype if mimetype else 'application/octet-stream'

    @property
    def is_code_file(self):
        return self.content_type in ([
            'css', 'js', 'javascript', 'html', 'text/css', 'text/html',
            'text/javascript'
        ])

    @classmethod
    def all_without_root(cls):
        return cls.query(cls.is_root == False).order(-cls.sort)

    @classmethod
    def code_files(cls):
        return cls.query(
            cls.content_type.IN([
                'css', 'js', 'javascript', 'html', 'text/css', 'text/html',
                'text/javascript'
            ]), ).order(-cls.sort, -cls.key)

    def make_directory(self):
        path = u'' + self.path
        if path[0:1] is u'/':
            path = path[1:]
        paths = path.split(u'/')
        last_parent = FileModel.root()
        if len(paths) > 1:
            for i in xrange(1, len(paths)):
                path_str = u'/'.join(paths[:i])
                if path_str is not u'':
                    collection = FileModel.get_by_path(path_str)
                    if collection is None:
                        collection = FileModel()
                        collection.name = paths[i]
                        collection.path = path_str
                        collection.parent_resource = last_parent.key
                        collection.is_collection = True
                        collection.put()
                    if collection != self and collection.is_collection is True:
                        last_parent = collection
        self.parent_resource = last_parent.key
        self.put()

    @classmethod
    def root(cls):
        root = cls.all().filter(cls.is_root == True).get()
        if not root:
            root = cls(path='', is_collection=True)
            root.name = '-Root-'
            root.is_root = True
            root.put()
        return root

    @classmethod
    def all_by_path(cls, path=''):
        query = cls.all().filter(cls.path == path + '%')
        return query

    @classmethod
    def get_by_path(cls, path=None):
        return cls.all().filter(cls.path == path).get() if path else cls.root()

    @classmethod
    def exists_with_path(cls, path='', is_collection=None):
        query = cls.all().filter(cls.path == path)
        if is_collection is not None:
            query = query.filter(cls.is_collection == True)
        return query.get(keys_only=True) is not None

    @classmethod
    def content_type_sort_by_name(cls, content_type):
        """ get record with content-type and sort by title """
        return cls.query(cls.content_type == content_type).order(cls.name)

    @classmethod
    def get_or_create(cls, path, content_type):
        n = cls.get_by_path(path)
        if n is None:
            n = cls()
            n.name = os.path.basename('%s' % path)
            n.path = path
            n.content_type = content_type
            n.put()
        return n

    def move_to_path(self, destination_path):
        """Moves this resource and all its children (if applicable) to a new path.
           Assumes that the new path is free and clear."""

        if self.is_collection:
            for child in self.children:
                child_name = os.path.basename(child.path)
                child_path = os.path.join(destination_path, child_name)
                child.move_to_path(child_path)

        self.path = destination_path
        self.put()

    def put(self):
        # type: () -> object
        # workaround for general non-solveable issue of no UNIQUE constraint concept in app engine datastore.
        # anytime we save, we look for the possibility of other duplicate Resources with the same path and delete them.

        try:
            for duped_resource in FileModel.all().filter(
                    FileModel.path == self.path):
                if self.key().id() != duped_resource.key().id():
                    logging.info(
                        'Deleting duplicate resource %s with path %s.' %
                        (duped_resource, duped_resource.path))
                    duped_resource.delete()
            if self.name != '-Root-':
                self.name = self.display_name
        except:
            pass
        paths = self.path.split('/')
        theme = ''
        if len(paths) >= 2 and paths[0] == 'themes':
            theme = paths[1]
        self.theme = theme
        super(FileModel, self).put()

    def delete(self):
        """Override delete to delete our associated ResourceData entity automatically."""
        if self.resource_data:
            n = self.resource_data.get()
            if n:
                n.key.delete()
        if self.last_version > 0:
            try:
                from plugins.code.models.code_model import CodeModel
                CodeModel.delete_with_target(self.key)
            except:
                pass
        self.key.delete()

    def delete_recursive(self):
        """Deletes this entity plus all of its children and other descendants."""
        if self.is_collection:
            for child in self.children:
                child.delete_recursive()
        self.delete()

    def export_response(self, href=None):
        datetime_format = '%Y-%m-%dT%H:%M:%SZ'

        response = ET.Element('D:response', {'xmlns:D': 'DAV:'})
        ET.SubElement(response, 'D:href').text = href
        propstat = ET.SubElement(response, 'D:propstat')
        prop = ET.SubElement(propstat, 'D:prop')

        if self.created:
            ET.SubElement(
                prop,
                'D:creationdate').text = self.created.strftime(datetime_format)

        ET.SubElement(prop, 'D:displayname').text = self.display_name

        if self.content_language:
            ET.SubElement(prop, 'D:getcontentlanguage').text = str(
                self.content_language)

        ET.SubElement(prop,
                      'D:getcontentlength').text = str(self.content_length)
        ET.SubElement(prop, 'D:getcontenttype').text = str(
            self.content_type_or_default)

        if self.modified:
            ET.SubElement(prop,
                          'D:getlastmodified').text = self.modified.strftime(
                              datetime_format)

        resourcetype = ET.SubElement(prop, 'D:resourcetype')

        if self.is_collection:
            ET.SubElement(resourcetype, 'D:collection')

        ET.SubElement(propstat, 'D:status').text = 'HTTP/1.1 200 OK'
        return response