def unmapped(self): unmapped = list() settings = s.get('invoices') params = [ settings['repository'], s.INVOICES_SELL_PRICE_TYPE, settings['price_level'] ] sql = """ SELECT P.ID, P.Name, P.GroupID, P.Info, KP.FinalPrice, MA.Mojoodi FROM KalaList AS P INNER JOIN CategoryMap AS CM ON P.GroupID = CM.id LEFT JOIN ProductMap AS PM ON P.ID = PM.id INNER JOIN KalaPrice AS KP ON P.ID = KP.KalaID LEFT JOIN dbo.Mojoodi_all('1000/00/00', '3000/00/00', ?, '23:59:59', 0) AS MA ON P.ID = MA.ID_Kala WHERE PM.id IS NULL AND KP.Type = ? AND KP.PriceID = ? """ for row in self.product.custom_sql(sql, params, method='fetchall'): unmapped.append({ 'id': row.ID, 'name': row.Name, 'info': row.Info, 'price': self._int(row.FinalPrice), 'quantity': self._int(row.Mojoodi), 'category_id': row.GroupID, }) return unmapped
def setUp(self): self.conn = connection.get(**s.get('test_db')) self.test_table = Table('Test') self.test_table.connection = self.conn # create test table sql = """ CREATE TABLE Test( c1 INT PRIMARY KEY, c2 VARCHAR(50) NOT NULL, c3 DATETIME NOT NULL, c4 BIT NOT NULL ) """ cursor = self.conn.cursor() cursor.execute(sql) # insert records into Test table sql = """ INSERT INTO Test(c1, c2, c3, c4) VALUES (?, ?, ?, ?) """ self.records = [ [i, 'test{}'.format(i), datetime.now(), True] for i in range(1, 11) ] cursor.executemany(sql, self.records) cursor.close() self.conn.commit()
def get(url=None, ckey=None, skey=None, version=None, timeout=None, wp_api=True): wc_settings = s.get('wc') url = url or wc_settings['url'] ckey = ckey or wc_settings['ckey'] skey = skey or wc_settings['skey'] version = version or wc_settings['version'] timeout = timeout or wc_settings['timeout'] # create wc api instance return API(url, ckey, skey, wp_api=wp_api, version=version, timeout=timeout)
def get(server=None, username=None, password=None, database=None, autocommit=False): db_settings = s.get('moein') server = server or db_settings['server'] username = username or db_settings['username'] password = password or db_settings['password'] database = database or db_settings['database'] return Connection(server, username, password, database, autocommit)
def setUp(self): self.endpoint = 'products' api = wc_api.get(**s.get('test_store')) self.wc_product = wc.get(api, self.endpoint) self.product_ids = [] self.products_data = [{ 'name': f'product {i}', 'regular_price': f'{i}000' } for i in range(1, 4)] for data in self.products_data: product = self.wc_product.create(data) self.product_ids.append(product['id'])
def tab_handler(self): self.tab.set({ 'general': s.get('general'), 'wc': s.get('wc'), 'moein': s.get('moein'), 'import_export': s.get('import_export'), 'orders': s.get('orders'), 'invoices': s.get('invoices'), 'engine': s.get('engine') }) self.ui.contents.showTab(self.ui.contents.SETTINGS)
def __init__(self, ui): # get settings settings = s.get('engine') # recipient engine self.engine = RecipientEngine( settings['interval'], settings['wc_update'], settings['convert_orders'] ) # ui self.ui = ui self.tab = ui.contents.status # connect signals # - ui self.ui.menu.btnStatus.clicked.connect(self.tab_handler) self.tab.btnStart.clicked.connect(self.start) self.tab.btnStop.clicked.connect(self.stop) # - engine self.engine.started.connect(self.tab.start) self.engine.finished.connect(self.tab.stop) self.engine.signals.error.connect(self.engine_error_handle)
def orders(self): settings = s.get('orders') orders = self.woocommerce.all(exclude=','.join( [str(im.wcid) for im in self.invoice_map.all()]), status=','.join(settings['status']), after=settings['after'], before=settings['before']) for order in orders: order['created_date'] = datetime.fromisoformat( order['date_created_gmt']) order['items'] = self.items(order['line_items']) order['items_subtotal'] = self.items_subtotal(order['line_items']) order['items_total'] = self.items_total(order['line_items']) order['items_discount'] = self.items_discount(order['line_items']) order['discount'] = int( order['discount_total']) - self.items_discount( order['line_items']) order['first_name'] = order['billing']['first_name'] or order[ 'shipping']['first_name'] order['last_name'] = order['billing']['last_name'] or order[ 'shipping']['last_name'] return orders
def mapped(self, update_required=False): mapped = list() settings = s.get('invoices') params = [ settings['repository'], s.INVOICES_SELL_PRICE_TYPE, settings['price_level'] ] sql = """ SELECT P.ID, P.Name, P.GroupID, P.Info, PM.wcid, PM.last_update, PM.update_required, KP.FinalPrice, MA.Mojoodi FROM KalaList AS P INNER JOIN ProductMap AS PM ON P.ID = PM.id INNER JOIN KalaPrice AS KP ON P.ID = KP.KalaID LEFT JOIN dbo.Mojoodi_all('1000/00/00', '3000/00/00', ?, '23:59:59', 0) AS MA ON P.ID = MA.ID_Kala WHERE KP.Type = ? AND KP.PriceID = ? """ # check for update required if update_required: sql += " AND PM.update_required = 1" for row in self.product.custom_sql(sql, params, method='fetchall'): mapped.append({ 'id': row.ID, 'name': row.Name, 'info': row.Info, 'price': self._int(row.FinalPrice), 'quantity': self._int(row.Mojoodi), 'category_id': row.GroupID, 'wcid': row.wcid, 'last_update': row.last_update, 'update_required': row.update_required }) return mapped
# standard import gettext # internal from src import settings as s # get current language current_lang = s.LOCALE_LANGUAGES[s.get('general')['language']] # install current language lang = gettext.translation(s.LOCALE_DOMAIN, localedir=s.LOCALE_DIR, languages=[current_lang]) lang.install() # create interface _ = lang.gettext
# standard import unittest # internal from src import settings as s from src import wc_api invalid_credentials = { 'url': s.get('test_store')['url'], 'ckey': 'ck_nul1sbjblc9oc4lt8izq26hkwcib9vhxtx88an6e', 'skey': 'cs_hwf9fvtntbu5ek105oez1obg99v5zijb6q5kcfqd', 'version': 'wc/v3' } class StatusCode(object): """Status Codes Collection""" Success = 200 # success Created = 201 # created BadRequest = 400 # invalid request, e.g. using unsupported HTTP method Unauthorized = 401 # authentication or permission error, e.g. incorrect API keys NotFound = 404 # request to resources that dont exist or are missing InternalError = 500 # server error class TestWCAPI(unittest.TestCase): """Test wc_api module""" STATUS_CODES = StatusCode() def test_get(self): api = wc_api.get()
def save(self, order): # get settings settings = s.get('invoices') # current date and time in jalali calendar date_frmt = '%Y/%m/%d' time_frmt = '%H:%M:%S' current_date = jdatetime.now().date().strftime(date_frmt) current_time = jdatetime.now().date().strftime(time_frmt) # order date and time in jalali calendar order_datetime = jdatetime.fromgregorian( datetime=order['created_date']) order_date = order_datetime.date().strftime(date_frmt) order_time = order_datetime.time().strftime(time_frmt) # detect customer if not order['customer_id']: customer_id = settings['guest'] else: try: customer_map = self.customer_map.get(wcid=order['customer_id']) customer_id = customer_map.id except DoesNotExists: self.customer.create({ 'Code': self.customer.max('Code') + 1, 'Fname': order['first_name'], 'LName': order['last_name'], 'Name': '{} {}'.format(order['first_name'], order['last_name']), 'BuyPriceLevel': settings['price_level'], 'SellPriceLevel': settings['price_level'], 'StartDate': current_date, 'Prefix': '', 'ShiftTo': '23:59:59', 'ShiftFrom': '00:00:00', 'Visitor': 0, 'CarryPrice': 0, 'VisitorBed': 0, 'EtebarNaghd': 0, 'VisitorPerc': 0, 'EtebarCheque': 0, 'MablaghAvalDore': 0, }) customer_id = self.customer.max('ID') self.customer_map.create({ 'id': customer_id, 'wcid': order['customer_id'], 'last_update': datetime.now() }) # get next invoice No invoice_no = self.invoice.custom_sql("SELECT dbo.NewFactorNo(?)", [settings['type']], method='fetchval') # prepare invoice fields fields = { 'FactorNo': invoice_no, 'FishNo': invoice_no, 'Type': settings['type'], 'IDShakhs': customer_id, 'UserID': 1, 'Date': order_date, 'Time': order_time, 'PaymentDate': order_date, 'DeliverDate': order_date, 'InsertDate': current_date, 'InsertTime': current_time, 'Info': '', 'JamKol': int(order['total']), 'GmeFactor': order['items_subtotal'], 'MandeFactor': int(order['total']), 'Maliat': int(order['total_tax']), 'Takhfif': order['discount'], 'TakhfifItem': order['items_discount'], 'CarryPrice': int(order['shipping_total']), 'CarryType': 0, 'Nagd': 0, 'Nagd2': 0, 'Naseh': 0, 'Naseh2': 0, 'Chek': 0, 'Chek2': 0, 'Anbar': 0, 'Confirmed': 0, 'VisitorPrice': 0, 'VisitorPerc': 0, 'PaymentValue': 0, 'PaymentType': 0, 'Tmp': 0, 'Converted': 0, 'MaliatPerc': 0, 'ServicePerc': 0, 'ServicePrice': 0 } # check for info if fields['CarryPrice']: fields['Info'] = _('carry price: {}').format(fields['CarryPrice']) # create invoice self.invoice.create(fields) invoice_id = self.invoice.max('ID') # insert items for i, item in enumerate(order['items'], 1): self.line_item.create({ 'FactorID': invoice_id, 'IDKala': item['id'], 'Tedad': item['quantity'], 'Tedad1': 0, 'Tedad2': item['quantity'], 'TedadStr': str(item['quantity']), 'Price': item['regular_price'], 'SumPrice': int(item['total']), 'Takhfif': item['discount'], 'TakhfifPerc': 0, 'TakhfifPerItem': 0, 'TakhfifIsGift': 0, 'Anbar': settings['repository'], 'Info': '', 'Row': i, 'VisitorPrice': 0, 'VisitorPerc': 0, 'PaymentValue': 0, 'PaymentType': 0, 'PaymentDate': order_date, 'JozDarKol': 0, 'Maliat': 0, 'Height': 0, 'Width': 0, 'Thick': 0, 'Density': 0, 'UnitType': 0, 'Amount': 0, 'Overhead': 0, 'Gift': 0, 'Value': 0, 'PriceLevelID': settings['price_level'], 'ValueEdited': 0 }) # create map self.invoice_map.create({ 'id': invoice_id, 'wcid': order['id'], 'last_update': datetime.now() })
def import2moein(self, wc_product): product_id = None # get info info = dict() # - sku if wc_product['sku']: info['sku'] = wc_product['sku'] # check for sku hint if s.get('import_export')['sku_hint'] and wc_product['sku']: try: product = self.product.get('ID', 'Info', Code=self._int(wc_product['sku'])) except DoesNotExists: pass else: product_id = product.ID # check for additional data self.product.update({'Info': self.setinfo(product.Info, info)}, ID=product_id) # if cannot find product by sku hinting, create new one if product_id is None: # check for category_map category_map = None for category in wc_product['categories']: try: category_map = self.category_map.get(wcid=category['id']) break except DoesNotExists: continue # if cannot find category_map, raise Exception if category_map is None: raise Exception( _('CategoryMap for product {} does not exists.').format( wc_product['name'])) # clean quantity and regualr_price value quantity = self._int(wc_product['stock_quantity']) regular_price = self._int(wc_product['regular_price']) # - create product self.product.create({ 'Name': wc_product['name'], 'GroupID': category_map.id, 'SellPrice': regular_price, 'Code': self.product.max('Code') + 1, 'MenuOrder': self.product.max('MenuOrder') + 1, 'Info': self.setinfo('', info), 'Unit2': 'عدد', 'BuyPrice': 0, 'SefareshPoint': 0, 'ShortCut': 0, 'Active': 1, 'Maliat': 1, 'UnitType': 0, 'Weight': 0, 'IncPerc': 0, 'IncPrice': 0, 'ValueCalcType': 0 }) product_id = self.product.max('ID') # - set price levels for pl in self.price_level.all(): self.product_price.create({ 'PriceID': pl.ID, 'KalaID': product_id, 'Type': s.INVOICES_BUY_PRICE_TYPE, 'Price': 0, '[Percent]': 0, 'FinalPrice': 0, 'Takhfif': 0 }) self.product_price.create({ 'PriceID': pl.ID, 'KalaID': product_id, 'Type': s.INVOICES_SELL_PRICE_TYPE, 'Price': regular_price, '[Percent]': 0, 'FinalPrice': regular_price, 'Takhfif': 0 }) # - quantity if quantity: self.product_repository.create({ 'IdKala': product_id, 'Tedad': quantity, 'SumPrice': regular_price * quantity, 'Price': regular_price, 'Anbar': s.get('invoices')['repository'], 'Tedad1': 0, 'Tedad2': 0 }) # create product map self.product_map.create({ 'id': product_id, 'wcid': wc_product['id'], 'last_update': datetime.now() })
def _bootstrap(self): # check for engine auto start if s.get('engine')['auto_start']: self.status.start()