Пример #1
0
    def render_for_user(self, resource, context):
        # Get review that belong to user
        query = [
            PhraseQuery('shop_module_review_author', resource.name),
            PhraseQuery('workflow_state', 'public'),
            PhraseQuery('format', 'shop_module_a_review')
        ]
        search = context.root.search(AndQuery(*query))
        brains = list(search.get_documents(sort_by='mtime', reverse=True))
        nb_reviews = len(brains)
        # Get viewboxes
        viewboxes = []
        for brain in brains[:5]:
            review = context.root.get_resource(brain.abspath)
            viewbox = Review_Viewbox().GET(review, context)
            viewboxes.append(viewbox)
        # Return namespace
        return {'nb_reviews': nb_reviews, 'viewboxes': viewboxes}

    def get_document_types(self):
        return []


register_resource_class(ShopModule_Review)
register_resource_class(ShopModule_AReview)
register_field('shop_module_review_author', String(is_indexed=True))
register_field('shop_module_review_note',
               Integer(is_indexed=True, is_stored=True))
register_field('shop_module_review_description', Unicode(is_stored=True))
Пример #2
0
        if (self.is_admin(resource, context) is False and
            cart.get_nb_products() == 0 and
            show_if_empty is False):
            self.set_view_is_empty(True)

        default_order_title = MSG(u'Commander')
        return merge_dicts(
            cart.get_namespace(resource),
            order_title=resource.get_property('order_title') or default_order_title,
            title=resource.get_title())



class CartBox(Box):

    class_id = 'vertical-item-cart-box'
    class_title = MSG(u'Boîte panier')
    view = CartBox_View()


    edit_schema = {'order_title': Unicode(multilingual=True),
                   'show_if_empty': Boolean}

    edit_widgets = [TextWidget('order_title', title=MSG(u'Order title')),
                    BooleanRadio('show_if_empty',
                                 title=MSG(u'Show cart if empty ?'))]


register_resource_class(CartBox)
register_box(CartBox, allow_instanciation=False)
Пример #3
0
        addresses = self.get_resource('addresses').handler
        for record in addresses.search(user=str(user_name)):
            return record
        return None

    def get_user_address_namespace(self, id):
        addresses = self.get_resource('addresses').handler
        return addresses.get_record_namespace(id)

    ##############################
    # Configuration
    ##############################
    def show_ht_price(self, context):
        if context.user:
            group = context.user.get_group(context)
            return group.get_property('show_ht_price')
        return False

    def has_pro_price(self):
        # XXX Improve in future
        root = self.get_root()
        query = [
            PhraseQuery('format', 'user-group'),
            PhraseQuery('name', 'pro')
        ]
        search = root.search(AndQuery(*query))
        return len(search) > 0


register_resource_class(Shop)
Пример #4
0
        return ro_database.get_handler(path, XMLFile)

    def get_namespace(self, resource, context):
        languages = context.site_root.get_property('website_languages')
        lang = context.accept_language.select_language(languages)
        return {
            'lang': lang,
            'username': resource.get_property('username') or ''
        }


class ShopModule_AddThis(ShopModule):

    class_id = 'shop_module_addthis'
    class_title = MSG(u'Add This')
    class_views = ['edit']
    class_description = MSG(u'Add this')

    item_schema = {'username': String, 'style': AddThis_Styles(default=1)}

    item_widgets = [
        TextWidget('username', title=MSG(u'Addthis account username')),
        SelectWidget('style', title=MSG(u'Style'), has_empty_option=False)
    ]

    def render(self, resource, context):
        return ShopModule_AddThis_View().GET(self, context)


register_resource_class(ShopModule_AddThis)
Пример #5
0
        'value': MSG(u'None')
    }, {
        'name': 'vertical',
        'value': MSG(u'Vertical')
    }, {
        'name': 'horizontal',
        'value': MSG(u'Horizontal')
    }]


class ShopModule_TwitterButton(ShopModule):

    class_id = 'shop_module_twitter_button'
    class_title = MSG(u'Twitter button')
    class_views = ['edit']
    class_description = MSG(u'Twitter button')

    item_schema = {'datacount': DataCount}

    item_widgets = [
        SelectWidget('datacount',
                     title=MSG(u'Data count'),
                     has_empty_option=False),
    ]

    def render(self, resource, context):
        return ShopModule_TwitterButton_View().GET(self, context)


register_resource_class(ShopModule_TwitterButton)
Пример #6
0
        BooleanRadio('enabled', title=MSG(u'Enabled')),
    ]

    # XXX Enabled means its enabled for delivery not for registration
    # People from south africa can register on website but not to be delivered
    # This distinction must be explicit

    @staticmethod
    def _make_resource(cls, folder, name, *args, **kw):
        Table._make_resource(cls, folder, name)
        # Import CSV with list of countries
        zones = []
        table = BaseCountries()
        csv = ro_database.get_handler(get_abspath('data/countries.csv'),
                                      CSVFile)
        for line in csv.get_rows():
            country = unicode(line[0], 'utf-8')
            zone = unicode(line[1], 'utf-8')
            if zone not in zones:
                zones.append(zone)
            table.add_record({
                'title': Property(country, language='fr'),
                'zone': str(zones.index(zone)),
                'enabled': True
            })
        folder.set_handler(name, table)


register_resource_class(Countries)
register_resource_class(CountriesZones)
Пример #7
0
        # Get values:
        coords = []
        for value in data.list:
            d, nb_visit = value
            d = d[0]
            d = date(int(d[0:4]), int(d[4:6]), int(d[6:8]))
            nb_visit = nb_visit[0]
            d = timegm(d.timetuple()) * 1000
            coords.append([d, nb_visit])
        return dumps(coords)


class ShopModule_GoogleAnalytics(ShopModule):

    class_id = 'shop_module_google_analytics'
    class_title = MSG(u'Google analytics')
    class_views = ['edit']
    class_description = MSG(u'Google analytics tracker')

    item_schema = {'tracking_id': String, 'table_id': String}
    item_widgets = [
        TextWidget('tracking_id', title=MSG(u'Tracking id')),
        TextWidget('table_id', title=MSG(u'Table id'))
    ]

    def render(self, resource, context):
        return ShopModule_GoogleAnalytics_View().GET(self, context)


register_resource_class(ShopModule_GoogleAnalytics)
Пример #8
0
# Import from itws
from itws.repository import Box
from itws.repository_views import Box_View


class LoginBox_View(Box_View):

    template = '/ui/vertical_depot/login_box.xml'

    def get_namespace(self, resource, context):
        namespace = {'title': resource.get_title()}
        is_connected = context.user is not None
        if is_connected:
            namespace['user'] = {
                'name': context.user.name,
                'title': context.user.get_title()
            }
        namespace['is_connected'] = is_connected
        return namespace


class LoginBox(Box):

    class_id = 'vertical-item-login-box'
    class_title = MSG(u'Login box')
    view = LoginBox_View()


register_resource_class(LoginBox)
Пример #9
0
class CheckPayment(PaymentWay):

    class_id = 'check-payment'
    class_title = MSG(u'Payment by check')
    class_description = MSG(u'Payment by check')
    class_views = ['configure', 'payments']

    # XXX found a good logo
    logo = '/ui/backoffice/payments/paybox/images/logo.png'
    payment_table = CheckPaymentTable

    # Views
    configure = CheckPayment_Configure()
    end = CheckPayment_End()

    # Order admin views
    order_view = CheckPayment_RecordView
    order_edit_view = CheckPayment_RecordEdit

    @classmethod
    def get_metadata_schema(cls):
        return merge_dicts(PaymentWay.get_metadata_schema(),
                           to=Unicode,
                           address=Unicode)


register_resource_class(CheckPayment)
register_resource_class(CheckPaymentTable)

register_payment_way(CheckPayment)
Пример #10
0
                'tree': tree}



class SubCategoriesBox(Box):

    class_id = 'vertical-item-sub-categories-box'
    class_title = MSG(u'Vertical item that list sub categories')
    class_version = '20100712'

    view = SubCategoriesBox_View()

    edit_schema = {'show_first_category': Boolean,
                   'show_second_level': Boolean,
                   'show_nb_products': Boolean,
                   'use_small_title': Boolean}

    edit_widgets = [
        BooleanRadio('show_first_category',
                                 title=MSG(u'Show level 1 ?')),
        BooleanRadio('show_second_level',
                                 title=MSG(u'Show level 2 ?')),
        BooleanRadio('show_nb_products',
                     title=MSG(u'Afficher le nombre de produits')),
        BooleanRadio('use_small_title', title=MSG(u'Use small title'))]



register_resource_class(SubCategoriesBox)
register_box(SubCategoriesBox, allow_instanciation=True)
Пример #11
0
Файл: root.py Проект: TZM/zmgc
    last_changes = DBResource_CommitLog(access='is_allowed_to_edit')
    
    def get_version_of_packages(self, context):
        versions = BaseRoot.get_version_of_packages(self, context)
        # check nodejs version
        try:
            nodejs = get_pipe(['node', '--version'])
            versions['nodejs'] = nodejs
        except OSError:
            versions['nodejs'] = None

        return versions
    #######################################################################
    # Access control
    #######################################################################
    def is_allowed_to_create_chapter(self, user, resource):
        if user is None:
            return False
        if self.is_admin(user, resource):
            return True
        user_get_chapters = user.get_chapters()
        if user_get_chapters:
            context = get_context()
            context.message = MSG_EXISTING_CHAPTER_ADMIN
            return False
        return True
###########################################################################
# Register
###########################################################################
register_resource_class(Root)
Пример #12
0
        # Get the namespace
        namespace = self.get_namespace(resource, context)
        if isinstance(namespace, Reference):
            return namespace

        # STL
        template = self.get_template(resource, context)
        if isinstance(template, (GeneratorType, XMLParser)):
            return stl(events=template, namespace=namespace)
        return stl(template, namespace)



class NotFoundPage(WebPage):

    class_id = '404'
    class_title = MSG(u'404 page')

    class_views = WebPage.class_views + ['control_panel']

    control_panel = GoToSpecificDocument(specific_document='../../',
                                         specific_view='control_panel',
                                         title=ControlPanel.title)

    # Hide in browse_content
    is_content = False



register_resource_class(NotFoundPage, format='application/xhtml+xml')
Пример #13
0
    class_id = 'orders'
    class_title = MSG(u'Orders')
    class_views = ['view']  # 'export']
    class_version = '20091127'

    # Views
    view = OrdersView()

    def get_document_types(self):
        return [Order]

    #############################
    # Export
    #############################
    export = Export(
        export_resource=Order,
        access='is_allowed_to_edit',
        file_columns=['name', 'state', 'total_price', 'creation_datetime'])


# Register catalog fields
register_field('customer_id', String(is_indexed=True))
register_field('is_payed', Boolean(is_stored=True))
register_field('creation_datetime', DateTime(is_stored=True, is_indexed=True))

# Register resources
register_resource_class(Order)
register_resource_class(Orders)
register_resource_class(OrdersProducts)
Пример #14
0
class Withdrawal(ShippingWay):
    """Withdrawal to the store.
    """
    class_id = 'withdrawal'
    class_title = MSG(u'Withdrawal')
    class_version = '20090910'
    class_description = MSG(u'Withdrawal at the store')

    img = '../ui/shop/images/noship.png'

    shipping_history_cls = WithdrawalTable

    @staticmethod
    def _make_resource(cls, folder, name, *args, **kw):
        kw['title'] = {'en': cls.class_title.gettext()}
        kw['description'] = {'en': cls.class_description.gettext()}
        kw['is_free'] = True
        ShippingWay._make_resource(cls, folder, name, *args, **kw)


    # Admin views
    order_view = Withdrawal_RecordView()
    order_add_view = Withdrawal_RecordAdd()
    order_edit_view = Withdrawal_RecordEdit()



register_resource_class(Withdrawal)
register_resource_class(WithdrawalTable)
Пример #15
0
            'enabled': True,
            'img': img,
            'name': 'default',
            'pretty_price': format_price(price),
            'price': price}


    def get_price(self, shipping_way, country, purchase_weight):
        shipping_way = self.get_resource(shipping_way)
        return shipping_way.get_price(country, purchase_weight)


    def get_namespace_shipping_way(self, context, name, country, weight):
        shipping = self.get_resource(name)
        return shipping.get_widget_namespace(context, country, weight)


    def get_shippings_records(self, context, ref=None):
        records = []
        for shipping_way in self.search_resources(cls=ShippingWay):
            history = shipping_way.get_resource('history')
            if ref:
                records.extend(history.handler.search(ref=ref))
            else:
                records.extend(history.handler.get_records())
        return records



register_resource_class(Shippings)
Пример #16
0
        abspath = self.get_canonical_path()
        query = AndQuery(PhraseQuery('parent_paths', str(abspath)),
                         PhraseQuery('format', 'category'))
        return len(root.search(query))

    @property
    def nb_products(self):
        return self.get_nb_products()

    @property
    def nb_categories(self):
        return self.get_nb_categories()

    #############################
    # Export
    #############################
    export = Export(export_resource=Product,
                    access='is_allowed_to_edit',
                    file_columns=[
                        'reference', 'state', 'frontoffice_uri', 'cover_uri',
                        'manufacturer', 'price_with_tax', 'description'
                    ])


register_resource_class(Category)

# Add m_title field if it does not already exist
if 'm_title' in get_register_fields() is False:
    register_field('m_title', Unicode(is_stored=True, is_indexed=True))
register_field('m_breadcrumb_title', Unicode(is_stored=True, is_indexed=True))
Пример #17
0
        else:
            thumbnail = {'flvthumb':flvthumb}

        return thumbnail


    def make_flv_thumbnail(self, destfolder, filename, width):
        """ Create a Thumb at t(ime)=0 (percent or time)
        """
        ffmpegthumbnailer = ['ffmpegthumbnailer', '-i', '%s.flv' % filename,
    '-o', '%s.png' % filename, '-t', '0', '-s', '%s' % width]
        get_pipe(ffmpegthumbnailer, cwd=destfolder)

    def make_thumbnail(self, destfolder, filename, width):
        """ Create a Thumb at t(ime)=0 (percent or time)
        """
        ffmpegthumbnailer = ['ffmpegthumbnailer', '-i', '%s' % filename,
    '-o', '%s.png' % filename, '-t', '0', '-s', '%s' % width]
        get_pipe(ffmpegthumbnailer, cwd=destfolder)

    def add_metadata_to_flv(self, destfolder, filename):
        """ Add some Metadata to the FLV file, as ffmpeg is not doing that well.
        """
        flvtool2 = ['flvtool2', '-U', '%s' % filename]
        get_pipe(flvtool2, cwd=destfolder)


###########################################################################
# Register
register_resource_class(VideoEncodingToFLV)
Пример #18
0
    def get_items(self, resource, context, *args):
        product_model = resource.get_property('product_model')
        query = PhraseQuery('product_model', product_model)
        return context.root.search(query)



class CrossSelling_Section(Folder):
    """
    XXX That should be a section_view on 0.62
    """

    class_id = 'section-cross-selling'
    class_title = MSG(u'Cross Selling Section')
    class_views = ['view', 'edit']

    view = CrossSelling_Section_View()
    edit = AutomaticEditView()

    # Edit views
    edit_schema = {'product_model': ProductModelsEnumerate}

    edit_widgets = [
            SelectWidget('product_model', title=MSG(u'Product model')),
            ]



register_resource_class(CrossSelling_Section)
Пример #19
0
        addresses = self.get_resource('addresses').handler
        for record in addresses.search(user=str(user_name)):
            return record
        return None


    def get_user_address_namespace(self, id):
        addresses = self.get_resource('addresses').handler
        return addresses.get_record_namespace(id)

    ##############################
    # Configuration
    ##############################
    def show_ht_price(self, context):
        if context.user:
            group = context.user.get_group(context)
            return group.get_property('show_ht_price')
        return False


    def has_pro_price(self):
        # XXX Improve in future
        root = self.get_root()
        query = [PhraseQuery('format', 'user-group'),
                 PhraseQuery('name', 'pro')]
        search = root.search(AndQuery(*query))
        return len(search) > 0


register_resource_class(Shop)
Пример #20
0
    class_schema = freeze(merge_dicts(
        Mission.class_schema,
        comment=comment_datatype(parameters_schema=merge_dicts(
            comment_datatype.parameters_schema,
            alert_datetime=DateTime,
            crm_m_nextaction=Unicode))))


    def update_20100927(self):
        comments = self.metadata.get_property('comment') or []
        # Migrate alert
        for comment in reversed(comments):
            alert = comment.get_parameter('alert_datetime')
            if alert:
                self.set_property('crm_m_alert', alert)
        # Migrate next action
        for comment in reversed(comments):
            nextaction = comment.get_parameter('crm_m_nextaction')
            if nextaction:
                self.set_property('crm_m_nextaction', nextaction)
        # Remove parameters
        for comment in comments:
            comment.set_parameter('alert_datetime', None)
            comment.set_parameter('crm_m_nextaction', None)
        # Save
        self.metadata.set_property('comment', comments)



register_resource_class(MissionUpdate)
Пример #21
0

    def get_price_impact(self, prefix):
        if prefix is None:
            prefix = self.parent.get_price_prefix()
        return self.get_property('%simpact_on_price' % prefix)


    def get_weight(self):
        base_weight = self.parent.get_property('weight')
        weight_impact = self.get_property('impact-on-weight')
        weight_value = self.get_property('weight-impact-value')
        if weight_impact == 'none':
            return base_weight
        elif weight_impact == 'increase':
            return base_weight + weight_value
        elif weight_impact == 'decrease':
            return base_weight - weight_value



    def get_document_types(self):
        return []




register_resource_class(Declination)
register_field('declination_title', Unicode(is_indexed=True, is_stored=True))
register_field('is_default', Boolean(is_indexed=True))
Пример #22
0
    # Views
    addresses_book = Addresses_Book()
    add_address = Addresses_AddAddress()
    edit_address = Addresses_EditAddress()
    search = Addresses_Search()

    view = Table_View(access='is_admin')
    last_changes = None
    add_record = None


    address_title = MSG(u"""
      Please give a name to your address.
      """)

    address_tip = MSG(u"(Example: Home, Office)")

    form = [
        SelectRadio('gender', title=MSG(u'Genre')),
        TextWidget('firstname', title=MSG(u'Firstname')),
        TextWidget('lastname', title=MSG(u'Lastname')),
        TextWidget('address_1', title=MSG(u'Address')),
        TextWidget('address_2', title=MSG(u'Address (next)')),
        TextWidget('zipcode', title=MSG(u'Zip Code')),
        TextWidget('town', title=MSG(u'Town')),
        SelectWidget('country', title=MSG(u'Country')),
        TextWidget('title', title=address_title, tip=address_tip),
        ]

register_resource_class(Addresses)
Пример #23
0
        # banner_path
        site_root = self.get_site_root()
        available_languages = site_root.get_property("website_languages")

        for language in available_languages:
            value = self.get_property("banner_path", language=language)
            if not value:
                continue

            # Calcul the old absolute path
            old_abs_path = source.resolve2(value)
            # Check if the target path has not been moved
            new_abs_path = resources_old2new.get(old_abs_path, old_abs_path)

            self.set_property("banner_path", target.get_pathto(new_abs_path), language=language)

    # Views
    edit = Theme_Edit()
    control_panel = ITWS_ControlPanel()
    browse_content = Folder_BrowseContent(access="is_allowed_to_edit")
    edit_footer = GoToSpecificDocument(
        access="is_allowed_to_edit", specific_document="footer/menu", title=MSG(u"Edit footer")
    )
    edit_turning_footer = GoToSpecificDocument(
        access="is_allowed_to_edit", specific_document="turning-footer/menu", title=MSG(u"Edit turning footer")
    )


# Register
register_resource_class(Theme)
Пример #24
0
        }, {
            'property': 'og:type',
            'content': 'product'
        }, {
            'property': 'og:url',
            'content': url
        }, {
            'property': 'og:site_name',
            'content': self.get_property('website_title')
        }, {
            'property': 'fb:admins',
            'content': self.get_property('fb_admins')
        }]


register_resource_class(ShopModule_Opengraph)

##############################
# Register opengraph schema
##############################

og_attributes = {'property': String, 'content': Unicode}


class OGElement(ElementSchema):

    attributes = og_attributes


og_elements = [
    OGElement('meta', skip_content=True),
Пример #25
0
    # Views
    addresses_book = Addresses_Book()
    add_address = Addresses_AddAddress()
    edit_address = Addresses_EditAddress()
    search = Addresses_Search()

    view = Table_View(access='is_admin')
    last_changes = None
    add_record = None

    address_title = MSG(u"""
      Please give a name to your address.
      """)

    address_tip = MSG(u"(Example: Home, Office)")

    form = [
        SelectRadio('gender', title=MSG(u'Genre')),
        TextWidget('firstname', title=MSG(u'Firstname')),
        TextWidget('lastname', title=MSG(u'Lastname')),
        TextWidget('address_1', title=MSG(u'Address')),
        TextWidget('address_2', title=MSG(u'Address (next)')),
        TextWidget('zipcode', title=MSG(u'Zip Code')),
        TextWidget('town', title=MSG(u'Town')),
        SelectWidget('country', title=MSG(u'Country')),
        TextWidget('title', title=address_title, tip=address_tip),
    ]


register_resource_class(Addresses)
Пример #26
0
        record = payments_table.get_record(id_record)
        get_value = payments_table.get_record_value
        # Validate payment with validator
        resource_validator = get_value(record, 'resource_validator')
        validator = root.get_resource(resource_validator)
        validator.set_payment_as_ok(payment_way, id_record, context)



    def send_confirmation_mail(self, payment_way, id_record, context):
        root = context.root
        payments_table = payment_way.get_resource('payments').handler
        record = payments_table.get_record(id_record)
        user = payments_table.get_record_value(record, 'user')
        user = root.get_resource('users/%s' % user)
        recipient = user.get_property('email')
        subject = self.mail_subject_template.gettext()
        amount = payments_table.get_record_value(record, 'amount')
        text = self.mail_body_template.gettext(id=id_record,
            payment_way=payment_way.name,
            ref=payments_table.get_record_value(record, 'ref'),
            amount=format_price(amount),
            subject_with_host=False)
        root.send_email(recipient, subject, text=text)





register_resource_class(Payments)
Пример #27
0
from itools.gettext import MSG
from itools.web import STLView

# Import from ikaaro
from ikaaro.registry import register_resource_class

# Import from shop
from payments import Payments
from shop_utils_views import Shop_Progress


class ShopPayments_PayView(STLView):

    template = "/ui/shop/payments_pay.xml"

    def get_namespace(self, resource, context):
        progress = Shop_Progress(index=5, title=MSG(u"Payment end"))
        return {"progress": progress.GET(resource, context), "body": self.body}


class ShopPayments(Payments):

    class_id = "shop-payments"
    class_title = MSG(u"Shop payment Module")

    # Configure
    pay_view = ShopPayments_PayView


register_resource_class(ShopPayments)
Пример #28
0

############################################################
# EditArea edit view (mix CSS_Edit and HTMLEditView)
############################################################

class CSS_Edit(Text_Edit):
    """Code editor view using the EditArea instead of a basic textarea or
    the WYSIWYG tinyMCE (that cannot edit source directly as far as I known
    [Armel])."""

    def _get_schema(self, resource, context):
        schema = File_Edit._get_schema(self, resource, context)
        return merge_dicts(schema, data=String)

    widgets = [
        timestamp_widget,
        ea_widget]

    title = "Edit CSS file"


class CSS(BaseCSS):

    edit = CSS_Edit()


# Overwrite class for 'text/css'
# Maybe automatic
register_resource_class(CSS)
Пример #29
0
    access = 'is_allowed_to_edit'
    title = MSG(u'Download google merchant CSV')

    def GET(self, resource, context):
        root = context.root
        csv = GoogleMerchantCSV()
        csv.add_row(csv.columns)
        search = context.root.search(format='product', workflow_state='public')
        for brain in search.get_documents():
            product = root.get_resource(brain.abspath)
            csv.add_product(product, context)
        # Return ODS
        context.set_content_type('text/csv')
        context.set_content_disposition('attachment', 'export.csv')
        return csv.to_str()



class ShopModule_GoogleMerchant(ShopModule):

    class_id = 'shop_module_google_merchant'
    class_title = MSG(u'Google merchant')
    class_views = ['edit', 'download_csv']
    class_description = MSG(u'Google merchant')

    download_csv = Download_CSV()



register_resource_class(ShopModule_GoogleMerchant)
Пример #30
0
            'title': self.get_property('default_shipping_way_title'),
            'description':
            self.get_property('default_shipping_way_description'),
            'enabled': True,
            'img': img,
            'name': 'default',
            'pretty_price': format_price(price),
            'price': price
        }

    def get_price(self, shipping_way, country, purchase_weight):
        shipping_way = self.get_resource(shipping_way)
        return shipping_way.get_price(country, purchase_weight)

    def get_namespace_shipping_way(self, context, name, country, weight):
        shipping = self.get_resource(name)
        return shipping.get_widget_namespace(context, country, weight)

    def get_shippings_records(self, context, ref=None):
        records = []
        for shipping_way in self.search_resources(cls=ShippingWay):
            history = shipping_way.get_resource('history')
            if ref:
                records.extend(history.handler.search(ref=ref))
            else:
                records.extend(history.handler.get_records())
        return records


register_resource_class(Shippings)
Пример #31
0
                                flvbody, flvextension = encoded['flvfile']
                                thumbfilename, thumbmimetype,
                                thumbbody, thumbextension = encoded['flvthumb']
                            # Create the video FLV and thumbnail PNG resources
                            video = get_resource_class(flvmimetype)
                            thumbnail = get_resource_class(thumbmimetype)
                            # Remove the original files
                            if vfs.exists(file.handler.uri):
                                vfs.remove(file.handler.uri)
                            if vfs.exists(file.metadata.uri):
                                vfs.remove(file.metadata.uri)
                            
                            video.make_resource(video, issue, name,
                                body=flvbody, filename=flvfilename,
                                extension=flvextension, format=flvmimetype)
                            thumbnail.make_resource(thumbnail, issue, thumbfilename,
                                body=thumbbody, filename=thumbfilename,
                                extension=thumbextension, format=thumbmimetype)
                            
                            # Clean the temporary folder
                            vfs.remove(dirname)
                            
                            pprint("====================")
                        pprint("xxxxxxxxxxxxxxxx")

###########################################################################
# Register
###########################################################################

register_resource_class(Tchack_Tracker)
Пример #32
0
class Download_CSV(BaseView):

    access = 'is_allowed_to_edit'
    title = MSG(u'Download google merchant CSV')

    def GET(self, resource, context):
        root = context.root
        csv = GoogleMerchantCSV()
        csv.add_row(csv.columns)
        search = context.root.search(format='product', workflow_state='public')
        for brain in search.get_documents():
            product = root.get_resource(brain.abspath)
            csv.add_product(product, context)
        # Return ODS
        context.set_content_type('text/csv')
        context.set_content_disposition('attachment', 'export.csv')
        return csv.to_str()


class ShopModule_GoogleMerchant(ShopModule):

    class_id = 'shop_module_google_merchant'
    class_title = MSG(u'Google merchant')
    class_views = ['edit', 'download_csv']
    class_description = MSG(u'Google merchant')

    download_csv = Download_CSV()


register_resource_class(ShopModule_GoogleMerchant)
Пример #33
0
    def _show_payment_form(self, context, payment):
        percent = self.get_property('percent')
        payment['mode'] = 'paybox' # XXX (Can have another name ?)
        if self.get_property('pay_tax'):
            payment['amount'] = payment['amount'] * (percent / decimal('100.0'))
        else:
            payment['amount'] = payment['amount_without_tax'] * (percent / decimal('100.0'))
        return self.parent.show_payment_form(context, payment)


    def get_payment_way_description(self, context, total_amount):
        msg = MSG(u"Pay {percent}% of {original_amount} now ({amount})")
        percent = self.get_property('percent')
        if self.get_property('pay_tax'):
            total_amount = total_amount['with_tax'].split(' ')[0]
            total_amount = decimal(total_amount)
        else:
            total_amount = total_amount['without_tax'].split(' ')[0]
            total_amount = decimal(total_amount)
        amount = total_amount * (percent / decimal('100.0'))
        msg = msg.gettext(percent=percent,
                          original_amount=format_price(total_amount),
                          amount=format_price(amount))
        return list(XMLParser(msg.encode('utf-8'))) + self.get_property('data')



register_resource_class(Deposit)
register_payment_way(Deposit)
Пример #34
0
        ]
        return context.root.search(AndQuery(*queries))

    def get_nb_items_to_show(self, resource):
        return resource.get_property("nb_items_to_show")


class ReviewBox(Box):

    class_id = "shop_module_review_sidebar"
    class_title = MSG(u"Bar that list last reviews")
    class_description = MSG(u"Bar that list last reviews")

    view = ReviewBox_View()

    edit_schema = {
        "show_title": Boolean,
        "nb_items_to_show": Integer,
        "note_range": IntegerRangeDatatype(default=[0, 5]),
    }

    edit_widgets = [
        BooleanRadio("show_title", title=MSG(u"Show title ?")),
        TextWidget("nb_items_to_show", title=MSG(u"Numbers of items to show ?")),
        NumberRangeWidget("note_range", title=MSG(u"Note range")),
    ]


register_resource_class(ReviewBox)
register_box(ReviewBox, allow_instanciation=True, is_content=True, is_side=False)
Пример #35
0
# Import from shop.payments
from cash_views import CashPayment_Configure, CashPayment_End
from cash_views import CashPayment_RecordView, CashPayment_RecordEdit
from shop.payments.payment_way import PaymentWay
from shop.payments.registry import register_payment_way


class CashPayment(PaymentWay):

    class_id = 'cash-payment'
    class_title = MSG(u'Payment by cash')
    class_description = MSG(u'Payment by cash')
    class_views = ['configure', 'payments']

    # Views
    configure = CashPayment_Configure()
    end = CashPayment_End()

    # Order admin views
    order_view = CashPayment_RecordView
    order_edit_view = CashPayment_RecordEdit

    @classmethod
    def get_metadata_schema(cls):
        return merge_dicts(PaymentWay.get_metadata_schema(), address=Unicode)


register_resource_class(CashPayment)
register_payment_way(CashPayment)
Пример #36
0
        _cls._make_resource(_cls, folder, name, **kw)


class ProductSidebar(SideBarAware, Folder):

    class_id = 'product-sidebar'
    class_views = ['browse_content']

    @staticmethod
    def _make_resource(cls, folder, name, *args, **kw):
        Folder._make_resource(cls, folder, name, **kw)
        _cls = SideBarAware
        _cls._make_resource(_cls, folder, name, **kw)


class ShopSidebar(SideBarAware, Folder):

    class_id = 'shop-sidebar'
    class_views = ['browse_content']

    @staticmethod
    def _make_resource(cls, folder, name, *args, **kw):
        Folder._make_resource(cls, folder, name, **kw)
        _cls = SideBarAware
        _cls._make_resource(_cls, folder, name, **kw)


register_resource_class(CategorySidebar)
register_resource_class(ProductSidebar)
register_resource_class(ShopSidebar)
        viewbox.skin_template = '/sidebar/viewbox.xml'
        for product in table.get_products(context, product_class_id, categories):
            namespace['viewboxes'].append(viewbox.GET(product, context))
        return namespace



class SideBarProductCrossSellingBox(Box):

    class_id = 'sidebar-product-cross-selling-box'
    class_version = '20090122'
    class_title = MSG(u'Vertical item cross selling (product)')
    class_description = MSG(u"""Show on sidebar the
                                cross selling configure in product""")

    view = SideBarCrossSellingBox_View()


    # XXX Need ?
    edit_schema = {'thumb_width': Integer(mandatory=True),
                   'thumb_height': Integer(mandatory=True)}

    edit_widgets = [TextWidget('thumb_width', size=3,
                               title=MSG(u'Largeur des miniatures')),
                    TextWidget('thumb_height', size=3,
                               title=MSG(u'Hauteur des miniatures'))]


register_resource_class(SideBarProductCrossSellingBox)
register_box(SideBarProductCrossSellingBox, allow_instanciation=True)
Пример #38
0
        if products_quantity <= 0:
            return

        if names:
            names_query = [PhraseQuery("name", name) for name in names]
            if len(names_query) > 1:
                names_query = OrQuery(*names_query)
            else:
                names_query = names_query[0]
            query.append(NotQuery(names_query))

        # Complete results
        sort = table.get_property("sort")
        if sort == "random":
            # Random selection
            results = root.search(AndQuery(*query))
            # XXX It's not relevant to make a random cross selling
            # with more than 1000 products
            brains = list(results.get_documents(size=1000))
            shuffle(brains)
            for brain in brains[:products_quantity]:
                yield root.get_resource(brain.abspath)
        elif sort == "last":
            results = root.search(AndQuery(*query))
            brains = list(results.get_documents(sort_by="ctime", reverse=True, size=products_quantity))
            for brain in brains:
                yield root.get_resource(brain.abspath)


register_resource_class(CrossSellingTable)
Пример #39
0

class ProductSidebar(SideBarAware, Folder):

    class_id = 'product-sidebar'
    class_views = ['browse_content']

    @staticmethod
    def _make_resource(cls, folder, name, *args,  **kw):
        Folder._make_resource(cls, folder, name, **kw)
        _cls = SideBarAware
        _cls._make_resource(_cls, folder, name, **kw)


class ShopSidebar(SideBarAware, Folder):

    class_id = 'shop-sidebar'
    class_views = ['browse_content']

    @staticmethod
    def _make_resource(cls, folder, name, *args,  **kw):
        Folder._make_resource(cls, folder, name, **kw)
        _cls = SideBarAware
        _cls._make_resource(_cls, folder, name, **kw)



register_resource_class(CategorySidebar)
register_resource_class(ProductSidebar)
register_resource_class(ShopSidebar)
Пример #40
0
        print 'SIGNATURE ', sign.hexdigest()
        return sign.hexdigest()

    def _show_payment_form(self, context, payment):
        kw = {
            'amout': '25',
            'currency': '978',  # Euros,
            'capture_delay': '3',
            'ctx_mode': 'TEST',
            'payment_cards': 'AMEX;CB;MASTERCARD;VISA',
            'payment_config': 'SINGLE',
            'site_id': '12345678',
            'trans_date': '20100303105332',
            'url_return': 'http://shop:8080',
            'trans_id': '1',
            'validation_mode': '0',  #Validation automatique
            'version': 'V1'
        }
        # Get signature
        kw['signature'] = self.get_signature(kw)
        # Return URI
        uri = get_reference(self.uri)
        uri.query = kw
        print '======>', uri
        return context.uri.resolve(uri)


register_resource_class(SystemPay)
register_payment_way(SystemPay)
#register_resource_class(PayboxTable)
Пример #41
0
    def get_quantity_in_stock(self):
        return self.get_property('stock-quantity')

    def get_reference(self):
        return self.get_property('reference')

    def get_price_impact(self, prefix):
        if prefix is None:
            prefix = self.parent.get_price_prefix()
        return self.get_property('%simpact_on_price' % prefix)

    def get_weight(self):
        base_weight = self.parent.get_property('weight')
        weight_impact = self.get_property('impact-on-weight')
        weight_value = self.get_property('weight-impact-value')
        if weight_impact == 'none':
            return base_weight
        elif weight_impact == 'increase':
            return base_weight + weight_value
        elif weight_impact == 'decrease':
            return base_weight - weight_value

    def get_document_types(self):
        return []


register_resource_class(Declination)
register_field('declination_title', Unicode(is_indexed=True, is_stored=True))
register_field('is_default', Boolean(is_indexed=True))
Пример #42
0

class DataCount(Enumerate):

    options = [{'name': 'none', 'value': MSG(u'None')},
               {'name': 'vertical', 'value': MSG(u'Vertical')},
               {'name': 'horizontal', 'value': MSG(u'Horizontal')}]


class ShopModule_TwitterButton(ShopModule):

    class_id = 'shop_module_twitter_button'
    class_title = MSG(u'Twitter button')
    class_views = ['edit']
    class_description = MSG(u'Twitter button')

    item_schema = {'datacount': DataCount}

    item_widgets = [
        SelectWidget('datacount', title=MSG(u'Data count'), has_empty_option=False),
        ]


    def render(self, resource, context):
        return ShopModule_TwitterButton_View().GET(self, context)




register_resource_class(ShopModule_TwitterButton)
Пример #43
0
    # Backoffice order views
    order_view = ShippingWay_RecordView()
    order_add_view = ShippingWay_RecordAdd()
    order_edit_view = ShippingWay_RecordEdit()




class ShippingWaysEnumerate(Enumerate):

    @classmethod
    def get_options(cls):
        options = []
        context = get_context()
        shop = get_shop(context.resource)
        shippings = shop.get_resource('shippings')
        for way in shippings.search_resources(cls=ShippingWay):
            shipping_groups = way.get_property('only_this_groups')
            if context.user.get_property('user_group') not in shipping_groups:
                continue
            options.append({'name': way.name,
                            'value': way.get_title(),
                            'enabled': way.get_property('enabled')})
        return options


register_resource_class(ShippingWay)
register_resource_class(ShippingWayTable)
register_resource_class(ShippingPrices)
Пример #44
0
    def get_skin(self, context):
        if context.get_query_value('is_admin_popup', type=Boolean) is True:
            return self.get_resource('/ui/admin-popup/')
        # Back-Office
        hostname = context.uri.authority
        if hostname[:6] == 'admin.' :
            return self.get_resource('/ui/backoffice/')
        # Front-Office
        class_skin = self.get_class_skin(context)
        skin = self.get_resource(class_skin, soft=True)
        if skin is None:
            skin = self.get_resource('/ui/default_skin/')
        return skin


    def is_allowed_to_view_for_authenticated(self, user, resource):
        if (resource.has_property('must_be_authentificated') and
            resource.get_property('must_be_authentificated')):
            return self.is_authenticated(user, resource)
        return self.is_allowed_to_view(user, resource)


register_resource_class(ShopWebSite)
register_document_type(ShopWebSite, WebSite.class_id)


# XXX Add a hack to change login page
from ikaaro.resource_ import DBResource
DBResource.login = Shop_Login()
Пример #45
0
        # Filter by price
        if resource.get_resource('prices-range', soft=True):
            namespace['filter_by_price'] = FilterByPriceBox_View().GET(
                resource, context)
        else:
            namespace['filter_by_price'] = None
        # XXX Hack Nb results
        nb_results = None
        if isinstance(context.view, Shop_ProductSearch):
            nb_results = str(context.view.nb_results)
        # Build namespace
        namespace['title'] = resource.get_title()
        namespace['product_search_text'] = query.get('product_search_text')
        namespace['show_list_categories'] = self.show_list_categories
        namespace['widget_categories'] = widget
        namespace['nb_results'] = nb_results
        # Return namespace
        return namespace


class SearchBox(BoxAware, Folder):

    class_id = 'sidebar-item-search-box'
    class_title = MSG(u'Search box')
    class_description = MSG(u'Product research box')
    view = SearchBox_View()


register_resource_class(SearchBox)
register_box(SearchBox, allow_instanciation=True)
Пример #46
0
# Import from ikaaro
from ikaaro.registry import register_resource_class

# Import from shop
from payments import Payments
from shop_utils_views import Shop_Progress


class ShopPayments_PayView(STLView):

    template = '/ui/shop/payments_pay.xml'

    def get_namespace(self, resource, context):
        progress = Shop_Progress(index=5, title=MSG(u'Payment end'))
        return {'progress': progress.GET(resource, context), 'body': self.body}



class ShopPayments(Payments):

    class_id = 'shop-payments'
    class_title = MSG(u'Shop payment Module')

    # Configure
    pay_view = ShopPayments_PayView



register_resource_class(ShopPayments)
Пример #47
0
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Import from the Standard Library

# Import from ikaaro
from ikaaro.registry import register_resource_class

# Import from wiki
from page import WikiPage


class ObsoleteWikiPage(WikiPage):
    class_schema_extensible = True


    def update_20090123(self):
        # Remove "data" property
        self.del_property('data')



register_resource_class(ObsoleteWikiPage)
Пример #48
0
        return {'title': resource.get_title(), 'tree': tree}


class SubCategoriesBox(Box):

    class_id = 'vertical-item-sub-categories-box'
    class_title = MSG(u'Vertical item that list sub categories')
    class_version = '20100712'

    view = SubCategoriesBox_View()

    edit_schema = {
        'show_first_category': Boolean,
        'show_second_level': Boolean,
        'show_nb_products': Boolean,
        'use_small_title': Boolean
    }

    edit_widgets = [
        BooleanRadio('show_first_category', title=MSG(u'Show level 1 ?')),
        BooleanRadio('show_second_level', title=MSG(u'Show level 2 ?')),
        BooleanRadio('show_nb_products',
                     title=MSG(u'Afficher le nombre de produits')),
        BooleanRadio('use_small_title', title=MSG(u'Use small title'))
    ]


register_resource_class(SubCategoriesBox)
register_box(SubCategoriesBox, allow_instanciation=True)
Пример #49
0

class CrossSelling_Section_View(Category_View):
    def get_items(self, resource, context, *args):
        product_model = resource.get_property('product_model')
        query = PhraseQuery('product_model', product_model)
        return context.root.search(query)


class CrossSelling_Section(Folder):
    """
    XXX That should be a section_view on 0.62
    """

    class_id = 'section-cross-selling'
    class_title = MSG(u'Cross Selling Section')
    class_views = ['view', 'edit']

    view = CrossSelling_Section_View()
    edit = AutomaticEditView()

    # Edit views
    edit_schema = {'product_model': ProductModelsEnumerate}

    edit_widgets = [
        SelectWidget('product_model', title=MSG(u'Product model')),
    ]


register_resource_class(CrossSelling_Section)
Пример #50
0
                    'PBX_RANG', 'PBX_DIFF', 'PBX_AUTOSEULE']:
            kw[key] = self.get_property(key)
        kw['PBX_DEVISE'] = shop.get_property('devise')
        # PBX_PORTEUR
        kw['PBX_PORTEUR'] = context.user.get_property('email')
        # En mode test:
        if not self.get_property('real_mode'):
            kw.update(self.test_configuration)
        # Attributes
        attributes = ['%s=%s' % (x[0], x[1]) for x in kw.items()]
        # Build cmd
        cmd = '%s %s' % (cgi_path, ' '.join(attributes))
        # Call the CGI
        file = popen(cmd)
        # Check if all is ok
        result = file.read()
        html = match ('.*?<HEAD>(.*?)</HTML>', result, DOTALL)
        if html is None:
            raise ValueError, u"Error, payment module can't be load"
        # We return the payment widget
        html = html.group(1)
        # Encapsulate in pay view
        view = payments.pay_view(body=HTMLFile(string=html).events)
        return view.GET(self, context)



register_resource_class(Paybox)
register_payment_way(Paybox)
register_resource_class(PayboxTable)
Пример #51
0
    def set_payment_as_ok(self, id_record, context):
        """ Overridable: for example to send a custom mail ..."""
        self.parent.set_payment_as_ok(self, id_record, context)


    def create_payment(self, context, payment):
        """ We add payment in payments table. Overridable:
        For example to auto-validate payment or to add additional informations
        """
        payments = self.get_resource('payments').handler
        record = payments.add_record(
            {'ref': payment['ref'],
             'amount': payment['amount'],
             'user': context.user.name,
             'resource_validator': payment['resource_validator']})
        return record


    def get_payment_way_description(self, context, total_amount):
        """ Overridable: for example to add available points... """
        return self.get_property('data')


    def is_enabled(self, context):
        """ Overridable: A payment way can be disabled according to context"""
        return  self.get_property('enabled')


register_resource_class(PaymentWay)
register_resource_class(PaymentWayTable)
Пример #52
0
    class_id = "sidebar-item-filter-order"
    class_title = MSG(u"Cross-Selling Table")
    class_handler = ResourcesOrderedTableFile

    order_root_path = "../"
    orderable_classes = (Filter_Criterium, Filter_Criterium_Categorie, FilterRange_Table)


class FilterBox(BoxAware, Folder):

    class_id = "sidebar-item-filter-box"
    class_title = MSG(u"Filter box")
    class_description = MSG(u"Filter box")
    class_views = ["edit", "browse_content", "new_resource"]
    view = FilterBox_View()

    @staticmethod
    def _make_resource(cls, folder, name, *args, **kw):
        Folder._make_resource(cls, folder, name, *args, **kw)
        # Order
        cls = OrderCriterium
        cls._make_resource(cls, folder, "%s/order" % name)

    def get_document_types(self):
        return [Filter_Criterium, Filter_Criterium_Categorie, FilterRange_Table]


register_resource_class(FilterBox)
register_box(FilterBox, allow_instanciation=True)
        return namespace


class SideBarProductCrossSellingBox(Box):

    class_id = 'sidebar-product-cross-selling-box'
    class_version = '20090122'
    class_title = MSG(u'Vertical item cross selling (product)')
    class_description = MSG(u"""Show on sidebar the
                                cross selling configure in product""")

    view = SideBarCrossSellingBox_View()

    # XXX Need ?
    edit_schema = {
        'thumb_width': Integer(mandatory=True),
        'thumb_height': Integer(mandatory=True)
    }

    edit_widgets = [
        TextWidget('thumb_width', size=3,
                   title=MSG(u'Largeur des miniatures')),
        TextWidget('thumb_height',
                   size=3,
                   title=MSG(u'Hauteur des miniatures'))
    ]


register_resource_class(SideBarProductCrossSellingBox)
register_box(SideBarProductCrossSellingBox, allow_instanciation=True)
Пример #54
0
    form = [
        HiddenWidget('name', None),
        TextWidget('title', title=MSG(u'Title')),
        TextWidget('color', title=MSG(u'Color')),
    ]


class EnumeratesFolder(Folder):
    """ EnumeratesFolder is a folder that
    contains all EnumerateTable of our application
    """

    class_id = 'enumerates-folder'
    class_title = MSG(u'Enumerates folder')
    class_views = ['view', 'new_resource']

    # Views
    view = EnumeratesFolder_View()
    new_resource = Folder.new_resource

    # Navigation
    context_menus = []

    def get_document_types(self):
        return [EnumerateTable]  # EnumerateTableColor]


register_resource_class(EnumerateTable)
register_resource_class(EnumerateTableColor)
register_resource_class(EnumeratesFolder)
Пример #55
0
    sort_reverse = True

    def get_items_search(self, resource, context, *args):
        query = PhraseQuery('format', 'user')
        return context.root.search(query)


    def get_nb_items_to_show(self, resource):
        return resource.get_property('nb_items_to_show')



class LastUsersBox(Box):

    class_id = 'shop_sidebar_last_users'
    class_title = MSG(u'Bar that list last users')
    class_description = MSG(u'Bar that list last users that registred into website')

    view = LastUsersBox_View()

    edit_schema = {'show_title': Boolean,
                   'nb_items_to_show': Integer}
    edit_widgets = [BooleanRadio('show_title', title=MSG(u'Show title ?')),
                    TextWidget('nb_items_to_show', title=MSG(u'Nb users to show ?'))]



register_resource_class(LastUsersBox)
register_box(LastUsersBox, allow_instanciation=True,
             is_content=True, is_side=False)
Пример #56
0

    def _show_payment_form(self, context, payment):
        amount_available = self.get_credit_available_for_user(context.user.name)
        remaining_to_pay = payment['amount'] - amount_available
        # Partial payment
        if remaining_to_pay > decimal('0'):
            # Delete credit
            users_credit = self.get_resource('users-credit')
            results = users_credit.handler.search(user=context.user.name)
            if len(results) == 0:
                raise ValueError, 'Error, credit do not exist'
            record = results[0]
            old_amount = users_credit.handler.get_record_value(record, 'amount')
            new_amount = old_amount - payment['amount']
            if new_amount < decimal('0'):
                users_credit.del_record(record.id)
            else:
                kw = {'amount': new_amount}
                users_credit.update_recod(record.id, **kw)
            # Encapsulate in pay view
            payment['mode'] = 'paybox' # XXX (Can have another name ?)
            payment['amount'] = remaining_to_pay
            return self.parent.show_payment_form(context, payment)
        # Complete payment
        return PaymentWay._show_payment_form(self, context, payment)


register_resource_class(CreditPayment)
register_payment_way(CreditPayment)